From 525d1bac9abdefd694c8da7ffb55bfd8b117cda1 Mon Sep 17 00:00:00 2001 From: Francois Aucamp Date: Tue, 23 Jul 2013 12:03:58 +0200 Subject: [PATCH 001/133] Add basic data/GPRS setup commands to modem class This allows the manipulation of PDP contexts (setting APNs, etc) and can initiate the first portion of a data session (the actual dialing). Not much use as-is, but can be extended later for MMS sending functionality, and with the use of pppd and a bit of hacking this can be used to set up and control "normal" data network connections via the GSM modem. --- gsmmodem/gprs.py | 96 ++++++++++++++++++++++++++++++++++ tools/gsmtermlib/atcommands.py | 24 +++++++++ 2 files changed, 120 insertions(+) create mode 100644 gsmmodem/gprs.py diff --git a/gsmmodem/gprs.py b/gsmmodem/gprs.py new file mode 100644 index 0000000..746715c --- /dev/null +++ b/gsmmodem/gprs.py @@ -0,0 +1,96 @@ +# -*- coding: utf8 -*- + +""" GPRS/Data-specific classes + +BRANCH: mms + +PLEASE NOTE: *Everything* in this file (PdpContext, GprsModem class, etc) is experimental. +This is NOT meant to be used in production in any way; the API is completely unstable, +no unit tests will be written for this in the forseeable future, and stuff may generally +break and cause riots. Please do not file bug reports against this branch unless you +have a patch to go along with it, but even then: remember that this entire "mms" branch +is exploratory; I simply want to see what the possibilities are with it. + +Use the "main" branch, and the GsmModem class if you want to build normal applications. +""" + +import re + +from .util import allLinesMatchingPattern +from .modem import GsmModem + +class PdpContext(object): + """ Packet Data Protocol (PDP) context parameter values """ + def __init__(self, cid, pdpType, apn, pdpAddress=None, dataCompression=0, headerCompression=0): + """ Construct a new Packet Data Protocol context + + @param cid: PDP Context Identifier - specifies a particular PDP context definition + @type cid: int + @param pdpType: the type of packet data protocol (IP, PPP, IPV6, etc) + @type pdpType: str + @param apn: Access Point Name; logical name used to select the GGSN or external packet data network + @type apn: str + @param pdpAddress: identifies the MT in the address space applicable to the PDP. If None, a dynamic address may be requested. + @type pdpAddress: str + @param dataCompression: PDP data compression; 0 == off, 1 == on + @type dataCompression: int + @param headerCompression: PDP header compression; 0 == off, 1 == on + @type headerCompression: int + """ + self.cid = cid + self.pdpType = pdpType + self.apn = apn + self.pdpAddress = pdpAddress + self.dataCompression = dataCompression + self.headerCompression = headerCompression + + +class GprsModem(GsmModem): + """ EXPERIMENTAL: Specialized version of GsmModem that includes GPRS/data-specific commands """ + + @property + def pdpContexts(self): + """ Currently-defined Packet Data Protocol (PDP) context list + + PDP paramter values returned include PDP type (IP, IPV6, PPP, X.25 etc), APN, + data compression, header compression, etc. + + @return: a list of currently-defined PDP contexts + """ + result = [] + cgdContResult = self.write('AT+CGDCONT?') + matches = allLinesMatchingPattern(re.compile(r'^\+CGDCONT:\s*(\d+),"([^"]+)","([^"]+)","([^"]+)",(\d+),(\d+)'), cgdContResult) + for cgdContMatch in matches: + cid, pdpType, apn, pdpAddress, dataCompression, headerCompression = cgdContMatch.groups() + pdpContext = PdpContext(cid, pdpType, apn, pdpAddress, dataCompression, headerCompression) + result.append(pdpContext) + return result + + @property + def defaultPdpContext(self): + """ @return: the default PDP context, or None if not defined """ + pdpContexts = self.pdpContexts + return pdpContexts[0] if len(pdpContexts) > 0 else None + @defaultPdpContext.setter + def defaultPdpContext(self, pdpContext): + """ Set the default PDP context (or clear it by setting it to None) """ + self.write('AT+CGDCONT=,"{0}","{1}","{2}",{3},{4}'.format(pdpContext.pdpType, pdpContext.apn, pdpContext.pdpAddress or '', pdpContext.dataCompression, pdpContext.headerCompression)) + + def definePdpContext(self, pdpContext): + """ Define a new Packet Data Protocol context, or overwrite an existing one + + @param pdpContext: The PDP context to define + @type pdpContext: gsmmodem.gprs.PdpContext + """ + self.write('AT+CGDCONT={0},"{1}","{2}","{3}",{4},{5}'.format(pdpContext.cid or '', pdpContext.pdpType, pdpContext.apn, pdpContext.pdpAddress or '', pdpContext.dataCompression, pdpContext.headerCompression)) + + def initDataConnection(self, pdpCid=1): + """ Initializes a packet data (GPRS) connection using the specified PDP Context ID """ + # From this point on, we don't want the read thread interfering + self.log.debug('Stopping read thread') + self.alive = False + self.rxThread.join() + self.log.debug('Init data connection') + self.write('ATD*99#', waitForResponse=False) + self.log.debug('Data connection open; ready for PPP comms') + # From here on we use PPP to communicate with the network diff --git a/tools/gsmtermlib/atcommands.py b/tools/gsmtermlib/atcommands.py index 7085179..fd14556 100644 --- a/tools/gsmtermlib/atcommands.py +++ b/tools/gsmtermlib/atcommands.py @@ -326,6 +326,30 @@ ('AT+ILRR', (c[7], 'DTE-DCE Local Rate Reporting')), ('AT+CRLP', (c[7], 'Radio Link Protocol Parameters')), ('AT+DOPT', (c[7], 'Radio Link Protocol Parameters')), +('AT+CGDCONT', (c[7], 'Define PDP Context', (('', 'PDP Context Identifier - a numeric parameter (1-32) which specifies a particular \ +PDP context definition. The parameter is local to the TE-MT interface and is used in \ +other PDP context-related commands.'), + ('', 'A string parameter which specifies the type of packet data protocol. (IP, IPV6, PPP, X.25 etc)'), + ('', 'Access Point Name. String parameter; logical name that is used to select the GGSN or external packet data network'), + ('', 'String parameter that identifies the MT in the address space applicable to the PDP. If null/omitted, a dynamic address may be requested.'), + ('', 'PDP data compression. Values:\n\ +0 - off (default)\n\ +1 - on'), + ('', 'PDP header compression. Values:\n\ +0 - off (default)\n\ +1 - on')), None, 'This command specifies the PDP (Packet Data Protocol) context parameter values, such as PDP type (IP, IPV6, PPP, X.25 etc), APN, data compression, header compression, etc.')), +('AT+CGATT', (c[7], 'GPRS attach or detach', (('', 'indicates the state of GPRS attachment:\n\ +0 - detached\n\ +1 - attached\n'),), None, 'The execution command is used to attach the MT to, or detach the MT from, the GPRS\ +service. After the command has completed, the MT remains in V.25ter command state.\n\ +Any active PDP contexts will be automatically deactivated when the attachment state changes to detached.')), + +('AT+CGACT', (c[7], 'PDP context activate or deactivate', (('', 'indicates the state of PDP context activation:\n\ +0 - deactivated\n\ +1 - activated\n'), + ('', 'a numeric parameter which specifies a particular PDP context.')), + None, 'The execution command is used to activate or deactivate the specified PDP context (s).\n\ +After the command has completed, the MT remains in V.25ter command state.')), # Fax ('AT+FTM', (c[8], 'Transmit Speed')), ('AT+FRM', (c[8], 'Receive Speed')), From af621b413d9d41eaef7ada015ad8abdf356f1506 Mon Sep 17 00:00:00 2001 From: Francois Aucamp Date: Fri, 26 Jul 2013 14:34:13 +0200 Subject: [PATCH 002/133] Commit for branch switch --- gsmmodem/gprs.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gsmmodem/gprs.py b/gsmmodem/gprs.py index 746715c..af164f4 100644 --- a/gsmmodem/gprs.py +++ b/gsmmodem/gprs.py @@ -87,10 +87,10 @@ def definePdpContext(self, pdpContext): def initDataConnection(self, pdpCid=1): """ Initializes a packet data (GPRS) connection using the specified PDP Context ID """ # From this point on, we don't want the read thread interfering - self.log.debug('Stopping read thread') - self.alive = False - self.rxThread.join() + #self.log.debug('Stopping read thread') + #self.alive = False + #self.rxThread.join() self.log.debug('Init data connection') - self.write('ATD*99#', waitForResponse=False) + self.write('ATD*99#', expectedResponseTermSeq="CONNECT\r") self.log.debug('Data connection open; ready for PPP comms') # From here on we use PPP to communicate with the network From 1e64387f9c425ebb4f75aee4586e49c3f28a9434 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Tue, 4 Feb 2014 15:45:32 -0200 Subject: [PATCH 003/133] deleteStoredSms: tweaked AT com for Siemens MC53 --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index ce9fac1..4aa5d52 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1080,7 +1080,7 @@ def deleteStoredSms(self, index, memory=None): :raise CommandError: if unable to delete the stored message """ self._setSmsMemory(readDelete=memory) - self.write('AT+CMGD={0},0'.format(index)) + self.write('AT+CMGD={0}'.format(index)) def deleteMultipleStoredSms(self, delFlag=4, memory=None): """ Deletes all SMS messages that have the specified read status. From 54ebfd8795c7f2eac7ebc06e418a6a254eb11110 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Mon, 17 Feb 2014 11:20:29 -0300 Subject: [PATCH 004/133] increased default timeout for AT response --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 4aa5d52..2174284 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -381,7 +381,7 @@ def _unlockSim(self, pin): else: raise PinRequiredError('AT+CPIN') - def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): + def write(self, data, waitForResponse=True, timeout=20, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): """ Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and From 9780c85114c5f411a79deb4b0b06a6edecf76466 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Wed, 19 Feb 2014 17:29:08 +0100 Subject: [PATCH 005/133] ReceivedSms.udh --- gsmmodem/modem.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 4eb242f..bee0fc1 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -49,11 +49,12 @@ def __init__(self, number, text, smsc=None): class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - def __init__(self, gsmModem, status, number, time, text, smsc=None): + def __init__(self, gsmModem, status, number, time, text, smsc=None, udh=None): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time + self.udh = udh def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ @@ -824,7 +825,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self.log.debug('Discarding line from +CMGL response: %s', line) else: if smsDict['type'] == 'SMS-DELIVER': - sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + 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']) else: @@ -1063,7 +1064,7 @@ def readStoredSms(self, index, memory=None): pdu = msgData[1] smsDict = decodeSmsPdu(pdu) if smsDict['type'] == 'SMS-DELIVER': - return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh')) elif smsDict['type'] == 'SMS-STATUS-REPORT': return StatusReport(self, int(stat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: From ff7e7551e19b298df0670613908a014efea349dd Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Wed, 19 Feb 2014 17:29:54 +0100 Subject: [PATCH 006/133] +CREG parsing fix +CREG: 2,1,"1727","0000C7EE" is now parsed correctly --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index bee0fc1..62d664a 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -597,7 +597,7 @@ def _cancelBlock(): checkCreg = True while block[0]: if checkCreg: - cregResult = lineMatching(r'^\+CREG:\s*(\d),(\d)$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 + cregResult = lineMatching(r'^\+CREG:\s*(\d),(\d)(,[^,]*,[^,]*)?$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 if cregResult: status = int(cregResult.group(2)) if status in (1, 5): From 4ce4081531b16a62dbd365b09b442b0cfac254c0 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Sat, 22 Feb 2014 05:58:33 -0300 Subject: [PATCH 007/133] enable sms notif only when callbacks are defined --- gsmmodem/modem.py | 59 +++++++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 62d664a..3e54269 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -131,11 +131,11 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): - super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) - self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback - self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback - self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback + def __init__(self, port, baudrate=115200, incomingCallCallback=None, smsReceivedCallback=None, smsStatusReportCallback=None): + super(GsmModem, self).__init__(port, baudrate, notifyCallback=self._handleModemNotification) + self.incomingCallCallback = incomingCallCallback or self._placeholderCallback + self.smsReceivedCallback = smsReceivedCallback + self.smsStatusReportCallback = smsStatusReportCallback # Flag indicating whether caller ID for incoming call notification has been set up self._callingLineIdentification = False # Flag indicating whether incoming call notifications have extended information @@ -334,7 +334,7 @@ def connect(self, pin=None): del cpmsSupport del cpmsLine - if self._smsReadSupported: + if self._smsReadSupported and (self.smsReceivedCallback or self.smsStatusReportCallback): try: self.write('AT+CNMI=2,1,0,2') # Set message notifications except CommandError: @@ -696,12 +696,12 @@ def sendUssd(self, ussdString, responseTimeout=15): self._ussdSessionEvent = None raise TimeoutException() - def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): + def dial(self, number, timeout=5, callStatusUpdateCallback=None): """ Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established - :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to + :param callStatusUpdateCallback: Callback function that is executed if the call's status changes due to remote events (i.e. when it is answered, the call is ended by the remote party) :return: The outgoing call @@ -721,7 +721,7 @@ def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice - call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) + call = Call(self, callId, callType, number, callStatusUpdateCallback) self.activeCalls[callId] = call return call @@ -732,7 +732,7 @@ def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): if self._dialEvent.wait(timeout): self._dialEvent = None callId, callType = self._dialResponse - call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) + call = Call(self, callId, callType, number, callStatusUpdateCallback) self.activeCalls[callId] = call return call else: # Call establishing timed out @@ -989,13 +989,18 @@ def _handleCallRejected(self, regexMatch, callId=None): def _handleSmsReceived(self, notificationLine): """ Handler for "new SMS" unsolicited notification line """ self.log.debug('SMS message received') - cmtiMatch = self.CMTI_REGEX.match(notificationLine) - if cmtiMatch: - msgMemory = cmtiMatch.group(1) - msgIndex = cmtiMatch.group(2) - sms = self.readStoredSms(msgIndex, msgMemory) - self.deleteStoredSms(msgIndex) - self.smsReceivedCallback(sms) + if self.smsReceivedCallback is not None: + cmtiMatch = self.CMTI_REGEX.match(notificationLine) + if cmtiMatch: + msgMemory = cmtiMatch.group(1) + msgIndex = cmtiMatch.group(2) + sms = self.readStoredSms(msgIndex, msgMemory) + try: + self.smsReceivedCallback(sms) + except Exception: + self.log.error('error in smsReceivedCallback', exc_info=True) + else: + self.deleteStoredSms(msgIndex) def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ @@ -1012,9 +1017,13 @@ def _handleSmsStatusReport(self, notificationLine): if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() - else: + elif self.smsStatusReportCallback: # Nothing is waiting for this report directly - use callback - self.smsStatusReportCallback(report) + try: + self.smsStatusReportCallback(report) + except Exception: + self.log.error('error in smsStatusReportCallback', exc_info=True) + def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index @@ -1150,10 +1159,6 @@ def _parseCusdResponse(self, lines): message = cusdMatches[0].group(2) return Ussd(self, sessionActive, message) - def _placeHolderCallback(self, *args): - """ Does nothing """ - self.log.debug('called with args: {0}'.format(args)) - def _pollCallStatus(self, expectedState, callId=None, timeout=None): """ Poll the status of outgoing calls. This is used for modems that do not have a known set of call status update notifications. @@ -1208,13 +1213,13 @@ class Call(object): DTMF_COMMAND_BASE = '+VTS=' dtmfSupport = False # Indicates whether or not DTMF tones can be sent in calls - def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallbackFunc=None): + def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallback=None): """ :param gsmModem: GsmModem instance that created this object :param number: The number that is being called """ self._gsmModem = weakref.proxy(gsmModem) - self._callStatusUpdateCallbackFunc = callStatusUpdateCallbackFunc + self._callStatusUpdateCallback = callStatusUpdateCallback # Unique ID of this call self.id = callId # Call type (VOICE == 0, etc) @@ -1233,8 +1238,8 @@ def answered(self): @answered.setter def answered(self, answered): self._answered = answered - if self._callStatusUpdateCallbackFunc: - self._callStatusUpdateCallbackFunc(self) + if self._callStatusUpdateCallback: + self._callStatusUpdateCallback(self) def sendDtmfTone(self, tones): """ Send one or more DTMF tones to the remote party (only allowed for an answered call) From 44257cf8500cca08de3c2ca17942cbbbfa0e56b0 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Sat, 22 Feb 2014 07:01:11 -0300 Subject: [PATCH 008/133] processStoredSms: more explicit error message --- gsmmodem/modem.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 3e54269..a073ef3 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -751,13 +751,16 @@ def processStoredSms(self, unreadOnly=False): :param unreadOnly: If True, only process unread SMS messages :type unreadOnly: boolean """ - states = [Sms.STATUS_RECEIVED_UNREAD] - if not unreadOnly: - states.insert(0, Sms.STATUS_RECEIVED_READ) - for msgStatus in states: - messages = self.listStoredSms(status=msgStatus, delete=True) - for sms in messages: - self.smsReceivedCallback(sms) + if self.smsReceivedCallback: + states = [Sms.STATUS_RECEIVED_UNREAD] + if not unreadOnly: + states.insert(0, Sms.STATUS_RECEIVED_READ) + for msgStatus in states: + messages = self.listStoredSms(status=msgStatus, delete=True) + for sms in messages: + self.smsReceivedCallback(sms) + else: + raise ValueError('GsmModem.smsReceivedCallback not set') def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. From 3468fa3b98d231f6284e7af3c28a746d244e8c3d Mon Sep 17 00:00:00 2001 From: Alessio Bogon Date: Thu, 11 Sep 2014 03:21:41 +0200 Subject: [PATCH 009/133] Patch to make it work with python 3.4 Taken from faucamp#39 Unit test won't work, a huge work is needed to completely port to python 3. But at least we have something working. --- gsmmodem/serial_comms.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index ac445f5..3a8b837 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -91,6 +91,8 @@ def _readLoop(self): rxBuffer = [] while self.alive: data = self.serial.read(1) + if isinstance(data, bytes): + data = data.decode() if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(data) @@ -118,6 +120,8 @@ def _readLoop(self): self.fatalErrorCallback(e) def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=None): + if isinstance(data, str): + data = data.encode() with self._txLock: if waitForResponse: if expectedResponseTermSeq: From 0076b9d0ce5eef82af525d48b0f6533467ed18d0 Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Fri, 12 Sep 2014 14:49:05 -0300 Subject: [PATCH 010/133] fix to _decodeAddressField() --- gsmmodem/pdu.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index f64c501..8df5edf 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -534,6 +534,12 @@ def _decodeDataCoding(octet): # We ignore other coding groups return 0 +def nibble2octet(o): + if o % 2: + return o / 2 + 1 + else: + return o / 2 + def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator @@ -549,7 +555,7 @@ def _decodeAddressField(byteIter, smscField=False, log=False): ton = (toa & 0x70) # bits 6,5,4 of type-of-address == type-of-number if ton == 0x50: # Alphanumberic number - addressLen /= 2 + addressLen = nibble2octet(addressLen) septets = unpackSeptets(byteIter, addressLen) addressValue = decodeGsm7(septets) return (addressValue, (addressLen + 2)) @@ -559,10 +565,7 @@ def _decodeAddressField(byteIter, smscField=False, log=False): if smscField: addressValue = decodeSemiOctets(byteIter, addressLen-1) else: - if addressLen % 2: - addressLen = int(addressLen / 2) + 1 - else: - addressLen = int(addressLen / 2) + addressLen = nibble2octet(addressLen) addressValue = decodeSemiOctets(byteIter, addressLen) addressLen += 1 # for the return value, add the toa byte if ton == 0x10: # International number From 9a34749c3ee3382c2782b8baad54c0c747cab53b Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Thu, 18 Sep 2014 06:23:46 -0300 Subject: [PATCH 011/133] SMS txt timeout 15 -> 60 seconds --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index a073ef3..53dde3b 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -644,7 +644,7 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=15, writeTerm=chr(26))) # example: +CMGS: xx + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=60, writeTerm=chr(26))) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') reference = int(result[7:]) From def3290620a02c5ee97243cfc17b79df66fbca0a Mon Sep 17 00:00:00 2001 From: Paolo Losi Date: Tue, 23 Sep 2014 18:03:25 -0300 Subject: [PATCH 012/133] FIX: pack and unpack septets of len zero --- gsmmodem/pdu.py | 11 ++++++++--- test/test_pdu.py | 5 +++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 8df5edf..a26fdd0 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -730,7 +730,10 @@ def packSeptets(octets, padBits=0): octets = iter(octets) shift = padBits if padBits == 0: - prevSeptet = next(octets) + try: + prevSeptet = next(octets) + except StopIteration: + return result else: prevSeptet = 0x00 for octet in octets: @@ -767,6 +770,8 @@ def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7): septets = iter(septets) if numberOfSeptets == None: numberOfSeptets = MAX_INT # Loop until StopIteration + if numberOfSeptets == 0: + return result i = 0 for octet in septets: i += 1 @@ -776,7 +781,7 @@ def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7): result.append(prevOctet >> 1) if i <= numberOfSeptets: result.append(octet & 0x7F) - prevOctet = octet + prevOctet = octet if i == numberOfSeptets: break else: @@ -789,7 +794,7 @@ def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7): if i == numberOfSeptets: break - if shift == 7: + if shift == 7 and prevOctet: b = prevOctet >> (8 - shift) if b: # The final septet value still needs to be unpacked diff --git a/test/test_pdu.py b/test/test_pdu.py index 70fcb67..77794de 100644 --- a/test/test_pdu.py +++ b/test/test_pdu.py @@ -47,7 +47,8 @@ class TestGsm7(unittest.TestCase): """ Tests the GSM-7 encoding/decoding algorithms """ def setUp(self): - self.tests = (('123', bytearray(b'123'), bytearray([49, 217, 12])), + self.tests = (('', bytearray(b''), bytearray([])), + ('123', bytearray(b'123'), bytearray([49, 217, 12])), ('12345678', bytearray(b'12345678'), bytearray([49, 217, 140, 86, 179, 221, 112])), ('123456789', bytearray(b'123456789'), bytearray([49, 217, 140, 86, 179, 221, 112, 57])), ('Hello World!', bytearray([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21]), bytearray([200, 50, 155, 253, 6, 93, 223, 114, 54, 57, 4])), @@ -487,4 +488,4 @@ def test_decode_invalidData(self): if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() From 5e31fdf6b9602dae594656d4c13c80762747db89 Mon Sep 17 00:00:00 2001 From: yuriykashin Date: Thu, 9 Oct 2014 21:33:06 +0800 Subject: [PATCH 013/133] Add UDH info in ReceivedSms. Thus we can handle continuations e.g. --- gsmmodem/modem.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..ea682b1 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -40,10 +40,11 @@ class Sms(object): 'STO SENT': STATUS_STORED_SENT, 'ALL': STATUS_ALL} - def __init__(self, number, text, smsc=None): + def __init__(self, number, text, smsc=None, udh=[]): self.number = number self.text = text self.smsc = smsc + self.udh = udh class ReceivedSms(Sms): @@ -827,7 +828,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self.log.debug('Discarding line from +CMGL response: %s', line) else: if smsDict['type'] == 'SMS-DELIVER': - sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + 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']) else: @@ -1066,7 +1067,7 @@ def readStoredSms(self, index, memory=None): pdu = msgData[1] smsDict = decodeSmsPdu(pdu) if smsDict['type'] == 'SMS-DELIVER': - return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', [])) elif smsDict['type'] == 'SMS-STATUS-REPORT': return StatusReport(self, int(stat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: From 576352c048a127d95d73e46cdfffe9caee7608d0 Mon Sep 17 00:00:00 2001 From: yuriykashin Date: Thu, 9 Oct 2014 22:01:30 +0800 Subject: [PATCH 014/133] Fix a mistake. --- gsmmodem/modem.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index ea682b1..8f606da 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -40,21 +40,21 @@ class Sms(object): 'STO SENT': STATUS_STORED_SENT, 'ALL': STATUS_ALL} - def __init__(self, number, text, smsc=None, udh=[]): + def __init__(self, number, text, smsc=None): self.number = number self.text = text self.smsc = smsc - self.udh = udh class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - def __init__(self, gsmModem, status, number, time, text, smsc=None): + def __init__(self, gsmModem, status, number, time, text, smsc=None, udh=[]): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time + self.udh = udh def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ From 81b43ce391f42a507753ddb4c0b31f89028e6291 Mon Sep 17 00:00:00 2001 From: yuriykashin Date: Sat, 7 Feb 2015 21:32:51 +0700 Subject: [PATCH 015/133] Dirty fix for https://github.com/yuriykashin/python-gsmmodem/issues/1 --- gsmmodem/modem.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 8f606da..4806cfc 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -826,6 +826,8 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): smsDict = decodeSmsPdu(line) except EncodingError: self.log.debug('Discarding line from +CMGL response: %s', line) + except: + pass else: if smsDict['type'] == 'SMS-DELIVER': sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', [])) From 29ca5f5ab030f3907f2d38d60f354a73c8382431 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 4 Aug 2015 14:32:09 +0800 Subject: [PATCH 016/133] Added a function sendSms under the class receivedSms to send message from within --- gsmmodem/modem.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..b7ba1b5 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -59,6 +59,10 @@ def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ return self._gsmModem.sendSms(self.number, message) + def sendSms(dnumber, message): + """ Convenience method that sends a SMS to someone else """ + return self._gsmModem.sendSms(dnumber, message) + class SentSms(Sms): """ An SMS message that has been sent (MO) """ From 2dbfe1cdb36fb7a8917431917da5031694c2b306 Mon Sep 17 00:00:00 2001 From: JeromeZ80 Date: Tue, 4 Aug 2015 16:02:06 +0800 Subject: [PATCH 017/133] Added access function for receivedSms class to use the modem functions. --- gsmmodem/modem.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index b7ba1b5..0eebe45 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -701,6 +701,21 @@ def sendUssd(self, ussdString, responseTimeout=15): else: # Response timed out self._ussdSessionEvent = None raise TimeoutException() + + + def checkFowarding(self, querytype): + """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd + :param querytype: The type of forwarding to check + + :return: Status + :rtype: Boolean + """ + try: + queryResponse = self.write('AT+CCFC={0},2'.format(querytype), timeout=responseTimeout) # Should respond with "OK" + except Exception: + raise + print(queryResponse) + return True def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call From 811df2425faed29381b2f68113b5db536e6a1eb3 Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Tue, 4 Aug 2015 16:21:49 +0800 Subject: [PATCH 018/133] Added getModem, setForwarding change typo on checkFowarding --- gsmmodem/modem.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 0eebe45..c747ce4 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -63,7 +63,10 @@ def sendSms(dnumber, message): """ Convenience method that sends a SMS to someone else """ return self._gsmModem.sendSms(dnumber, message) - + def getModem(dnumber, message): + """ Convenience method that returns the gsm modem instance """ + return self._gsmModem + class SentSms(Sms): """ An SMS message that has been sent (MO) """ @@ -703,7 +706,7 @@ def sendUssd(self, ussdString, responseTimeout=15): raise TimeoutException() - def checkFowarding(self, querytype): + def checkForwarding(self, querytype, timeout=ResponseTimeout): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param querytype: The type of forwarding to check @@ -716,6 +719,24 @@ def checkFowarding(self, querytype): raise print(queryResponse) return True + + + def setForwarding(self, fwdType, fwdEnable, fwdNumber, timeout=ResponseTimeout): + """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd + :param fwdType: The type of forwarding to set + :param fwdEnable: 1 to enable, 0 to disable, 2 to query, 3 to register, 4 to erase + :param fwdNumber: Number to forward to + + :return: Success or not + :rtype: Boolean + """ + try: + queryResponse = self.write('AT+CCFC={0},{1}.{2}'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" + except Exception: + raise + return False + print(queryResponse) + return True def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call From 3a14eb13d25f678dbc5770b407b500fcbda73487 Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Tue, 4 Aug 2015 16:24:21 +0800 Subject: [PATCH 019/133] Fixed bug on responseTimeout --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index c747ce4..16ae3e8 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -706,7 +706,7 @@ def sendUssd(self, ussdString, responseTimeout=15): raise TimeoutException() - def checkForwarding(self, querytype, timeout=ResponseTimeout): + def checkForwarding(self, querytype, timeout=15): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param querytype: The type of forwarding to check @@ -721,7 +721,7 @@ def checkForwarding(self, querytype, timeout=ResponseTimeout): return True - def setForwarding(self, fwdType, fwdEnable, fwdNumber, timeout=ResponseTimeout): + def setForwarding(self, fwdType, fwdEnable, fwdNumber, timeout=15): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param fwdType: The type of forwarding to set :param fwdEnable: 1 to enable, 0 to disable, 2 to query, 3 to register, 4 to erase From c4637739e0203cb2ad43c4d2a9ec8f72d88666a9 Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Tue, 4 Aug 2015 16:26:24 +0800 Subject: [PATCH 020/133] Fixed parameter bug in checkForwarding and setForwarding --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 16ae3e8..b379fda 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -706,7 +706,7 @@ def sendUssd(self, ussdString, responseTimeout=15): raise TimeoutException() - def checkForwarding(self, querytype, timeout=15): + def checkForwarding(self, querytype, responseTimeout=15): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param querytype: The type of forwarding to check @@ -721,7 +721,7 @@ def checkForwarding(self, querytype, timeout=15): return True - def setForwarding(self, fwdType, fwdEnable, fwdNumber, timeout=15): + def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param fwdType: The type of forwarding to set :param fwdEnable: 1 to enable, 0 to disable, 2 to query, 3 to register, 4 to erase From 4e3b931a43f199464f9333ce6d1525cfbdcdae23 Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Tue, 4 Aug 2015 16:33:25 +0800 Subject: [PATCH 021/133] Bug period in setForwarding --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index b379fda..34dcd33 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -731,7 +731,7 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},{1}.{2}'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},{1},{2}'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" except Exception: raise return False From 36bc98acf0f1153ff94936ff3d1b3a624f5d54dd Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Tue, 4 Aug 2015 16:46:13 +0800 Subject: [PATCH 022/133] Wrap setForwarding with " param fwdNumber --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 34dcd33..01e34d8 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -731,12 +731,12 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},{1},{2}'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},{1},"{2}"'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" except Exception: raise return False print(queryResponse) - return True + return queryResponse def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call From b38331a5a56ded7160197b7ceefcab93f1784a36 Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Wed, 5 Aug 2015 18:59:10 +0800 Subject: [PATCH 023/133] Fixed bug in getModem Should have no parameters. --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 01e34d8..6948c7a 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -63,7 +63,7 @@ def sendSms(dnumber, message): """ Convenience method that sends a SMS to someone else """ return self._gsmModem.sendSms(dnumber, message) - def getModem(dnumber, message): + def getModem(): """ Convenience method that returns the gsm modem instance """ return self._gsmModem From 923ab50e0c5a5bc2af65438f0022644b5bd37ffa Mon Sep 17 00:00:00 2001 From: jeromez80 Date: Wed, 5 Aug 2015 19:03:08 +0800 Subject: [PATCH 024/133] Bug in sendSms and getModem functions Included self parameter --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 6948c7a..2598f7f 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -59,11 +59,11 @@ def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ return self._gsmModem.sendSms(self.number, message) - def sendSms(dnumber, message): + def sendSms(self, dnumber, message): """ Convenience method that sends a SMS to someone else """ return self._gsmModem.sendSms(dnumber, message) - def getModem(): + def getModem(self): """ Convenience method that returns the gsm modem instance """ return self._gsmModem From 2b665907df6845dad3b98d45b8fdc0f971ee653f Mon Sep 17 00:00:00 2001 From: Enrico Polesel Date: Sat, 2 Jan 2016 22:57:09 +0100 Subject: [PATCH 025/133] Option to disable request for delivery report Just initialize the GsmModem object with requestDelivery=False (default is True) --- gsmmodem/modem.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..41bc45e 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -130,7 +130,7 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback @@ -160,7 +160,8 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece self._smsMemReadDelete = None # Preferred message storage memory for reads/deletes ( parameter used for +CPMS) self._smsMemWrite = None # Preferred message storage memory for writes ( parameter used for +CPMS) self._smsReadSupported = True # Whether or not reading SMS messages is supported via AT commands - + self.requestDelivery = requestDelivery + def connect(self, pin=None): """ Opens the port and initializes the modem and SIM card @@ -300,7 +301,10 @@ def connect(self, pin=None): # Some modems delete the SMSC number when setting text-mode SMS parameters; preserve it if needed if currentSmscNumber != None: self._smscNumber = None # clear cache - self.write('AT+CSMP=49,167,0,0', parseError=False) # Enable delivery reports + if self.requestDelivery: + self.write('AT+CSMP=49,167,0,0', parseError=False) # Enable delivery reports + else: + self.write('AT+CSMP=17,167,0,0', parseError=False) # Not enable delivery reports # ...check SMSC again to ensure it did not change if currentSmscNumber != None and self.smsc != currentSmscNumber: self.smsc = currentSmscNumber From 9625cb8fd666c90b15b129bbd809e3f11d40ea51 Mon Sep 17 00:00:00 2001 From: Alejandro Madariaga Angeles Date: Sat, 16 Jan 2016 01:17:12 -0600 Subject: [PATCH 026/133] added "waittingForModemToStartInSeconds" argument to GsmModem.conect(), added AT_CNMI property to GsmModem. The waittingForModemToStartInSeconds arg allows to wait after the serial connection has started, and before sending the AT commands. The AT_CNMI proprety of the GsmModem class allow to specify the CNMI parameter of the gsm modem, this helps to set up the incoming sms notifications. --- gsmmodem/modem.py | 17 ++++++++++++----- tools/identify-modem.py | 6 ++++-- tools/sendsms.py | 14 +++++++++----- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..707d4aa 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -4,6 +4,7 @@ import sys, re, logging, weakref, time, threading, abc, codecs from datetime import datetime +from time import sleep from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError @@ -130,11 +131,12 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, AT_CNMI=""): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback + self.AT_CNMI = AT_CNMI or "2,1,0,2" # Flag indicating whether caller ID for incoming call notification has been set up self._callingLineIdentification = False # Flag indicating whether incoming call notifications have extended information @@ -161,7 +163,7 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece self._smsMemWrite = None # Preferred message storage memory for writes ( parameter used for +CPMS) self._smsReadSupported = True # Whether or not reading SMS messages is supported via AT commands - def connect(self, pin=None): + def connect(self, pin=None, waitingForModemToStartInSeconds=0): """ Opens the port and initializes the modem and SIM card :param pin: The SIM card PIN code, if any @@ -170,8 +172,13 @@ def connect(self, pin=None): :raise PinRequiredError: if the SIM card requires a PIN but none was provided :raise IncorrectPinError: if the specified PIN is incorrect """ - self.log.info('Connecting to modem on port %s at %dbps', self.port, self.baudrate) + + self.log.info('Connecting to modem on port %s at %dbps', self.port, self.baudrate) super(GsmModem, self).connect() + + if waitingForModemToStartInSeconds > 0: + sleep(waitingForModemToStartInSeconds) + # Send some initialization commands to the modem try: self.write('ATZ') # reset configuration @@ -338,7 +345,7 @@ def connect(self, pin=None): if self._smsReadSupported: try: - self.write('AT+CNMI=2,1,0,2') # Set message notifications + self.write('AT+CNMI=' + self.AT_CNMI) # Set message notifications except CommandError: # Message notifications not supported self._smsReadSupported = False @@ -384,7 +391,7 @@ def _unlockSim(self, pin): else: raise PinRequiredError('AT+CPIN') - def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): + def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): """ Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and diff --git a/tools/identify-modem.py b/tools/identify-modem.py index b56bdf9..1a2167d 100755 --- a/tools/identify-modem.py +++ b/tools/identify-modem.py @@ -21,7 +21,8 @@ def parseArgs(): parser.add_argument('port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_argument('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_argument('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') - parser.add_argument('-d', '--debug', action='store_true', help='dump modem debug information (for python-gsmmodem development)') + parser.add_argument('-d', '--debug', action='store_true', help='dump modem debug information (for python-gsmmodem development)') + parser.add_argument('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') return parser.parse_args() def parseArgsPy26(): @@ -32,6 +33,7 @@ def parseArgsPy26(): parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_option('-d', '--debug', action='store_true', help='dump modem debug information (for python-gsmmodem development)') + parser.add_option('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') options, args = parser.parse_args() if len(args) != 1: parser.error('Incorrect number of arguments - please specify a PORT to connect to, e.g. {0} /dev/ttyUSB0'.format(sys.argv[0])) @@ -46,7 +48,7 @@ def main(): print('Connecting to GSM modem on {0}...'.format(args.port)) try: - modem.connect(args.pin) + modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) except PinRequiredError: sys.stderr.write('Error: SIM card PIN required. Please specify a PIN with the -p argument.\n') sys.exit(1) diff --git a/tools/sendsms.py b/tools/sendsms.py index 31c42bd..e519a12 100755 --- a/tools/sendsms.py +++ b/tools/sendsms.py @@ -19,8 +19,10 @@ def parseArgs(): parser.add_argument('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_argument('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_argument('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') - parser.add_argument('-d', '--deliver', action='store_true', help='wait for SMS delivery report') - parser.add_argument('destination', metavar='DESTINATION', help='destination mobile number') + parser.add_argument('-d', '--deliver', action='store_true', help='wait for SMS delivery report') + parser.add_argument('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') + parser.add_argument('--CNMI', default='', help='Set the CNMI of the modem, used for message notifications') + parser.add_argument('destination', metavar='DESTINATION', help='destination mobile number') return parser.parse_args() def parseArgsPy26(): @@ -30,7 +32,9 @@ def parseArgsPy26(): parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') - parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') + parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') + parser.add_option('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') + parser.add_option('--CNMI', default='', help='Set the CNMI of the modem, used for message notifications') parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) options, args = parser.parse_args() if len(args) != 1: @@ -44,13 +48,13 @@ def main(): if args.port == None: sys.stderr.write('Error: No port specified. Please specify the port to which the GSM modem is connected using the -i argument.\n') sys.exit(1) - modem = GsmModem(args.port, args.baud) + modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) # Uncomment the following line to see what the modem is doing: #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) print('Connecting to GSM modem on {0}...'.format(args.port)) try: - modem.connect(args.pin) + modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) except PinRequiredError: sys.stderr.write('Error: SIM card PIN required. Please specify a PIN with the -p argument.\n') sys.exit(1) From 7f6e089d1eda7a41e45be4a6a35af030fcba1033 Mon Sep 17 00:00:00 2001 From: Cyril Roques Date: Tue, 19 Jan 2016 17:15:41 +0100 Subject: [PATCH 027/133] Ignore bad formated characters on serial line --- gsmmodem/serial_comms.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 3a8b837..d1c4c54 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -92,7 +92,10 @@ def _readLoop(self): while self.alive: data = self.serial.read(1) if isinstance(data, bytes): - data = data.decode() + try: + data = data.decode() + except UnicodeDecodeError: + data = '' if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(data) From 0010fbdbbdb75533bc6acc4864965a05bc073b48 Mon Sep 17 00:00:00 2001 From: Alejandro Madariaga Angeles Date: Mon, 8 Feb 2016 00:04:48 -0600 Subject: [PATCH 028/133] Changed the wait fro modem to start, from sleep to hearth beats --- gsmmodem/modem.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 707d4aa..3b27945 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -177,7 +177,12 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): super(GsmModem, self).connect() if waitingForModemToStartInSeconds > 0: - sleep(waitingForModemToStartInSeconds) + while waitingForModemToStartInSeconds > 0: + try: + self.write('AT', waitForResponse=True, timeout=0.5) + break + except TimeoutException: + waitingForModemToStartInSeconds -= 0.5 # Send some initialization commands to the modem try: @@ -509,7 +514,7 @@ def supportedCommands(self): try: # AT+CLAC responses differ between modems. Most respond with +CLAC: and then a comma-separated list of commands # while others simply return each command on a new line, with no +CLAC: prefix - response = self.write('AT+CLAC') + response = self.write('AT+CLAC', timeout=10) if len(response) == 2: # Single-line response, comma separated commands = response[0] if commands.startswith('+CLAC'): From 138a3d28c41628c1260fbe5a1dbc49f543138f2a Mon Sep 17 00:00:00 2001 From: foXes68 Date: Fri, 1 Apr 2016 20:56:49 +0300 Subject: [PATCH 029/133] Update serial_comms.py --- gsmmodem/serial_comms.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 3f28c2f..3b47bba 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -90,7 +90,7 @@ def _readLoop(self): readTermLen = len(readTermSeq) rxBuffer = [] while self.alive: - data = self.serial.read(1) + data = self.serial.read(1).decode() #Python 3.x compatibility if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(data) @@ -124,7 +124,7 @@ def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=N self._expectResponseTermSeq = list(expectedResponseTermSeq) self._response = [] self._responseEvent = threading.Event() - self.serial.write(data) + self.serial.write(data.encode()) #Python 3.x compatibility if self._responseEvent.wait(timeout): self._responseEvent = None self._expectResponseTermSeq = False From e87cca6f6be89971312f6ecc1bfeb3d86addd812 Mon Sep 17 00:00:00 2001 From: Raghav Date: Wed, 8 Jun 2016 22:46:03 +0530 Subject: [PATCH 030/133] ZTE fixes --- gsmmodem/modem.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..4afb875 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -118,7 +118,7 @@ class GsmModem(SerialComms): # Used for parsing caller ID announcements for incoming calls. Group 1 is the number CLIP_REGEX = re.compile(r'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications - CMTI_REGEX = re.compile(r'^\+CMTI:\s*"([^"]+)",(\d+)$') + CMTI_REGEX = re.compile(r'^\+CMTI:\s*"([^"]+)",\s*(\d+)$') # Used for parsing SMS message reads (text mode) CMGR_SM_DELIVER_REGEX_TEXT = None # Used for parsing SMS status report message reads (text mode) @@ -338,7 +338,7 @@ def connect(self, pin=None): if self._smsReadSupported: try: - self.write('AT+CNMI=2,1,0,2') # Set message notifications + self.write('AT+CNMI=2,1') # Set message notifications except CommandError: # Message notifications not supported self._smsReadSupported = False @@ -549,7 +549,7 @@ def _compileSmsRegexes(self): self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: - self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') + self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR:\s*(\d*),\s*"{0,1}([^"]*)"{0,1},\s*(\d+)$') @property def smsc(self): From 727840575c8a2aac05cbae8fc28b0dc11ab46686 Mon Sep 17 00:00:00 2001 From: Raghav Date: Thu, 9 Jun 2016 08:48:51 +0530 Subject: [PATCH 031/133] regex fix for ussd --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 4afb875..ab4f35b 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -126,7 +126,7 @@ class GsmModem(SerialComms): # Used for parsing SMS message reads (PDU mode) CMGR_REGEX_PDU = None # Used for parsing USSD event notifications - CUSD_REGEX = re.compile(r'\+CUSD:\s*(\d),"(.*?)",(\d+)', re.DOTALL) + CUSD_REGEX = re.compile(r'\+CUSD:\s*(\d),\s*"(.*?)",\s*(\d+)', re.DOTALL) # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') From 0c2401911e9988812021a3c687373484379582ec Mon Sep 17 00:00:00 2001 From: eri Date: Sat, 11 Jun 2016 15:19:56 +0300 Subject: [PATCH 032/133] unicoded sms support --- gsmmodem/modem.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..648ab44 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -10,14 +10,24 @@ from .pdu import encodeSmsSubmitPdu, decodeSmsPdu from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr -from . import compat # For Python 2.6 compatibility +#from . import compat # For Python 2.6 compatibility from gsmmodem.util import lineMatching from gsmmodem.exceptions import EncodingError PYTHON_VERSION = sys.version_info[0] + +CTRLZ = chr(26) +TERMINATOR = '\r' + + if PYTHON_VERSION >= 3: xrange = range dictValuesIter = dict.values dictItemsIter = dict.items + unicode = str + TERMINATOR = b'\r' + CTRLZ = b'\x1a' + + else: #pragma: no cover dictValuesIter = dict.itervalues dictItemsIter = dict.iteritems @@ -300,7 +310,7 @@ def connect(self, pin=None): # Some modems delete the SMSC number when setting text-mode SMS parameters; preserve it if needed if currentSmscNumber != None: self._smscNumber = None # clear cache - self.write('AT+CSMP=49,167,0,0', parseError=False) # Enable delivery reports + self.write('AT+CSMP=49,167,0,8', parseError=False) # Enable delivery reports # ...check SMSC again to ensure it did not change if currentSmscNumber != None and self.smsc != currentSmscNumber: self.smsc = currentSmscNumber @@ -384,7 +394,7 @@ def _unlockSim(self, pin): else: raise PinRequiredError('AT+CPIN') - def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): + def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm=TERMINATOR, expectedResponseTermSeq=None): """ Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and @@ -409,6 +419,11 @@ def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTer :return: A list containing the response lines from the modem, or None if waitForResponse is False :rtype: list """ + + if isinstance(data, unicode): + data = bytes(data,"ascii") + + self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) @@ -640,13 +655,13 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou :raise TimeoutException: if the operation times out """ if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=chr(26))) + self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq=b'> ') + result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=CTRLZ)) else: pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: - self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=15, writeTerm=chr(26))) # example: +CMGS: xx + self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq=b'> ') + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=15, writeTerm=CTRLZ)) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') reference = int(result[7:]) From 4288c6cd3860199a3da79d0c33df79e0b4645da6 Mon Sep 17 00:00:00 2001 From: eri Date: Sat, 11 Jun 2016 15:31:48 +0300 Subject: [PATCH 033/133] python 3.2,3.3 compatibility --- gsmmodem/serial_comms.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index ac445f5..4545deb 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -93,7 +93,7 @@ def _readLoop(self): data = self.serial.read(1) if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) - rxBuffer.append(data) + rxBuffer.append(ord(data)) if rxBuffer[-readTermLen:] == readTermSeq: # A line (or other logical segment) has been read line = ''.join(rxBuffer[:-readTermLen]) From 057b76dc2038ce8a205a002c256882a91b761ee3 Mon Sep 17 00:00:00 2001 From: eri Date: Sat, 11 Jun 2016 16:42:44 +0300 Subject: [PATCH 034/133] bytes for python3 --- gsmmodem/serial_comms.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 4545deb..ac66c25 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -86,25 +86,25 @@ def _readLoop(self): Reads lines from the connected device """ try: - readTermSeq = list(self.RX_EOL_SEQ) + readTermSeq = bytearray(self.RX_EOL_SEQ) readTermLen = len(readTermSeq) - rxBuffer = [] + rxBuffer = bytearray() while self.alive: data = self.serial.read(1) if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(ord(data)) - if rxBuffer[-readTermLen:] == readTermSeq: + if rxBuffer[-readTermLen:] == readTermSeq: # A line (or other logical segment) has been read - line = ''.join(rxBuffer[:-readTermLen]) - rxBuffer = [] + line = bytes(rxBuffer[:-readTermLen]) + rxBuffer = bytearray() if len(line) > 0: #print 'calling handler' self._handleLineRead(line) elif self._expectResponseTermSeq: if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq: - line = ''.join(rxBuffer) - rxBuffer = [] + line = bytes(rxBuffer) + rxBuffer = bytearray() self._handleLineRead(line, checkForResponseTerm=False) #else: #' ' @@ -121,7 +121,7 @@ def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=N with self._txLock: if waitForResponse: if expectedResponseTermSeq: - self._expectResponseTermSeq = list(expectedResponseTermSeq) + self._expectResponseTermSeq = bytearray(expectedResponseTermSeq) self._response = [] self._responseEvent = threading.Event() self.serial.write(data) From 6d27b55857f2ee093a817ecef40e844b7cc08d47 Mon Sep 17 00:00:00 2001 From: eri Date: Sun, 12 Jun 2016 00:09:01 +0300 Subject: [PATCH 035/133] supporting modem's info channel with new pyserial --- gsmmodem/modem.py | 4 ++-- gsmmodem/serial_comms.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 648ab44..04f4b39 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -140,8 +140,8 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): - super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None,*a,**kw): + super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification,*a,**kw) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index ac66c25..c2ba22b 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -42,9 +42,12 @@ def __init__(self, port, baudrate=115200, notifyCallbackFunc=None, fatalErrorCal self.notifyCallback = notifyCallbackFunc or self._placeholderCallback self.fatalErrorCallback = fatalErrorCallbackFunc or self._placeholderCallback + self.com_args = args + self.com_kwargs = kwargs + def connect(self): """ Connects to the device and starts the read thread """ - self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout) + self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout,*self.com_args,**self.com_kwargs) # Start read thread self.alive = True self.rxThread = threading.Thread(target=self._readLoop) From c6a5fbf89e0b1e3d5278c335e19556449f567740 Mon Sep 17 00:00:00 2001 From: eri Date: Sun, 12 Jun 2016 01:04:56 +0300 Subject: [PATCH 036/133] porting str to bytes for python3 --- gsmmodem/modem.py | 92 ++++++++++++++++++++-------------------- gsmmodem/serial_comms.py | 6 +-- 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 04f4b39..260154f 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -122,13 +122,13 @@ class GsmModem(SerialComms): log = logging.getLogger('gsmmodem.modem.GsmModem') # Used for parsing AT command errors - CM_ERROR_REGEX = re.compile(r'^\+(CM[ES]) ERROR: (\d+)$') + CM_ERROR_REGEX = re.compile(b'^\+(CM[ES]) ERROR: (\d+)$') # Used for parsing signal strength query responses - CSQ_REGEX = re.compile(r'^\+CSQ:\s*(\d+),') + CSQ_REGEX = re.compile(b'^\+CSQ:\s*(\d+),') # Used for parsing caller ID announcements for incoming calls. Group 1 is the number - CLIP_REGEX = re.compile(r'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') + CLIP_REGEX = re.compile(b'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications - CMTI_REGEX = re.compile(r'^\+CMTI:\s*"([^"]+)",(\d+)$') + CMTI_REGEX = re.compile(b'^\+CMTI:\s*"([^"]+)",(\d+)$') # Used for parsing SMS message reads (text mode) CMGR_SM_DELIVER_REGEX_TEXT = None # Used for parsing SMS status report message reads (text mode) @@ -136,9 +136,9 @@ class GsmModem(SerialComms): # Used for parsing SMS message reads (PDU mode) CMGR_REGEX_PDU = None # Used for parsing USSD event notifications - CUSD_REGEX = re.compile(r'\+CUSD:\s*(\d),"(.*?)",(\d+)', re.DOTALL) + CUSD_REGEX = re.compile(b'\+CUSD:\s*(\d),"(.*?)",(\d+)', re.DOTALL) # Used for parsing SMS status reports - CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') + CDSI_REGEX = re.compile(b'\+CDSI:\s*"([^"]+)",(\d+)$') def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None,*a,**kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification,*a,**kw) @@ -197,7 +197,7 @@ def connect(self, pin=None): pinCheckComplete = False self.write('ATE0') # echo off try: - cfun = int(lineStartingWith('+CFUN:', self.write('AT+CFUN?'))[7:]) # example response: +CFUN: 1 + cfun = int(lineStartingWith(b'+CFUN:', self.write('AT+CFUN?'))[7:]) # example response: +CFUN: 1 if cfun != 1: self.write('AT+CFUN=1') except CommandError: @@ -235,7 +235,7 @@ def connect(self, pin=None): if enableWind: try: - wind = lineStartingWith('+WIND:', self.write('AT+WIND?')) # Check current WIND value; example response: +WIND: 63 + wind = lineStartingWith(b'+WIND:', self.write('AT+WIND?')) # Check current WIND value; example response: +WIND: 63 except CommandError: # Modem does not support +WIND notifications. See if we can detect other known call update notifications pass @@ -261,9 +261,9 @@ def connect(self, pin=None): if callUpdateTableHint == 1: # Use Hauwei's ^NOTIFICATIONs self.log.info('Loading Huawei call state update table') - self._callStatusUpdates = ((re.compile(r'^\^ORIG:(\d),(\d)$'), self._handleCallInitiated), - (re.compile(r'^\^CONN:(\d),(\d)$'), self._handleCallAnswered), - (re.compile(r'^\^CEND:(\d),(\d),(\d)+,(\d)+$'), self._handleCallEnded)) + self._callStatusUpdates = ((re.compile(b'^\^ORIG:(\d),(\d)$'), self._handleCallInitiated), + (re.compile(b'^\^CONN:(\d),(\d)$'), self._handleCallAnswered), + (re.compile(b'^\^CEND:(\d),(\d),(\d)+,(\d)+$'), self._handleCallEnded)) self._mustPollCallStatus = False # Huawei modems use ^DTMF to send DTMF tones; use that instead Call.DTMF_COMMAND_BASE = '^DTMF={cid},' @@ -271,9 +271,9 @@ def connect(self, pin=None): elif callUpdateTableHint == 2: # Wavecom modem: +WIND notifications supported self.log.info('Loading Wavecom call state update table') - self._callStatusUpdates = ((re.compile(r'^\+WIND: 5,(\d)$'), self._handleCallInitiated), - (re.compile(r'^OK$'), self._handleCallAnswered), - (re.compile(r'^\+WIND: 6,(\d)$'), self._handleCallEnded)) + self._callStatusUpdates = ((re.compile(b'^\+WIND: 5,(\d)$'), self._handleCallInitiated), + (re.compile(b'^OK$'), self._handleCallAnswered), + (re.compile(b'^\+WIND: 6,(\d)$'), self._handleCallEnded)) self._waitForAtdResponse = False # Wavecom modems return OK only when the call is answered self._mustPollCallStatus = False if commands == None: # older modem, assume it has standard DTMF support @@ -281,9 +281,9 @@ def connect(self, pin=None): elif callUpdateTableHint == 3: # ZTE # Use ZTE notifications ("CONNECT"/"HANGUP", but no "call initiated" notification) self.log.info('Loading ZTE call state update table') - self._callStatusUpdates = ((re.compile(r'^CONNECT$'), self._handleCallAnswered), - (re.compile(r'^HANGUP:\s*(\d+)$'), self._handleCallEnded), - (re.compile(r'^OK$'), self._handleCallRejected)) + self._callStatusUpdates = ((re.compile(b'^CONNECT$'), self._handleCallAnswered), + (re.compile(b'^HANGUP:\s*(\d+)$'), self._handleCallEnded), + (re.compile(b'^OK$'), self._handleCallRejected)) self._waitForAtdResponse = False # ZTE modems do not return an immediate OK only when the call is answered self._mustPollCallStatus = False self._waitForCallInitUpdate = False # ZTE modems do not provide "call initiated" updates @@ -293,7 +293,7 @@ def connect(self, pin=None): # Unknown modem - we do not know what its call updates look like. Use polling instead self.log.info('Unknown/generic modem type - will use polling for call state updates') self._mustPollCallStatus = True - self._pollCallStatusRegex = re.compile('^\+CLCC:\s+(\d+),(\d),(\d),(\d),([^,]),"([^,]*)",(\d+)$') + self._pollCallStatusRegex = re.compile(b'^\+CLCC:\s+(\d+),(\d),(\d),(\d),([^,]),"([^,]*)",(\d+)$') self._waitForAtdResponse = True # Most modems return OK immediately after issuing ATD # General meta-information setup @@ -317,13 +317,13 @@ def connect(self, pin=None): # Set message storage, but first check what the modem supports - example response: +CPMS: (("SM","BM","SR"),("SM")) try: - cpmsLine = lineStartingWith('+CPMS', self.write('AT+CPMS=?')) + cpmsLine = lineStartingWith(b'+CPMS', self.write('AT+CPMS=?')) except CommandError: # Modem does not support AT+CPMS; SMS reading unavailable self._smsReadSupported = False self.log.warning('SMS preferred message storage query not supported by modem. SMS reading unavailable.') else: - cpmsSupport = cpmsLine.split(' ', 1)[1].split('),(') + cpmsSupport = cpmsLine.split(b' ', 1)[1].split(b'),(') # Do a sanity check on the memory types returned - Nokia S60 devices return empty strings, for example for memItem in cpmsSupport: if len(memItem) == 0: @@ -333,14 +333,14 @@ def connect(self, pin=None): break else: # Suppported memory types look fine, continue - preferredMemoryTypes = ('"ME"', '"SM"', '"SR"') + preferredMemoryTypes = (b'"ME"', b'"SM"', b'"SR"') cpmsItems = [''] * len(cpmsSupport) for i in xrange(len(cpmsSupport)): for memType in preferredMemoryTypes: if memType in cpmsSupport[i]: if i == 0: self._smsMemReadDelete = memType - cpmsItems[i] = memType + cpmsItems[i] = memType.decode('ascii') break self.write('AT+CPMS={0}'.format(','.join(cpmsItems))) # Set message storage del cpmsSupport @@ -377,18 +377,18 @@ def _unlockSim(self, pin): """ Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """ # Unlock the SIM card if needed try: - cpinResponse = lineStartingWith('+CPIN', self.write('AT+CPIN?', timeout=0.25)) + cpinResponse = lineStartingWith(b'+CPIN', self.write('AT+CPIN?', timeout=0.25)) except TimeoutException as timeout: # Wavecom modems do not end +CPIN responses with "OK" (github issue #19) - see if just the +CPIN response was returned if timeout.data != None: - cpinResponse = lineStartingWith('+CPIN', timeout.data) + cpinResponse = lineStartingWith(b'+CPIN', timeout.data) if cpinResponse == None: # No useful response read raise timeout else: # Nothing read (real timeout) raise timeout - if cpinResponse != '+CPIN: READY': + if cpinResponse != b'+CPIN: READY': if pin != None: self.write('AT+CPIN="{0}"'.format(pin)) else: @@ -431,7 +431,7 @@ def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTer if waitForResponse: cmdStatusLine = responseLines[-1] if parseError: - if 'ERROR' in cmdStatusLine: + if b'ERROR' in cmdStatusLine: cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine) if cmErrorMatch: errorType = cmErrorMatch.group(1) @@ -450,14 +450,14 @@ def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTer else: self._writeWait = 0 # The modem was just waiting for the SIM card return result - if errorType == 'CME': + if errorType == b'CME': raise CmeError(data, int(errorCode)) else: # CMS error raise CmsError(data, int(errorCode)) else: raise CommandError(data) - elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands - raise CommandError(data + '({0})'.format(cmdStatusLine)) + elif cmdStatusLine == b'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands + raise CommandError('{} ({})'.format(data,cmdStatusLine)) return responseLines @property @@ -507,7 +507,7 @@ def imsi(self): @property def networkName(self): """ :return: the name of the GSM Network Operator to which the modem is connected """ - copsMatch = lineMatching(r'^\+COPS: (\d),(\d),"(.+)",{0,1}\d*$', self.write('AT+COPS?')) # response format: +COPS: mode,format,"operator_name",x + copsMatch = lineMatching(b'^\+COPS: (\d),(\d),"(.+)",{0,1}\d*$', self.write('AT+COPS?')) # response format: +COPS: mode,format,"operator_name",x if copsMatch: return copsMatch.group(3) @@ -520,7 +520,7 @@ def supportedCommands(self): response = self.write('AT+CLAC') if len(response) == 2: # Single-line response, comma separated commands = response[0] - if commands.startswith('+CLAC'): + if commands.startswith(b'+CLAC'): commands = commands[6:] # remove the +CLAC: prefix before splitting return commands.split(',') elif len(response) > 2: # Multi-line response @@ -561,10 +561,10 @@ def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: - self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') - self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') + self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(b'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') + self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(b'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: - self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') + self.CMGR_REGEX_PDU = re.compile(b'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') @property def smsc(self): @@ -575,7 +575,7 @@ def smsc(self): except SmscNumberUnknownError: pass # Some modems return a CMS 330 error if the value isn't set else: - cscaMatch = lineMatching(r'\+CSCA:\s*"([^,]+)",(\d+)$', readSmsc) + cscaMatch = lineMatching(b'\+CSCA:\s*"([^,]+)",(\d+)$', readSmsc) if cscaMatch: self._smscNumber = cscaMatch.group(1) return self._smscNumber @@ -614,7 +614,7 @@ def _cancelBlock(): checkCreg = True while block[0]: if checkCreg: - cregResult = lineMatching(r'^\+CREG:\s*(\d),(\d)$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 + cregResult = lineMatching(b'^\+CREG:\s*(\d),(\d)$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 if cregResult: status = int(cregResult.group(2)) if status in (1, 5): @@ -656,12 +656,12 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou """ if self._smsTextMode: self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq=b'> ') - result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=CTRLZ)) + result = lineStartingWith(b'+CMGS:', self.write(text, timeout=15, writeTerm=CTRLZ)) else: pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq=b'> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=15, writeTerm=CTRLZ)) # example: +CMGS: xx + result = lineStartingWith(b'+CMGS:', self.write(str(pdu), timeout=15, writeTerm=CTRLZ)) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') reference = int(result[7:]) @@ -701,7 +701,7 @@ def sendUssd(self, ussdString, responseTimeout=15): # Some modems issue the +CUSD response before the acknowledgment "OK" - check for that if len(cusdResponse) > 1: - cusdResponseFound = lineStartingWith('+CUSD', cusdResponse) != None + cusdResponseFound = lineStartingWith(b'+CUSD', cusdResponse) != None if cusdResponseFound: self._ussdSessionEvent = None # Cancel thread sync lock return self._parseCusdResponse(cusdResponse) @@ -795,7 +795,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): messages = [] delMessages = set() if self._smsTextMode: - cmglRegex= re.compile(r'^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') + cmglRegex= re.compile(b'^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') for key, val in dictItemsIter(Sms.TEXT_MODE_STATUS_MAP): if status == val: statusStr = key @@ -817,7 +817,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): msgIndex, msgStatus, number, msgTime = cmglMatch.groups() msgLines = [] else: - if line != 'OK': + if line != b'OK': msgLines.append(line) if msgIndex != None and len(msgLines) > 0: msgText = '\n'.join(msgLines) @@ -825,7 +825,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText)) delMessages.add(int(msgIndex)) else: - cmglRegex = re.compile(r'^\+CMGL:\s*(\d+),\s*(\d+),.*$') + cmglRegex = re.compile(b'^\+CMGL:\s*(\d+),\s*(\d+),.*$') readPdu = False result = self.write('AT+CMGL={0}'.format(status)) for line in result: @@ -875,19 +875,19 @@ def __threadedHandleModemNotification(self, lines): :param lines The lines that were read """ for line in lines: - if 'RING' in line: + if b'RING' in line: # Incoming call (or existing call is ringing) self._handleIncomingCall(lines) return - elif line.startswith('+CMTI'): + elif line.startswith(b'+CMTI'): # New SMS message indication self._handleSmsReceived(line) return - elif line.startswith('+CUSD'): + elif line.startswith(b'+CUSD'): # USSD notification - either a response or a MT-USSD ("push USSD") message self._handleUssd(lines) return - elif line.startswith('+CDSI'): + elif line.startswith(b'+CDSI'): # SMS status report self._handleSmsStatusReport(line) return diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index c2ba22b..25a8504 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -16,9 +16,9 @@ class SerialComms(object): log = logging.getLogger('gsmmodem.serial_comms.SerialComms') # End-of-line read terminator - RX_EOL_SEQ = '\r\n' + RX_EOL_SEQ = b'\r\n' # End-of-response terminator - RESPONSE_TERM = re.compile(r'^OK|ERROR|(\+CM[ES] ERROR: \d+)|(COMMAND NOT SUPPORT)$') + RESPONSE_TERM = re.compile(b'^OK|ERROR|(\+CM[ES] ERROR: \d+)|(COMMAND NOT SUPPORT)$') # Default timeout for serial port reads (in seconds) timeout = 1 @@ -94,7 +94,7 @@ def _readLoop(self): rxBuffer = bytearray() while self.alive: data = self.serial.read(1) - if data != '': # check for timeout + if data : # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(ord(data)) if rxBuffer[-readTermLen:] == readTermSeq: From 073a46340f30098c3ee223443b2f74865f36f49c Mon Sep 17 00:00:00 2001 From: eri Date: Sun, 12 Jun 2016 01:15:48 +0300 Subject: [PATCH 037/133] zte fixes --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 260154f..6175345 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -128,7 +128,7 @@ class GsmModem(SerialComms): # Used for parsing caller ID announcements for incoming calls. Group 1 is the number CLIP_REGEX = re.compile(b'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications - CMTI_REGEX = re.compile(b'^\+CMTI:\s*"([^"]+)",(\d+)$') + CMTI_REGEX = re.compile(b'^\+CMTI:\s*"([^"]+)",\s*(\d+)$') # Used for parsing SMS message reads (text mode) CMGR_SM_DELIVER_REGEX_TEXT = None # Used for parsing SMS status report message reads (text mode) @@ -564,7 +564,7 @@ def _compileSmsRegexes(self): self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(b'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(b'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: - self.CMGR_REGEX_PDU = re.compile(b'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') + self.CMGR_REGEX_PDU = re.compile(b'^\+CMGR:\s*(\d*),\s*"{0,1}([^"]*)"{0,1},\s*(\d+)$') @property def smsc(self): From 537904d0752d73ff8d89c3848af8265c09eb2603 Mon Sep 17 00:00:00 2001 From: alex-eri Date: Sun, 12 Jun 2016 01:33:26 +0300 Subject: [PATCH 038/133] drop 2.6 and 3.2 due site libraries used with drops --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 44d47c8..0edb3b2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,9 @@ language: python python: + - "3.5" + - "3.4" - "3.3" - - "3.2" - "2.7" - - "2.6" install: # Install unittest2 on Python 2.6 - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install --use-mirrors unittest2; fi From b29a157c323855ca8cf88c78fdbd1f75366d3016 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 12:12:18 +0200 Subject: [PATCH 039/133] Support for modems which hangs after AT command for getting list of device features --- gsmmodem/modem.py | 270 +++++++++++++++++++++++++--------------------- 1 file changed, 147 insertions(+), 123 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..e4e6bc0 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -48,13 +48,13 @@ def __init__(self, number, text, smsc=None): class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - + def __init__(self, gsmModem, status, number, time, text, smsc=None): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time - + def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ return self._gsmModem.sendSms(self.number, message) @@ -62,7 +62,7 @@ def reply(self, message): class SentSms(Sms): """ An SMS message that has been sent (MO) """ - + ENROUTE = 0 # Status indicating message is still enroute to destination DELIVERED = 1 # Status indicating message has been received by destination handset FAILED = 2 # Status indicating message delivery has failed @@ -71,11 +71,11 @@ def __init__(self, number, text, reference, smsc=None): super(SentSms, self).__init__(number, text, smsc) self.report = None # Status report for this SMS (StatusReport object) self.reference = reference - + @property def status(self): """ Status of this SMS. Can be ENROUTE, DELIVERED or FAILED - + The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' """ @@ -87,15 +87,15 @@ def status(self): class StatusReport(Sms): """ An SMS status/delivery report - + Note: the 'status' attribute of this class refers to this status report SM's status (whether it has been read, etc). To find the status of the message that caused this status report, use the 'deliveryStatus' attribute. """ - + DELIVERED = 0 # SMS delivery status: delivery successful FAILED = 68 # SMS delivery status: delivery failed - + def __init__(self, gsmModem, status, reference, number, timeSent, timeFinalized, deliveryStatus, smsc=None): super(StatusReport, self).__init__(number, None, smsc) self._gsmModem = weakref.proxy(gsmModem) @@ -108,7 +108,7 @@ def __init__(self, gsmModem, status, reference, number, timeSent, timeFinalized, class GsmModem(SerialComms): """ Main class for interacting with an attached GSM modem """ - + log = logging.getLogger('gsmmodem.modem.GsmModem') # Used for parsing AT command errors @@ -129,7 +129,7 @@ class GsmModem(SerialComms): CUSD_REGEX = re.compile(r'\+CUSD:\s*(\d),"(.*?)",(\d+)', re.DOTALL) # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') - + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback @@ -163,26 +163,26 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece def connect(self, pin=None): """ Opens the port and initializes the modem and SIM card - + :param pin: The SIM card PIN code, if any :type pin: str - + :raise PinRequiredError: if the SIM card requires a PIN but none was provided :raise IncorrectPinError: if the specified PIN is incorrect """ - self.log.info('Connecting to modem on port %s at %dbps', self.port, self.baudrate) + self.log.info('Connecting to modem on port %s at %dbps', self.port, self.baudrate) super(GsmModem, self).connect() # Send some initialization commands to the modem - try: + try: self.write('ATZ') # reset configuration except CommandError: # Some modems require a SIM PIN at this stage already; unlock it now # Attempt to enable detailed error messages (to catch incorrect PIN error) # but ignore if it fails - self.write('AT+CMEE=1', parseError=False) + self.write('AT+CMEE=1', parseError=False) self._unlockSim(pin) pinCheckComplete = True - self.write('ATZ') # reset configuration + self.write('ATZ') # reset configuration else: pinCheckComplete = False self.write('ATE0') # echo off @@ -192,7 +192,7 @@ def connect(self, pin=None): self.write('AT+CFUN=1') except CommandError: pass # just ignore if the +CFUN command isn't supported - + self.write('AT+CMEE=1') # enable detailed error messages (even if it has already been set - ATZ may reset this) if not pinCheckComplete: self._unlockSim(pin) @@ -288,7 +288,7 @@ def connect(self, pin=None): # General meta-information setup self.write('AT+COPS=3,0', parseError=False) # Use long alphanumeric name format - + # SMS setup self.write('AT+CMGF={0}'.format(1 if self._smsTextMode else 0)) # Switch to text or PDU mode for SMS messages self._compileSmsRegexes() @@ -335,7 +335,7 @@ def connect(self, pin=None): self.write('AT+CPMS={0}'.format(','.join(cpmsItems))) # Set message storage del cpmsSupport del cpmsLine - + if self._smsReadSupported: try: self.write('AT+CNMI=2,1,0,2') # Set message notifications @@ -343,7 +343,7 @@ def connect(self, pin=None): # Message notifications not supported self._smsReadSupported = False self.log.warning('Incoming SMS notifications not supported by modem. SMS receiving unavailable.') - + # Incoming call notification setup try: self.write('AT+CLIP=1') # Enable calling line identification presentation @@ -358,11 +358,11 @@ def connect(self, pin=None): self._extendedIncomingCallIndication = False self.log.warning('Extended format incoming call indication not supported by modem. Error: {0}'.format(crcError)) else: - self._extendedIncomingCallIndication = True + self._extendedIncomingCallIndication = True # Call control setup self.write('AT+CVHU=0', parseError=False) # Enable call hang-up with ATH command (ignore if command not supported) - + def _unlockSim(self, pin): """ Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """ # Unlock the SIM card if needed @@ -383,7 +383,7 @@ def _unlockSim(self, pin): self.write('AT+CPIN="{0}"'.format(pin)) else: raise PinRequiredError('AT+CPIN') - + def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): """ Write data to the modem. @@ -411,7 +411,7 @@ def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTer """ self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) - if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) + if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) time.sleep(self._writeWait) if waitForResponse: cmdStatusLine = responseLines[-1] @@ -448,9 +448,9 @@ def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTer @property def signalStrength(self): """ Checks the modem's cellular network signal strength - + :raise CommandError: if an error occurs - + :return: The network signal strength as an integer between 0 and 99, or -1 if it is unknown :rtype: int """ @@ -465,12 +465,12 @@ def signalStrength(self): def manufacturer(self): """ :return: The modem's manufacturer's name """ return self.write('AT+CGMI')[0] - + @property def model(self): """ :return: The modem's model name """ return self.write('AT+CGMM')[0] - + @property def revision(self): """ :return: The modem's software revision, or None if not known/supported """ @@ -478,17 +478,17 @@ def revision(self): return self.write('AT+CGMR')[0] except CommandError: return None - + @property def imei(self): """ :return: The modem's serial number (IMEI number) """ return self.write('AT+CGSN')[0] - + @property def imsi(self): """ :return: The IMSI (International Mobile Subscriber Identity) of the SIM card. The PIN may need to be entered before reading the IMSI """ return self.write('AT+CIMI')[0] - + @property def networkName(self): """ :return: the name of the GSM Network Operator to which the modem is connected """ @@ -513,6 +513,30 @@ def supportedCommands(self): else: self.log.debug('Unhandled +CLAC response: {0}'.format(response)) return None + except TimeoutException: + # Try interactive command recognition + commands = [] + checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS'] + + # Check if modem is still alive + try: + response = self.write('AT') + except: + raise TimeoutException + + # Check all commands that will by considered + for command in checkable_commands: + try: + # Compose AT command that will read values under specified function + at_command='AT'+command+'=?' + response = self.write(at_command) + # If there are values inside response - add command to the list + commands.append(command) + except: + continue + + # Return found commands + return commands except CommandError: return None @@ -528,7 +552,7 @@ def smsTextMode(self, textMode): self.write('AT+CMGF={0}'.format(1 if textMode else 0)) self._smsTextMode = textMode self._compileSmsRegexes() - + def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ # Switch to the correct memory type if required @@ -550,7 +574,7 @@ def _compileSmsRegexes(self): self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$') - + @property def smsc(self): """ :return: The default SMSC number stored on the SIM card """ @@ -574,11 +598,11 @@ def smsc(self, smscNumber): def waitForNetworkCoverage(self, timeout=None): """ Block until the modem has GSM network coverage. - - This method blocks until the modem is registered with the network + + This method blocks until the modem is registered with the network and the signal strength is greater than 0, optionally timing out if a timeout was specified - + :param timeout: Maximum time to wait for network coverage, in seconds :type timeout: int or float @@ -591,8 +615,8 @@ def waitForNetworkCoverage(self, timeout=None): block = [True] if timeout != None: # Set up a timeout mechanism - def _cancelBlock(): - block[0] = False + def _cancelBlock(): + block[0] = False t = threading.Timer(timeout, _cancelBlock) t.start() ss = -1 @@ -623,10 +647,10 @@ def _cancelBlock(): else: # If this is reached, the timer task has triggered raise TimeoutException() - + def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeout=15, sendFlash=False): """ Send an SMS text message - + :param destination: the recipient's phone number :type destination: str :param text: the message text @@ -634,8 +658,8 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou :param waitForDeliveryReport: if True, this method blocks until a delivery report is received for the sent message :type waitForDeliveryReport: boolean :param deliveryReport: the maximum time in seconds to wait for a delivery report (if "waitForDeliveryReport" is True) - :type deliveryTimeout: int or float - + :type deliveryTimeout: int or float + :raise CommandError: if an error occurs while attempting to send the message :raise TimeoutException: if the operation times out """ @@ -668,12 +692,12 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou def sendUssd(self, ussdString, responseTimeout=15): """ Starts a USSD session by dialing the the specified USSD string, or \ sends the specified string in the existing USSD session (if any) - + :param ussdString: The USSD access number to dial :param responseTimeout: Maximum time to wait a response, in seconds - + :raise TimeoutException: if no response is received in time - + :return: The USSD response message/session (as a Ussd object) :rtype: gsmmodem.modem.Ussd """ @@ -695,9 +719,9 @@ def sendUssd(self, ussdString, responseTimeout=15): self._ussdSessionEvent = None return self._ussdResponse else: # Response timed out - self._ussdSessionEvent = None + self._ussdSessionEvent = None raise TimeoutException() - + def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call @@ -743,13 +767,13 @@ def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): def processStoredSms(self, unreadOnly=False): """ Process all SMS messages currently stored on the device/SIM card. - - Reads all (or just unread) received SMS messages currently stored on the - device/SIM card, initiates "SMS received" events for them, and removes + + Reads all (or just unread) received SMS messages currently stored on the + device/SIM card, initiates "SMS received" events for them, and removes them from the SIM card. This is useful if SMS messages were received during a period that python-gsmmodem was not running but the modem was powered on. - + :param unreadOnly: If True, only process unread SMS messages :type unreadOnly: boolean """ @@ -763,16 +787,16 @@ def processStoredSms(self, unreadOnly=False): def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. - + The messages are read from the memory set by the "memory" parameter. - + :param status: Filter messages based on this read status; must be 0-4 (see Sms class) :type status: int :param memory: The memory type to read from. If None, use the current default SMS read memory :type memory: str or None :param delete: If True, delete returned messages from the device/SIM card :type delete: bool - + :return: A list of Sms objects containing the messages read :rtype: list """ @@ -791,7 +815,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): msgLines = [] msgIndex = msgStatus = number = msgTime = None for line in result: - cmglMatch = cmglRegex.match(line) + cmglMatch = cmglRegex.match(line) if cmglMatch: # New message; save old one if applicable if msgIndex != None and len(msgLines) > 0: @@ -846,17 +870,17 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): def _handleModemNotification(self, lines): """ Handler for unsolicited notifications from the modem - + This method simply spawns a separate thread to handle the actual notification (in order to release the read thread so that the handlers are able to write back to the modem, etc) - + :param lines The lines that were read """ threading.Thread(target=self.__threadedHandleModemNotification, kwargs={'lines': lines}).start() - + def __threadedHandleModemNotification(self, lines): """ Implementation of _handleModemNotification() to be run in a separate thread - + :param lines The lines that were read """ for line in lines: @@ -877,7 +901,7 @@ def __threadedHandleModemNotification(self, lines): self._handleSmsStatusReport(line) return else: - # Check for call status updates + # Check for call status updates for updateRegex, handlerFunc in self._callStatusUpdates: match = updateRegex.match(line) if match: @@ -885,8 +909,8 @@ def __threadedHandleModemNotification(self, lines): handlerFunc(match) return # If this is reached, the notification wasn't handled - self.log.debug('Unhandled unsolicited modem notification: %s', lines) - + self.log.debug('Unhandled unsolicited modem notification: %s', lines) + def _handleIncomingCall(self, lines): self.log.debug('Handling incoming call') ringLine = lines.pop(0) @@ -899,7 +923,7 @@ def _handleIncomingCall(self, lines): callType = None try: # Re-enable extended format of incoming indication (optional) - self.write('AT+CRC=1') + self.write('AT+CRC=1') except CommandError: self.log.warn('Extended incoming call indication format changed externally; unable to re-enable') self._extendedIncomingCallIndication = False @@ -920,7 +944,7 @@ def _handleIncomingCall(self, lines): callerNumber = ton = callerName = None else: callerNumber = ton = callerName = None - + call = None for activeCall in dictValuesIter(self.activeCalls): if activeCall.number == callerNumber: @@ -930,8 +954,8 @@ def _handleIncomingCall(self, lines): callId = len(self.activeCalls) + 1; call = IncomingCall(self, callerNumber, ton, callerName, callId, callType) self.activeCalls[callId] = call - self.incomingCallCallback(call) - + self.incomingCallCallback(call) + def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ if self._dialEvent: @@ -945,7 +969,7 @@ def _handleCallInitiated(self, regexMatch, callId=None, callType=1): else: self._dialResponse = callId, callType self._dialEvent.set() - + def _handleCallAnswered(self, regexMatch, callId=None): """ Handler for "outgoing call answered" event notification line """ if regexMatch: @@ -998,7 +1022,7 @@ def _handleSmsReceived(self, notificationLine): sms = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) self.smsReceivedCallback(sms) - + def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ self.log.debug('SMS status report received') @@ -1008,26 +1032,26 @@ def _handleSmsStatusReport(self, notificationLine): msgIndex = cdsiMatch.group(2) report = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) - # Update sent SMS status if possible - if report.reference in self.sentSms: + # Update sent SMS status if possible + if report.reference in self.sentSms: self.sentSms[report.reference].report = report - if self._smsStatusReportEvent: + if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() else: # Nothing is waiting for this report directly - use callback self.smsStatusReportCallback(report) - + def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index - + :param index: The index of the SMS message in the specified memory :type index: int :param memory: The memory type to read from. If None, use the current default SMS read memory :type memory: str or None - + :raise CommandError: if unable to read the stored message - + :return: The SMS message :rtype: subclass of gsmmodem.modem.Sms (either ReceivedSms or StatusReport) """ @@ -1047,7 +1071,7 @@ def readStoredSms(self, index, memory=None): if cmgrMatch: msgStatus, reference, number, sentTime, deliverTime, deliverStatus = cmgrMatch.groups() if msgStatus.startswith('"'): - msgStatus = msgStatus[1:-1] + msgStatus = msgStatus[1:-1] if len(msgStatus) == 0: msgStatus = "REC UNREAD" return StatusReport(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], int(reference), number, parseTextModeTimeStr(sentTime), parseTextModeTimeStr(deliverTime), int(deliverStatus)) @@ -1071,37 +1095,37 @@ def readStoredSms(self, index, memory=None): return StatusReport(self, int(stat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: raise CommandError('Invalid PDU type for readStoredSms(): {0}'.format(smsDict['type'])) - + def deleteStoredSms(self, index, memory=None): """ Deletes the SMS message stored at the specified index in modem/SIM card memory - + :param index: The index of the SMS message in the specified memory :type index: int :param memory: The memory type to delete from. If None, use the current default SMS read/delete memory :type memory: str or None - + :raise CommandError: if unable to delete the stored message """ self._setSmsMemory(readDelete=memory) self.write('AT+CMGD={0},0'.format(index)) - + def deleteMultipleStoredSms(self, delFlag=4, memory=None): """ Deletes all SMS messages that have the specified read status. - + The messages are read from the memory set by the "memory" parameter. The value of the "delFlag" paramater is the same as the "DelFlag" parameter of the +CMGD command: 1: Delete All READ messages 2: Delete All READ and SENT messages 3: Delete All READ, SENT and UNSENT messages 4: Delete All messages (this is the default) - + :param delFlag: Controls what type of messages to delete; see description above. :type delFlag: int :param memory: The memory type to delete from. If None, use the current default SMS read/delete memory :type memory: str or None :param delete: If True, delete returned messages from the device/SIM card :type delete: bool - + :raise ValueErrror: if "delFlag" is not in range [1,4] :raise CommandError: if unable to delete the stored messages """ @@ -1110,7 +1134,7 @@ def deleteMultipleStoredSms(self, delFlag=4, memory=None): self.write('AT+CMGD=1,{0}'.format(delFlag)) else: raise ValueError('"delFlag" must be in range [1,4]') - + def _handleUssd(self, lines): """ Handler for USSD event notification line(s) """ if self._ussdSessionEvent: @@ -1118,7 +1142,7 @@ def _handleUssd(self, lines): self._ussdResponse = self._parseCusdResponse(lines) # Notify waiting thread self._ussdSessionEvent.set() - + def _parseCusdResponse(self, lines): """ Parses one or more +CUSD notification lines (for USSD) :return: USSD response object @@ -1155,14 +1179,14 @@ def _parseCusdResponse(self, lines): def _placeHolderCallback(self, *args): """ Does nothing """ self.log.debug('called with args: {0}'.format(args)) - + def _pollCallStatus(self, expectedState, callId=None, timeout=None): - """ Poll the status of outgoing calls. + """ Poll the status of outgoing calls. This is used for modems that do not have a known set of call status update notifications. - + :param expectedState: The internal state we are waiting for. 0 == initiated, 1 == answered, 2 = hangup :type expectedState: int - + :raise TimeoutException: If a timeout was specified, and has occurred """ callDone = False @@ -1182,7 +1206,7 @@ def _pollCallStatus(self, expectedState, callId=None, timeout=None): # Determine call state stat = int(clcc.group(3)) if expectedState == 0: # waiting for call initiated - if stat == 2 or stat == 3: # Dialing or ringing ("alerting") + if stat == 2 or stat == 3: # Dialing or ringing ("alerting") callId = int(clcc.group(1)) callType = int(clcc.group(4)) self._handleCallInitiated(None, callId, callType) # if self_dialEvent is None, this does nothing @@ -1191,7 +1215,7 @@ def _pollCallStatus(self, expectedState, callId=None, timeout=None): if stat == 0: # Call active callId = int(clcc.group(1)) self._handleCallAnswered(None, callId) - expectedState = 2 # Now wait for call hangup + expectedState = 2 # Now wait for call hangup elif expectedState == 2 : # waiting for remote hangup # Since there was no +CLCC response, the call is no longer active callDone = True @@ -1206,23 +1230,23 @@ def _pollCallStatus(self, expectedState, callId=None, timeout=None): class Call(object): """ A voice call """ - + DTMF_COMMAND_BASE = '+VTS=' dtmfSupport = False # Indicates whether or not DTMF tones can be sent in calls - + def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallbackFunc=None): """ :param gsmModem: GsmModem instance that created this object - :param number: The number that is being called + :param number: The number that is being called """ self._gsmModem = weakref.proxy(gsmModem) self._callStatusUpdateCallbackFunc = callStatusUpdateCallbackFunc # Unique ID of this call self.id = callId # Call type (VOICE == 0, etc) - self.type = callType + self.type = callType # The remote number of this call (destination or origin) - self.number = number + self.number = number # Flag indicating whether the call has been answered or not (backing field for "answered" property) self._answered = False # Flag indicating whether or not the call is active @@ -1237,22 +1261,22 @@ def answered(self, answered): self._answered = answered if self._callStatusUpdateCallbackFunc: self._callStatusUpdateCallbackFunc(self) - + def sendDtmfTone(self, tones): - """ Send one or more DTMF tones to the remote party (only allowed for an answered call) - + """ Send one or more DTMF tones to the remote party (only allowed for an answered call) + Note: this is highly device-dependent, and might not work - + :param digits: A str containining one or more DTMF tones to play, e.g. "3" or "\*123#" - :raise CommandError: if the command failed/is not supported + :raise CommandError: if the command failed/is not supported :raise InvalidStateException: if the call has not been answered, or is ended while the command is still executing - """ + """ if self.answered: dtmfCommandBase = self.DTMF_COMMAND_BASE.format(cid=self.id) toneLen = len(tones) if len(tones) > 1: - cmd = ('AT{0}{1};{0}' + ';{0}'.join(tones[1:])).format(dtmfCommandBase, tones[0]) + cmd = ('AT{0}{1};{0}' + ';{0}'.join(tones[1:])).format(dtmfCommandBase, tones[0]) else: cmd = 'AT{0}{1}'.format(dtmfCommandBase, tones) try: @@ -1268,10 +1292,10 @@ def sendDtmfTone(self, tones): raise e else: raise InvalidStateException('Call is not active (it has not yet been answered, or it has ended).') - + def hangup(self): """ End the phone call. - + Does nothing if the call is already inactive. """ if self.active: @@ -1283,10 +1307,10 @@ def hangup(self): class IncomingCall(Call): - + CALL_TYPE_MAP = {'VOICE': 0} - - """ Represents an incoming call, conveniently allowing access to call meta information and -control """ + + """ Represents an incoming call, conveniently allowing access to call meta information and -control """ def __init__(self, gsmModem, number, ton, callerName, callId, callType): """ :param gsmModem: GsmModem instance that created this object @@ -1295,25 +1319,25 @@ def __init__(self, gsmModem, number, ton, callerName, callId, callType): :param callType: Type of the incoming call (VOICE, FAX, DATA, etc) """ if type(callType) == str: - callType = self.CALL_TYPE_MAP[callType] - super(IncomingCall, self).__init__(gsmModem, callId, callType, number) + callType = self.CALL_TYPE_MAP[callType] + super(IncomingCall, self).__init__(gsmModem, callId, callType, number) # Type attribute of the incoming call self.ton = ton - self.callerName = callerName + self.callerName = callerName # Flag indicating whether the call is ringing or not - self.ringing = True + self.ringing = True # Amount of times this call has rung (before answer/hangup) self.ringCount = 1 - + def answer(self): - """ Answer the phone call. + """ Answer the phone call. :return: self (for chaining method calls) """ if self.ringing: self._gsmModem.write('ATA') self.ringing = False self.answered = True - return self + return self def hangup(self): """ End the phone call. """ @@ -1322,32 +1346,32 @@ def hangup(self): class Ussd(object): """ Unstructured Supplementary Service Data (USSD) message. - + This class contains convenient methods for replying to a USSD prompt and to cancel the USSD session """ - + def __init__(self, gsmModem, sessionActive, message): self._gsmModem = weakref.proxy(gsmModem) # Indicates if the session is active (True) or has been closed (False) self.sessionActive = sessionActive self.message = message - + def reply(self, message): - """ Sends a reply to this USSD message in the same USSD session - + """ Sends a reply to this USSD message in the same USSD session + :raise InvalidStateException: if the USSD session is not active (i.e. it has ended) - + :return: The USSD response message/session (as a Ussd object) """ if self.sessionActive: return self._gsmModem.sendUssd(message) else: raise InvalidStateException('USSD session is inactive') - + def cancel(self): """ Terminates/cancels the USSD session (without sending a reply) - + Does nothing if the USSD session is inactive. """ if self.sessionActive: From 4c0187ec9cd96de445173d92313580538e109b7e Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 14:13:37 +0200 Subject: [PATCH 040/133] Support for SMS encoding AT command --- gsmmodem/modem.py | 109 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e4e6bc0..0841963 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -7,7 +7,7 @@ from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError -from .pdu import encodeSmsSubmitPdu, decodeSmsPdu +from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, encodeGsm7 from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr from . import compat # For Python 2.6 compatibility @@ -160,6 +160,10 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece self._smsMemReadDelete = None # Preferred message storage memory for reads/deletes ( parameter used for +CPMS) self._smsMemWrite = None # Preferred message storage memory for writes ( parameter used for +CPMS) self._smsReadSupported = True # Whether or not reading SMS messages is supported via AT commands + self._smsEncoding = 'GSM' # Default SMS encoding + self._smsSupportedEncodingNames = None # List of available encoding names + self._commands = None # List of supported AT commands + def connect(self, pin=None): """ Opens the port and initializes the modem and SIM card @@ -199,6 +203,7 @@ def connect(self, pin=None): # Get list of supported commands from modem commands = self.supportedCommands + self._commands = commands # Device-specific settings callUpdateTableHint = 0 # unknown modem @@ -516,7 +521,7 @@ def supportedCommands(self): except TimeoutException: # Try interactive command recognition commands = [] - checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS'] + checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS', '+CSCS'] # Check if modem is still alive try: @@ -553,6 +558,93 @@ def smsTextMode(self, textMode): self._smsTextMode = textMode self._compileSmsRegexes() + @property + def smsSupportedEncoding(self): + """ + :raise NotImplementedError: If an error occures during AT command response parsing. + :return: List of supported encoding names. """ + + # Check if command is available + if self._commands == None: + self._commands = self.supportedCommands + + if not '+CSCS' in self._commands: + self._smsSupportedEncodingNames = [] + return self._smsSupportedEncodingNames + + # Get available encoding names + response = self.write('AT+CSCS=?') + + # Check response length (should be 2 - list of options and command status) + if len(response) != 2: + self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + raise NotImplementedError + + # Extract encoding names list + try: + enc_list = enc_list[0] # Get the first line + enc_list = enc_list[6:] # Remove '+CSCS' prefix + # Extract AT list in format ("str", "str2", "str3") + enc_list = enc_list.split('(')[1] + enc_list = enc_list.split(')')[0] + enc_list = enc_list.split(',') + enc_list = [x.split('"')[1] for x in enc_list] + except: + self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + raise NotImplementedError + + self._smsSupportedEncodingNames = enc_list + return self._smsSupportedEncodingNames + + @property + def smsEncoding(self): + """ :return: Encoding name if encoding command is available, else GSM. """ + if self._commands == None: + self._commands = self.supportedCommands + + if '+CSCS' in self._commands: + response = self.write('AT+CSCS?') + + if len(response) == 2: + encoding = response[0] + if encoding.startswith('+CSCS'): + encoding = encoding[6:].split('"') # remove the +CSCS: prefix before splitting + if len(encoding) == 3: + self._smsEncoding = encoding[1] + else: + self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + else: + self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + + return self._smsEncoding + @smsEncoding.setter + def smsEncoding(self, encoding): + """ Set encoding for SMS inside PDU mode. + + :return: True if encoding successfully set, otherwise False. """ + + # Check if command is available + if self._commands == None: + self._commands = self.supportedCommands + + if not '+CSCS' in self._commands: + return False + + # Check if command is available + if self._commands == None: + self.smsSupportedEncoding() + + # Check if desired encoding is available + if encoding in self._smsSupportedEncodingNames: + # Set encoding + response = self.write('AT+CSCS={0}'.format(encoding)) + if len(response) == 1: + if response[0].lower() == 'ok': + self._smsEncoding = encoding + return True + + return False + def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ # Switch to the correct memory type if required @@ -663,6 +755,19 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou :raise CommandError: if an error occurs while attempting to send the message :raise TimeoutException: if the operation times out """ + + # Check input text to select appropriate mode (text or PDU) + # Check encoding + try: + encodedText = encodeGsm7(text) + except ValueError: + self.smsTextMode(False) + + # Check message length + if len(text) > 160: + self.smsTextMode(False) + + # Send SMS via AT commands if self._smsTextMode: self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq='> ') result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=chr(26))) From b463d4d46cdc68c000922fdfc7ae6b40b9d8202c Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 14:30:25 +0200 Subject: [PATCH 041/133] Support for SMS encoding AT command - bugfixes --- gsmmodem/modem.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 0841963..0fde627 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -582,7 +582,7 @@ def smsSupportedEncoding(self): # Extract encoding names list try: - enc_list = enc_list[0] # Get the first line + enc_list = response[0] # Get the first line enc_list = enc_list[6:] # Remove '+CSCS' prefix # Extract AT list in format ("str", "str2", "str3") enc_list = enc_list.split('(')[1] @@ -631,13 +631,13 @@ def smsEncoding(self, encoding): return False # Check if command is available - if self._commands == None: - self.smsSupportedEncoding() + if self._smsSupportedEncodingNames == None: + self.smsSupportedEncoding # Check if desired encoding is available if encoding in self._smsSupportedEncodingNames: # Set encoding - response = self.write('AT+CSCS={0}'.format(encoding)) + response = self.write('AT+CSCS="{0}"'.format(encoding)) if len(response) == 1: if response[0].lower() == 'ok': self._smsEncoding = encoding @@ -761,11 +761,11 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou try: encodedText = encodeGsm7(text) except ValueError: - self.smsTextMode(False) + self.smsTextMode = False # Check message length if len(text) > 160: - self.smsTextMode(False) + self.smsTextMode = False # Send SMS via AT commands if self._smsTextMode: From 53dacbfb700966f865a80fa9246b51ada5ce2d33 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 14:45:25 +0200 Subject: [PATCH 042/133] Automatic change of modem sms encoding before sending --- gsmmodem/modem.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 0fde627..eebc3a2 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -761,6 +761,7 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou try: encodedText = encodeGsm7(text) except ValueError: + encodedText = None self.smsTextMode = False # Check message length @@ -772,6 +773,14 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq='> ') result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=chr(26))) else: + # Set GSM modem SMS encoding format + # Encode message text and set data coding scheme based on text contents + if encodedText == None: + # Cannot encode text using GSM-7; use UCS2 instead + self.smsEncoding = 'UCS2' + else: + self.smsEncoding = 'GSM' + pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq='> ') From 386c34b74cd660887af316e8f13fc1a0a061316e Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 15:15:17 +0200 Subject: [PATCH 043/133] BUGFIX: explicitly convert input text to UTF-8 (default encoding is host-dependent) --- gsmmodem/pdu.py | 227 ++++++++++++++++++++++++------------------------ 1 file changed, 114 insertions(+), 113 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index ee15ebc..abdd83a 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -45,20 +45,20 @@ class SmsPduTzInfo(tzinfo): """ Simple implementation of datetime.tzinfo for handling timestamp GMT offsets specified in SMS PDUs """ - + def __init__(self, pduOffsetStr=None): - """ + """ :param pduOffset: 2 semi-octet timezone offset as specified by PDU (see GSM 03.40 spec) - :type pduOffset: str - + :type pduOffset: str + Note: pduOffsetStr is optional in this constructor due to the special requirement for pickling mentioned in the Python docs. It should, however, be used (or otherwise pduOffsetStr must be manually set) - """ + """ self._offset = None if pduOffsetStr != None: self._setPduOffsetStr(pduOffsetStr) - + def _setPduOffsetStr(self, pduOffsetStr): # See if the timezone difference is positive/negative by checking MSB of first semi-octet tzHexVal = int(pduOffsetStr, 16) @@ -66,10 +66,10 @@ def _setPduOffsetStr(self, pduOffsetStr): self._offset = timedelta(minutes=(int(pduOffsetStr) * 15)) else: # negative self._offset = timedelta(minutes=(int('{0:0>2X}'.format(tzHexVal & 0x7F)) * -15)) - + def utcoffset(self, dt): return self._offset - + def dst(self, dt): """ We do not have enough info in the SMS PDU to implement daylight savings time """ return timedelta(0) @@ -77,17 +77,17 @@ def dst(self, dt): class InformationElement(object): """ User Data Header (UDH) Information Element (IE) implementation - + This represents a single field ("information element") in the PDU's User Data Header. The UDH itself contains one or more of these information elements. - + If the IEI (IE identifier) is recognized, the class will automatically - specialize into one of the subclasses of InformationElement, + specialize into one of the subclasses of InformationElement, e.g. Concatenation or PortAddress, allowing the user to easily access the specific (and useful) attributes of these special cases. """ - + def __new__(cls, *args, **kwargs): #iei, ieLen, ieData): """ Causes a new InformationElement class, or subclass thereof, to be created. If the IEI is recognized, a specific @@ -99,17 +99,17 @@ def __new__(cls, *args, **kwargs): #iei, ieLen, ieData): else: return super(InformationElement, cls).__new__(cls) return super(InformationElement, targetClass).__new__(targetClass) - + def __init__(self, iei, ieLen=0, ieData=None): self.id = iei # IEI self.dataLength = ieLen # IE Length self.data = ieData or [] # raw IE data - + @classmethod def decode(cls, byteIter): """ Decodes a single IE at the current position in the specified - byte iterator - + byte iterator + :return: An InformationElement (or subclass) instance for the decoded IE :rtype: InformationElement, or subclass thereof """ @@ -119,7 +119,7 @@ def decode(cls, byteIter): for i in xrange(ieLen): ieData.append(next(byteIter)) return InformationElement(iei, ieLen, ieData) - + def encode(self): """ Encodes this IE and returns the resulting bytes """ result = bytearray() @@ -127,7 +127,7 @@ def encode(self): result.append(self.dataLength) result.extend(self.data) return result - + def __len__(self): """ Exposes the IE's total length (including the IEI and IE length octet) in octets """ return self.dataLength + 2 @@ -176,16 +176,16 @@ def encode(self): class PortAddress(InformationElement): """ IE that indicates an Application Port Addressing Scheme. - + This implementation handles both 8-bit and 16-bit concatenation indication, and exposes the specific useful details of this IE as instance variables. - + Exposes: destination: The destination port number source: The source port number """ - + def __init__(self, iei=0x04, ieLen=0, ieData=None): super(PortAddress, self).__init__(iei, ieLen, ieData) if ieData != None: @@ -194,7 +194,7 @@ def __init__(self, iei=0x04, ieLen=0, ieData=None): else: # 0x05: 16-bit port addressing scheme self.destination = ieData[0] << 8 | ieData[1] self.source = ieData[2] << 8 | ieData[3] - + def encode(self): if self.destination > 0xFF or self.source > 0xFF: self.id = 0x05 # 16-bit @@ -216,7 +216,7 @@ def encode(self): class Pdu(object): """ Encoded SMS PDU. Contains raw PDU data and related meta-information """ - + def __init__(self, data, tpduLength): """ Constructor :param data: the raw PDU data (as bytes) @@ -226,18 +226,18 @@ def __init__(self, data, tpduLength): """ self.data = data self.tpduLength = tpduLength - + def __str__(self): global PYTHON_VERSION if PYTHON_VERSION < 3: return str(self.data).encode('hex').upper() else: #pragma: no cover - return str(codecs.encode(self.data, 'hex_codec'), 'ascii').upper() + return str(codecs.encode(self.data, 'hex_codec'), 'ascii').upper() def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requestStatusReport=True, rejectDuplicates=False, sendFlash=False): """ Creates an SMS-SUBMIT PDU for sending a message with the specified text to the specified number - + :param number: the destination mobile number :type number: str :param text: the message text @@ -250,10 +250,10 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ :type smsc: str :param rejectDuplicates: Flag that controls the TP-RD parameter (messages with same destination and reference may be rejected if True) :type rejectDuplicates: bool - + :return: A list of one or more tuples containing the SMS PDU (as a bytearray, and the length of the TPDU part :rtype: list of tuples - """ + """ tpduFirstOctet = 0x01 # SMS-SUBMIT PDU if validity != None: # Validity period format (TP-VPF) is stored in bits 4,3 of the first TPDU octet @@ -264,16 +264,16 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ elif type(validity) == datetime: # Absolute (TP-VP is semi-octet encoded date) tpduFirstOctet |= 0x18 # bit4 == 1, bit3 == 1 - validityPeriod = _encodeTimestamp(validity) + validityPeriod = _encodeTimestamp(validity) else: - raise TypeError('"validity" must be of type datetime.timedelta (for relative value) or datetime.datetime (for absolute value)') + raise TypeError('"validity" must be of type datetime.timedelta (for relative value) or datetime.datetime (for absolute value)') else: validityPeriod = None if rejectDuplicates: tpduFirstOctet |= 0x04 # bit2 == 1 if requestStatusReport: tpduFirstOctet |= 0x20 # bit5 == 1 - + # Encode message text and set data coding scheme based on text contents try: encodedText = encodeGsm7(text) @@ -281,8 +281,8 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ # Cannot encode text using GSM-7; use UCS2 instead alphabet = 0x08 # UCS2 else: - alphabet = 0x00 # GSM-7 - + alphabet = 0x00 # GSM-7 + # Check if message should be concatenated if len(text) > MAX_MESSAGE_LENGTH[alphabet]: # Text too long for single PDU - add "concatenation" User Data Header @@ -294,16 +294,16 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ else: concatHeaderPrototype = None pduCount = 1 - + # Construct required PDU(s) - pdus = [] + pdus = [] for i in xrange(pduCount): pdu = bytearray() if smsc: pdu.extend(_encodeAddressField(smsc, smscField=True)) else: - pdu.append(0x00) # Don't supply an SMSC number - use the one configured in the device - + pdu.append(0x00) # Don't supply an SMSC number - use the one configured in the device + udh = bytearray() if concatHeaderPrototype != None: concatHeader = copy(concatHeaderPrototype) @@ -315,19 +315,19 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ udh.extend(concatHeader.encode()) else: pduText = text - - udhLen = len(udh) - + + udhLen = len(udh) + pdu.append(tpduFirstOctet) pdu.append(reference) # message reference - # Add destination number + # Add destination number pdu.extend(_encodeAddressField(number)) pdu.append(0x00) # Protocol identifier - no higher-level protocol - + pdu.append(alphabet if not sendFlash else (0x10 if alphabet == 0x00 else 0x18)) if validityPeriod: pdu.extend(validityPeriod) - + if alphabet == 0x00: # GSM-7 encodedText = encodeGsm7(pduText) userDataLength = len(encodedText) # Payload size in septets/characters @@ -341,8 +341,8 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ elif alphabet == 0x08: # UCS2 userData = encodeUcs2(pduText) userDataLength = len(userData) - - if udhLen > 0: + + if udhLen > 0: userDataLength += udhLen + 1 # +1 for the UDH length indicator byte pdu.append(userDataLength) pdu.append(udhLen) @@ -356,15 +356,15 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ def decodeSmsPdu(pdu): """ Decodes SMS pdu data and returns a tuple in format (number, text) - + :param pdu: PDU data as a hex string, or a bytearray containing PDU octects :type pdu: str or bytearray - + :raise EncodingError: If the specified PDU data cannot be decoded - + :return: The decoded SMS data as a dictionary - :rtype: dict - """ + :rtype: dict + """ try: pdu = toByteArray(pdu) except Exception as e: @@ -372,13 +372,13 @@ def decodeSmsPdu(pdu): raise EncodingError(e) result = {} pduIter = iter(pdu) - + smscNumber, smscBytesRead = _decodeAddressField(pduIter, smscField=True) result['smsc'] = smscNumber result['tpdu_length'] = len(pdu) - smscBytesRead - - tpduFirstOctet = next(pduIter) - + + tpduFirstOctet = next(pduIter) + pduType = tpduFirstOctet & 0x03 # bits 1-0 if pduType == 0x00: # SMS-DELIVER or SMS-DELIVER REPORT result['type'] = 'SMS-DELIVER' @@ -399,7 +399,7 @@ def decodeSmsPdu(pdu): validityPeriodFormat = (tpduFirstOctet & 0x18) >> 3 # bits 4,3 if validityPeriodFormat == 0x02: # TP-VP field present and integer represented (relative) result['validity'] = _decodeRelativeValidityPeriod(next(pduIter)) - elif validityPeriodFormat == 0x03: # TP-VP field present and semi-octet represented (absolute) + elif validityPeriodFormat == 0x03: # TP-VP field present and semi-octet represented (absolute) result['validity'] = _decodeTimestamp(pduIter) userDataLen = next(pduIter) udhPresent = (tpduFirstOctet & 0x40) != 0 @@ -411,10 +411,10 @@ def decodeSmsPdu(pdu): result['number'] = _decodeAddressField(pduIter)[0] result['time'] = _decodeTimestamp(pduIter) result['discharge'] = _decodeTimestamp(pduIter) - result['status'] = next(pduIter) + result['status'] = next(pduIter) else: raise EncodingError('Unknown SMS message type: {0}. First TPDU octet was: {1}'.format(pduType, tpduFirstOctet)) - + return result def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent): @@ -471,7 +471,7 @@ def _decodeRelativeValidityPeriod(tpVp): def _encodeRelativeValidityPeriod(validityPeriod): """ Encodes the specified relative validity period timedelta into an integer for use in an SMS PDU (based on the table in section 9.2.3.12 of GSM 03.40) - + :param validityPeriod: The validity period to encode :type validityPeriod: datetime.timedelta :rtype: int @@ -490,21 +490,21 @@ def _encodeRelativeValidityPeriod(validityPeriod): else: raise ValueError('Validity period too long; tpVp limited to 1 octet (max value: 255)') return tpVp - + def _decodeTimestamp(byteIter): """ Decodes a 7-octet timestamp """ dateStr = decodeSemiOctets(byteIter, 7) - timeZoneStr = dateStr[-2:] + timeZoneStr = dateStr[-2:] return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr)) def _encodeTimestamp(timestamp): """ Encodes a 7-octet timestamp from the specified date - + Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases - + :param timestamp: The timestamp to encode :type timestamp: datetime.datetime - + :return: The encoded timestamp :rtype: bytearray """ @@ -531,14 +531,14 @@ def _decodeDataCoding(octet): alphabet = (octet & 0x0C) >> 2 return alphabet # 0x00 == GSM-7, 0x01 == 8-bit data, 0x02 == UCS2 # We ignore other coding groups - return 0 + return 0 def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator - + :param byteIter: Iterator over bytearray - :type byteIter: iter(bytearray) - + :type byteIter: iter(bytearray) + :return: Tuple containing the address value and amount of bytes read (value is or None if it is empty (zero-length)) :rtype: tuple """ @@ -546,14 +546,14 @@ def _decodeAddressField(byteIter, smscField=False, log=False): if addressLen > 0: toa = next(byteIter) ton = (toa & 0x70) # bits 6,5,4 of type-of-address == type-of-number - if ton == 0x50: - # Alphanumberic number + if ton == 0x50: + # Alphanumberic number addressLen = int(math.ceil(addressLen / 2.0)) septets = unpackSeptets(byteIter, addressLen) addressValue = decodeGsm7(septets) return (addressValue, (addressLen + 2)) else: - # ton == 0x00: Unknown (might be international, local, etc) - leave as is + # ton == 0x00: Unknown (might be international, local, etc) - leave as is # ton == 0x20: National number if smscField: addressValue = decodeSemiOctets(byteIter, addressLen-1) @@ -561,7 +561,7 @@ def _decodeAddressField(byteIter, smscField=False, log=False): if addressLen % 2: addressLen = int(addressLen / 2) + 1 else: - addressLen = int(addressLen / 2) + addressLen = int(addressLen / 2) addressValue = decodeSemiOctets(byteIter, addressLen) addressLen += 1 # for the return value, add the toa byte if ton == 0x10: # International number @@ -572,16 +572,16 @@ def _decodeAddressField(byteIter, smscField=False, log=False): def _encodeAddressField(address, smscField=False): """ Encodes the address into an address field - + :param address: The address to encode (phone number or alphanumeric) :type byteIter: str - + :return: Encoded SMS PDU address field :rtype: bytearray """ # First, see if this is a number or an alphanumeric string toa = 0x80 | 0x00 | 0x01 # Type-of-address start | Unknown type-of-number | ISDN/tel numbering plan - alphaNumeric = False + alphaNumeric = False if address.isalnum(): # Might just be a local number if address.isdigit(): @@ -605,10 +605,10 @@ def _encodeAddressField(address, smscField=False): alphaNumeric = True if alphaNumeric: addressValue = packSeptets(encodeGsm7(address, False)) - addressLen = len(addressValue) * 2 + addressLen = len(addressValue) * 2 else: addressValue = encodeSemiOctets(address) - if smscField: + if smscField: addressLen = len(addressValue) + 1 else: addressLen = len(address) @@ -620,7 +620,7 @@ def _encodeAddressField(address, smscField=False): def encodeSemiOctets(number): """ Semi-octet encoding algorithm (e.g. for phone numbers) - + :return: bytearray containing the encoded octets :rtype: bytearray """ @@ -631,12 +631,12 @@ def encodeSemiOctets(number): def decodeSemiOctets(encodedNumber, numberOfOctets=None): """ Semi-octet decoding algorithm(e.g. for phone numbers) - + :param encodedNumber: The semi-octet-encoded telephone number (in bytearray format or hex string) :type encodedNumber: bytearray, str or iter(bytearray) :param numberOfOctets: The expected amount of octets after decoding (i.e. when to stop) :type numberOfOctets: int - + :return: decoded telephone number :rtype: string """ @@ -644,8 +644,8 @@ def decodeSemiOctets(encodedNumber, numberOfOctets=None): if type(encodedNumber) in (str, bytes): encodedNumber = bytearray(codecs.decode(encodedNumber, 'hex_codec')) i = 0 - for octet in encodedNumber: - hexVal = hex(octet)[2:].zfill(2) + for octet in encodedNumber: + hexVal = hex(octet)[2:].zfill(2) number.append(hexVal[1]) if hexVal[0] != 'f': number.append(hexVal[0]) @@ -659,20 +659,20 @@ def decodeSemiOctets(encodedNumber, numberOfOctets=None): def encodeGsm7(plaintext, discardInvalid=False): """ GSM-7 text encoding algorithm - + Encodes the specified text string into GSM-7 octets (characters). This method does not pack the characters into septets. - + :param text: the text string to encode - :param discardInvalid: if True, characters that cannot be encoded will be silently discarded - + :param discardInvalid: if True, characters that cannot be encoded will be silently discarded + :raise ValueError: if the text string cannot be encoded using GSM-7 encoding (unless discardInvalid == True) - + :return: A bytearray containing the string encoded in GSM-7 encoding :rtype: bytearray """ result = bytearray() - if PYTHON_VERSION >= 3: + if PYTHON_VERSION >= 3: plaintext = str(plaintext) for char in plaintext: idx = GSM7_BASIC.find(char) @@ -687,12 +687,12 @@ def encodeGsm7(plaintext, discardInvalid=False): def decodeGsm7(encodedText): """ GSM-7 text decoding algorithm - + Decodes the specified GSM-7-encoded string into a plaintext string. - + :param encodedText: the text string to encode :type encodedText: bytearray or str - + :return: A string containing the decoded text :rtype: str """ @@ -713,13 +713,13 @@ def decodeGsm7(encodedText): def packSeptets(octets, padBits=0): """ Packs the specified octets into septets - + Typically the output of encodeGsm7 would be used as input to this function. The resulting bytearray contains the original GSM-7 characters packed into septets ready for transmission. - + :rtype: bytearray """ - result = bytearray() + result = bytearray() if type(octets) == str: octets = iter(rawStrToByteArray(octets)) elif type(octets) == bytearray: @@ -733,63 +733,63 @@ def packSeptets(octets, padBits=0): septet = octet & 0x7f; if shift == 7: # prevSeptet has already been fully added to result - shift = 0 + shift = 0 prevSeptet = septet - continue + continue b = ((septet << (7 - shift)) & 0xFF) | (prevSeptet >> shift) prevSeptet = septet shift += 1 - result.append(b) + result.append(b) if shift != 7: # There is a bit "left over" from prevSeptet result.append(prevSeptet >> shift) return result def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7): - """ Unpacks the specified septets into octets - + """ Unpacks the specified septets into octets + :param septets: Iterator or iterable containing the septets packed into octets :type septets: iter(bytearray), bytearray or str :param numberOfSeptets: The amount of septets to unpack (or None for all remaining in "septets") :type numberOfSeptets: int or None - + :return: The septets unpacked into octets :rtype: bytearray - """ - result = bytearray() + """ + result = bytearray() if type(septets) == str: septets = iter(rawStrToByteArray(septets)) elif type(septets) == bytearray: - septets = iter(septets) - if numberOfSeptets == None: + septets = iter(septets) + if numberOfSeptets == None: numberOfSeptets = MAX_INT # Loop until StopIteration i = 0 for octet in septets: i += 1 if shift == 7: shift = 1 - if prevOctet != None: - result.append(prevOctet >> 1) + if prevOctet != None: + result.append(prevOctet >> 1) if i <= numberOfSeptets: result.append(octet & 0x7F) - prevOctet = octet + prevOctet = octet if i == numberOfSeptets: break else: continue b = ((octet << shift) & 0x7F) | (prevOctet >> (8 - shift)) - - prevOctet = octet + + prevOctet = octet result.append(b) shift += 1 - + if i == numberOfSeptets: break if shift == 7: b = prevOctet >> (8 - shift) if b: # The final septet value still needs to be unpacked - result.append(b) + result.append(b) return result def decodeUcs2(byteIter, numBytes): @@ -807,15 +807,16 @@ def decodeUcs2(byteIter, numBytes): def encodeUcs2(text): """ UCS2 text encoding algorithm - + Encodes the specified text string into UCS2-encoded bytes. - + :param text: the text string to encode - + :return: A bytearray containing the string encoded in UCS2 encoding :rtype: bytearray """ result = bytearray() + text = text.decode('UTF-8') for b in map(ord, text): result.append(b >> 8) result.append(b & 0xFF) From e3875305958136e2dc10bb6bea750976d4d9b4f5 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 5 Jul 2016 15:54:30 +0200 Subject: [PATCH 044/133] Lorger timeout in order to support VERY long messages --- gsmmodem/modem.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index eebc3a2..09d9dba 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -770,8 +770,8 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou # Send SMS via AT commands if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(destination), timeout=3, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(text, timeout=15, writeTerm=chr(26))) + self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=chr(26))) else: # Set GSM modem SMS encoding format # Encode message text and set data coding scheme based on text contents @@ -779,12 +779,12 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou # Cannot encode text using GSM-7; use UCS2 instead self.smsEncoding = 'UCS2' else: - self.smsEncoding = 'GSM' + self.smsEncoding = 'GSM' pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: - self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=3, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=15, writeTerm=chr(26))) # example: +CMGS: xx + self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=chr(26))) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') reference = int(result[7:]) From 240d2f6fba88a0ec4970dee388517ae0d07d5bdc Mon Sep 17 00:00:00 2001 From: "Benny Simonsen (dovre)" Date: Mon, 8 Aug 2016 14:39:06 +0200 Subject: [PATCH 045/133] Support SIM800L - Tries to configure CNMI to a SIM800L supported mode if original setting fails (could be done via checking supported modes) - Delivery Status reports are delivered via CDS instead of CDSI (Probably Since the status reports are stored in TE) Added support for getting the the delivery status that way. --- gsmmodem/modem.py | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..bd468e8 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -129,6 +129,7 @@ class GsmModem(SerialComms): CUSD_REGEX = re.compile(r'\+CUSD:\s*(\d),"(.*?)",(\d+)', re.DOTALL) # Used for parsing SMS status reports CDSI_REGEX = re.compile(r'\+CDSI:\s*"([^"]+)",(\d+)$') + CDS_REGEX = re.compile(r'\+CDS:\s*([0-9]+)"$') def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) @@ -340,9 +341,12 @@ def connect(self, pin=None): try: self.write('AT+CNMI=2,1,0,2') # Set message notifications except CommandError: - # Message notifications not supported - self._smsReadSupported = False - self.log.warning('Incoming SMS notifications not supported by modem. SMS receiving unavailable.') + try: + self.write('AT+CNMI=2,1,0,1,0') # Set message notifications, using TE for delivery reports + except CommandError: + # Message notifications not supported + self._smsReadSupported = False + self.log.warning('Incoming SMS notifications not supported by modem. SMS receiving unavailable.') # Incoming call notification setup try: @@ -859,6 +863,7 @@ def __threadedHandleModemNotification(self, lines): :param lines The lines that were read """ + next_line_is_te_statusreport = False for line in lines: if 'RING' in line: # Incoming call (or existing call is ringing) @@ -876,6 +881,17 @@ def __threadedHandleModemNotification(self, lines): # SMS status report self._handleSmsStatusReport(line) return + elif line.startswith('+CDS'): + # SMS status report at next line + next_line_is_te_statusreport = True + cdsMatch = self.CDS_REGEX.match(line) + if cdsMatch: + next_line_is_te_statusreport_length = int(cdsMatch.group(1)) + else: + next_line_is_te_statusreport_length = -1 + elif next_line_is_te_statusreport: + self._handleSmsStatusReportTe(next_line_is_te_statusreport_length, line) + return else: # Check for call status updates for updateRegex, handlerFunc in self._callStatusUpdates: @@ -1017,7 +1033,29 @@ def _handleSmsStatusReport(self, notificationLine): else: # Nothing is waiting for this report directly - use callback self.smsStatusReportCallback(report) - + + def _handleSmsStatusReportTe(self, length, notificationLine): + """ Handler for TE SMS status reports """ + self.log.debug('TE SMS status report received') + try: + smsDict = decodeSmsPdu(notificationLine) + except EncodingError: + self.log.debug('Discarding notification line from +CDS response: %s', notificationLine) + else: + if smsDict['type'] == 'SMS-STATUS-REPORT': + report = StatusReport(self, int(smsDict['status']), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) + else: + raise CommandError('Invalid PDU type for readStoredSms(): {0}'.format(smsDict['type'])) + # Update sent SMS status if possible + if report.reference in self.sentSms: + self.sentSms[report.reference].report = report + if self._smsStatusReportEvent: + # A sendSms() call is waiting for this response - notify waiting thread + self._smsStatusReportEvent.set() + else: + # Nothing is waiting for this report directly - use callback + self.smsStatusReportCallback(report) + def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index From 37360a49966cc8b8870b97ef3850a44ef1da6279 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 18 Aug 2016 10:39:22 +0200 Subject: [PATCH 046/133] tomchy/master utf8 decode fix --- gsmmodem/pdu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index abdd83a..5f7447d 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -816,7 +816,7 @@ def encodeUcs2(text): :rtype: bytearray """ result = bytearray() - text = text.decode('UTF-8') + for b in map(ord, text): result.append(b >> 8) result.append(b & 0xFF) From db4f8fbe363ffac32cc21b61f82f20a5a3d942ec Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 18 Aug 2016 10:48:40 +0200 Subject: [PATCH 047/133] alex-eri/master merge fix --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index bf269ac..7af41da 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -148,7 +148,7 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(b'\+CDSI:\s*"([^"]+)",(\d+)$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, *a, **kw): + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback From 3306c00eb5172e466607a04d167f215fcd0d6e46 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 18 Aug 2016 12:53:10 +0200 Subject: [PATCH 048/133] handling incoming DTMF from fataevalex/master --- gsmmodem/modem.py | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 0eb64e5..acb72e3 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -184,6 +184,8 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece self._smsEncoding = 'GSM' # Default SMS encoding self._smsSupportedEncodingNames = None # List of available encoding names self._commands = None # List of supported AT commands + #Pool of detected DTMF + self.dtmfpool = [] def connect(self, pin=None, waitingForModemToStartInSeconds=0): """ Opens the port and initializes the modem and SIM card @@ -271,6 +273,10 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Attempt to identify modem type directly (if not already) - for outgoing call status updates if callUpdateTableHint == 0: + if 'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC + Call.dtmfSupport = True + self.write('AT+DDET=1') # enable detect incoming DTMF + if self.manufacturer.lower() == 'huawei': callUpdateTableHint = 1 # huawei else: @@ -1099,6 +1105,10 @@ def __threadedHandleModemNotification(self, lines): elif next_line_is_te_statusreport: self._handleSmsStatusReportTe(next_line_is_te_statusreport_length, line) return + elif line.startswith('+DTMF'): + # New incoming DTMF + self._handleIncomingDTMF(line) + return else: # Check for call status updates for updateRegex, handlerFunc in self._callStatusUpdates: @@ -1108,8 +1118,24 @@ def __threadedHandleModemNotification(self, lines): handlerFunc(match) return # If this is reached, the notification wasn't handled - self.log.debug('Unhandled unsolicited modem notification: %s', lines) - + self.log.debug('Unhandled unsolicited modem notification: %s', lines) + + #Simcom modem able detect incoming DTMF + def _handleIncomingDTMF(self,line): + self.log.debug('Handling incoming DTMF') + + try: + dtmf_num=line.split(':')[1].replace(" ","") + self.dtmfpool.append(dtmf_num) + self.log.debug('DTMF number is {0}'.format(dtmf_num)) + except: + self.log.debug('Error parce DTMF number on line {0}'.format(line)) + def GetIncomingDTMF(self): + if (len(self.dtmfpool)==0): + return None + else: + return self.dtmfpool.pop(0) + def _handleIncomingCall(self, lines): self.log.debug('Handling incoming call') ringLine = lines.pop(0) @@ -1496,13 +1522,11 @@ def sendDtmfTone(self, tones): if self.answered: dtmfCommandBase = self.DTMF_COMMAND_BASE.format(cid=self.id) toneLen = len(tones) - if len(tones) > 1: - cmd = ('AT{0}{1};{0}' + ';{0}'.join(tones[1:])).format(dtmfCommandBase, tones[0]) - else: - cmd = 'AT{0}{1}'.format(dtmfCommandBase, tones) - try: - self._gsmModem.write(cmd, timeout=(5 + toneLen)) - except CmeError as e: + for tone in list(tones): + try: + self._gsmModem.write('AT{0}{1}'.format(dtmfCommandBase,tone), timeout=(5 + toneLen)) + + except CmeError as e: if e.code == 30: # No network service - can happen if call is ended during DTMF transmission (but also if DTMF is sent immediately after call is answered) raise InterruptedException('No network service', e) From 3e66fd502604f3ff0e32f64d0b7f6e4937b09b43 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 18 Aug 2016 14:49:20 +0200 Subject: [PATCH 049/133] Undo drop of 'Func' from incomingCallCallbackFunc and smsReceivedCallbackFunc callback names for compatibility reasons. We can do this change later. --- gsmmodem/modem.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 5a6c861..18cfc81 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -150,10 +150,10 @@ class GsmModem(SerialComms): CDSI_REGEX = re.compile(b'\+CDSI:\s*"([^"]+)",(\d+)$') CDS_REGEX = re.compile(b'\+CDS:\s*([0-9]+)"$') - def __init__(self, port, baudrate=115200, incomingCallCallback=None, smsReceivedCallback=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): - super(GsmModem, self).__init__(port, baudrate, notifyCallback=self._handleModemNotification, *a, **kw) - self.incomingCallCallback = incomingCallCallback or self._placeholderCallback - self.smsReceivedCallback = smsReceivedCallback + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): + super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) + self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback + self.smsReceivedCallback = smsReceivedCallbackFunc self.smsStatusReportCallback = smsStatusReportCallback self.requestDelivery = requestDelivery self.AT_CNMI = AT_CNMI or "2,1,0,2" From 376235aba8921222414adba65f596ec0dcd68a50 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 18 Aug 2016 15:02:51 +0200 Subject: [PATCH 050/133] dirty fix warning --- gsmmodem/modem.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 3dc54cc..fefcf03 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1048,6 +1048,8 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self.log.debug('Discarding line from +CMGL response: %s', line) except: pass + # dirty fix warning: https://github.com/yuriykashin/python-gsmmodem/issues/1 + # todo: make better fix else: if smsDict['type'] == 'SMS-DELIVER': sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', [])) From 99a416f8100ade1ceab5a0d27efef53f4a9444b2 Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 19 Aug 2016 15:33:16 +0200 Subject: [PATCH 051/133] Another fixes for broken paolo-losi's variable renames --- gsmmodem/modem.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index fefcf03..ba35384 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -916,12 +916,12 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): print(queryResponse) return queryResponse - def dial(self, number, timeout=5, callStatusUpdateCallback=None): + def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established - :param callStatusUpdateCallback: Callback function that is executed if the call's status changes due to + :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to remote events (i.e. when it is answered, the call is ended by the remote party) :return: The outgoing call @@ -941,7 +941,7 @@ def dial(self, number, timeout=5, callStatusUpdateCallback=None): self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice - call = Call(self, callId, callType, number, callStatusUpdateCallback) + call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call @@ -952,7 +952,7 @@ def dial(self, number, timeout=5, callStatusUpdateCallback=None): if self._dialEvent.wait(timeout): self._dialEvent = None callId, callType = self._dialResponse - call = Call(self, callId, callType, number, callStatusUpdateCallback) + call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call else: # Call establishing timed out @@ -1498,13 +1498,13 @@ class Call(object): DTMF_COMMAND_BASE = '+VTS=' dtmfSupport = False # Indicates whether or not DTMF tones can be sent in calls - def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallback=None): + def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallbackFunc=None): """ :param gsmModem: GsmModem instance that created this object :param number: The number that is being called """ self._gsmModem = weakref.proxy(gsmModem) - self._callStatusUpdateCallback = callStatusUpdateCallback + self._callStatusUpdateCallbackFunc = callStatusUpdateCallbackFunc # Unique ID of this call self.id = callId # Call type (VOICE == 0, etc) @@ -1523,8 +1523,8 @@ def answered(self): @answered.setter def answered(self, answered): self._answered = answered - if self._callStatusUpdateCallback: - self._callStatusUpdateCallback(self) + if self._callStatusUpdateCallbackFunc: + self._callStatusUpdateCallbackFunc(self) def sendDtmfTone(self, tones): """ Send one or more DTMF tones to the remote party (only allowed for an answered call) From eaa2c61a5f9c7dcb5bb111211d82849e6232dfc1 Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 19 Aug 2016 16:57:01 +0200 Subject: [PATCH 052/133] version 0.10 merged all enhancements made in the last 3 years. todo next: fix unit tests, fix possible bugs after merging --- AUTHORS | 12 ++++++++++++ ChangeLog | 16 ++++++++++++++++ README.rst | 5 +++-- requirements.txt | 2 +- setup.py | 2 +- 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/AUTHORS b/AUTHORS index ec8a6f3..09a3e3f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -8,4 +8,16 @@ the01 Frederico Rosmaninho David Beitey BOOMER74 +Cyril-Roques +PeteLawler +alex-eri +tomchy +bennyslbs +epol +rags22489664 +fataevalex +paolo-losi +yuriykashin +foXes68 +babca diff --git a/ChangeLog b/ChangeLog index 56cd87c..17fd9c0 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,19 @@ +* Thu Aug 18 2016 babca - 0.10 +– Probably a new code maintainer for 2016 +- All commits published for the last 3 years merged into a one branch +– Compatibilty for python3 added, needs further testing! +– experimental GPRS support +– more: + – change AT_CNMI command if needed + – waitingForModemToStartInSeconds + – timeouts increased + – ability to check SMS encodings supported by modem - smsSupportedEncoding() + – better modem specific support (incl. simcom) + – TE SMS status reports handling support + – option to disable requesting delivery reports + – incoming DTMF support +– todo: check AT+CMGD support for 1 or 2 params and use appropriate command format + * Thu Jul 18 2013 Francois Aucamp - 0.9 - Added UDH support for SMS PDUs - Stored messages APIs made public diff --git a/README.rst b/README.rst index 054ef08..a22cee3 100644 --- a/README.rst +++ b/README.rst @@ -31,7 +31,8 @@ Bundled utilities: Requirements ------------ -- Python 2.6 or later +- Python 2.7 or later +- Python 3.3 or later - pyserial @@ -100,7 +101,7 @@ Building documentation This package contains `Sphinx `_-based documentation. To manually build or test the documentation locally, do the following:: - git clone https://github.com/faucamp/python-gsmmodem.git + git clone https://github.com/babca/python-gsmmodem.git cd python-gsmmodem pip install .[doc] cd doc diff --git a/requirements.txt b/requirements.txt index f59baab..8b2635b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -pyserial>=2.6 \ No newline at end of file +pyserial>=3.1.1 \ No newline at end of file diff --git a/setup.py b/setup.py index e7ef2ed..13a1c7b 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ test_command = [sys.executable, '-m', 'unittest', 'discover'] coverage_command = ['coverage', 'run', '-m', 'unittest', 'discover'] -VERSION = 0.9 +VERSION = 0.10 class RunUnitTests(Command): """ run unit tests """ From b1825d8bf1ccf0bab15006b26ff5c9a3c8c20fc5 Mon Sep 17 00:00:00 2001 From: Benny Simonsen Date: Sat, 20 Aug 2016 08:19:40 +0200 Subject: [PATCH 053/133] Re-added _placeHolderCallback It is needed as a default callback function if no callback is specified. Fixes craching while sending SMS without specifing smsStatusReportCallback. I have also fixed for smsReceivedCallbackFunc, but didn't get a crash because I had a call back function. --- gsmmodem/modem.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index ba35384..19476fd 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -153,8 +153,8 @@ class GsmModem(SerialComms): def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback - self.smsReceivedCallback = smsReceivedCallbackFunc - self.smsStatusReportCallback = smsStatusReportCallback + self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback + self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback self.requestDelivery = requestDelivery self.AT_CNMI = AT_CNMI or "2,1,0,2" # Flag indicating whether caller ID for incoming call notification has been set up @@ -1444,6 +1444,10 @@ def _parseCusdResponse(self, lines): message = cusdMatches[0].group(2) return Ussd(self, sessionActive, message) + def _placeHolderCallback(self, *args): + """ Does nothing """ + self.log.debug('called with args: {0}'.format(args)) + def _pollCallStatus(self, expectedState, callId=None, timeout=None): """ Poll the status of outgoing calls. This is used for modems that do not have a known set of call status update notifications. From ba050b8be114d7ed23eb5aaee8b65b458afc34d1 Mon Sep 17 00:00:00 2001 From: Benny Simonsen Date: Sat, 20 Aug 2016 08:46:18 +0200 Subject: [PATCH 054/133] Not all modems support +CLAC (At least not SIM800L) The +CLAC check results in a CommandError, which gave return None, changed to check checkable_commmands instead. --- gsmmodem/modem.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 19476fd..c94836a 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -565,7 +565,7 @@ def supportedCommands(self): else: self.log.debug('Unhandled +CLAC response: {0}'.format(response)) return None - except TimeoutException: + except (TimeoutException, CommandError): # Try interactive command recognition commands = [] checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS', '+CSCS'] @@ -589,8 +589,6 @@ def supportedCommands(self): # Return found commands return commands - except CommandError: - return None @property def smsTextMode(self): From ad5d52d497e5089e3aa746cb9965afd91eec31c8 Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 7 Sep 2016 11:17:06 +0200 Subject: [PATCH 055/133] setup.py new pip repo package name --- .gitignore | 2 ++ setup.py | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index b06378c..cce4692 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,5 @@ htmlcov # Working copy files *.swp + +.DS_Store diff --git a/setup.py b/setup.py index 13a1c7b..6bc942a 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ test_command = [sys.executable, '-m', 'unittest', 'discover'] coverage_command = ['coverage', 'run', '-m', 'unittest', 'discover'] -VERSION = 0.10 +VERSION = "0.10" class RunUnitTests(Command): """ run unit tests """ @@ -58,15 +58,15 @@ def run(self): subprocess.call(['coverage', 'report']) raise SystemExit(errno) -setup(name='python-gsmmodem', +setup(name='python-gsmmodem-new', version='{0}'.format(VERSION), description='Control an attached GSM modem: send/receive SMS messages, handle calls, etc', license='LGPLv3+', author='Francois Aucamp', author_email='francois.aucamp@gmail.com', - url='https://github.com/faucamp/python-gsmmodem', - download_url='https://github.com/faucamp/python-gsmmodem/archive/{0}.tar.gz'.format(VERSION), + url='https://github.com/babca/python-gsmmodem', + download_url='https://github.com/babca/python-gsmmodem/archive/{0}.tar.gz'.format(VERSION), long_description="""\ python-gsmmodem is a module that allows easy control of a GSM modem attached From 2627925594305ddcb9ef2aa650601c978a43e4f1 Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 7 Sep 2016 14:03:05 +0200 Subject: [PATCH 056/133] readme update --- README.rst | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/README.rst b/README.rst index a22cee3..c4805ac 100644 --- a/README.rst +++ b/README.rst @@ -39,45 +39,48 @@ Requirements How to install this package --------------------------- -There are two ways to install ``python-gsmmodem``: +There are two ways to install ``python-gsmmodem-new`` package: Automatic installation ~~~~~~~~~~~~~~~~~~~~~~ :: - pip install python-gsmmodem + pip install python-gsmmodem-new `pip `_ will automatically download and install all dependencies, as required. You can also utilise ``easy_install`` in the same manner as using ``pip`` above. -If you are utilising ``python-gsmmodem`` as part of another project, +If you are utilising ``python-gsmmodem-new`` as part of another project, add it to your ``install_requires`` section of your ``setup.py`` file and upon your project's installation, it will be pulled in automatically. -Manual installation -~~~~~~~~~~~~~~~~~~~ +Manual installation from PyPI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Download and extract the ``python-gsmmodem-new`` archive from `PyPI +`_ for the current release +version, or clone from GitHub:: + + git clone https://github.com/babca/python-gsmmodem.git -Download and extract the ``python-gsmmodem`` archive from `PyPI -`_ for the current release -version, or clone from `GitHub `_. Next, do this:: python setup.py install -Note that ``python-gsmmodem`` relies on ``pyserial`` for serial communications: +Note that ``python-gsmmodem-new`` package relies on ``pyserial`` for serial communications: http://pyserial.sourceforge.net Testing the package ------------------- -.. |Build Status| image:: https://travis-ci.org/faucamp/python-gsmmodem.png?branch=master -.. _Build Status: https://travis-ci.org/faucamp/python-gsmmodem +.. |Build Status| image:: https://travis-ci.org/babca/python-gsmmodem.png?branch=master +.. _Build Status: https://travis-ci.org/babca/python-gsmmodem -.. |Coverage Status| image:: https://coveralls.io/repos/faucamp/python-gsmmodem/badge.png?branch=master +.. |Coverage Status| image:: https://coveralls.io/repos/babca/python-gsmmodem/badge.png?branch=master .. _Coverage Status: https://coveralls.io/r/faucamp/python-gsmmodem |Build Status|_ |Coverage Status|_ From acaba6c2cd72425a52843c45a6fed8276d7acd16 Mon Sep 17 00:00:00 2001 From: lucasea777 Date: Thu, 8 Sep 2016 13:01:08 -0300 Subject: [PATCH 057/133] Update modem.py:277 TypeError: 'str' does not support the buffer interface --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index c94836a..03ed0a0 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -274,7 +274,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Attempt to identify modem type directly (if not already) - for outgoing call status updates if callUpdateTableHint == 0: - if 'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC + if b'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC Call.dtmfSupport = True self.write('AT+DDET=1') # enable detect incoming DTMF From 4723c7d8d67e5db432fdbba4b3fd498df122c201 Mon Sep 17 00:00:00 2001 From: Luks777 Date: Mon, 12 Sep 2016 17:31:34 -0300 Subject: [PATCH 058/133] passing dsrdtr=True and rtscts=True to Serial to avoid Broken Pipe error Related issue: https://github.com/pyserial/pyserial/issues/67#issuecomment-216068315 --- gsmmodem/serial_comms.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 41bc3ee..8dd1a45 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -47,7 +47,8 @@ def __init__(self, port, baudrate=115200, notifyCallbackFunc=None, fatalErrorCal def connect(self): """ Connects to the device and starts the read thread """ - self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout,*self.com_args,**self.com_kwargs) + self.serial = serial.Serial(dsrdtr=True, rtscts=True, port=self.port, baudrate=self.baudrate, + timeout=self.timeout,*self.com_args,**self.com_kwargs) # Start read thread self.alive = True self.rxThread = threading.Thread(target=self._readLoop) From d7ac12826f5080b8c7acb21a9a9a99232ad19eea Mon Sep 17 00:00:00 2001 From: Luks777 Date: Mon, 12 Sep 2016 17:43:18 -0300 Subject: [PATCH 059/133] Bug solved: prepending the 'b' letter when using .format() sending AT+CMGD=1,value instead of AT+CMGD=1,b'value' This solution is probably an overkill but it solves the issue. --- gsmmodem/modem.py | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 03ed0a0..bf45f2e 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -19,6 +19,8 @@ CTRLZ = chr(26) TERMINATOR = '\r' +def d(obj): + return obj.decode() if type(obj) == bytes else obj if PYTHON_VERSION >= 3: xrange = range @@ -334,7 +336,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): self.write('AT+CMGF={0}'.format(1 if self._smsTextMode else 0)) # Switch to text or PDU mode for SMS messages self._compileSmsRegexes() if self._smscNumber != None: - self.write('AT+CSCA="{0}"'.format(self._smscNumber)) # Set default SMSC number + self.write('AT+CSCA="{0}"'.format(d(self._smscNumber))) # Set default SMSC number currentSmscNumber = self._smscNumber else: currentSmscNumber = self.smsc @@ -427,7 +429,7 @@ def _unlockSim(self, pin): raise timeout if cpinResponse != b'+CPIN: READY': if pin != None: - self.write('AT+CPIN="{0}"'.format(pin)) + self.write('AT+CPIN="{0}"'.format(d(pin))) else: raise PinRequiredError('AT+CPIN') @@ -682,7 +684,7 @@ def smsEncoding(self, encoding): # Check if desired encoding is available if encoding in self._smsSupportedEncodingNames: # Set encoding - response = self.write('AT+CSCS="{0}"'.format(encoding)) + response = self.write('AT+CSCS="{0}"'.format(d(encoding))) if len(response) == 1: if response[0].lower() == 'ok': self._smsEncoding = encoding @@ -696,11 +698,11 @@ def _setSmsMemory(self, readDelete=None, write=None): if write != None and write != self._smsMemWrite: self.write() readDel = readDelete or self._smsMemReadDelete - self.write('AT+CPMS="{0}","{1}"'.format(readDel, write)) + self.write('AT+CPMS="{0}","{1}"'.format(d(readDel), d(write))) self._smsMemReadDelete = readDel self._smsMemWrite = write elif readDelete != None and readDelete != self._smsMemReadDelete: - self.write('AT+CPMS="{0}"'.format(readDelete)) + self.write('AT+CPMS="{0}"'.format(d(readDelete))) self._smsMemReadDelete = readDelete def _compileSmsRegexes(self): @@ -730,7 +732,7 @@ def smsc(self, smscNumber): """ Set the default SMSC number to use when sending SMS messages """ if smscNumber != self._smscNumber: if self.alive: - self.write('AT+CSCA="{0}"'.format(smscNumber)) + self.write('AT+CSCA="{0}"'.format(d(smscNumber))) self._smscNumber = smscNumber def waitForNetworkCoverage(self, timeout=None): @@ -815,7 +817,7 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou # Send SMS via AT commands if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq=b'> ') + self.write('AT+CMGS="{0}"'.format(d(destination)), timeout=5, expectedResponseTermSeq=b'> ') result = lineStartingWith(b'+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) else: # Set GSM modem SMS encoding format @@ -862,7 +864,7 @@ def sendUssd(self, ussdString, responseTimeout=15): """ self._ussdSessionEvent = threading.Event() try: - cusdResponse = self.write('AT+CUSD=1,"{0}",15'.format(ussdString), timeout=responseTimeout) # Should respond with "OK" + cusdResponse = self.write('AT+CUSD=1,"{0}",15'.format(d(ussdString)), timeout=responseTimeout) # Should respond with "OK" except Exception: self._ussdSessionEvent = None # Cancel the thread sync lock raise @@ -890,7 +892,7 @@ def checkForwarding(self, querytype, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},2'.format(querytype), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},2'.format(d(querytype)), timeout=responseTimeout) # Should respond with "OK" except Exception: raise print(queryResponse) @@ -907,7 +909,7 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},{1},"{2}"'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},{1},"{2}"'.format(d(fwdType), d(fwdEnable), d(fwdNumber)), timeout=responseTimeout) # Should respond with "OK" except Exception: raise return False @@ -929,13 +931,13 @@ def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): # Wait for the "call originated" notification message self._dialEvent = threading.Event() try: - self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) + self.write('ATD{0};'.format(d(number)), timeout=timeout, waitForResponse=self._waitForAtdResponse) except Exception: self._dialEvent = None # Cancel the thread sync lock raise else: # Don't wait for a call init update - base the call ID on the number of active calls - self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) + self.write('ATD{0};'.format(d(number)), timeout=timeout, waitForResponse=self._waitForAtdResponse) self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice @@ -1006,7 +1008,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): break else: raise ValueError('Invalid status value: {0}'.format(status)) - result = self.write('AT+CMGL="{0}"'.format(statusStr)) + result = self.write('AT+CMGL="{0}"'.format(d(statusStr))) msgLines = [] msgIndex = msgStatus = number = msgTime = None for line in result: @@ -1031,7 +1033,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): else: cmglRegex = re.compile(b'^\+CMGL:\s*(\d+),\s*(\d+),.*$') readPdu = False - result = self.write('AT+CMGL={0}'.format(status)) + result = self.write('AT+CMGL={0}'.format(d(status))) for line in result: if not readPdu: cmglMatch = cmglRegex.match(line) @@ -1321,7 +1323,7 @@ def readStoredSms(self, index, memory=None): """ # Switch to the correct memory type if required self._setSmsMemory(readDelete=memory) - msgData = self.write('AT+CMGR={0}'.format(index)) + msgData = self.write('AT+CMGR={0}'.format(d(index))) # Parse meta information if self._smsTextMode: cmgrMatch = self.CMGR_SM_DELIVER_REGEX_TEXT.match(msgData[0]) @@ -1371,7 +1373,7 @@ def deleteStoredSms(self, index, memory=None): :raise CommandError: if unable to delete the stored message """ self._setSmsMemory(readDelete=memory) - self.write('AT+CMGD={0},0'.format(index)) + self.write('AT+CMGD={0},0'.format(d(index))) # TODO: make a check how many params are supported by the modem and use the right command. For example, Siemens MC35, TC35 take only one parameter. #self.write('AT+CMGD={0}'.format(index)) @@ -1397,7 +1399,7 @@ def deleteMultipleStoredSms(self, delFlag=4, memory=None): """ if 0 < delFlag <= 4: self._setSmsMemory(readDelete=memory) - self.write('AT+CMGD=1,{0}'.format(delFlag)) + self.write('AT+CMGD=1,{0}'.format(d(delFlag))) else: raise ValueError('"delFlag" must be in range [1,4]') @@ -1543,7 +1545,7 @@ def sendDtmfTone(self, tones): toneLen = len(tones) for tone in list(tones): try: - self._gsmModem.write('AT{0}{1}'.format(dtmfCommandBase,tone), timeout=(5 + toneLen)) + self._gsmModem.write('AT{0}{1}'.format(d(dtmfCommandBase),d(tone)), timeout=(5 + toneLen)) except CmeError as e: if e.code == 30: From 46e07b1cd5b3b2b14d98c72e5631e0c52296700a Mon Sep 17 00:00:00 2001 From: babca Date: Tue, 13 Sep 2016 12:23:33 +0200 Subject: [PATCH 060/133] update readme --- README.rst | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index c4805ac..74c3e3a 100644 --- a/README.rst +++ b/README.rst @@ -39,10 +39,10 @@ Requirements How to install this package --------------------------- -There are two ways to install ``python-gsmmodem-new`` package: +There are multiple ways to install ``python-gsmmodem-new`` package: -Automatic installation -~~~~~~~~~~~~~~~~~~~~~~ +Automatic installation of the latest "stable" release from PyPI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: @@ -56,8 +56,8 @@ If you are utilising ``python-gsmmodem-new`` as part of another project, add it to your ``install_requires`` section of your ``setup.py`` file and upon your project's installation, it will be pulled in automatically. -Manual installation from PyPI -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Manual installation of the latest "stable" release from PyPI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Download and extract the ``python-gsmmodem-new`` archive from `PyPI `_ for the current release @@ -72,6 +72,17 @@ Next, do this:: Note that ``python-gsmmodem-new`` package relies on ``pyserial`` for serial communications: http://pyserial.sourceforge.net +Installation of the latest commit from GitHub +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Clone from GitHub:: + + git clone https://github.com/babca/python-gsmmodem.git + cd python-gsmmodem/ + python setup.py install + +Note that ``python-gsmmodem-new`` package relies on ``pyserial`` for serial communications: +http://pyserial.sourceforge.net Testing the package ------------------- From 42618a5e568785d88bfd5a49a86a03e907ae8db5 Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 14 Sep 2016 10:45:55 +0200 Subject: [PATCH 061/133] CPIN command timeout increased Timeout increased from 0.25s to 15s according to an existing patch in a network-manager (Ubuntu) https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/607517 Closes #11 --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index bf45f2e..e05cbf6 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -416,7 +416,7 @@ def _unlockSim(self, pin): """ Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """ # Unlock the SIM card if needed try: - cpinResponse = lineStartingWith(b'+CPIN', self.write('AT+CPIN?', timeout=0.25)) + cpinResponse = lineStartingWith(b'+CPIN', self.write('AT+CPIN?', timeout=15)) except TimeoutException as timeout: # Wavecom modems do not end +CPIN responses with "OK" (github issue #19) - see if just the +CPIN response was returned if timeout.data != None: From 8beb5574bce77a9b80e0510eadf6ba69d6bf3b58 Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 14 Sep 2016 11:51:20 +0200 Subject: [PATCH 062/133] updated readme --- README.rst | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.rst b/README.rst index 74c3e3a..0ff96d9 100644 --- a/README.rst +++ b/README.rst @@ -59,13 +59,8 @@ upon your project's installation, it will be pulled in automatically. Manual installation of the latest "stable" release from PyPI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Download and extract the ``python-gsmmodem-new`` archive from `PyPI -`_ for the current release -version, or clone from GitHub:: - - git clone https://github.com/babca/python-gsmmodem.git - -Next, do this:: +Download a ``python-gsmmodem-new`` archive from `PyPI +`_, extract it and install the package with command:: python setup.py install From c7a4636e5e20a077e36505158735a66cac50c36f Mon Sep 17 00:00:00 2001 From: babca Date: Sat, 29 Oct 2016 21:20:16 +0200 Subject: [PATCH 063/133] added getter for SIM Own Number --- examples/own_number_demo.py | 38 +++++++++++++++++++++++++++ gsmmodem/modem.py | 52 +++++++++++++++++++++++++++++++++++-- 2 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 examples/own_number_demo.py diff --git a/examples/own_number_demo.py b/examples/own_number_demo.py new file mode 100644 index 0000000..af715ab --- /dev/null +++ b/examples/own_number_demo.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +"""\ +Demo: read own phone number +""" + +from __future__ import print_function + +import logging + +PORT = '/dev/vmodem0' +BAUDRATE = 115200 +PIN = None # SIM card PIN (if any) + +from gsmmodem.modem import GsmModem + +def main(): + print('Initializing modem...') + # Uncomment the following line to see what the modem is doing: + logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) + modem = GsmModem(PORT, BAUDRATE) + modem.connect(PIN) + + number = modem.ownNumber + print("The SIM card phone number is:") + print(number) + + # Uncomment the following block to change your own number. + # modem.ownNumber = "+000123456789" # lease empty for removing the phone entry altogether + + # number = modem.ownNumber + # print("A new phone number is:") + # print(number) + + # modem.close(); + +if __name__ == '__main__': + main() diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e05cbf6..c1e9ed4 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -570,7 +570,7 @@ def supportedCommands(self): except (TimeoutException, CommandError): # Try interactive command recognition commands = [] - checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS', '+CSCS'] + checkable_commands = ['^CVOICE', '+VTS', '^DTMF', '^USSDMODE', '+WIND', '+ZPAS', '+CSCS', '+CNUM'] # Check if modem is still alive try: @@ -735,6 +735,55 @@ def smsc(self, smscNumber): self.write('AT+CSCA="{0}"'.format(d(smscNumber))) self._smscNumber = smscNumber + @property + def ownNumber(self): + """ Query subscriber phone number. + + It must be stored on SIM by operator. + If is it not stored already, it usually is possible to store the number by user. + + :raise TimeoutException: if a timeout was specified and reached + + + :return: Subscriber SIM phone number. Returns None if not known + :rtype: int + """ + + try: + if "+CNUM" in self._commands: + response = self.write('AT+CNUM') + else: + # temporarily switch to "own numbers" phonebook, read position 1 and than switch back + response = self.write('AT+CPBS?') + selected_phonebook = response[0][6:].split('"')[1] # first line, remove the +CSCS: prefix, split, first parameter + + if selected_phonebook is not "ON": + self.write('AT+CPBS="ON"') + + response = self.write("AT+CPBR=1") + self.write('AT+CPBS="{0}"'.format(selected_phonebook)) + + if response is "OK": # command is supported, but no number is set + return None + elif len(response) == 2: # OK and phone number. Actual number is in the first line, second parameter, and is placed inside quotation marks + first_line = response[0] + second_param = first_line.split(',')[1] + return second_param[1:-1] + elif len(response) > 2: # Multi-line response + self.log.debug('Unhandled +CNUM/+CPBS response: {0}'.format(response)) + return None + + except (TimeoutException, CommandError): + raise + + @ownNumber.setter + def ownNumber(self, phone_number): + actual_phonebook = self.write('AT+CPBS?') + if actual_phonebook is not "ON": + self.write('AT+CPBS="ON"') + self.write('AT+CPBW=1,"' + phone_number + '"') + + def waitForNetworkCoverage(self, timeout=None): """ Block until the modem has GSM network coverage. @@ -749,7 +798,6 @@ def waitForNetworkCoverage(self, timeout=None): :raise InvalidStateException: if the modem is not going to receive network coverage (SIM blocked, etc) :return: the current signal strength - :rtype: int """ block = [True] if timeout != None: From 6cda6113e6766da0b94d3815d287ff98d489025c Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sat, 5 Nov 2016 16:02:45 +0100 Subject: [PATCH 064/133] prepending the 'b' letter to missing commands --- gsmmodem/modem.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index c1e9ed4..e04afba 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -654,7 +654,7 @@ def smsEncoding(self): if len(response) == 2: encoding = response[0] - if encoding.startswith('+CSCS'): + if encoding.startswith(b'+CSCS'): encoding = encoding[6:].split('"') # remove the +CSCS: prefix before splitting if len(encoding) == 3: self._smsEncoding = encoding[1] @@ -1150,7 +1150,7 @@ def __threadedHandleModemNotification(self, lines): # SMS status report self._handleSmsStatusReport(line) return - elif line.startswith('+CDS'): + elif line.startswith(b'+CDS'): # SMS status report at next line next_line_is_te_statusreport = True cdsMatch = self.CDS_REGEX.match(line) @@ -1161,7 +1161,7 @@ def __threadedHandleModemNotification(self, lines): elif next_line_is_te_statusreport: self._handleSmsStatusReportTe(next_line_is_te_statusreport_length, line) return - elif line.startswith('+DTMF'): + elif line.startswith(b'+DTMF'): # New incoming DTMF self._handleIncomingDTMF(line) return From ea1f5e5170ffae21585d90ce363acc3fcf728a88 Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sat, 5 Nov 2016 16:04:06 +0100 Subject: [PATCH 065/133] add decoding for lines.pop in _handleIncomingCall() --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e04afba..501d619 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1194,7 +1194,7 @@ def GetIncomingDTMF(self): def _handleIncomingCall(self, lines): self.log.debug('Handling incoming call') - ringLine = lines.pop(0) + ringLine = d(lines.pop(0)) if self._extendedIncomingCallIndication: try: callType = ringLine.split(' ', 1)[1] From b374753418a2a62215e13e649ea611c6aed3342a Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sat, 5 Nov 2016 18:45:45 +0100 Subject: [PATCH 066/133] add regex matching for CNUM / ownNumber --- gsmmodem/modem.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 501d619..010264f 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -138,6 +138,8 @@ class GsmModem(SerialComms): CSQ_REGEX = re.compile(b'^\+CSQ:\s*(\d+),') # Used for parsing caller ID announcements for incoming calls. Group 1 is the number CLIP_REGEX = re.compile(b'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') + # Used for parsing own number. Group 1 is the number + CNUM_REGEX = re.compile(b'^\+CNUM:\s*".*?","(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications CMTI_REGEX = re.compile(b'^\+CMTI:\s*"([^"]+)",\s*(\d+)$') # Used for parsing SMS message reads (text mode) @@ -766,9 +768,13 @@ def ownNumber(self): if response is "OK": # command is supported, but no number is set return None elif len(response) == 2: # OK and phone number. Actual number is in the first line, second parameter, and is placed inside quotation marks - first_line = response[0] - second_param = first_line.split(',')[1] - return second_param[1:-1] + cnumLine = response[0] + cnumMatch = self.CNUM_REGEX.match(cnumLine) + if cnumMatch: + return cnumMatch.group(1) + else: + self.log.debug('Error parse +CNUM response: {0}'.format(response)) + return None elif len(response) > 2: # Multi-line response self.log.debug('Unhandled +CNUM/+CPBS response: {0}'.format(response)) return None @@ -1185,7 +1191,7 @@ def _handleIncomingDTMF(self,line): self.dtmfpool.append(dtmf_num) self.log.debug('DTMF number is {0}'.format(dtmf_num)) except: - self.log.debug('Error parce DTMF number on line {0}'.format(line)) + self.log.debug('Error parse DTMF number on line {0}'.format(line)) def GetIncomingDTMF(self): if (len(self.dtmfpool)==0): return None From d71e0a2e84c2a2850ab350dc277741eeb29c5f4f Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Tue, 8 Nov 2016 21:59:00 +0100 Subject: [PATCH 067/133] add decoding for enc_list response --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 010264f..ed3ad84 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -631,7 +631,7 @@ def smsSupportedEncoding(self): # Extract encoding names list try: - enc_list = response[0] # Get the first line + enc_list = d(response[0]) # Get the first line enc_list = enc_list[6:] # Remove '+CSCS' prefix # Extract AT list in format ("str", "str2", "str3") enc_list = enc_list.split('(')[1] From 428aae450f43f1e8e6b813cbc871358e6e84ea29 Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Tue, 8 Nov 2016 22:06:35 +0100 Subject: [PATCH 068/133] add gsmbusy property --- gsmmodem/modem.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 010264f..e0ec66b 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -181,6 +181,7 @@ def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsRece self._pollCallStatusRegex = None # Regular expression used when polling outgoing call status self._writeWait = 0 # Time (in seconds to wait after writing a command (adjusted when 515 errors are detected) self._smsTextMode = False # Storage variable for the smsTextMode property + self._gsmBusy = 0 # Storage variable for the GSMBUSY property self._smscNumber = None # Default SMSC number self._smsRef = 0 # Sent SMS reference counter self._smsMemReadDelete = None # Preferred message storage memory for reads/deletes ( parameter used for +CPMS) @@ -715,7 +716,26 @@ def _compileSmsRegexes(self): self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(b'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: self.CMGR_REGEX_PDU = re.compile(b'^\+CMGR:\s*(\d*),\s*"{0,1}([^"]*)"{0,1},\s*(\d+)$') - + + @property + def gsmBusy(self): + """ :return: Current GSMBUSY state """ + try: + response = self.write('AT+GSMBUSY?') + response = d(response[0]) # Get the first line + response = response[10] # Remove '+GSMBUSY: ' prefix + self._gsmBusy = response + except: + pass # If error is related to ME funtionality: +CME ERROR: + return self._gsmBusy + @gsmBusy.setter + def gsmBusy(self, gsmBusy): + """ Sete GSMBUSY state """ + if gsmBusy != self._gsmBusy: + if self.alive: + self.write('AT+GSMBUSY="{0}"'.format(d(gsmBusy))) + self._gsmBusy = gsmBusy + @property def smsc(self): """ :return: The default SMSC number stored on the SIM card """ From 663c112a8bebd7c92e12a1a25af362b368d76e82 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 10 Nov 2016 16:28:48 +0100 Subject: [PATCH 069/133] v0.11 --- ChangeLog | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ChangeLog b/ChangeLog index 17fd9c0..68209f6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +* Thu Nov 10 2016 babca - 0.11 +- added getter for SIM own number +- added option for blocking incoming calls (GSMBUSY) +- various python3 fixes + * Thu Aug 18 2016 babca - 0.10 – Probably a new code maintainer for 2016 - All commits published for the last 3 years merged into a one branch From ffa64adf4baf35ccafa6a317ea1173e5ec82ff2a Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 10 Nov 2016 16:29:39 +0100 Subject: [PATCH 070/133] v0.11 --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 0ff96d9..3791a7e 100644 --- a/README.rst +++ b/README.rst @@ -1,5 +1,5 @@ -python-gsmmodem -=============== +python-gsmmodem-new v0.11 +========================= *GSM modem module for Python* python-gsmmodem is a module that allows easy control of a GSM modem attached From 19c0a5cbfce9e4bb86e927df0457425e48e32290 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 10 Nov 2016 16:39:50 +0100 Subject: [PATCH 071/133] v0.11 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 6bc942a..bc73f7d 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ test_command = [sys.executable, '-m', 'unittest', 'discover'] coverage_command = ['coverage', 'run', '-m', 'unittest', 'discover'] -VERSION = "0.10" +VERSION = "0.11" class RunUnitTests(Command): """ run unit tests """ From c5ad8b2e6f7a8f9825629bb00ca0bd6564b3f103 Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sat, 19 Nov 2016 18:06:09 +0100 Subject: [PATCH 072/133] change to prepend + always for CLIP --- gsmmodem/modem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index a627490..6e976c1 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -137,7 +137,7 @@ class GsmModem(SerialComms): # Used for parsing signal strength query responses CSQ_REGEX = re.compile(b'^\+CSQ:\s*(\d+),') # Used for parsing caller ID announcements for incoming calls. Group 1 is the number - CLIP_REGEX = re.compile(b'^\+CLIP:\s*"(\+{0,1}\d+)",(\d+).*$') + CLIP_REGEX = re.compile(b'^\+CLIP:\s*"\+{0,1}(\d+)",(\d+).*$') # Used for parsing own number. Group 1 is the number CNUM_REGEX = re.compile(b'^\+CNUM:\s*".*?","(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications @@ -1240,7 +1240,7 @@ def _handleIncomingCall(self, lines): clipLine = lines.pop(0) clipMatch = self.CLIP_REGEX.match(clipLine) if clipMatch: - callerNumber = clipMatch.group(1) + callerNumber = b'+' + clipMatch.group(1) ton = clipMatch.group(2) #TODO: re-add support for this callerName = None From f47568897e0f8240edb487c9b2c85c52df5e5def Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sun, 20 Nov 2016 13:48:23 +0100 Subject: [PATCH 073/133] Remove trailing whitespace --- examples/incoming_call_demo.py | 12 +-- examples/own_number_demo.py | 4 +- examples/sms_handler_demo.py | 8 +- gsmmodem/modem.py | 54 ++++++------ gsmmodem/serial_comms.py | 52 ++++++------ tools/gsmterm.py | 16 ++-- tools/gsmtermlib/atcommands.py | 2 +- tools/gsmtermlib/posoptparse.py | 2 +- tools/gsmtermlib/terminal.py | 144 ++++++++++++++++---------------- tools/gsmtermlib/trie.py | 45 +++++----- tools/identify-modem.py | 12 +-- tools/sendsms.py | 8 +- 12 files changed, 179 insertions(+), 180 deletions(-) mode change 100644 => 100755 examples/own_number_demo.py diff --git a/examples/incoming_call_demo.py b/examples/incoming_call_demo.py index 3ef9a22..6e8f4bc 100755 --- a/examples/incoming_call_demo.py +++ b/examples/incoming_call_demo.py @@ -4,7 +4,7 @@ Demo: handle incoming calls Simple demo app that listens for incoming calls, displays the caller ID, -optionally answers the call and plays sone DTMF tones (if supported by modem), +optionally answers the call and plays sone DTMF tones (if supported by modem), and hangs up the call. """ @@ -27,29 +27,29 @@ def handleIncomingCall(call): print('Answering call and playing some DTMF tones...') call.answer() # Wait for a bit - some older modems struggle to send DTMF tone immediately after answering a call - time.sleep(2.0) + time.sleep(2.0) try: call.sendDtmfTone('9515999955951') except InterruptedException as e: # Call was ended during playback - print('DTMF playback interrupted: {0} ({1} Error {2})'.format(e, e.cause.type, e.cause.code)) + print('DTMF playback interrupted: {0} ({1} Error {2})'.format(e, e.cause.type, e.cause.code)) finally: if call.answered: print('Hanging up call.') call.hangup() - else: + else: print('Modem has no DTMF support - hanging up call.') call.hangup() else: print(' Call from {0} is still ringing...'.format(call.number)) - + def main(): print('Initializing modem...') #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, incomingCallCallbackFunc=handleIncomingCall) modem.connect(PIN) print('Waiting for incoming calls...') - try: + try: modem.rxThread.join(2**31) # Specify a (huge) timeout so that it essentially blocks indefinitely, but still receives CTRL+C interrupt signal finally: modem.close() diff --git a/examples/own_number_demo.py b/examples/own_number_demo.py old mode 100644 new mode 100755 index af715ab..e8faebe --- a/examples/own_number_demo.py +++ b/examples/own_number_demo.py @@ -13,14 +13,14 @@ PIN = None # SIM card PIN (if any) from gsmmodem.modem import GsmModem - + def main(): print('Initializing modem...') # Uncomment the following line to see what the modem is doing: logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE) modem.connect(PIN) - + number = modem.ownNumber print("The SIM card phone number is:") print(number) diff --git a/examples/sms_handler_demo.py b/examples/sms_handler_demo.py index ef1cb69..bab17bf 100755 --- a/examples/sms_handler_demo.py +++ b/examples/sms_handler_demo.py @@ -22,16 +22,16 @@ def handleSms(sms): print('Replying to SMS...') sms.reply(u'SMS received: "{0}{1}"'.format(sms.text[:20], '...' if len(sms.text) > 20 else '')) print('SMS sent.\n') - + def main(): print('Initializing modem...') # Uncomment the following line to see what the modem is doing: logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) modem = GsmModem(PORT, BAUDRATE, smsReceivedCallbackFunc=handleSms) - modem.smsTextMode = False + modem.smsTextMode = False modem.connect(PIN) - print('Waiting for SMS message...') - try: + print('Waiting for SMS message...') + try: modem.rxThread.join(2**31) # Specify a (huge) timeout so that it essentially blocks indefinitely, but still receives CTRL+C interrupt signal finally: modem.close(); diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 6e976c1..2c1bf11 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -29,8 +29,8 @@ def d(obj): unicode = str TERMINATOR = b'\r' CTRLZ = b'\x1a' - - + + else: #pragma: no cover dictValuesIter = dict.itervalues dictItemsIter = dict.iteritems @@ -80,7 +80,7 @@ def sendSms(self, dnumber, message): def getModem(self): """ Convenience method that returns the gsm modem instance """ return self._gsmModem - + class SentSms(Sms): """ An SMS message that has been sent (MO) """ @@ -153,7 +153,7 @@ class GsmModem(SerialComms): # Used for parsing SMS status reports CDSI_REGEX = re.compile(b'\+CDSI:\s*"([^"]+)",(\d+)$') CDS_REGEX = re.compile(b'\+CDS:\s*([0-9]+)"$') - + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback @@ -280,7 +280,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Attempt to identify modem type directly (if not already) - for outgoing call status updates if callUpdateTableHint == 0: if b'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC - Call.dtmfSupport = True + Call.dtmfSupport = True self.write('AT+DDET=1') # enable detect incoming DTMF if self.manufacturer.lower() == 'huawei': @@ -395,7 +395,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Message notifications not supported self._smsReadSupported = False self.log.warning('Incoming SMS notifications not supported by modem. SMS receiving unavailable.') - + # Incoming call notification setup try: self.write('AT+CLIP=1') # Enable calling line identification presentation @@ -461,11 +461,11 @@ def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTe :return: A list containing the response lines from the modem, or None if waitForResponse is False :rtype: list """ - + if isinstance(data, unicode): data = bytes(data,"ascii") - - + + self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) @@ -763,7 +763,7 @@ def ownNumber(self): It must be stored on SIM by operator. If is it not stored already, it usually is possible to store the number by user. - + :raise TimeoutException: if a timeout was specified and reached @@ -778,13 +778,13 @@ def ownNumber(self): # temporarily switch to "own numbers" phonebook, read position 1 and than switch back response = self.write('AT+CPBS?') selected_phonebook = response[0][6:].split('"')[1] # first line, remove the +CSCS: prefix, split, first parameter - + if selected_phonebook is not "ON": self.write('AT+CPBS="ON"') - + response = self.write("AT+CPBR=1") self.write('AT+CPBS="{0}"'.format(selected_phonebook)) - + if response is "OK": # command is supported, but no number is set return None elif len(response) == 2: # OK and phone number. Actual number is in the first line, second parameter, and is placed inside quotation marks @@ -798,14 +798,14 @@ def ownNumber(self): elif len(response) > 2: # Multi-line response self.log.debug('Unhandled +CNUM/+CPBS response: {0}'.format(response)) return None - + except (TimeoutException, CommandError): raise @ownNumber.setter def ownNumber(self, phone_number): actual_phonebook = self.write('AT+CPBS?') - if actual_phonebook is not "ON": + if actual_phonebook is not "ON": self.write('AT+CPBS="ON"') self.write('AT+CPBW=1,"' + phone_number + '"') @@ -971,8 +971,8 @@ def checkForwarding(self, querytype, responseTimeout=15): raise print(queryResponse) return True - - + + def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): """ Check forwarding status: 0=Unconditional, 1=Busy, 2=NoReply, 3=NotReach, 4=AllFwd, 5=AllCondFwd :param fwdType: The type of forwarding to set @@ -989,7 +989,7 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): return False print(queryResponse) return queryResponse - + def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call @@ -1188,7 +1188,7 @@ def __threadedHandleModemNotification(self, lines): self._handleSmsStatusReportTe(next_line_is_te_statusreport_length, line) return elif line.startswith(b'+DTMF'): - # New incoming DTMF + # New incoming DTMF self._handleIncomingDTMF(line) return else: @@ -1200,12 +1200,12 @@ def __threadedHandleModemNotification(self, lines): handlerFunc(match) return # If this is reached, the notification wasn't handled - self.log.debug('Unhandled unsolicited modem notification: %s', lines) - + self.log.debug('Unhandled unsolicited modem notification: %s', lines) + #Simcom modem able detect incoming DTMF def _handleIncomingDTMF(self,line): self.log.debug('Handling incoming DTMF') - + try: dtmf_num=line.split(':')[1].replace(" ","") self.dtmfpool.append(dtmf_num) @@ -1217,7 +1217,7 @@ def GetIncomingDTMF(self): return None else: return self.dtmfpool.pop(0) - + def _handleIncomingCall(self, lines): self.log.debug('Handling incoming call') ringLine = d(lines.pop(0)) @@ -1334,7 +1334,7 @@ def _handleSmsReceived(self, notificationLine): self.log.error('error in smsReceivedCallback', exc_info=True) else: self.deleteStoredSms(msgIndex) - + def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ self.log.debug('SMS status report received') @@ -1357,7 +1357,7 @@ def _handleSmsStatusReport(self, notificationLine): except Exception: self.log.error('error in smsStatusReportCallback', exc_info=True) - + self.smsStatusReportCallback(report) def _handleSmsStatusReportTe(self, length, notificationLine): @@ -1617,10 +1617,10 @@ def sendDtmfTone(self, tones): if self.answered: dtmfCommandBase = self.DTMF_COMMAND_BASE.format(cid=self.id) toneLen = len(tones) - for tone in list(tones): + for tone in list(tones): try: self._gsmModem.write('AT{0}{1}'.format(d(dtmfCommandBase),d(tone)), timeout=(5 + toneLen)) - + except CmeError as e: if e.code == 30: # No network service - can happen if call is ended during DTMF transmission (but also if DTMF is sent immediately after call is answered) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 8dd1a45..d7d2b7e 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -12,51 +12,51 @@ class SerialComms(object): """ Wraps all low-level serial communications (actual read/write operations) """ - + log = logging.getLogger('gsmmodem.serial_comms.SerialComms') - + # End-of-line read terminator RX_EOL_SEQ = b'\r\n' # End-of-response terminator RESPONSE_TERM = re.compile(b'^OK|ERROR|(\+CM[ES] ERROR: \d+)|(COMMAND NOT SUPPORT)$') # Default timeout for serial port reads (in seconds) timeout = 1 - + def __init__(self, port, baudrate=115200, notifyCallbackFunc=None, fatalErrorCallbackFunc=None, *args, **kwargs): """ Constructor - + :param fatalErrorCallbackFunc: function to call if a fatal error occurs in the serial device reading thread :type fatalErrorCallbackFunc: func - """ + """ self.alive = False self.port = port self.baudrate = baudrate - + self._responseEvent = None # threading.Event() self._expectResponseTermSeq = None # expected response terminator sequence self._response = None # Buffer containing response to a written command self._notification = [] # Buffer containing lines from an unsolicited notification from the modem # Reentrant lock for managing concurrent write access to the underlying serial port self._txLock = threading.RLock() - - self.notifyCallback = notifyCallbackFunc or self._placeholderCallback + + self.notifyCallback = notifyCallbackFunc or self._placeholderCallback self.fatalErrorCallback = fatalErrorCallbackFunc or self._placeholderCallback - + self.com_args = args self.com_kwargs = kwargs - + def connect(self): - """ Connects to the device and starts the read thread """ + """ Connects to the device and starts the read thread """ self.serial = serial.Serial(dsrdtr=True, rtscts=True, port=self.port, baudrate=self.baudrate, timeout=self.timeout,*self.com_args,**self.com_kwargs) # Start read thread - self.alive = True + self.alive = True self.rxThread = threading.Thread(target=self._readLoop) self.rxThread.daemon = True self.rxThread.start() def close(self): - """ Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """ + """ Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """ self.alive = False self.rxThread.join() self.serial.close() @@ -71,7 +71,7 @@ def _handleLineRead(self, line, checkForResponseTerm=True): #print 'response:', self._response self.log.debug('response: %s', self._response) self._responseEvent.set() - else: + else: # Nothing was waiting for this - treat it as a notification self._notification.append(line) if self.serial.inWaiting() == 0: @@ -79,14 +79,14 @@ def _handleLineRead(self, line, checkForResponseTerm=True): #print 'notification:', self._notification self.log.debug('notification: %s', self._notification) self.notifyCallback(self._notification) - self._notification = [] + self._notification = [] def _placeholderCallback(self, *args, **kwargs): """ Placeholder callback function (does nothing) """ - + def _readLoop(self): """ Read thread main loop - + Reads lines from the connected device """ try: @@ -102,14 +102,14 @@ def _readLoop(self): # A line (or other logical segment) has been read line = bytes(rxBuffer[:-readTermLen]) rxBuffer = bytearray() - if len(line) > 0: - #print 'calling handler' + if len(line) > 0: + #print 'calling handler' self._handleLineRead(line) elif self._expectResponseTermSeq: if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq: - line = bytes(rxBuffer) + line = bytes(rxBuffer) rxBuffer = bytearray() - self._handleLineRead(line, checkForResponseTerm=False) + self._handleLineRead(line, checkForResponseTerm=False) #else: #' ' except serial.SerialException as e: @@ -120,16 +120,16 @@ def _readLoop(self): pass # Notify the fatal error handler self.fatalErrorCallback(e) - + def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=None): if isinstance(data, str): data = data.encode() - with self._txLock: + with self._txLock: if waitForResponse: if expectedResponseTermSeq: - self._expectResponseTermSeq = bytearray(expectedResponseTermSeq) + self._expectResponseTermSeq = bytearray(expectedResponseTermSeq) self._response = [] - self._responseEvent = threading.Event() + self._responseEvent = threading.Event() self.serial.write(data) if self._responseEvent.wait(timeout): self._responseEvent = None @@ -143,5 +143,5 @@ def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=N raise TimeoutException(self._response) else: raise TimeoutException() - else: + else: self.serial.write(data) diff --git a/tools/gsmterm.py b/tools/gsmterm.py index 8a86431..3a2acb9 100755 --- a/tools/gsmterm.py +++ b/tools/gsmterm.py @@ -14,33 +14,33 @@ def parseArgs(): """ Argument parser for Python 2.7 and above """ from argparse import ArgumentParser - parser = ArgumentParser(description='User-friendly terminal for interacting with a connected GSM modem.') + parser = ArgumentParser(description='User-friendly terminal for interacting with a connected GSM modem.') parser.add_argument('port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_argument('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') - parser.add_argument('-r', '--raw', action='store_true', help='switch to raw terminal mode') + parser.add_argument('-r', '--raw', action='store_true', help='switch to raw terminal mode') return parser.parse_args() def parseArgsPy26(): """ Argument parser for Python 2.6 """ - from gsmtermlib.posoptparse import PosOptionParser, Option - parser = PosOptionParser(description='User-friendly terminal for interacting with a connected GSM modem.') + from gsmtermlib.posoptparse import PosOptionParser, Option + parser = PosOptionParser(description='User-friendly terminal for interacting with a connected GSM modem.') parser.add_positional_argument(Option('--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.')) parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') - parser.add_option('-r', '--raw', action='store_true', help='switch to raw terminal mode') + parser.add_option('-r', '--raw', action='store_true', help='switch to raw terminal mode') options, args = parser.parse_args() - if len(args) != 1: + if len(args) != 1: parser.error('Incorrect number of arguments - please specify a PORT to connect to, e.g. {0} /dev/ttyUSB0'.format(sys.argv[0])) else: options.port = args[0] return options - + def main(): args = parseArgsPy26() if sys.version_info[0] == 2 and sys.version_info[1] < 7 else parseArgs() if args.raw: gsmTerm = RawTerm(args.port, args.baud) else: gsmTerm = GsmTerm(args.port, args.baud) - + gsmTerm.start() gsmTerm.rxThread.join() print('Done.') diff --git a/tools/gsmtermlib/atcommands.py b/tools/gsmtermlib/atcommands.py index fd14556..f3baaad 100644 --- a/tools/gsmtermlib/atcommands.py +++ b/tools/gsmtermlib/atcommands.py @@ -124,7 +124,7 @@ 1: registered, home network.\n2: not registered, ME currently searching for a new operator to register to.\n\ 3: registration denied.\n4: unknown.\n5: registered, roaming.'), ('', 'string type; two byte location area code in hexadecimal format'), - ('', 'string type; two byte cell ID in hexadecimal format')), + ('', 'string type; two byte cell ID in hexadecimal format')), 'This command is used by the application to ascertain the registration status of the device.')), ('AT+WOPN', (c[2], 'Read Operator Name')), ('AT+WOPN', (c[2], 'Selection of Preferred PLMN List')), diff --git a/tools/gsmtermlib/posoptparse.py b/tools/gsmtermlib/posoptparse.py index c540f61..8707803 100644 --- a/tools/gsmtermlib/posoptparse.py +++ b/tools/gsmtermlib/posoptparse.py @@ -1,5 +1,5 @@ """ PosOptionParser class gotten from Douglas Mayle at StackOverflow: -http://stackoverflow.com/a/664614/1980416 +http://stackoverflow.com/a/664614/1980416 Used for positional argument support similar to argparse (for Python 2.6 compatibility) """ diff --git a/tools/gsmtermlib/terminal.py b/tools/gsmtermlib/terminal.py index 4bc665d..dcea328 100644 --- a/tools/gsmtermlib/terminal.py +++ b/tools/gsmtermlib/terminal.py @@ -16,13 +16,13 @@ from .trie import Trie from gsmmodem.exceptions import TimeoutException -# first choose a platform dependant way to read single characters from the console +# first choose a platform dependant way to read single characters from the console global console if os.name == 'nt': import msvcrt class Console(object): - + CURSOR_UP = '{0}{1}'.format(chr(0xe0), chr(0x48)) CURSOR_DOWN = '{0}{1}'.format(chr(0xe0), chr(0x50)) CURSOR_LEFT = '{0}{1}'.format(chr(0xe0), chr(0x4b)) @@ -31,7 +31,7 @@ class Console(object): DELETE = '' HOME = '' END = '' - + def __init__(self): pass @@ -59,7 +59,7 @@ def getkey(self): elif os.name == 'posix': import termios, tty class Console(object): - + CURSOR_UP = '{0}{1}{2}'.format(chr(27), chr(91), chr(65)) CURSOR_DOWN = '{0}{1}{2}'.format(chr(27), chr(91), chr(66)) CURSOR_LEFT = '{0}{1}{2}'.format(chr(27), chr(91), chr(68)) @@ -67,7 +67,7 @@ class Console(object): DELETE = '{0}{1}{2}{3}'.format(chr(27), chr(91), chr(51), chr(126)) HOME = '{0}{1}{2}'.format(chr(27), chr(79), chr(72)) END = '{0}{1}{2}'.format(chr(27), chr(79), chr(70)) - + def __init__(self): self.fd = sys.stdin.fileno() @@ -80,14 +80,14 @@ def setup(self): termios.tcsetattr(self.fd, termios.TCSANOW, new) # def setup(self): -# self.oldSettings = termios.tcgetattr(self.fd) -# tty.setraw(self.fd) +# self.oldSettings = termios.tcgetattr(self.fd) +# tty.setraw(self.fd) def getkey(self): c = os.read(self.fd, 4) #print (len(c)) #for a in c: - # print('rx:',ord(a)) + # print('rx:',ord(a)) return c def cleanup(self): @@ -106,24 +106,24 @@ def cleanup_console(): class RawTerm(SerialComms): - """ "Raw" terminal - basically just copies console input to serial, and prints out anything read """ - - EXIT_CHARACTER = '\x1d' # CTRL+] + """ "Raw" terminal - basically just copies console input to serial, and prints out anything read """ + + EXIT_CHARACTER = '\x1d' # CTRL+] WRITE_TERM = '\r' # Write terminator character - + def __init__(self, port, baudrate=9600): super(RawTerm, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification) self.port = port self.baudrate = baudrate self.echo = True - + def _handleModemNotification(self, lines): for line in lines: print(line) - + def printStartMessage(self): print('\nRaw terminal connected to {0} at {1}bps.\nPress CTRL+] to exit.\n'.format(self.port, self.baudrate)) - + def start(self): self.connect() # Start input thread @@ -131,24 +131,24 @@ def start(self): self.inputThread = threading.Thread(target=self._inputLoop) self.inputThread.daemon = True self.inputThread.start() - self.printStartMessage() - + self.printStartMessage() + def stop(self): self.alive = False if threading.current_thread() != self.inputThread: self.inputThread.join() self.close() - + def _inputLoop(self): """ Loop and copy console->serial until EXIT_CHARCTER character is found. """ try: while self.alive: try: - c = console.getkey() + c = console.getkey() except KeyboardInterrupt: print('kbint') c = serial.to_bytes([3]) - if c == self.EXIT_CHARACTER: + if c == self.EXIT_CHARACTER: self.stop() elif c == '\n': # Convert newline input into \r @@ -169,22 +169,22 @@ def _inputLoop(self): class GsmTerm(RawTerm): """ User-friendly terminal for interacting with a GSM modem. - + Some features: tab-completion, help """ - + PROMPT = 'GSM> ' SMS_PROMPT = '> ' EXIT_CHARACTER_2 = chr(4) # CTRL+D - + BACKSPACE_CHARACTER = chr(127) CTRL_Z_CHARACTER = chr(26) # Used when entering SMS messages with AT+CMGS ESC_CHARACTER = chr(27) # Used to cancel entering SMS messages with AT+CMGS - + RESET_SEQ = '\033[0m' COLOR_SEQ = '\033[1;{0}m' BOLD_SEQ = '\033[1m' - + # ANSI colour escapes COLOR_RED = COLOR_SEQ.format(30+1) COLOR_GREEN = COLOR_SEQ.format(30+2) @@ -200,7 +200,7 @@ def __init__(self, port, baudrate=9600, useColor=True): self.history = [] self.historyPos = 0 self.useColor = useColor - self.cursorPos = 0 + self.cursorPos = 0 if self.useColor: self.PROMPT = self._color(self.COLOR_GREEN, self.PROMPT) self.SMS_PROMPT = self._color(self.COLOR_GREEN, self.SMS_PROMPT) @@ -218,7 +218,7 @@ def _color(self, color, msg): if self.useColor: return '{0}{1}{2}'.format(color, msg, self.RESET_SEQ) else: - return msg + return msg def _boldFace(self, msg): """ Converts a message to be printed to the user's terminal in bold """ @@ -232,32 +232,32 @@ def _handleModemNotification(self, lines): if lines[-1] == 'ERROR': print(self._color(self.COLOR_RED, '\n'.join(lines))) else: - print(self._color(self.COLOR_CYAN, '\n'.join(lines))) + print(self._color(self.COLOR_CYAN, '\n'.join(lines))) self._refreshInputPrompt() - + def _addToHistory(self, command): self.history.append(command) if len(self.history) > 100: self.history = self.history[1:] - + def _inputLoop(self): """ Loop and copy console->serial until EXIT_CHARCTER character is found. """ - + # Switch statement for handling "special" characters actionChars = {self.EXIT_CHARACTER: self._exit, self.EXIT_CHARACTER_2: self._exit, - + console.CURSOR_LEFT: self._cursorLeft, console.CURSOR_RIGHT: self._cursorRight, console.CURSOR_UP: self._cursorUp, console.CURSOR_DOWN: self._cursorDown, - + '\n': self._doConfirmInput, '\t': self._doCommandCompletion, - + self.CTRL_Z_CHARACTER: self._handleCtrlZ, self.ESC_CHARACTER: self._handleEsc, - + self.BACKSPACE_CHARACTER: self._handleBackspace, console.DELETE: self._handleDelete, console.HOME: self._handleHome, @@ -270,7 +270,7 @@ def _inputLoop(self): except KeyboardInterrupt: c = serial.to_bytes([3]) if c in actionChars: - # Handle character directly + # Handle character directly actionChars[c]() elif len(c) == 1 and self._isPrintable(c): self.inputBuffer.insert(self.cursorPos, c) @@ -293,7 +293,7 @@ def _handleCtrlZ(self): self.cursorPos = 0 sys.stdout.write('\n') self._refreshInputPrompt() - + def _handleEsc(self): """ Handler for CTRL+Z keypresses """ if self._typingSms: @@ -305,7 +305,7 @@ def _handleEsc(self): def _exit(self): """ Shuts down the terminal (and app) """ self._removeInputPrompt() - print(self._color(self.COLOR_YELLOW, 'CLOSING TERMINAL...')) + print(self._color(self.COLOR_YELLOW, 'CLOSING TERMINAL...')) self.stop() def _cursorLeft(self): @@ -336,7 +336,7 @@ def _cursorDown(self): if self.historyPos < len(self.history)-1: clearLen = len(self.inputBuffer) self.historyPos += 1 - self.inputBuffer = list(self.history[self.historyPos]) + self.inputBuffer = list(self.history[self.historyPos]) self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(clearLen) @@ -346,13 +346,13 @@ def _handleBackspace(self): #print( 'cp:',self.cursorPos,'was:', self.inputBuffer) self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:] self.cursorPos -= 1 - #print ('cp:', self.cursorPos,'is:', self.inputBuffer) + #print ('cp:', self.cursorPos,'is:', self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer)+1) def _handleDelete(self): """ Handles "delete" characters """ if self.cursorPos < len(self.inputBuffer): - self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:] + self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:] self._refreshInputPrompt(len(self.inputBuffer)+1) def _handleHome(self): @@ -374,24 +374,24 @@ def _doConfirmInput(self): self.cursorPos = 0 sys.stdout.write('\n') self._refreshInputPrompt() - return - # Convert newline input into \r\n + return + # Convert newline input into \r\n if len(self.inputBuffer) > 0: inputStr = ''.join(self.inputBuffer).strip() self.inputBuffer = [] self.cursorPos = 0 - inputStrLen = len(inputStr) + inputStrLen = len(inputStr) if len(inputStr) > 0: self._addToHistory(inputStr) self.historyPos = len(self.history) if inputStrLen > 2: if inputStr[0] == '?': # ?COMMAND - # Help requested with function + # Help requested with function self._printCommandHelp(inputStr[1:]) return elif inputStr[-1] == inputStr[-2] == '?': # COMMAND?? # Help requested with function - cmd = inputStr[:-3 if inputStr[-3] == '=' else -2] + cmd = inputStr[:-3 if inputStr[-3] == '=' else -2] self._printCommandHelp(cmd) return inputStrLower = inputStr.lower() @@ -399,9 +399,9 @@ def _doConfirmInput(self): # Alternative help invocation self._printCommandHelp(inputStr[5:]) return - elif inputStrLower.startswith('ls'): + elif inputStrLower.startswith('ls'): if inputStrLower == 'lscat': - sys.stdout.write('\n') + sys.stdout.write('\n') for category in self.completion.categories: sys.stdout.write('{0}\n'.format(category)) self._refreshInputPrompt(len(self.inputBuffer)) @@ -411,9 +411,9 @@ def _doConfirmInput(self): for command in self.completion: sys.stdout.write('{0:<8} - {1}\n'.format(command, self.completion[command][1])) self._refreshInputPrompt(len(self.inputBuffer)) - return + return else: - ls = inputStrLower.split(' ', 1) + ls = inputStrLower.split(' ', 1) if len(ls) == 2: category = ls[1].lower() if category in [cat.lower() for cat in self.completion.categories]: @@ -426,26 +426,26 @@ def _doConfirmInput(self): return elif inputStrLower.startswith('load'): # Load a file containing AT commands to issue - load = inputStr.split(' ', 1) - if len(load) == 2: + load = inputStr.split(' ', 1) + if len(load) == 2: filename = load[1].strip() try: f = open(filename, 'r') except IOError: sys.stdout.write('\n{0}\n'.format(self._color(self.COLOR_RED, 'File not found: "{0}"'.format(filename)))) - self._refreshInputPrompt(len(self.inputBuffer)) + self._refreshInputPrompt(len(self.inputBuffer)) else: atCommands = f.readlines() - f.close() + f.close() sys.stdout.write('\n') - for atCommand in atCommands: + for atCommand in atCommands: atCommand = atCommand.strip() if len(atCommand) > 0 and atCommand[0] != '#': self.inputBuffer = list(atCommand.strip()) self._refreshInputPrompt(len(self.inputBuffer)) self._doConfirmInput() time.sleep(0.1) - return + return if len(inputStr) > 0: if inputStrLower.startswith('at+cmgs='): # Prepare for SMS input @@ -455,11 +455,11 @@ def _doConfirmInput(self): sys.stdout.flush() response = self.write(inputStr + self.WRITE_TERM, waitForResponse=True, timeout=3, expectedResponseTermSeq='> ') except TimeoutException: - self._typingSms = False + self._typingSms = False else: - sys.stdout.write(self._color(self.COLOR_YELLOW, 'Type your SMS message, and press CTRL+Z to send it or press ESC to cancel.\n')) + sys.stdout.write(self._color(self.COLOR_YELLOW, 'Type your SMS message, and press CTRL+Z to send it or press ESC to cancel.\n')) self.SMS_PROMPT = self._color(self.COLOR_GREEN, response[0]) - self._refreshInputPrompt() + self._refreshInputPrompt() return self.serial.write(inputStr) self.serial.write(self.WRITE_TERM) @@ -468,7 +468,7 @@ def _doConfirmInput(self): sys.stdout.flush() def _printGeneralHelp(self): - sys.stdout.write(self._color(self.COLOR_WHITE, '\n\n== GSMTerm Help ==\n\n')) + sys.stdout.write(self._color(self.COLOR_WHITE, '\n\n== GSMTerm Help ==\n\n')) sys.stdout.write('{0} Press the up & down arrow keys to move backwards or forwards through your command history.\n\n'.format(self._color(self.COLOR_YELLOW, 'Command History:'))) sys.stdout.write('{0} Press the TAB key to provide command completion suggestions. Press the TAB key after a command is fully typed (with or without a "=" character) to quickly see its syntax.\n\n'.format(self._color(self.COLOR_YELLOW, 'Command Completion:'))) sys.stdout.write('{0} Type a command, followed with two quesetion marks to access its documentation, e.g. "??". Alternatively, precede the command with a question mark ("?"), or type "help ".\n\n'.format(self._color(self.COLOR_YELLOW, 'Command Documentation:'))) @@ -491,7 +491,7 @@ def _printCommandHelp(self, command=None): noHelp = commandHelp == None if noHelp: sys.stdout.write('\r No help available for: {0}\n'.format(self._color(self.COLOR_WHITE, command))) - else: + else: sys.stdout.write('\n\n{0} ({1})\n\n'.format(self._color(self.COLOR_WHITE, commandHelp[1]), command)) sys.stdout.write('{0} {1}\n'.format(self._color(self.COLOR_YELLOW, 'Category:'), commandHelp[0])) if len(commandHelp) == 2: @@ -499,8 +499,8 @@ def _printCommandHelp(self, command=None): self._refreshInputPrompt(len(self.inputBuffer)) return sys.stdout.write('{0} {1}\n'.format(self._color(self.COLOR_YELLOW, 'Description:'), commandHelp[4])) - - valuesIsEnum = len(commandHelp) >= 6 + + valuesIsEnum = len(commandHelp) >= 6 if valuesIsEnum: # "Values" is an enum of allowed values (not multiple variables); use custom label sys.stdout.write('{0} '.format(self._color(self.COLOR_YELLOW, commandHelp[5]))) else: @@ -513,11 +513,11 @@ def _printCommandHelp(self, command=None): sys.stdout.write('\n') first = True for value, valueDesc in commandValues: - if first: + if first: first = False else: syntax.append(',' if not valuesIsEnum else '|') - syntax.append(self._color(self.COLOR_MAGENTA, value)) + syntax.append(self._color(self.COLOR_MAGENTA, value)) sys.stdout.write(' {0} {1}\n'.format(self._color(self.COLOR_MAGENTA, value), valueDesc.replace('\n', '\n' + ' ' * (len(value) + 2)) if valueDesc != None else '')) else: sys.stdout.write('No parameters.\n') @@ -531,18 +531,18 @@ def _printCommandHelp(self, command=None): self._refreshInputPrompt(len(self.inputBuffer)) def _doCommandCompletion(self): - """ Command-completion method """ + """ Command-completion method """ prefix = ''.join(self.inputBuffer).strip().upper() matches = self.completion.keys(prefix) - matchLen = len(matches) + matchLen = len(matches) if matchLen == 0 and prefix[-1] == '=': - try: + try: command = prefix[:-1] except KeyError: - pass + pass else: self.__printCommandSyntax(command) - elif matchLen > 0: + elif matchLen > 0: if matchLen == 1: if matches[0] == prefix: # User has already entered command - show command syntax @@ -584,10 +584,10 @@ def __printCommandSyntax(self, command): self._refreshInputPrompt(len(self.inputBuffer)) def _isPrintable(self, char): - return 33 <= ord(char) <= 126 or char.isspace() + return 33 <= ord(char) <= 126 or char.isspace() def _refreshInputPrompt(self, clearLen=0): - termPrompt = self.SMS_PROMPT if self._typingSms else self.PROMPT + termPrompt = self.SMS_PROMPT if self._typingSms else self.PROMPT endPoint = clearLen if clearLen > 0 else len(self.inputBuffer) sys.stdout.write('\r{0}{1}{2}{3}'.format(termPrompt, ''.join(self.inputBuffer), (clearLen - len(self.inputBuffer)) * ' ', console.CURSOR_LEFT * (endPoint - self.cursorPos))) sys.stdout.flush() diff --git a/tools/gsmtermlib/trie.py b/tools/gsmtermlib/trie.py index 184a2fd..c63f1db 100644 --- a/tools/gsmtermlib/trie.py +++ b/tools/gsmtermlib/trie.py @@ -13,30 +13,30 @@ class Trie(object): - + def __init__(self, key=None, value=None): - self.slots = {} + self.slots = {} self.key = key self.value = value def __setitem__(self, key, value): - if key == None: + if key == None: raise ValueError('Key may not be None') - + if len(key) == 0: - # All of the original key's chars have been nibbled away + # All of the original key's chars have been nibbled away self.value = value self.key = '' - return - + return + c = key[0] - + if c not in self.slots: # Unused slot - no collision if self.key != None and len(self.key) > 0: # This was a "leaf" previously - create a new branch for its current value branchC = self.key[0] - branchKey = self.key[1:] if len(self.key) > 1 else '' + branchKey = self.key[1:] if len(self.key) > 1 else '' self.slots[branchC] = Trie(branchKey, self.value) self.key = None self.value = None @@ -45,15 +45,15 @@ def __setitem__(self, key, value): else: self.slots[c][key[1:]] = value else: - # Store specified value in a new branch and return + # Store specified value in a new branch and return self.slots[c] = Trie(key[1:], value) else: trie = self.slots[c] - trie[key[1:]] = value + trie[key[1:]] = value def __delitem__(self, key): - if key == None: + if key == None: raise ValueError('Key may not be None') if len(key) == 0: if self.key == '': @@ -75,9 +75,9 @@ def __delitem__(self, key): del trie[key[1:]] else: raise KeyError(key) - + def __getitem__(self, key): - if key == None: + if key == None: raise ValueError('Key may not be None') if len(key) == 0: if self.key == '': @@ -85,7 +85,7 @@ def __getitem__(self, key): return self.value else: raise KeyError(key) - c = key[0] + c = key[0] if c in self.slots: trie = self.slots[c] return trie[key[1:]] @@ -118,13 +118,13 @@ def _allKeys(self, prefix): """ Private implementation method. Use keys() instead. """ global dictItemsIter result = [prefix + self.key] if self.key != None else [] - for key, trie in dictItemsIter(self.slots): - result.extend(trie._allKeys(prefix + key)) + for key, trie in dictItemsIter(self.slots): + result.extend(trie._allKeys(prefix + key)) return result def keys(self, prefix=None): - """ Return all or possible keys in this trie - + """ Return all or possible keys in this trie + If prefix is None, return all keys. If prefix is a string, return all keys that start with this string """ @@ -132,7 +132,7 @@ def keys(self, prefix=None): return self._allKeys('') else: return self._filteredKeys(prefix, '') - + def _filteredKeys(self, key, prefix): global dictKeysIter global dictItemsIter @@ -140,7 +140,7 @@ def _filteredKeys(self, key, prefix): result = [prefix + self.key] if self.key != None else [] for c, trie in dictItemsIter(self.slots): result.extend(trie._allKeys(prefix + c)) - else: + else: c = key[0] if c in dictKeysIter(self.slots): result = [] @@ -178,9 +178,8 @@ def _longestCommonPrefix(self, key, prefix): return self.slots[c]._longestCommonPrefix(key[1:], prefix + c) else: return '' # nothing starts with the specified prefix - + def __iter__(self): for k in list(self.keys()): yield k raise StopIteration - \ No newline at end of file diff --git a/tools/identify-modem.py b/tools/identify-modem.py index 1a2167d..44b7e65 100755 --- a/tools/identify-modem.py +++ b/tools/identify-modem.py @@ -17,7 +17,7 @@ def parseArgs(): """ Argument parser for Python 2.7 and above """ from argparse import ArgumentParser - parser = ArgumentParser(description='Identify and debug attached GSM modem') + parser = ArgumentParser(description='Identify and debug attached GSM modem') parser.add_argument('port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_argument('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_argument('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') @@ -27,15 +27,15 @@ def parseArgs(): def parseArgsPy26(): """ Argument parser for Python 2.6 """ - from gsmtermlib.posoptparse import PosOptionParser, Option - parser = PosOptionParser(description='Identify and debug attached GSM modem') + from gsmtermlib.posoptparse import PosOptionParser, Option + parser = PosOptionParser(description='Identify and debug attached GSM modem') parser.add_positional_argument(Option('--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.')) parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_option('-d', '--debug', action='store_true', help='dump modem debug information (for python-gsmmodem development)') parser.add_option('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') options, args = parser.parse_args() - if len(args) != 1: + if len(args) != 1: parser.error('Incorrect number of arguments - please specify a PORT to connect to, e.g. {0} /dev/ttyUSB0'.format(sys.argv[0])) else: options.port = args[0] @@ -44,8 +44,8 @@ def parseArgsPy26(): def main(): args = parseArgsPy26() if sys.version_info[0] == 2 and sys.version_info[1] < 7 else parseArgs() print ('args:',args) - modem = GsmModem(args.port, args.baud) - + modem = GsmModem(args.port, args.baud) + print('Connecting to GSM modem on {0}...'.format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) diff --git a/tools/sendsms.py b/tools/sendsms.py index e519a12..55860cc 100755 --- a/tools/sendsms.py +++ b/tools/sendsms.py @@ -24,7 +24,7 @@ def parseArgs(): parser.add_argument('--CNMI', default='', help='Set the CNMI of the modem, used for message notifications') parser.add_argument('destination', metavar='DESTINATION', help='destination mobile number') return parser.parse_args() - + def parseArgsPy26(): """ Argument parser for Python 2.6 """ from gsmtermlib.posoptparse import PosOptionParser, Option @@ -35,9 +35,9 @@ def parseArgsPy26(): parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') parser.add_option('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') parser.add_option('--CNMI', default='', help='Set the CNMI of the modem, used for message notifications') - parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) + parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) options, args = parser.parse_args() - if len(args) != 1: + if len(args) != 1: parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0])) else: options.destination = args[0] @@ -51,7 +51,7 @@ def main(): modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) # Uncomment the following line to see what the modem is doing: #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) - + print('Connecting to GSM modem on {0}...'.format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) From 2404881ab9eeebe578ef62e2de6b1dabde4e1e0f Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sun, 20 Nov 2016 13:54:00 +0100 Subject: [PATCH 074/133] Change to use bytes in serial_comms Python 2 and 3 --- gsmmodem/modem.py | 11 +++-------- gsmmodem/serial_comms.py | 4 ++-- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 2c1bf11..95fcfe8 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -16,8 +16,8 @@ from gsmmodem.exceptions import EncodingError PYTHON_VERSION = sys.version_info[0] -CTRLZ = chr(26) -TERMINATOR = '\r' +CTRLZ = b'\x1a' +TERMINATOR = b'\r' def d(obj): return obj.decode() if type(obj) == bytes else obj @@ -27,10 +27,6 @@ def d(obj): dictValuesIter = dict.values dictItemsIter = dict.items unicode = str - TERMINATOR = b'\r' - CTRLZ = b'\x1a' - - else: #pragma: no cover dictValuesIter = dict.itervalues dictItemsIter = dict.iteritems @@ -463,8 +459,7 @@ def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTe """ if isinstance(data, unicode): - data = bytes(data,"ascii") - + data = data.encode() self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index d7d2b7e..84ae0d2 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -94,8 +94,8 @@ def _readLoop(self): readTermLen = len(readTermSeq) rxBuffer = bytearray() while self.alive: - data = self.serial.read(1).decode() #Python 3.x compatibility - if data != '': # check for timeout + data = self.serial.read(1) + if data != b'': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(ord(data)) if rxBuffer[-readTermLen:] == readTermSeq: From f7f8147e9c5d69bef93170845794ce8411ec2ef9 Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sun, 20 Nov 2016 15:40:37 +0100 Subject: [PATCH 075/133] Move all en/deocde() to serial_comm No b' prefixes any more in modem.py! --- gsmmodem/modem.py | 116 +++++++++++++++++++-------------------- gsmmodem/serial_comms.py | 11 ++-- 2 files changed, 61 insertions(+), 66 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 95fcfe8..61b2186 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -16,8 +16,8 @@ from gsmmodem.exceptions import EncodingError PYTHON_VERSION = sys.version_info[0] -CTRLZ = b'\x1a' -TERMINATOR = b'\r' +CTRLZ = '\x1a' +TERMINATOR = '\r' def d(obj): return obj.decode() if type(obj) == bytes else obj @@ -26,7 +26,6 @@ def d(obj): xrange = range dictValuesIter = dict.values dictItemsIter = dict.items - unicode = str else: #pragma: no cover dictValuesIter = dict.itervalues dictItemsIter = dict.iteritems @@ -129,15 +128,15 @@ class GsmModem(SerialComms): log = logging.getLogger('gsmmodem.modem.GsmModem') # Used for parsing AT command errors - CM_ERROR_REGEX = re.compile(b'^\+(CM[ES]) ERROR: (\d+)$') + CM_ERROR_REGEX = re.compile('^\+(CM[ES]) ERROR: (\d+)$') # Used for parsing signal strength query responses - CSQ_REGEX = re.compile(b'^\+CSQ:\s*(\d+),') + CSQ_REGEX = re.compile('^\+CSQ:\s*(\d+),') # Used for parsing caller ID announcements for incoming calls. Group 1 is the number - CLIP_REGEX = re.compile(b'^\+CLIP:\s*"\+{0,1}(\d+)",(\d+).*$') + CLIP_REGEX = re.compile('^\+CLIP:\s*"\+{0,1}(\d+)",(\d+).*$') # Used for parsing own number. Group 1 is the number - CNUM_REGEX = re.compile(b'^\+CNUM:\s*".*?","(\+{0,1}\d+)",(\d+).*$') + CNUM_REGEX = re.compile('^\+CNUM:\s*".*?","(\+{0,1}\d+)",(\d+).*$') # Used for parsing new SMS message indications - CMTI_REGEX = re.compile(b'^\+CMTI:\s*"([^"]+)",\s*(\d+)$') + CMTI_REGEX = re.compile('^\+CMTI:\s*"([^"]+)",\s*(\d+)$') # Used for parsing SMS message reads (text mode) CMGR_SM_DELIVER_REGEX_TEXT = None # Used for parsing SMS status report message reads (text mode) @@ -145,10 +144,10 @@ class GsmModem(SerialComms): # Used for parsing SMS message reads (PDU mode) CMGR_REGEX_PDU = None # Used for parsing USSD event notifications - CUSD_REGEX = re.compile(b'\+CUSD:\s*(\d),\s*"(.*?)",\s*(\d+)', re.DOTALL) + CUSD_REGEX = re.compile('\+CUSD:\s*(\d),\s*"(.*?)",\s*(\d+)', re.DOTALL) # Used for parsing SMS status reports - CDSI_REGEX = re.compile(b'\+CDSI:\s*"([^"]+)",(\d+)$') - CDS_REGEX = re.compile(b'\+CDS:\s*([0-9]+)"$') + CDSI_REGEX = re.compile('\+CDSI:\s*"([^"]+)",(\d+)$') + CDS_REGEX = re.compile('\+CDS:\s*([0-9]+)"$') def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) @@ -224,7 +223,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): pinCheckComplete = False self.write('ATE0') # echo off try: - cfun = int(lineStartingWith(b'+CFUN:', self.write('AT+CFUN?'))[7:]) # example response: +CFUN: 1 + cfun = int(lineStartingWith('+CFUN:', self.write('AT+CFUN?'))[7:]) # example response: +CFUN: 1 if cfun != 1: self.write('AT+CFUN=1') except CommandError: @@ -263,7 +262,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): if enableWind: try: - wind = lineStartingWith(b'+WIND:', self.write('AT+WIND?')) # Check current WIND value; example response: +WIND: 63 + wind = lineStartingWith('+WIND:', self.write('AT+WIND?')) # Check current WIND value; example response: +WIND: 63 except CommandError: # Modem does not support +WIND notifications. See if we can detect other known call update notifications pass @@ -275,7 +274,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Attempt to identify modem type directly (if not already) - for outgoing call status updates if callUpdateTableHint == 0: - if b'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC + if 'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC Call.dtmfSupport = True self.write('AT+DDET=1') # enable detect incoming DTMF @@ -293,9 +292,9 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): if callUpdateTableHint == 1: # Use Hauwei's ^NOTIFICATIONs self.log.info('Loading Huawei call state update table') - self._callStatusUpdates = ((re.compile(b'^\^ORIG:(\d),(\d)$'), self._handleCallInitiated), - (re.compile(b'^\^CONN:(\d),(\d)$'), self._handleCallAnswered), - (re.compile(b'^\^CEND:(\d),(\d),(\d)+,(\d)+$'), self._handleCallEnded)) + self._callStatusUpdates = ((re.compile('^\^ORIG:(\d),(\d)$'), self._handleCallInitiated), + (re.compile('^\^CONN:(\d),(\d)$'), self._handleCallAnswered), + (re.compile('^\^CEND:(\d),(\d),(\d)+,(\d)+$'), self._handleCallEnded)) self._mustPollCallStatus = False # Huawei modems use ^DTMF to send DTMF tones; use that instead Call.DTMF_COMMAND_BASE = '^DTMF={cid},' @@ -303,9 +302,9 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): elif callUpdateTableHint == 2: # Wavecom modem: +WIND notifications supported self.log.info('Loading Wavecom call state update table') - self._callStatusUpdates = ((re.compile(b'^\+WIND: 5,(\d)$'), self._handleCallInitiated), - (re.compile(b'^OK$'), self._handleCallAnswered), - (re.compile(b'^\+WIND: 6,(\d)$'), self._handleCallEnded)) + self._callStatusUpdates = ((re.compile('^\+WIND: 5,(\d)$'), self._handleCallInitiated), + (re.compile('^OK$'), self._handleCallAnswered), + (re.compile('^\+WIND: 6,(\d)$'), self._handleCallEnded)) self._waitForAtdResponse = False # Wavecom modems return OK only when the call is answered self._mustPollCallStatus = False if commands == None: # older modem, assume it has standard DTMF support @@ -313,9 +312,9 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): elif callUpdateTableHint == 3: # ZTE # Use ZTE notifications ("CONNECT"/"HANGUP", but no "call initiated" notification) self.log.info('Loading ZTE call state update table') - self._callStatusUpdates = ((re.compile(b'^CONNECT$'), self._handleCallAnswered), - (re.compile(b'^HANGUP:\s*(\d+)$'), self._handleCallEnded), - (re.compile(b'^OK$'), self._handleCallRejected)) + self._callStatusUpdates = ((re.compile('^CONNECT$'), self._handleCallAnswered), + (re.compile('^HANGUP:\s*(\d+)$'), self._handleCallEnded), + (re.compile('^OK$'), self._handleCallRejected)) self._waitForAtdResponse = False # ZTE modems do not return an immediate OK only when the call is answered self._mustPollCallStatus = False self._waitForCallInitUpdate = False # ZTE modems do not provide "call initiated" updates @@ -325,7 +324,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Unknown modem - we do not know what its call updates look like. Use polling instead self.log.info('Unknown/generic modem type - will use polling for call state updates') self._mustPollCallStatus = True - self._pollCallStatusRegex = re.compile(b'^\+CLCC:\s+(\d+),(\d),(\d),(\d),([^,]),"([^,]*)",(\d+)$') + self._pollCallStatusRegex = re.compile('^\+CLCC:\s+(\d+),(\d),(\d),(\d),([^,]),"([^,]*)",(\d+)$') self._waitForAtdResponse = True # Most modems return OK immediately after issuing ATD # General meta-information setup @@ -352,13 +351,13 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): # Set message storage, but first check what the modem supports - example response: +CPMS: (("SM","BM","SR"),("SM")) try: - cpmsLine = lineStartingWith(b'+CPMS', self.write('AT+CPMS=?')) + cpmsLine = lineStartingWith('+CPMS', self.write('AT+CPMS=?')) except CommandError: # Modem does not support AT+CPMS; SMS reading unavailable self._smsReadSupported = False self.log.warning('SMS preferred message storage query not supported by modem. SMS reading unavailable.') else: - cpmsSupport = cpmsLine.split(b' ', 1)[1].split(b'),(') + cpmsSupport = cpmsLine.split(' ', 1)[1].split('),(') # Do a sanity check on the memory types returned - Nokia S60 devices return empty strings, for example for memItem in cpmsSupport: if len(memItem) == 0: @@ -368,14 +367,14 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): break else: # Suppported memory types look fine, continue - preferredMemoryTypes = (b'"ME"', b'"SM"', b'"SR"') + preferredMemoryTypes = ('"ME"', '"SM"', '"SR"') cpmsItems = [''] * len(cpmsSupport) for i in xrange(len(cpmsSupport)): for memType in preferredMemoryTypes: if memType in cpmsSupport[i]: if i == 0: self._smsMemReadDelete = memType - cpmsItems[i] = memType.decode('ascii') + cpmsItems[i] = memType break self.write('AT+CPMS={0}'.format(','.join(cpmsItems))) # Set message storage del cpmsSupport @@ -415,18 +414,18 @@ def _unlockSim(self, pin): """ Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """ # Unlock the SIM card if needed try: - cpinResponse = lineStartingWith(b'+CPIN', self.write('AT+CPIN?', timeout=15)) + cpinResponse = lineStartingWith('+CPIN', self.write('AT+CPIN?', timeout=15)) except TimeoutException as timeout: # Wavecom modems do not end +CPIN responses with "OK" (github issue #19) - see if just the +CPIN response was returned if timeout.data != None: - cpinResponse = lineStartingWith(b'+CPIN', timeout.data) + cpinResponse = lineStartingWith('+CPIN', timeout.data) if cpinResponse == None: # No useful response read raise timeout else: # Nothing read (real timeout) raise timeout - if cpinResponse != b'+CPIN: READY': + if cpinResponse != '+CPIN: READY': if pin != None: self.write('AT+CPIN="{0}"'.format(d(pin))) else: @@ -458,9 +457,6 @@ def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTe :rtype: list """ - if isinstance(data, unicode): - data = data.encode() - self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) @@ -468,7 +464,7 @@ def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTe if waitForResponse: cmdStatusLine = responseLines[-1] if parseError: - if b'ERROR' in cmdStatusLine: + if 'ERROR' in cmdStatusLine: cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine) if cmErrorMatch: errorType = cmErrorMatch.group(1) @@ -487,13 +483,13 @@ def write(self, data, waitForResponse=True, timeout=10, parseError=True, writeTe else: self._writeWait = 0 # The modem was just waiting for the SIM card return result - if errorType == b'CME': + if errorType == 'CME': raise CmeError(data, int(errorCode)) else: # CMS error raise CmsError(data, int(errorCode)) else: raise CommandError(data) - elif cmdStatusLine == b'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands + elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands raise CommandError('{} ({})'.format(data,cmdStatusLine)) return responseLines @@ -544,7 +540,7 @@ def imsi(self): @property def networkName(self): """ :return: the name of the GSM Network Operator to which the modem is connected """ - copsMatch = lineMatching(b'^\+COPS: (\d),(\d),"(.+)",{0,1}\d*$', self.write('AT+COPS?')) # response format: +COPS: mode,format,"operator_name",x + copsMatch = lineMatching('^\+COPS: (\d),(\d),"(.+)",{0,1}\d*$', self.write('AT+COPS?')) # response format: +COPS: mode,format,"operator_name",x if copsMatch: return copsMatch.group(3) @@ -557,7 +553,7 @@ def supportedCommands(self): response = self.write('AT+CLAC', timeout=10) if len(response) == 2: # Single-line response, comma separated commands = response[0] - if commands.startswith(b'+CLAC'): + if commands.startswith('+CLAC'): commands = commands[6:] # remove the +CLAC: prefix before splitting return commands.split(',') elif len(response) > 2: # Multi-line response @@ -652,7 +648,7 @@ def smsEncoding(self): if len(response) == 2: encoding = response[0] - if encoding.startswith(b'+CSCS'): + if encoding.startswith('+CSCS'): encoding = encoding[6:].split('"') # remove the +CSCS: prefix before splitting if len(encoding) == 3: self._smsEncoding = encoding[1] @@ -707,10 +703,10 @@ def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: - self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(b'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') - self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(b'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') + self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile('^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') + self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile('^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: - self.CMGR_REGEX_PDU = re.compile(b'^\+CMGR:\s*(\d*),\s*"{0,1}([^"]*)"{0,1},\s*(\d+)$') + self.CMGR_REGEX_PDU = re.compile('^\+CMGR:\s*(\d*),\s*"{0,1}([^"]*)"{0,1},\s*(\d+)$') @property def gsmBusy(self): @@ -740,7 +736,7 @@ def smsc(self): except SmscNumberUnknownError: pass # Some modems return a CMS 330 error if the value isn't set else: - cscaMatch = lineMatching(b'\+CSCA:\s*"([^,]+)",(\d+)$', readSmsc) + cscaMatch = lineMatching('\+CSCA:\s*"([^,]+)",(\d+)$', readSmsc) if cscaMatch: self._smscNumber = cscaMatch.group(1) return self._smscNumber @@ -831,7 +827,7 @@ def _cancelBlock(): checkCreg = True while block[0]: if checkCreg: - cregResult = lineMatching(b'^\+CREG:\s*(\d),(\d)(,[^,]*,[^,]*)?$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 + cregResult = lineMatching('^\+CREG:\s*(\d),(\d)(,[^,]*,[^,]*)?$', self.write('AT+CREG?', parseError=False)) # example result: +CREG: 0,1 if cregResult: status = int(cregResult.group(2)) if status in (1, 5): @@ -886,8 +882,8 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou # Send SMS via AT commands if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(d(destination)), timeout=5, expectedResponseTermSeq=b'> ') - result = lineStartingWith(b'+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) + self.write('AT+CMGS="{0}"'.format(d(destination)), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) else: # Set GSM modem SMS encoding format # Encode message text and set data coding scheme based on text contents @@ -899,8 +895,8 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) for pdu in pdus: - self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq=b'> ') - result = lineStartingWith(b'+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx + self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') reference = int(result[7:]) @@ -940,7 +936,7 @@ def sendUssd(self, ussdString, responseTimeout=15): # Some modems issue the +CUSD response before the acknowledgment "OK" - check for that if len(cusdResponse) > 1: - cusdResponseFound = lineStartingWith(b'+CUSD', cusdResponse) != None + cusdResponseFound = lineStartingWith('+CUSD', cusdResponse) != None if cusdResponseFound: self._ussdSessionEvent = None # Cancel thread sync lock return self._parseCusdResponse(cusdResponse) @@ -1070,7 +1066,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): messages = [] delMessages = set() if self._smsTextMode: - cmglRegex= re.compile(b'^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') + cmglRegex= re.compile('^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') for key, val in dictItemsIter(Sms.TEXT_MODE_STATUS_MAP): if status == val: statusStr = key @@ -1092,7 +1088,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): msgIndex, msgStatus, number, msgTime = cmglMatch.groups() msgLines = [] else: - if line != b'OK': + if line != 'OK': msgLines.append(line) if msgIndex != None and len(msgLines) > 0: msgText = '\n'.join(msgLines) @@ -1100,7 +1096,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText)) delMessages.add(int(msgIndex)) else: - cmglRegex = re.compile(b'^\+CMGL:\s*(\d+),\s*(\d+),.*$') + cmglRegex = re.compile('^\+CMGL:\s*(\d+),\s*(\d+),.*$') readPdu = False result = self.write('AT+CMGL={0}'.format(d(status))) for line in result: @@ -1155,23 +1151,23 @@ def __threadedHandleModemNotification(self, lines): """ next_line_is_te_statusreport = False for line in lines: - if b'RING' in line: + if 'RING' in line: # Incoming call (or existing call is ringing) self._handleIncomingCall(lines) return - elif line.startswith(b'+CMTI'): + elif line.startswith('+CMTI'): # New SMS message indication self._handleSmsReceived(line) return - elif line.startswith(b'+CUSD'): + elif line.startswith('+CUSD'): # USSD notification - either a response or a MT-USSD ("push USSD") message self._handleUssd(lines) return - elif line.startswith(b'+CDSI'): + elif line.startswith('+CDSI'): # SMS status report self._handleSmsStatusReport(line) return - elif line.startswith(b'+CDS'): + elif line.startswith('+CDS'): # SMS status report at next line next_line_is_te_statusreport = True cdsMatch = self.CDS_REGEX.match(line) @@ -1182,7 +1178,7 @@ def __threadedHandleModemNotification(self, lines): elif next_line_is_te_statusreport: self._handleSmsStatusReportTe(next_line_is_te_statusreport_length, line) return - elif line.startswith(b'+DTMF'): + elif line.startswith('+DTMF'): # New incoming DTMF self._handleIncomingDTMF(line) return @@ -1235,7 +1231,7 @@ def _handleIncomingCall(self, lines): clipLine = lines.pop(0) clipMatch = self.CLIP_REGEX.match(clipLine) if clipMatch: - callerNumber = b'+' + clipMatch.group(1) + callerNumber = '+' + clipMatch.group(1) ton = clipMatch.group(2) #TODO: re-add support for this callerName = None diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 84ae0d2..7706f43 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -18,7 +18,7 @@ class SerialComms(object): # End-of-line read terminator RX_EOL_SEQ = b'\r\n' # End-of-response terminator - RESPONSE_TERM = re.compile(b'^OK|ERROR|(\+CM[ES] ERROR: \d+)|(COMMAND NOT SUPPORT)$') + RESPONSE_TERM = re.compile('^OK|ERROR|(\+CM[ES] ERROR: \d+)|(COMMAND NOT SUPPORT)$') # Default timeout for serial port reads (in seconds) timeout = 1 @@ -100,14 +100,14 @@ def _readLoop(self): rxBuffer.append(ord(data)) if rxBuffer[-readTermLen:] == readTermSeq: # A line (or other logical segment) has been read - line = bytes(rxBuffer[:-readTermLen]) + line = rxBuffer[:-readTermLen].decode() rxBuffer = bytearray() if len(line) > 0: #print 'calling handler' self._handleLineRead(line) elif self._expectResponseTermSeq: if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq: - line = bytes(rxBuffer) + line = rxBuffer.decode() rxBuffer = bytearray() self._handleLineRead(line, checkForResponseTerm=False) #else: @@ -122,12 +122,11 @@ def _readLoop(self): self.fatalErrorCallback(e) def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=None): - if isinstance(data, str): - data = data.encode() + data = data.encode() with self._txLock: if waitForResponse: if expectedResponseTermSeq: - self._expectResponseTermSeq = bytearray(expectedResponseTermSeq) + self._expectResponseTermSeq = bytearray(expectedResponseTermSeq.encode()) self._response = [] self._responseEvent = threading.Event() self.serial.write(data) From 9af951251e359c71e5dac9568ffd3e9b59374bbd Mon Sep 17 00:00:00 2001 From: "Daniel A. Maierhofer" Date: Sun, 20 Nov 2016 15:42:21 +0100 Subject: [PATCH 076/133] Remove unnecessary d() calls --- gsmmodem/modem.py | 49 ++++++++++++++++++++++------------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 61b2186..552c014 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -19,9 +19,6 @@ CTRLZ = '\x1a' TERMINATOR = '\r' -def d(obj): - return obj.decode() if type(obj) == bytes else obj - if PYTHON_VERSION >= 3: xrange = range dictValuesIter = dict.values @@ -334,7 +331,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): self.write('AT+CMGF={0}'.format(1 if self._smsTextMode else 0)) # Switch to text or PDU mode for SMS messages self._compileSmsRegexes() if self._smscNumber != None: - self.write('AT+CSCA="{0}"'.format(d(self._smscNumber))) # Set default SMSC number + self.write('AT+CSCA="{0}"'.format(self._smscNumber)) # Set default SMSC number currentSmscNumber = self._smscNumber else: currentSmscNumber = self.smsc @@ -427,7 +424,7 @@ def _unlockSim(self, pin): raise timeout if cpinResponse != '+CPIN: READY': if pin != None: - self.write('AT+CPIN="{0}"'.format(d(pin))) + self.write('AT+CPIN="{0}"'.format(pin)) else: raise PinRequiredError('AT+CPIN') @@ -623,8 +620,8 @@ def smsSupportedEncoding(self): # Extract encoding names list try: - enc_list = d(response[0]) # Get the first line - enc_list = enc_list[6:] # Remove '+CSCS' prefix + enc_list = response[0] # Get the first line + enc_list = enc_list[6:] # Remove '+CSCS: ' prefix # Extract AT list in format ("str", "str2", "str3") enc_list = enc_list.split('(')[1] enc_list = enc_list.split(')')[0] @@ -678,7 +675,7 @@ def smsEncoding(self, encoding): # Check if desired encoding is available if encoding in self._smsSupportedEncodingNames: # Set encoding - response = self.write('AT+CSCS="{0}"'.format(d(encoding))) + response = self.write('AT+CSCS="{0}"'.format(encoding)) if len(response) == 1: if response[0].lower() == 'ok': self._smsEncoding = encoding @@ -692,11 +689,11 @@ def _setSmsMemory(self, readDelete=None, write=None): if write != None and write != self._smsMemWrite: self.write() readDel = readDelete or self._smsMemReadDelete - self.write('AT+CPMS="{0}","{1}"'.format(d(readDel), d(write))) + self.write('AT+CPMS="{0}","{1}"'.format(readDel, write)) self._smsMemReadDelete = readDel self._smsMemWrite = write elif readDelete != None and readDelete != self._smsMemReadDelete: - self.write('AT+CPMS="{0}"'.format(d(readDelete))) + self.write('AT+CPMS="{0}"'.format(readDelete)) self._smsMemReadDelete = readDelete def _compileSmsRegexes(self): @@ -713,7 +710,7 @@ def gsmBusy(self): """ :return: Current GSMBUSY state """ try: response = self.write('AT+GSMBUSY?') - response = d(response[0]) # Get the first line + response = response[0] # Get the first line response = response[10] # Remove '+GSMBUSY: ' prefix self._gsmBusy = response except: @@ -724,7 +721,7 @@ def gsmBusy(self, gsmBusy): """ Sete GSMBUSY state """ if gsmBusy != self._gsmBusy: if self.alive: - self.write('AT+GSMBUSY="{0}"'.format(d(gsmBusy))) + self.write('AT+GSMBUSY="{0}"'.format(gsmBusy)) self._gsmBusy = gsmBusy @property @@ -745,7 +742,7 @@ def smsc(self, smscNumber): """ Set the default SMSC number to use when sending SMS messages """ if smscNumber != self._smscNumber: if self.alive: - self.write('AT+CSCA="{0}"'.format(d(smscNumber))) + self.write('AT+CSCA="{0}"'.format(smscNumber)) self._smscNumber = smscNumber @property @@ -882,7 +879,7 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou # Send SMS via AT commands if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(d(destination)), timeout=5, expectedResponseTermSeq='> ') + self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq='> ') result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) else: # Set GSM modem SMS encoding format @@ -929,7 +926,7 @@ def sendUssd(self, ussdString, responseTimeout=15): """ self._ussdSessionEvent = threading.Event() try: - cusdResponse = self.write('AT+CUSD=1,"{0}",15'.format(d(ussdString)), timeout=responseTimeout) # Should respond with "OK" + cusdResponse = self.write('AT+CUSD=1,"{0}",15'.format(ussdString), timeout=responseTimeout) # Should respond with "OK" except Exception: self._ussdSessionEvent = None # Cancel the thread sync lock raise @@ -957,7 +954,7 @@ def checkForwarding(self, querytype, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},2'.format(d(querytype)), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},2'.format(querytype), timeout=responseTimeout) # Should respond with "OK" except Exception: raise print(queryResponse) @@ -974,7 +971,7 @@ def setForwarding(self, fwdType, fwdEnable, fwdNumber, responseTimeout=15): :rtype: Boolean """ try: - queryResponse = self.write('AT+CCFC={0},{1},"{2}"'.format(d(fwdType), d(fwdEnable), d(fwdNumber)), timeout=responseTimeout) # Should respond with "OK" + queryResponse = self.write('AT+CCFC={0},{1},"{2}"'.format(fwdType, fwdEnable, fwdNumber), timeout=responseTimeout) # Should respond with "OK" except Exception: raise return False @@ -996,13 +993,13 @@ def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): # Wait for the "call originated" notification message self._dialEvent = threading.Event() try: - self.write('ATD{0};'.format(d(number)), timeout=timeout, waitForResponse=self._waitForAtdResponse) + self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) except Exception: self._dialEvent = None # Cancel the thread sync lock raise else: # Don't wait for a call init update - base the call ID on the number of active calls - self.write('ATD{0};'.format(d(number)), timeout=timeout, waitForResponse=self._waitForAtdResponse) + self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice @@ -1073,7 +1070,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): break else: raise ValueError('Invalid status value: {0}'.format(status)) - result = self.write('AT+CMGL="{0}"'.format(d(statusStr))) + result = self.write('AT+CMGL="{0}"'.format(statusStr)) msgLines = [] msgIndex = msgStatus = number = msgTime = None for line in result: @@ -1098,7 +1095,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): else: cmglRegex = re.compile('^\+CMGL:\s*(\d+),\s*(\d+),.*$') readPdu = False - result = self.write('AT+CMGL={0}'.format(d(status))) + result = self.write('AT+CMGL={0}'.format(status)) for line in result: if not readPdu: cmglMatch = cmglRegex.match(line) @@ -1211,7 +1208,7 @@ def GetIncomingDTMF(self): def _handleIncomingCall(self, lines): self.log.debug('Handling incoming call') - ringLine = d(lines.pop(0)) + ringLine = lines.pop(0) if self._extendedIncomingCallIndication: try: callType = ringLine.split(' ', 1)[1] @@ -1388,7 +1385,7 @@ def readStoredSms(self, index, memory=None): """ # Switch to the correct memory type if required self._setSmsMemory(readDelete=memory) - msgData = self.write('AT+CMGR={0}'.format(d(index))) + msgData = self.write('AT+CMGR={0}'.format(index)) # Parse meta information if self._smsTextMode: cmgrMatch = self.CMGR_SM_DELIVER_REGEX_TEXT.match(msgData[0]) @@ -1438,7 +1435,7 @@ def deleteStoredSms(self, index, memory=None): :raise CommandError: if unable to delete the stored message """ self._setSmsMemory(readDelete=memory) - self.write('AT+CMGD={0},0'.format(d(index))) + self.write('AT+CMGD={0},0'.format(index)) # TODO: make a check how many params are supported by the modem and use the right command. For example, Siemens MC35, TC35 take only one parameter. #self.write('AT+CMGD={0}'.format(index)) @@ -1464,7 +1461,7 @@ def deleteMultipleStoredSms(self, delFlag=4, memory=None): """ if 0 < delFlag <= 4: self._setSmsMemory(readDelete=memory) - self.write('AT+CMGD=1,{0}'.format(d(delFlag))) + self.write('AT+CMGD=1,{0}'.format(delFlag)) else: raise ValueError('"delFlag" must be in range [1,4]') @@ -1610,7 +1607,7 @@ def sendDtmfTone(self, tones): toneLen = len(tones) for tone in list(tones): try: - self._gsmModem.write('AT{0}{1}'.format(d(dtmfCommandBase),d(tone)), timeout=(5 + toneLen)) + self._gsmModem.write('AT{0}{1}'.format(dtmfCommandBase,tone), timeout=(5 + toneLen)) except CmeError as e: if e.code == 30: From 47facc8c05b3d4d63c9ff202e5cff033574d2c08 Mon Sep 17 00:00:00 2001 From: babca Date: Thu, 24 Nov 2016 12:27:44 +0100 Subject: [PATCH 077/133] fix invalid literal for int() with base 10 pduOffsetStr is base 16 --- gsmmodem/pdu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index ee531a2..fe9d3cf 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -63,7 +63,7 @@ def _setPduOffsetStr(self, pduOffsetStr): # See if the timezone difference is positive/negative by checking MSB of first semi-octet tzHexVal = int(pduOffsetStr, 16) if tzHexVal & 0x80 == 0: # positive - self._offset = timedelta(minutes=(int(pduOffsetStr) * 15)) + self._offset = timedelta(minutes=(int(pduOffsetStr, 16) * 15)) else: # negative self._offset = timedelta(minutes=(int('{0:0>2X}'.format(tzHexVal & 0x7F)) * -15)) From 964f104adcbe341047f44ac9b672d7dab7d80101 Mon Sep 17 00:00:00 2001 From: Peter Lawler Date: Thu, 12 Jan 2017 18:21:11 +1100 Subject: [PATCH 078/133] Minor doc correction deliveryTimeout is incorrectly documented as deliveryReport --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 552c014..3e511bc 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -858,7 +858,7 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou :type text: str :param waitForDeliveryReport: if True, this method blocks until a delivery report is received for the sent message :type waitForDeliveryReport: boolean - :param deliveryReport: the maximum time in seconds to wait for a delivery report (if "waitForDeliveryReport" is True) + :param deliveryTimeout: the maximum time in seconds to wait for a delivery report (if "waitForDeliveryReport" is True) :type deliveryTimeout: int or float :raise CommandError: if an error occurs while attempting to send the message From 64637decda5a03dbb6795f599f8a800908ae66f2 Mon Sep 17 00:00:00 2001 From: Taha Jahangir Date: Thu, 23 Feb 2017 10:36:49 +0330 Subject: [PATCH 079/133] Add optional argument for message text in sendsms util --- tools/sendsms.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tools/sendsms.py b/tools/sendsms.py index 55860cc..f92e7bf 100755 --- a/tools/sendsms.py +++ b/tools/sendsms.py @@ -22,7 +22,9 @@ def parseArgs(): parser.add_argument('-d', '--deliver', action='store_true', help='wait for SMS delivery report') parser.add_argument('-w', '--wait', type=int, default=0, help='Wait for modem to start, in seconds') parser.add_argument('--CNMI', default='', help='Set the CNMI of the modem, used for message notifications') + parser.add_argument('--debug', action='store_true', help='turn on debug (serial port dump)') parser.add_argument('destination', metavar='DESTINATION', help='destination mobile number') + parser.add_argument('message', nargs='?', metavar='MESSAGE', help='message to send, defaults to stdin-prompt') return parser.parse_args() def parseArgsPy26(): @@ -41,6 +43,7 @@ def parseArgsPy26(): parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0])) else: options.destination = args[0] + options.message = None return options def main(): @@ -49,9 +52,10 @@ def main(): sys.stderr.write('Error: No port specified. Please specify the port to which the GSM modem is connected using the -i argument.\n') sys.exit(1) modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) - # Uncomment the following line to see what the modem is doing: - #logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) - + if args.debug: + # enable dump on serial port + logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) + print('Connecting to GSM modem on {0}...'.format(args.port)) try: modem.connect(args.pin, waitingForModemToStartInSeconds=args.wait) @@ -69,8 +73,11 @@ def main(): modem.close() sys.exit(1) else: - print('\nPlease type your message and press enter to send it:') - text = raw_input('> ') + if args.message is None: + print('\nPlease type your message and press enter to send it:') + text = raw_input('> ') + else: + text = args.message if args.deliver: print ('\nSending SMS and waiting for delivery report...') else: From 356f3edbd099b37ada4f835d656697735eb04279 Mon Sep 17 00:00:00 2001 From: Taha Jahangir Date: Thu, 23 Feb 2017 11:09:31 +0330 Subject: [PATCH 080/133] Add an option in sendsms.py to prevent concurrent modem access --- tools/sendsms.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tools/sendsms.py b/tools/sendsms.py index f92e7bf..c1082e4 100755 --- a/tools/sendsms.py +++ b/tools/sendsms.py @@ -17,6 +17,7 @@ def parseArgs(): from argparse import ArgumentParser parser = ArgumentParser(description='Simple script for sending SMS messages') parser.add_argument('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') + parser.add_argument('-l', '--lock-path', metavar='PATH', help='Use oslo.concurrency to prevent concurrent access to modem') parser.add_argument('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_argument('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_argument('-d', '--deliver', action='store_true', help='wait for SMS delivery report') @@ -44,6 +45,7 @@ def parseArgsPy26(): else: options.destination = args[0] options.message = None + options.lock_path = None return options def main(): @@ -51,6 +53,21 @@ def main(): if args.port == None: sys.stderr.write('Error: No port specified. Please specify the port to which the GSM modem is connected using the -i argument.\n') sys.exit(1) + + if args.lock_path is None: + send_sms(args) + else: + try: + from oslo_concurrency import lockutils + except ImportError: + print('oslo_concurrency package is missing') + sys.exit(1) + # apply `lockutils.synchronized` decorator and run + decorator = lockutils.synchronized('python_gsmmodem_sendsms', external=True, lock_path=args.lock_path) + decorator(send_sms)(args) + + +def send_sms(args): modem = GsmModem(args.port, args.baud, AT_CNMI=args.CNMI) if args.debug: # enable dump on serial port From 6633fc5c0769923d2addc4a34636c8d9a57d51e4 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 01:25:09 +0100 Subject: [PATCH 081/133] PDU: Fix message concatenation --- gsmmodem/modem.py | 40 +++++++++---------- gsmmodem/pdu.py | 97 +++++++++++++++++++++++++++++++++++++++++++---- test/test_pdu.py | 27 +++++++++++++ 3 files changed, 137 insertions(+), 27 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 3e511bc..4fc176b 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -871,36 +871,38 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou encodedText = encodeGsm7(text) except ValueError: encodedText = None - self.smsTextMode = False - # Check message length - if len(text) > 160: - self.smsTextMode = False + # Force binary mode for simplicity. Text mode is not necessary. + self.smsTextMode = False - # Send SMS via AT commands - if self._smsTextMode: - self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) + # Set GSM modem SMS encoding format + # Encode message text and set data coding scheme based on text contents + if encodedText == None: + # Cannot encode text using GSM-7; use UCS2 instead + self.smsEncoding = 'UCS2' else: - # Set GSM modem SMS encoding format - # Encode message text and set data coding scheme based on text contents - if encodedText == None: - # Cannot encode text using GSM-7; use UCS2 instead - self.smsEncoding = 'UCS2' - else: - self.smsEncoding = 'GSM' + self.smsEncoding = 'GSM' + + # Encode text into PDUs + pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) + + # Send SMS PDUs via AT commands + for pdu in pdus: + self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx - pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) - for pdu in pdus: - self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') + + # Keep SMS reference number in order to pair delivery reports with sent message reference = int(result[7:]) self._smsRef = reference + 1 if self._smsRef > 255: self._smsRef = 0 + + # Create sent SMS object for future delivery checks sms = SentSms(destination, text, reference) + # Add a weak-referenced entry for this SMS (allows us to update the SMS state if a status report is received) self.sentSms[reference] = sms if waitForDeliveryReport: diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index fe9d3cf..adcbae2 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -43,6 +43,11 @@ 0x04: 140, # 8-bit 0x08: 70} # UCS2 +# Maximum message sizes for each data coding for multipart messages +MAX_MULTIPART_MESSAGE_LENGTH = {0x00: 153, # GSM-7 + 0x04: 133, # 8-bit TODO: Check this value! + 0x08: 67} # UCS2 + class SmsPduTzInfo(tzinfo): """ Simple implementation of datetime.tzinfo for handling timestamp GMT offsets specified in SMS PDUs """ @@ -276,19 +281,29 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ # Encode message text and set data coding scheme based on text contents try: - encodedText = encodeGsm7(text) + encodedTextLength = len(encodeGsm7(text)) except ValueError: # Cannot encode text using GSM-7; use UCS2 instead + encodedTextLength = len(text) alphabet = 0x08 # UCS2 else: alphabet = 0x00 # GSM-7 # Check if message should be concatenated - if len(text) > MAX_MESSAGE_LENGTH[alphabet]: + if encodedTextLength > MAX_MESSAGE_LENGTH[alphabet]: # Text too long for single PDU - add "concatenation" User Data Header concatHeaderPrototype = Concatenation() concatHeaderPrototype.reference = reference - pduCount = int(len(text) / MAX_MESSAGE_LENGTH[alphabet]) + 1 + + # Devide whole text into parts + if alphabet == 0x00: + pduTextParts = divideTextGsm7(text) + elif alphabet == 0x08: + pduTextParts = divideTextUcs2(text) + else: + raise NotImplementedError + + pduCount = len(pduTextParts) concatHeaderPrototype.parts = pduCount tpduFirstOctet |= 0x40 else: @@ -308,10 +323,8 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ if concatHeaderPrototype != None: concatHeader = copy(concatHeaderPrototype) concatHeader.number = i + 1 - if alphabet == 0x00: - pduText = text[i*153:(i+1) * 153] - elif alphabet == 0x08: - pduText = text[i * 67 : (i + 1) * 67] + pduText = pduTextParts[i] + pduTextLength = len(pduText) udh.extend(concatHeader.encode()) else: pduText = text @@ -714,6 +727,49 @@ def decodeGsm7(encodedText): result.append(GSM7_BASIC[b]) return ''.join(result) +def divideTextGsm7(plainText): + """ GSM7 message dividing algorithm + + Divides text into list of chunks that could be stored in a single, GSM7-encoded SMS message. + + :param plainText: the text string to divide + :type plainText: str + + :return: A list of strings + :rtype: list of str + """ + result = [] + + plainStartPtr = 0 + plainStopPtr = 0 + chunkByteSize = 0 + + if PYTHON_VERSION >= 3: + plaintext = str(plaintext) + while plainStopPtr < len(plainText): + char = plainText[plainStopPtr] + idx = GSM7_BASIC.find(char) + if idx != -1: + chunkByteSize = chunkByteSize + 1; + elif char in GSM7_EXTENDED: + chunkByteSize = chunkByteSize + 2; + elif not discardInvalid: + raise ValueError('Cannot encode char "{0}" using GSM-7 encoding'.format(char)) + + plainStopPtr = plainStopPtr + 1 + if chunkByteSize > MAX_MULTIPART_MESSAGE_LENGTH[0x00]: + plainStopPtr = plainStopPtr - 1 + + if chunkByteSize >= MAX_MULTIPART_MESSAGE_LENGTH[0x00]: + result.append(plainText[plainStartPtr:plainStopPtr]) + plainStartPtr = plainStopPtr + chunkByteSize = 0 + + if chunkByteSize > 0: + result.append(plainText[plainStartPtr:]) + + return result + def packSeptets(octets, padBits=0): """ Packs the specified octets into septets @@ -824,8 +880,33 @@ def encodeUcs2(text): :rtype: bytearray """ result = bytearray() - + for b in map(ord, text): result.append(b >> 8) result.append(b & 0xFF) return result + +def divideTextUcs2(plainText): + """ UCS-2 message dividing algorithm + + Divides text into list of chunks that could be stored in a single, UCS-2 -encoded SMS message. + + :param plainText: the text string to divide + :type plainText: str + + :return: A list of strings + :rtype: list of str + """ + result = [] + resultLength = 0 + + fullChunksCount = int(len(plainText) / MAX_MULTIPART_MESSAGE_LENGTH[0x08]) + for i in range(fullChunksCount): + result.append(plainText[i * MAX_MULTIPART_MESSAGE_LENGTH[0x08] : (i + 1) * MAX_MULTIPART_MESSAGE_LENGTH[0x08]]) + resultLength = resultLength + MAX_MULTIPART_MESSAGE_LENGTH[0x08] + + # Add last, not fully filled chunk + if resultLength < len(plainText): + result.append(plainText[resultLength:]) + + return result diff --git a/test/test_pdu.py b/test/test_pdu.py index cf8ccde..f4094e4 100644 --- a/test/test_pdu.py +++ b/test/test_pdu.py @@ -493,6 +493,33 @@ def test_decode_invalidData(self): pdu = 'AEFDSDFSDFSDFS' self.assertRaises(gsmmodem.exceptions.EncodingError, gsmmodem.pdu.decodeSmsPdu, pdu) + def test_encode_Gsm7_divideSMS(self): + """ Tests whether text will be devided into a correct number of chunks while using GSM-7 alphabet""" + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060" + self.assertEqual(len(gsmmodem.pdu.divideTextGsm7(text)), 1) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345-070 12345-080 12345-090 12345-100 12345-010 12345-020 12345-030 12345-040 12345-050 123" + self.assertEqual(len(gsmmodem.pdu.divideTextGsm7(text)), 1) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345-070 12345-080 12345-090 12345-100 12345-010 12345-020 12345-030 12345-040 12345-050 1234" + self.assertEqual(len(gsmmodem.pdu.divideTextGsm7(text)), 2) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345-070 12345-080 12345-090 12345-100 12345-010 12345-020 12345-030 12345-040 12345-050 12]" + self.assertEqual(len(gsmmodem.pdu.divideTextGsm7(text)), 2) + text = "12345-010,12345-020,12345-030,12345-040,12345-050,12345-060,12345-070,12345-080,12345-090,12345-100,12345-110,12345-120,12345-130,12345-140,12345-150,[[[[[[[[" + self.assertEqual(len(gsmmodem.pdu.divideTextGsm7(text)), 2) + + def test_encode_Ucs2_divideSMS(self): + """ Tests whether text will be devided into a correct number of chunks while using UCS-2 alphabet""" + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 1) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 1234567" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 1) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345678" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 2) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 123456[" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 1) + text = "12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 1234567[" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 2) + text = "12345-010,12345-020,12345-030,12345-040,12345-050,12345-060,123456 12345-010,12345-020,12345-030,12345-040,12345-050,12345-060,1234567" + self.assertEqual(len(gsmmodem.pdu.divideTextUcs2(text)), 2) if __name__ == "__main__": unittest.main() From c378122a8a7a66212819d6c0ea1be8918aaa12be Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 14:30:58 +0100 Subject: [PATCH 082/133] PDU: Support text mode for sending SMS messages --- gsmmodem/modem.py | 52 +++++++++++++++++++++++++++-------------------- gsmmodem/pdu.py | 26 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 22 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 4fc176b..ac1dc45 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -8,7 +8,7 @@ from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError -from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, encodeGsm7 +from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, encodeGsm7, encodeTextMode from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr #from . import compat # For Python 2.6 compatibility @@ -866,30 +866,38 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou """ # Check input text to select appropriate mode (text or PDU) - # Check encoding - try: - encodedText = encodeGsm7(text) - except ValueError: - encodedText = None - - # Force binary mode for simplicity. Text mode is not necessary. - self.smsTextMode = False - - # Set GSM modem SMS encoding format - # Encode message text and set data coding scheme based on text contents - if encodedText == None: - # Cannot encode text using GSM-7; use UCS2 instead - self.smsEncoding = 'UCS2' + if self._smsTextMode: + try: + encodedText = encodeTextMode(text) + except ValueError: + self._smsTextMode = False + + if self._smsTextMode: + # Send SMS via AT commands + self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) else: - self.smsEncoding = 'GSM' + # Check encoding + try: + encodedText = encodeGsm7(text) + except ValueError: + encodedText = None + + # Set GSM modem SMS encoding format + # Encode message text and set data coding scheme based on text contents + if encodedText == None: + # Cannot encode text using GSM-7; use UCS2 instead + self.smsEncoding = 'UCS2' + else: + self.smsEncoding = 'GSM' - # Encode text into PDUs - pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) + # Encode text into PDUs + pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash) - # Send SMS PDUs via AT commands - for pdu in pdus: - self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') - result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx + # Send SMS PDUs via AT commands + for pdu in pdus: + self.write('AT+CMGS={0}'.format(pdu.tpduLength), timeout=5, expectedResponseTermSeq='> ') + result = lineStartingWith('+CMGS:', self.write(str(pdu), timeout=35, writeTerm=CTRLZ)) # example: +CMGS: xx if result == None: raise CommandError('Modem did not respond with +CMGS response') diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index adcbae2..dbe1bd4 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -673,6 +673,32 @@ def decodeSemiOctets(encodedNumber, numberOfOctets=None): break return ''.join(number) +def encodeTextMode(plaintext): + """ Text mode checker + + Tests whther SMS could be sent in text mode + + :param text: the text string to encode + + :raise ValueError: if the text string cannot be sent in text mode + + :return: Passed string + :rtype: str + """ + if PYTHON_VERSION >= 3: + plaintext = str(plaintext) + for char in plaintext: + idx = GSM7_BASIC.find(char) + if idx != -1: + continue + elif not discardInvalid: + raise ValueError('Cannot encode char "{0}" inside text mode'.format(char)) + + if len(plaintext) > MAX_MESSAGE_LENGTH[0x00]: + raise ValueError('Massage is too long for inside text mode (maximum {0} characters)'.format(MAX_MESSAGE_LENGTH[0x00])) + + return plaintext + def encodeGsm7(plaintext, discardInvalid=False): """ GSM-7 text encoding algorithm From d421b8822ff26c21685db0552a0fababa5dd558c Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 14:40:06 +0100 Subject: [PATCH 083/133] Unittest: Fix SMS-related unit tests --- test/fakemodems.py | 3 ++- test/test_modem.py | 56 +++++++++++++++++++++++++++++++++------------- 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/test/fakemodems.py b/test/fakemodems.py index efd9575..8be638e 100644 --- a/test/fakemodems.py +++ b/test/fakemodems.py @@ -99,7 +99,8 @@ def __init__(self): 'AT+WIND?\r': ['ERROR\r\n'], 'AT+WIND=50\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['ERROR\r\n'], - 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} + 'AT+CSCS=?\r': ['+CSCS: ("GSM",UCS2")\r\n', 'OK\r\n'], + 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} def getResponse(self, cmd): if not self._pinLock and cmd == 'AT+CLCC\r': diff --git a/test/test_modem.py b/test/test_modem.py index 8d49897..5c6ab85 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1321,28 +1321,42 @@ def writeCallbackFunc2(data): self.assertEqual(sms.reference, ref, 'Sent SMS reference incorrect. Expected "{0}", got "{1}"'.format(ref, sms.reference)) self.assertEqual(sms.status, gsmmodem.modem.SentSms.ENROUTE, 'Sent SMS status should have been {0} ("ENROUTE"), but is: {1}'.format(gsmmodem.modem.SentSms.ENROUTE, sms.status)) self.modem.close() - + def test_sendSmsPduMode(self): """ Tests sending a SMS messages in PDU mode """ self.initModem(None) self.modem.smsTextMode = False # Set modem to PDU mode + self.modem._smsEncoding = "GSM" self.assertFalse(self.modem.smsTextMode) + self.firstSMS = True for number, message, index, smsTime, smsc, pdu, sms_deliver_tpdu_length, ref, mem in self.tests: self.modem._smsRef = ref calcPdu = gsmmodem.pdu.encodeSmsSubmitPdu(number, message, ref)[0] pduHex = codecs.encode(compat.str(calcPdu.data), 'hex_codec').upper() if PYTHON_VERSION >= 3: pduHex = str(pduHex, 'ascii') - + def writeCallbackFunc(data): + def writeCallbackFuncReadCSCS(data): + self.assertEqual('AT+CSCS=?\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS=?', data)) + self.firstSMS = False + def writeCallbackFunc2(data): + self.assertEqual('AT+CMGS={0}\r'.format(calcPdu.tpduLength), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGS={0}'.format(calcPdu.tpduLength), data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc3 + self.modem.serial.flushResponseSequence = False + self.modem.serial.responseSequence = ['> \r\n', '+CMGS: {0}\r\n'.format(ref), 'OK\r\n'] + + def writeCallbackFunc3(data): self.assertEqual('{0}{1}'.format(pduHex, chr(26)), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('{0}{1}'.format(pduHex, chr(26)), data)) - self.modem.serial.flushResponseSequence = True - self.assertEqual('AT+CMGS={0}\r'.format(calcPdu.tpduLength), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGS={0}'.format(calcPdu.tpduLength), data)) + self.modem.serial.flushResponseSequence = True + + if self.firstSMS: + return writeCallbackFuncReadCSCS(data) + self.assertEqual('AT+CSCS="{0}"\r'.format(self.modem._smsEncoding), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS="{0}"'.format(self.modem._smsEncoding), data)) self.modem.serial.writeCallbackFunc = writeCallbackFunc2 + self.modem.serial.writeCallbackFunc = writeCallbackFunc - self.modem.serial.flushResponseSequence = False - self.modem.serial.responseSequence = ['> \r\n', '+CMGS: {0}\r\n'.format(ref), 'OK\r\n'] sms = self.modem.sendSms(number, message) self.assertIsInstance(sms, gsmmodem.modem.SentSms) self.assertEqual(sms.number, number, 'Sent SMS has invalid number. Expected "{0}", got "{1}"'.format(number, sms.number)) @@ -1351,34 +1365,46 @@ def writeCallbackFunc2(data): self.assertEqual(sms.reference, ref, 'Sent SMS reference incorrect. Expected "{0}", got "{1}"'.format(ref, sms.reference)) self.assertEqual(sms.status, gsmmodem.modem.SentSms.ENROUTE, 'Sent SMS status should have been {0} ("ENROUTE"), but is: {1}'.format(gsmmodem.modem.SentSms.ENROUTE, sms.status)) self.modem.close() - + def test_sendSmsResponseMixedWithUnsolictedMessages(self): """ Tests sending a SMS messages (PDU mode), but with unsolicted messages mixed into the modem responses - the only difference here is that the modem's responseSequence contains unsolicted messages taken from github issue #11 """ self.initModem(None) - self.modem.smsTextMode = False # Set modem to PDU mode + self.modem.smsTextMode = False # Set modem to PDU mode + self.modem._smsEncoding = "GSM" + self.firstSMS = True for number, message, index, smsTime, smsc, pdu, sms_deliver_tpdu_length, ref, mem in self.tests: self.modem._smsRef = ref calcPdu = gsmmodem.pdu.encodeSmsSubmitPdu(number, message, ref)[0] pduHex = codecs.encode(compat.str(calcPdu.data), 'hex_codec').upper() if PYTHON_VERSION >= 3: pduHex = str(pduHex, 'ascii') - + def writeCallbackFunc(data): + def writeCallbackFuncReadCSCS(data): + self.assertEqual('AT+CSCS=?\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS=?', data)) + self.firstSMS = False + def writeCallbackFunc2(data): + self.assertEqual('AT+CMGS={0}\r'.format(calcPdu.tpduLength), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGS={0}'.format(calcPdu.tpduLength), data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc3 + self.modem.serial.flushResponseSequence = True + # Note thee +ZDONR and +ZPASR unsolicted messages in the "response" + self.modem.serial.responseSequence = ['+ZDONR: "METEOR",272,3,"CS_ONLY","ROAM_OFF"\r\n', '+ZPASR: "UMTS"\r\n', '> \r\n'] + + def writeCallbackFunc3(data): self.assertEqual('{0}{1}'.format(pduHex, chr(26)), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('{0}{1}'.format(pduHex, chr(26)), data)) # Note thee +ZDONR and +ZPASR unsolicted messages in the "response" self.modem.serial.responseSequence = ['+ZDONR: "METEOR",272,3,"CS_ONLY","ROAM_OFF"\r\n', '+ZPASR: "UMTS"\r\n', '+ZDONR: "METEOR",272,3,"CS_PS","ROAM_OFF"\r\n', '+ZPASR: "UMTS"\r\n', '+CMGS: {0}\r\n'.format(ref), 'OK\r\n'] - self.assertEqual('AT+CMGS={0}\r'.format(calcPdu.tpduLength), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGS={0}'.format(calcPdu.tpduLength), data)) + + if self.firstSMS: + return writeCallbackFuncReadCSCS(data) + self.assertEqual('AT+CSCS="{0}"\r'.format(self.modem._smsEncoding), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS="{0}"'.format(self.modem._smsEncoding), data)) self.modem.serial.writeCallbackFunc = writeCallbackFunc2 + self.modem.serial.writeCallbackFunc = writeCallbackFunc - self.modem.serial.flushResponseSequence = True - - # Note thee +ZDONR and +ZPASR unsolicted messages in the "response" - self.modem.serial.responseSequence = ['+ZDONR: "METEOR",272,3,"CS_ONLY","ROAM_OFF"\r\n', '+ZPASR: "UMTS"\r\n', '> \r\n'] - sms = self.modem.sendSms(number, message) self.assertIsInstance(sms, gsmmodem.modem.SentSms) self.assertEqual(sms.number, number, 'Sent SMS has invalid number. Expected "{0}", got "{1}"'.format(number, sms.number)) From faeaa46a7a01c7edb9f82a374eb0b0e7d7aaa5fc Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 14:52:27 +0100 Subject: [PATCH 084/133] PDU: Add limited alphabet for text-mode messages --- gsmmodem/pdu.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index dbe1bd4..d358ea7 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -24,6 +24,7 @@ toByteArray = lambda x: bytearray(x.decode('hex')) if type(x) in (str, unicode) else x rawStrToByteArray = bytearray +TEXT_MODE = ('\n\r !\"#%&\'()*+,-./0123456789:;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') # TODO: Check if all of them are supported inside text mode # Tables can be found at: http://en.wikipedia.org/wiki/GSM_03.38#GSM_7_bit_default_alphabet_and_extension_table_of_3GPP_TS_23.038_.2F_GSM_03.38 GSM7_BASIC = ('@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ`¿abcdefghijklmnopqrstuvwxyzäöñüà') GSM7_EXTENDED = {chr(0xFF): 0x0A, @@ -688,10 +689,10 @@ def encodeTextMode(plaintext): if PYTHON_VERSION >= 3: plaintext = str(plaintext) for char in plaintext: - idx = GSM7_BASIC.find(char) + idx = TEXT_MODE.find(char) if idx != -1: continue - elif not discardInvalid: + else: raise ValueError('Cannot encode char "{0}" inside text mode'.format(char)) if len(plaintext) > MAX_MESSAGE_LENGTH[0x00]: From 24711df395844f5567f974b957e501ad0a8552b3 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 15:51:19 +0100 Subject: [PATCH 085/133] Unittest: Fix modem/edgeCases unit tests --- test/test_modem.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_modem.py b/test/test_modem.py index 8d49897..dc4a891 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -680,6 +680,7 @@ def test_cnmiNotSupported(self): global FAKE_MODEM FAKE_MODEM = copy(fakemodems.GenericTestModem()) FAKE_MODEM.responses['AT+CNMI=2,1,0,2\r'] = ['ERROR\r\n'] + FAKE_MODEM.responses['AT+CNMI=2,1,0,1,0\r'] = ['ERROR\r\n'] # This should pass without any problem, and AT+CNMI=2,1,0,2 should at least have been attempted during connect() cnmiWritten = [False] def writeCallbackFunc(data): From 4b67377e9adc7524f6a9e6e2ab81b4f0dada041c Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 16:47:16 +0100 Subject: [PATCH 086/133] Unittest: Fix gsmmodem/GeneralApi unit tests and invalid response inside interactive command recognition procedure --- gsmmodem/modem.py | 5 ++++- test/fakemodems.py | 3 ++- test/test_modem.py | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 3e511bc..8fa2778 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -581,7 +581,10 @@ def supportedCommands(self): continue # Return found commands - return commands + if len(commands) == 0: + return None + else: + return commands @property def smsTextMode(self): diff --git a/test/fakemodems.py b/test/fakemodems.py index efd9575..aac0ab5 100644 --- a/test/fakemodems.py +++ b/test/fakemodems.py @@ -99,7 +99,8 @@ def __init__(self): 'AT+WIND?\r': ['ERROR\r\n'], 'AT+WIND=50\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['ERROR\r\n'], - 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} + 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n'], + 'AT\r': ['OK\r\n']} def getResponse(self, cmd): if not self._pinLock and cmd == 'AT+CLCC\r': diff --git a/test/test_modem.py b/test/test_modem.py index 8d49897..b47f17c 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -195,6 +195,8 @@ def writeCallbackFunc(data): def test_supportedCommands(self): def writeCallbackFunc(data): + if data == 'AT\r': # Handle keep-alive AT command + return self.assertEqual('AT+CLAC\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CLAC\r', data)) self.modem.serial.writeCallbackFunc = writeCallbackFunc tests = ((['+CLAC:&C,D,E,\S,+CGMM,^DTMF\r\n', 'OK\r\n'], ['&C', 'D', 'E', '\S', '+CGMM', '^DTMF']), From e8db39169cd5d2c9e613be068ba17d7b5c29c40a Mon Sep 17 00:00:00 2001 From: Mikhail Knyazev Date: Mon, 6 Mar 2017 20:17:31 +0300 Subject: [PATCH 087/133] Fix alphanumeric address decoding --- gsmmodem/pdu.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index fe9d3cf..e5d43c5 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -533,12 +533,6 @@ def _decodeDataCoding(octet): # We ignore other coding groups return 0 -def nibble2octet(o): - if o % 2: - return o / 2 + 1 - else: - return o / 2 - def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator @@ -554,7 +548,7 @@ def _decodeAddressField(byteIter, smscField=False, log=False): ton = (toa & 0x70) # bits 6,5,4 of type-of-address == type-of-number if ton == 0x50: # Alphanumberic number - addressLen = nibble2octet(addressLen) + addressLen = int(math.ceil(addressLen / 2.0)) septets = unpackSeptets(byteIter, addressLen) addressValue = decodeGsm7(septets) return (addressValue, (addressLen + 2)) @@ -564,7 +558,10 @@ def _decodeAddressField(byteIter, smscField=False, log=False): if smscField: addressValue = decodeSemiOctets(byteIter, addressLen-1) else: - addressLen = nibble2octet(addressLen) + if addressLen % 2: + addressLen = int(addressLen / 2) + 1 + else: + addressLen = int(addressLen / 2) addressValue = decodeSemiOctets(byteIter, addressLen) addressLen += 1 # for the return value, add the toa byte if ton == 0x10: # International number From 75772b716158931b48aa4f3130d68a28219fa3d0 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 20:21:11 +0100 Subject: [PATCH 088/133] Modem/calls: Fix string/unicode to int call type translation --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 3e511bc..214f748 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1646,7 +1646,7 @@ def __init__(self, gsmModem, number, ton, callerName, callId, callType): :param ton: TON (type of number/address) in integer format :param callType: Type of the incoming call (VOICE, FAX, DATA, etc) """ - if type(callType) == str: + if callType in self.CALL_TYPE_MAP: callType = self.CALL_TYPE_MAP[callType] super(IncomingCall, self).__init__(gsmModem, callId, callType, number) # Type attribute of the incoming call From e3bfe98382b5ec9bd3c22e07de1e01315f892c41 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 20:28:22 +0100 Subject: [PATCH 089/133] Unittest: Add responses for command recognition queies inside fake modems --- test/fakemodems.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/fakemodems.py b/test/fakemodems.py index efd9575..b9e04bd 100644 --- a/test/fakemodems.py +++ b/test/fakemodems.py @@ -95,9 +95,12 @@ def __init__(self): self._callId = None self.commandsNoPinRequired = ['ATZ\r', 'ATE0\r', 'AT+CFUN?\r', 'AT+CFUN=1\r', 'AT+CMEE=1\r'] self.responses = {'AT+CPMS=?\r': ['+CPMS: ("ME","MT","SM","SR"),("ME","MT","SM","SR"),("ME","MT","SM","SR")\r\n', 'OK\r\n'], + 'AT+CLAC=?\r': ['ERROR\r\n'], 'AT+CLAC\r': ['ERROR\r\n'], + 'AT+WIND=?\r': ['ERROR\r\n'], 'AT+WIND?\r': ['ERROR\r\n'], 'AT+WIND=50\r': ['ERROR\r\n'], + 'AT+ZPAS=?\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['ERROR\r\n'], 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} @@ -379,7 +382,9 @@ def __init__(self): 'AT+CGMR\r': ['M6280_V1.0.0 M6280_V1.0.0 1 [Sep 4 2008 12:00:00]\r\n', 'OK\r\n'], 'AT+CIMI\r': ['111111111111111\r\n', 'OK\r\n'], 'AT+CGSN\r': ['111111111111111\r\n', 'OK\r\n'], + 'AT+CLAC=?\r': ['ERROR\r\n'], 'AT+CLAC\r': ['ERROR\r\n'], + 'AT+WIND=?\r': ['ERROR\r\n'], 'AT+WIND?\r': ['ERROR\r\n'], 'AT+WIND=50\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['+BEARTYPE: "UMTS","CS_PS"\r\n', 'OK\r\n'], @@ -541,10 +546,14 @@ def __init__(self): 'AT+CGMR\r': ['V ICPR72_08w44.1\r\n', '24-11-08\r\n', 'RM-348\r\n', '(c) Nokia\r\n', '11.049\r\n', 'OK\r\n'], 'AT+CIMI\r': ['111111111111111\r\n', 'OK\r\n'], 'AT+CGSN\r': ['111111111111111\r\n', 'OK\r\n'], + 'AT+CNMI=?\r': ['ERROR\r\n'], # SMS reading and notifications not supported 'AT+CNMI=2,1,0,2\r': ['ERROR\r\n'], # SMS reading and notifications not supported + 'AT+CLAC=?\r': ['ERROR\r\n'], 'AT+CLAC\r': ['ERROR\r\n'], + 'AT+WIND=?\r': ['ERROR\r\n'], 'AT+WIND?\r': ['ERROR\r\n'], 'AT+WIND=50\r': ['ERROR\r\n'], + 'AT+ZPAS=?\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['ERROR\r\n'], 'AT+CPMS="SM","SM","SR"\r': ['ERROR\r\n'], 'AT+CPMS=?\r': ['+CPMS: (),(),()\r\n', 'OK\r\n'], # not supported From a33ae738b58a3ff359d190f1090f0516fdf7fb6e Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 20:36:25 +0100 Subject: [PATCH 090/133] Unittest: support iterative calling --- test/test_modem.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_modem.py b/test/test_modem.py index 8d49897..b0863ca 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1220,12 +1220,14 @@ def testDtmf(self): tests = (('3', 'AT{0}3\r'.format(fakeModem.dtmfCommandBase.format(cid=call.id))), ('1234', 'AT{0}1;{0}2;{0}3;{0}4\r'.format(fakeModem.dtmfCommandBase.format(cid=call.id))), ('#0*', 'AT{0}#;{0}0;{0}*\r'.format(fakeModem.dtmfCommandBase.format(cid=call.id)))) - + for tones, expectedCommand in tests: def writeCallbackFunc(data): + expectedCommand = 'AT{0}{1}\r'.format(fakeModem.dtmfCommandBase.format(cid=call.id), tones[self.currentTone]) + self.currentTone += 1; self.assertEqual(expectedCommand, data, 'Invalid data written to modem for tones: "{0}"; expected "{1}", got: "{2}". Modem: {3}'.format(tones, expectedCommand[:-1].format(cid=self.id), data[:-1] if data[-1] == '\r' else data, fakeModem)) self.modem.serial.writeCallbackFunc = writeCallbackFunc - call.sendDtmfTone(tones) + self.currentTone = 0; # Now attempt to send DTMF tones in an inactive call self.modem.serial.writeCallbackFunc = None From e500f311c21264ac60caf3f5f7f7ef55e111d2ad Mon Sep 17 00:00:00 2001 From: babca Date: Mon, 6 Mar 2017 22:01:25 +0100 Subject: [PATCH 091/133] Better alphanumeric address decoding fix --- gsmmodem/pdu.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index d358ea7..4b0ab43 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -547,11 +547,8 @@ def _decodeDataCoding(octet): # We ignore other coding groups return 0 -def nibble2octet(o): - if o % 2: - return o / 2 + 1 - else: - return o / 2 +def nibble2octet(addressLen): + addressLen = int((addressLen + 1) / 2) def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator From d13b4a928fade76f045b8f13e761903dbdbbbdaa Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Mon, 6 Mar 2017 22:16:37 +0100 Subject: [PATCH 092/133] Modem: add handler for modems which does not support AT+CSCS command --- gsmmodem/modem.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 0213479..486415a 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -609,6 +609,10 @@ def smsSupportedEncoding(self): if self._commands == None: self._commands = self.supportedCommands + if self._commands == None: + self._smsSupportedEncodingNames = [] + return self._smsSupportedEncodingNames + if not '+CSCS' in self._commands: self._smsSupportedEncodingNames = [] return self._smsSupportedEncodingNames @@ -643,6 +647,9 @@ def smsEncoding(self): if self._commands == None: self._commands = self.supportedCommands + if self._commands == None: + return self._smsEncoding + if '+CSCS' in self._commands: response = self.write('AT+CSCS?') @@ -668,6 +675,9 @@ def smsEncoding(self, encoding): if self._commands == None: self._commands = self.supportedCommands + if self._commands == None: + return False + if not '+CSCS' in self._commands: return False From 00a2525a9c50427171873d8172f8f0fec6ec7ab8 Mon Sep 17 00:00:00 2001 From: babca Date: Mon, 6 Mar 2017 22:21:06 +0100 Subject: [PATCH 093/133] import math removed math module not used anymore - removed --- gsmmodem/pdu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 4b0ab43..389f8c3 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -4,7 +4,7 @@ from __future__ import unicode_literals -import sys, codecs, math +import sys, codecs from datetime import datetime, timedelta, tzinfo from copy import copy from .exceptions import EncodingError From fe7acc7fdce101a91364d5ee1ee88382abbbc5f4 Mon Sep 17 00:00:00 2001 From: babca Date: Mon, 6 Mar 2017 22:55:30 +0100 Subject: [PATCH 094/133] mistake in nibble2octet --- gsmmodem/pdu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 389f8c3..bda121d 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -548,7 +548,7 @@ def _decodeDataCoding(octet): return 0 def nibble2octet(addressLen): - addressLen = int((addressLen + 1) / 2) + return int((addressLen + 1) / 2) def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator From e1852344d65e094223d28b0ff05b4550a16446a9 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 01:58:56 +0100 Subject: [PATCH 095/133] PDU: fix invalid decoding of large time zone values. Resolves #15. --- gsmmodem/pdu.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index bda121d..6a9e183 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -68,10 +68,17 @@ def __init__(self, pduOffsetStr=None): def _setPduOffsetStr(self, pduOffsetStr): # See if the timezone difference is positive/negative by checking MSB of first semi-octet tzHexVal = int(pduOffsetStr, 16) + # In order to read time zone 'minute' shift: + # - Remove MSB (sign) + # - Read HEX value as decimal + # - Multiply by 15 + # See: https://en.wikipedia.org/wiki/GSM_03.40#Time_Format + tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 + if tzHexVal & 0x80 == 0: # positive - self._offset = timedelta(minutes=(int(pduOffsetStr, 16) * 15)) + self._offset = timedelta(minutes=(tzOffsetMinutes)) else: # negative - self._offset = timedelta(minutes=(int('{0:0>2X}'.format(tzHexVal & 0x7F)) * -15)) + self._offset = timedelta(minutes=(-tzOffsetMinutes)) def utcoffset(self, dt): return self._offset From a55822a4872d66570ace23a304860ee425cbdb88 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 02:30:40 +0100 Subject: [PATCH 096/133] PDU: possible fix for invalid decoding of large time zone values. --- gsmmodem/pdu.py | 7 ++++++- test/test_modem.py | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 6a9e183..712a2c3 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -73,7 +73,12 @@ def _setPduOffsetStr(self, pduOffsetStr): # - Read HEX value as decimal # - Multiply by 15 # See: https://en.wikipedia.org/wiki/GSM_03.40#Time_Format - tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 + try: + tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 + except: + # Possible fix for #15 + tzHexVal = (tzHexVal & 0x0F)*0x10 + (tzHexVal & 0x0F) / 0x10 + tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 if tzHexVal & 0x80 == 0: # positive self._offset = timedelta(minutes=(tzOffsetMinutes)) diff --git a/test/test_modem.py b/test/test_modem.py index 4de1825..f12684c 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -2070,6 +2070,32 @@ def writeCallbackFunc3(data): time.sleep(0.1) self.modem.close() + def test_receiveSmsPduMode_zeroLengthSmscAndHugeTimeZoneValue(self): + """ Test receiving PDU-mode SMS using data captured from failed operations/bug reports """ + modemResponse = ['+CMGR: 1,,26\r\n', '0006230E9126983575169498610103409544C26101034095448200\r\n', 'OK\r\n'] + + callbackInfo = [False, '', '', -1, None, '', None] + def smsCallbackFunc1(sms): + try: + self.assertIsInstance(sms, gsmmodem.modem.StatusReport) + self.assertEqual(sms.status, gsmmodem.modem.Sms.STATUS_RECEIVED_READ) + finally: + callbackInfo[0] = True + + def writeCallback1(data): + if data.startswith('AT+CMGR'): + self.modem.serial.flushResponseSequence = True + self.modem.serial.responseSequence = modemResponse + + self.initModem(smsStatusReportCallback=smsCallbackFunc1) + # Fake a "new message" notification + self.modem.serial.writeCallbackFunc = writeCallback1 + self.modem.serial.flushResponseSequence = True + self.modem.serial.responseSequence = ['+CDSI: "SM",1\r\n'] + # Wait for the handler function to finish + while callbackInfo[0] == False: + time.sleep(0.1) + From 6de5cba20e62faee994620ed35674aa7c7c24801 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 04:25:38 +0100 Subject: [PATCH 097/133] PDU: Use integer type explicitly inisde time zone conversion --- gsmmodem/pdu.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 712a2c3..bc563b8 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -77,7 +77,7 @@ def _setPduOffsetStr(self, pduOffsetStr): tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 except: # Possible fix for #15 - tzHexVal = (tzHexVal & 0x0F)*0x10 + (tzHexVal & 0x0F) / 0x10 + tzHexVal = int((tzHexVal & 0x0F) * 0x10) + int((tzHexVal & 0x0F) / 0x10) tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 if tzHexVal & 0x80 == 0: # positive @@ -781,7 +781,7 @@ def divideTextGsm7(plainText): chunkByteSize = 0 if PYTHON_VERSION >= 3: - plaintext = str(plaintext) + plainText = str(plainText) while plainStopPtr < len(plainText): char = plainText[plainStopPtr] idx = GSM7_BASIC.find(char) From 8903fb24c4a9020a579389038d3d10f505eb9dbd Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 04:26:58 +0100 Subject: [PATCH 098/133] Unittest: Python3+ compatibility --- gsmmodem/modem.py | 2 +- gsmmodem/serial_comms.py | 2 +- test/fakemodems.py | 18 ++++++++++++++++++ test/test_modem.py | 2 ++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e052e1c..10f4bed 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1243,7 +1243,7 @@ def _handleIncomingCall(self, lines): # Re-enable extended format of incoming indication (optional) self.write('AT+CRC=1') except CommandError: - self.log.warn('Extended incoming call indication format changed externally; unable to re-enable') + self.log.warning('Extended incoming call indication format changed externally; unable to re-enable') self._extendedIncomingCallIndication = False else: callType = None diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 7706f43..22e722c 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -95,7 +95,7 @@ def _readLoop(self): rxBuffer = bytearray() while self.alive: data = self.serial.read(1) - if data != b'': # check for timeout + if len(data) != 0: # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(ord(data)) if rxBuffer[-readTermLen:] == readTermSeq: diff --git a/test/fakemodems.py b/test/fakemodems.py index cc25974..30e4f2d 100644 --- a/test/fakemodems.py +++ b/test/fakemodems.py @@ -21,6 +21,9 @@ def __init__(self): self.dtmfCommandBase = '+VTS=' def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + if self.deviceBusyErrorCounter > 0: self.deviceBusyErrorCounter -= 1 return ['+CME ERROR: 515\r\n'] @@ -107,6 +110,9 @@ def __init__(self): 'AT\r': ['OK\r\n']} def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + if not self._pinLock and cmd == 'AT+CLCC\r': if self._callNumber: if self._callState == 0: @@ -171,6 +177,9 @@ def __init__(self): self.commandsNoPinRequired = ['ATZ\r', 'ATE0\r', 'AT+CFUN?\r', 'AT+CFUN=1\r', 'AT+CMEE=1\r'] def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + if cmd == 'AT+CFUN=1\r': self.deviceBusyErrorCounter = 2 # This modem takes quite a while to recover from this return ['OK\r\n'] @@ -338,6 +347,9 @@ def __init__(self): self.dtmfCommandBase = '^DTMF={cid},' def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + # Device defaults to ^USSDMODE == 1 if cmd.startswith('AT+CUSD=1') and self._ussdMode == 1: return ['ERROR\r\n'] @@ -395,6 +407,9 @@ def __init__(self): 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + if not self._pinLock: if cmd.startswith('AT+CSMP='): # Clear the SMSC number (this behaviour was reported in issue #8 on github) @@ -486,6 +501,9 @@ def __init__(self): 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n']} def getResponse(self, cmd): + if type(cmd) == bytes: + cmd = cmd.decode() + if not self._pinLock: if cmd.startswith('AT+CSMP='): # Clear the SMSC number (this behaviour was reported in issue #8 on github) diff --git a/test/test_modem.py b/test/test_modem.py index f12684c..2a3f50f 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -101,6 +101,8 @@ def _setupReadValue(self, command): def write(self, data): if self.writeCallbackFunc != None: + if type(data) == bytes: + data = data.decode() self.writeCallbackFunc(data) self.writeQueue.append(data) From 925874ac5a8ddcee7196a3fbe718b7357e7f5576 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 12:51:28 +0100 Subject: [PATCH 099/133] Travis: remove --use-mirrors flag (deprecated) --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0edb3b2..6846889 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,9 +6,9 @@ python: - "2.7" install: # Install unittest2 on Python 2.6 - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install --use-mirrors unittest2; fi + - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi # Install coveralls (for coveralls.io integration) - pip install coveralls - - pip install -r requirements.txt --use-mirrors + - pip install -r requirements.txt script: python setup.py coverage after_success: coveralls From a8b449d1369f670f61e35a4c582d9521e00f92cc Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Tue, 7 Mar 2017 15:50:16 +0100 Subject: [PATCH 100/133] PDU: Invalid, non-BCD time zone values --- gsmmodem/pdu.py | 12 +++++----- test/test_modem.py | 59 +++++++++++++++++++++++++++++----------------- 2 files changed, 44 insertions(+), 27 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index bc563b8..a1ed036 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -73,12 +73,12 @@ def _setPduOffsetStr(self, pduOffsetStr): # - Read HEX value as decimal # - Multiply by 15 # See: https://en.wikipedia.org/wiki/GSM_03.40#Time_Format - try: - tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 - except: - # Possible fix for #15 - tzHexVal = int((tzHexVal & 0x0F) * 0x10) + int((tzHexVal & 0x0F) / 0x10) - tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 + + # Possible fix for #15 - convert invalid character to BCD-value + if (tzHexVal & 0x0F) > 0x9: + tzHexVal +=0x06 + + tzOffsetMinutes = int('{0:0>2X}'.format(tzHexVal & 0x7F)) * 15 if tzHexVal & 0x80 == 0: # positive self._offset = timedelta(minutes=(tzOffsetMinutes)) diff --git a/test/test_modem.py b/test/test_modem.py index 2a3f50f..014bc02 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -2072,31 +2072,48 @@ def writeCallbackFunc3(data): time.sleep(0.1) self.modem.close() - def test_receiveSmsPduMode_zeroLengthSmscAndHugeTimeZoneValue(self): + def test_receiveSmsPduMode_invalidPDUsRecordedFromModems(self): """ Test receiving PDU-mode SMS using data captured from failed operations/bug reports """ - modemResponse = ['+CMGR: 1,,26\r\n', '0006230E9126983575169498610103409544C26101034095448200\r\n', 'OK\r\n'] + tests = ((['+CMGR: 1,,26\r\n', '0006230E9126983575169498610103409544C26101034095448200\r\n', 'OK\r\n'], # see: babca/python-gsmmodem#15 + Sms.STATUS_RECEIVED_READ, # message read status + '+62895357614989', # number + 35, # reference + datetime(2016, 10, 30, 4, 59, 44, tzinfo=SimpleOffsetTzInfo(8)), # sentTime + datetime(2016, 10, 30, 4, 59, 44, tzinfo=SimpleOffsetTzInfo(7)), # deliverTime + StatusReport.DELIVERED), # delivery status + ) - callbackInfo = [False, '', '', -1, None, '', None] - def smsCallbackFunc1(sms): - try: - self.assertIsInstance(sms, gsmmodem.modem.StatusReport) - self.assertEqual(sms.status, gsmmodem.modem.Sms.STATUS_RECEIVED_READ) - finally: - callbackInfo[0] = True + callbackDone = [False] - def writeCallback1(data): - if data.startswith('AT+CMGR'): - self.modem.serial.flushResponseSequence = True - self.modem.serial.responseSequence = modemResponse + for modemResponse, msgStatus, number, reference, sentTime, deliverTime, deliveryStatus in tests: + def smsCallbackFunc1(sms): + try: + self.assertIsInstance(sms, gsmmodem.modem.StatusReport) + self.assertEqual(sms.status, msgStatus, 'Status report read status incorrect. Expected: "{0}", got: "{1}"'.format(msgStatus, sms.status)) + self.assertEqual(sms.number, number, 'SMS sender number incorrect. Expected: "{0}", got: "{1}"'.format(number, sms.number)) + self.assertEqual(sms.reference, reference, 'Status report SMS reference number incorrect. Expected: "{0}", got: "{1}"'.format(reference, sms.reference)) + self.assertIsInstance(sms.timeSent, datetime, 'SMS sent time type invalid. Expected: datetime.datetime, got: {0}"'.format(type(sms.timeSent))) + self.assertEqual(sms.timeSent, sentTime, 'SMS sent time incorrect. Expected: "{0}", got: "{1}"'.format(sentTime, sms.timeSent)) + self.assertIsInstance(sms.timeFinalized, datetime, 'SMS finalized time type invalid. Expected: datetime.datetime, got: {0}"'.format(type(sms.timeFinalized))) + self.assertEqual(sms.timeFinalized, deliverTime, 'SMS finalized time incorrect. Expected: "{0}", got: "{1}"'.format(deliverTime, sms.timeFinalized)) + self.assertEqual(sms.deliveryStatus, deliveryStatus, 'SMS delivery status incorrect. Expected: "{0}", got: "{1}"'.format(deliveryStatus, sms.deliveryStatus)) + self.assertEqual(sms.smsc, None, 'This SMS should not have any SMSC information') + finally: + callbackDone[0] = True - self.initModem(smsStatusReportCallback=smsCallbackFunc1) - # Fake a "new message" notification - self.modem.serial.writeCallbackFunc = writeCallback1 - self.modem.serial.flushResponseSequence = True - self.modem.serial.responseSequence = ['+CDSI: "SM",1\r\n'] - # Wait for the handler function to finish - while callbackInfo[0] == False: - time.sleep(0.1) + def writeCallback1(data): + if data.startswith('AT+CMGR'): + self.modem.serial.flushResponseSequence = True + self.modem.serial.responseSequence = modemResponse + + self.initModem(smsStatusReportCallback=smsCallbackFunc1) + # Fake a "new message" notification + self.modem.serial.writeCallbackFunc = writeCallback1 + self.modem.serial.flushResponseSequence = True + self.modem.serial.responseSequence = ['+CDSI: "SM",1\r\n'] + # Wait for the handler function to finish + while callbackDone[0] == False: + time.sleep(0.1) From aae5290439db0082c5a9e6d2b3e93038ad34a0c0 Mon Sep 17 00:00:00 2001 From: babca Date: Tue, 7 Mar 2017 21:04:38 +0100 Subject: [PATCH 101/133] Travis and Coveralls badges fixed + updated to SVG --- README.rst | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 3791a7e..e1db329 100644 --- a/README.rst +++ b/README.rst @@ -82,12 +82,11 @@ http://pyserial.sourceforge.net Testing the package ------------------- -.. |Build Status| image:: https://travis-ci.org/babca/python-gsmmodem.png?branch=master +.. |Build Status| image:: https://travis-ci.org/babca/python-gsmmodem.svg?branch=master .. _Build Status: https://travis-ci.org/babca/python-gsmmodem - -.. |Coverage Status| image:: https://coveralls.io/repos/babca/python-gsmmodem/badge.png?branch=master -.. _Coverage Status: https://coveralls.io/r/faucamp/python-gsmmodem +.. |Coverage Status| image:: https://coveralls.io/repos/github/faucamp/python-gsmmodem/badge.svg?branch=master +.. _Coverage Status: https://coveralls.io/github/faucamp/python-gsmmodem?branch=master |Build Status|_ |Coverage Status|_ From fcec8f8e0667a33766b6895c7b7fe7298dbe48b5 Mon Sep 17 00:00:00 2001 From: babca Date: Tue, 7 Mar 2017 21:35:34 +0100 Subject: [PATCH 102/133] Coverage badge now pointing to babca repo --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index e1db329..91c4e39 100644 --- a/README.rst +++ b/README.rst @@ -85,8 +85,8 @@ Testing the package .. |Build Status| image:: https://travis-ci.org/babca/python-gsmmodem.svg?branch=master .. _Build Status: https://travis-ci.org/babca/python-gsmmodem -.. |Coverage Status| image:: https://coveralls.io/repos/github/faucamp/python-gsmmodem/badge.svg?branch=master -.. _Coverage Status: https://coveralls.io/github/faucamp/python-gsmmodem?branch=master +.. |Coverage Status| image:: https://coveralls.io/repos/github/babca/python-gsmmodem/badge.svg?branch=master +.. _Coverage Status: https://coveralls.io/github/babca/python-gsmmodem?branch=master |Build Status|_ |Coverage Status|_ From 3628336fe897e828ab839fac205ea311b98b8692 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 03:05:52 +0100 Subject: [PATCH 103/133] Unittest: Test if modem will switch to UCS2 in case of unicode character inside message --- test/fakemodems.py | 2 +- test/test_modem.py | 77 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/test/fakemodems.py b/test/fakemodems.py index 30e4f2d..706c5e0 100644 --- a/test/fakemodems.py +++ b/test/fakemodems.py @@ -105,7 +105,7 @@ def __init__(self): 'AT+WIND=50\r': ['ERROR\r\n'], 'AT+ZPAS=?\r': ['ERROR\r\n'], 'AT+ZPAS?\r': ['ERROR\r\n'], - 'AT+CSCS=?\r': ['+CSCS: ("GSM",UCS2")\r\n', 'OK\r\n'], + 'AT+CSCS=?\r': ['+CSCS: ("GSM","UCS2")\r\n', 'OK\r\n'], 'AT+CPIN?\r': ['+CPIN: READY\r\n', 'OK\r\n'], 'AT\r': ['OK\r\n']} diff --git a/test/test_modem.py b/test/test_modem.py index 2a3f50f..4b908e0 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf8 -*- """ Test suite for gsmmodem.modem """ @@ -1304,6 +1305,82 @@ def initModem(self, smsReceivedCallbackFunc): self.modem = gsmmodem.modem.GsmModem('-- PORT IGNORED DURING TESTS --', smsReceivedCallbackFunc=smsReceivedCallbackFunc) self.modem.connect() + def test_sendSmsLeaveTextModeOnInvalidCharacter(self): + """ Tests sending SMS messages in text mode """ + self.initModem(None) + self.modem.smsTextMode = True # Set modem to text mode + self.assertTrue(self.modem.smsTextMode) + # PDUs checked on https://www.diafaan.com/sms-tutorials/gsm-modem-tutorial/online-sms-pdu-decoder/ + tests = (('+0123456789', 'Helló worłd!', + 1, + datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), + '+2782913593', + [('00218E0A91103254769800081C00480065006C006C00C300B300200077006F007200C5008200640021', 40, 142)], + 'SM', + 'UCS2'), + ('+0123456789', 'Hello world!\n Hello world!\n Hello world!\n Hello world!\n Helló worłd!', + 1, + datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), + '+2782913593', + [('00618F0A91103254769800088C0500038F020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A0020002000480065006C006C00C300B300200077006F0072', 152, 143), + ('00618F0A91103254769800080E0500038F020200C5008200640021', 26, 143)], + 'SM', + 'UCS2'),) + + for number, message, index, smsTime, smsc, pdus, mem, encoding in tests: + def writeCallbackFunc(data): + def writeCallbackFunc2(data): + # Second step - get available encoding schemes + self.assertEqual('AT+CSCS=?\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS=?', data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc3 + + def writeCallbackFunc3(data): + # Third step - set encoding + self.assertEqual('AT+CSCS="{0}"\r'.format(encoding), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS="{0}"\r'.format(encoding), data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc4 + + def writeCallbackFunc4(data): + # Fourth step - send PDU length + tpdu_length = pdus[self.currentPdu][1] + ref = pdus[self.currentPdu][2] + self.assertEqual('AT+CMGS={0}\r'.format(tpdu_length), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGS={0}'.format(tpdu_length), data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc5 + self.modem.serial.flushResponseSequence = False + self.modem.serial.responseSequence = ['> \r\n', '+CMGS: {0}\r\n'.format(ref), 'OK\r\n'] + + def writeCallbackFunc5(data): + # Fifth step - send SMS PDU + pdu = pdus[self.currentPdu][0] + self.assertEqual('{0}{1}'.format(pdu, chr(26)), data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('{0}{1}'.format(pdu, chr(26)), data)) + self.modem.serial.flushResponseSequence = True + self.currentPdu += 1 + if len(pdus) > self.currentPdu: + self.modem.serial.writeCallbackFunc = writeCallbackFunc4 + + # First step - change to PDU mode + self.assertEqual('AT+CMGF=0\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGF=0', data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc2 + self.currentPdu = 0 + self.modem._smsRef = pdus[self.currentPdu][2] + + self.modem.serial.writeCallbackFunc = writeCallbackFunc + self.modem.serial.flushResponseSequence = True + sms = self.modem.sendSms(number, message) + self.assertFalse(self.modem.smsTextMode) + self.assertEqual(self.modem._smsEncoding, encoding, 'Modem uses invalid encoding. Expected "{0}", got "{1}"'.format(encoding, self.modem._smsEncoding)) + self.assertIsInstance(sms, gsmmodem.modem.SentSms) + self.assertEqual(sms.number, number, 'Sent SMS has invalid number. Expected "{0}", got "{1}"'.format(number, sms.number)) + self.assertEqual(sms.text, message, 'Sent SMS has invalid text. Expected "{0}", got "{1}"'.format(message, sms.text)) + self.assertIsInstance(sms.reference, int, 'Sent SMS reference type incorrect. Expected "{0}", got "{1}"'.format(int, type(sms.reference))) + ref = pdus[0][2] # All refference numbers should be equal + self.assertEqual(sms.reference, ref, 'Sent SMS reference incorrect. Expected "{0}", got "{1}"'.format(ref, sms.reference)) + self.assertEqual(sms.status, gsmmodem.modem.SentSms.ENROUTE, 'Sent SMS status should have been {0} ("ENROUTE"), but is: {1}'.format(gsmmodem.modem.SentSms.ENROUTE, sms.status)) + # Reset mode and encoding + self.modem._smsTextMode = True # Set modem to text mode + self.modem._smsEncoding = "GSM" # Set encoding to GSM-7 + self.modem._smsSupportedEncodingNames = None # Force modem to ask about possible encoding names + self.modem.close() + def test_sendSmsTextMode(self): """ Tests sending SMS messages in text mode """ self.initModem(None) From ebb49b8cde5ccc089553976d89a8ce010cf1a3c0 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 03:06:27 +0100 Subject: [PATCH 104/133] Modem: use setters/getters to set/unset TextMode --- gsmmodem/modem.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 10f4bed..b86f576 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -328,7 +328,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): self.write('AT+COPS=3,0', parseError=False) # Use long alphanumeric name format # SMS setup - self.write('AT+CMGF={0}'.format(1 if self._smsTextMode else 0)) # Switch to text or PDU mode for SMS messages + self.write('AT+CMGF={0}'.format(1 if self.smsTextMode else 0)) # Switch to text or PDU mode for SMS messages self._compileSmsRegexes() if self._smscNumber != None: self.write('AT+CSCA="{0}"'.format(self._smscNumber)) # Set default SMSC number @@ -711,7 +711,7 @@ def _setSmsMemory(self, readDelete=None, write=None): def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ - if self._smsTextMode: + if self.smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile('^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile('^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') @@ -879,13 +879,13 @@ def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeou """ # Check input text to select appropriate mode (text or PDU) - if self._smsTextMode: + if self.smsTextMode: try: encodedText = encodeTextMode(text) except ValueError: - self._smsTextMode = False + self.smsTextMode = False - if self._smsTextMode: + if self.smsTextMode: # Send SMS via AT commands self.write('AT+CMGS="{0}"'.format(destination), timeout=5, expectedResponseTermSeq='> ') result = lineStartingWith('+CMGS:', self.write(text, timeout=35, writeTerm=CTRLZ)) @@ -1085,7 +1085,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self._setSmsMemory(readDelete=memory) messages = [] delMessages = set() - if self._smsTextMode: + if self.smsTextMode: cmglRegex= re.compile('^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') for key, val in dictItemsIter(Sms.TEXT_MODE_STATUS_MAP): if status == val: @@ -1410,7 +1410,7 @@ def readStoredSms(self, index, memory=None): self._setSmsMemory(readDelete=memory) msgData = self.write('AT+CMGR={0}'.format(index)) # Parse meta information - if self._smsTextMode: + if self.smsTextMode: cmgrMatch = self.CMGR_SM_DELIVER_REGEX_TEXT.match(msgData[0]) if cmgrMatch: msgStatus, number, msgTime = cmgrMatch.groups() From 8f80ae945a5c7ec53d3e52b7b758369276bd46f0 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 03:43:48 +0100 Subject: [PATCH 105/133] PDU: Python 2.* has problem with handling unicode strings without specifying decoding scheme --- gsmmodem/pdu.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index bc563b8..a061764 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -272,6 +272,10 @@ def encodeSmsSubmitPdu(number, text, reference=0, validity=None, smsc=None, requ :return: A list of one or more tuples containing the SMS PDU (as a bytearray, and the length of the TPDU part :rtype: list of tuples """ + if PYTHON_VERSION < 3: + if type(text) == str: + text = text.decode('UTF-8') + tpduFirstOctet = 0x01 # SMS-SUBMIT PDU if validity != None: # Validity period format (TP-VPF) is stored in bits 4,3 of the first TPDU octet From 7bcfbe0ee654bf20790b81d4eed1e96563eb7401 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 03:44:18 +0100 Subject: [PATCH 106/133] Unittest: fix test vectors --- test/test_modem.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_modem.py b/test/test_modem.py index 4b908e0..83717d3 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1315,15 +1315,15 @@ def test_sendSmsLeaveTextModeOnInvalidCharacter(self): 1, datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), '+2782913593', - [('00218E0A91103254769800081C00480065006C006C00C300B300200077006F007200C5008200640021', 40, 142)], + [('00218E0A91103254769800081800480065006C006C00F300200077006F0072014200640021', 36, 142)], 'SM', 'UCS2'), - ('+0123456789', 'Hello world!\n Hello world!\n Hello world!\n Hello world!\n Helló worłd!', + ('+0123456789', 'Hello world!\n Hello world!\n Hello world!\n Hello world!\n-> Helló worłd! ', 1, datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), '+2782913593', - [('00618F0A91103254769800088C0500038F020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A0020002000480065006C006C00C300B300200077006F0072', 152, 143), - ('00618F0A91103254769800080E0500038F020200C5008200640021', 26, 143)], + [('00618F0A91103254769800088C0500038F020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002D003E002000480065006C006C00F300200077006F0072', 152, 143), + ('00618F0A91103254769800080E0500038F02020142006400210020', 26, 143)], 'SM', 'UCS2'),) From 09065e63a26e38eb3e5f6035fea7323143aad36b Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 15:44:03 +0100 Subject: [PATCH 107/133] PDU: Solve problem with unicode strings inside Python 2.7 --- gsmmodem/pdu.py | 6 ++++++ test/test_modem.py | 28 ++++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index a061764..7eb61ba 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -701,6 +701,9 @@ def encodeTextMode(plaintext): """ if PYTHON_VERSION >= 3: plaintext = str(plaintext) + elif type(plaintext) == str: + plaintext = plaintext.decode('UTF-8') + for char in plaintext: idx = TEXT_MODE.find(char) if idx != -1: @@ -730,6 +733,9 @@ def encodeGsm7(plaintext, discardInvalid=False): result = bytearray() if PYTHON_VERSION >= 3: plaintext = str(plaintext) + elif type(plaintext) == str: + plaintext = plaintext.decode('UTF-8') + for char in plaintext: idx = GSM7_BASIC.find(char) if idx != -1: diff --git a/test/test_modem.py b/test/test_modem.py index 83717d3..c5d715a 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1315,15 +1315,30 @@ def test_sendSmsLeaveTextModeOnInvalidCharacter(self): 1, datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), '+2782913593', - [('00218E0A91103254769800081800480065006C006C00F300200077006F0072014200640021', 36, 142)], + [('00218D0A91103254769800081800480065006C006C00F300200077006F0072014200640021', 36, 141)], 'SM', 'UCS2'), + ('+0123456789', 'Hellò wor£d!', + 2, + datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), + '82913593', + [('00218E0A91103254769800000CC8329B8D00DDDFF2003904', 23, 142)], + 'SM', + 'GSM'), + ('+0123456789', '12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345-070 12345-080 12345-090 12345-100 12345-110 12345-120 12345-130 12345-140 12345-150 12345-160-Hellò wor£d!', + 3, + datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), + '82913593', + [('00618F0A9110325476980000A00500038F020162B219ADD682C560A0986C46ABB560321828269BD16A2DD80C068AC966B45A0B46838162B219ADD682D560A0986C46ABB560361828269BD16A2DD80D068AC966B45A0B86838162B219ADD682E560A0986C46ABB562301828269BD16AAD580C068AC966B45A2B26838162B219ADD68ACD60A0986C46ABB562341828269BD16AAD580D068AC966', 152, 143), +('00618F0A91103254769800001A0500038F020268B556CC066B21CB6C3602747FCB03E410', 35, 143)], + 'SM', + 'GSM'), ('+0123456789', 'Hello world!\n Hello world!\n Hello world!\n Hello world!\n-> Helló worłd! ', - 1, + 4, datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), '+2782913593', - [('00618F0A91103254769800088C0500038F020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002D003E002000480065006C006C00F300200077006F0072', 152, 143), - ('00618F0A91103254769800080E0500038F02020142006400210020', 26, 143)], + [('0061900A91103254769800088C05000390020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002D003E002000480065006C006C00F300200077006F0072', 152, 144), + ('0061900A91103254769800080E0500039002020142006400210020', 26, 144)], 'SM', 'UCS2'),) @@ -1348,6 +1363,9 @@ def writeCallbackFunc4(data): self.modem.serial.flushResponseSequence = False self.modem.serial.responseSequence = ['> \r\n', '+CMGS: {0}\r\n'.format(ref), 'OK\r\n'] + def writeCallbackFuncRaiseError(data): + self.assertEqual(self.currentPdu, len(pdus) - 1, 'Invalid data written to modem; expected {0} PDUs, got {1} PDU'.format(len(pdus), self.currentPdu + 1)) + def writeCallbackFunc5(data): # Fifth step - send SMS PDU pdu = pdus[self.currentPdu][0] @@ -1356,6 +1374,8 @@ def writeCallbackFunc5(data): self.currentPdu += 1 if len(pdus) > self.currentPdu: self.modem.serial.writeCallbackFunc = writeCallbackFunc4 + else: + self.modem.serial.writeCallbackFunc = writeCallbackFuncRaiseError # First step - change to PDU mode self.assertEqual('AT+CMGF=0\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CMGF=0', data)) From 91d8d0714e442270ba2f95912dcc2146fc6a8809 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 16:16:01 +0100 Subject: [PATCH 108/133] Unittest: Fall into GSM while user sends too long messages --- gsmmodem/pdu.py | 4 ++-- test/test_modem.py | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/gsmmodem/pdu.py b/gsmmodem/pdu.py index 7eb61ba..1e16450 100644 --- a/gsmmodem/pdu.py +++ b/gsmmodem/pdu.py @@ -712,7 +712,7 @@ def encodeTextMode(plaintext): raise ValueError('Cannot encode char "{0}" inside text mode'.format(char)) if len(plaintext) > MAX_MESSAGE_LENGTH[0x00]: - raise ValueError('Massage is too long for inside text mode (maximum {0} characters)'.format(MAX_MESSAGE_LENGTH[0x00])) + raise ValueError('Message is too long for text mode (maximum {0} characters)'.format(MAX_MESSAGE_LENGTH[0x00])) return plaintext @@ -799,7 +799,7 @@ def divideTextGsm7(plainText): chunkByteSize = chunkByteSize + 1; elif char in GSM7_EXTENDED: chunkByteSize = chunkByteSize + 2; - elif not discardInvalid: + else: raise ValueError('Cannot encode char "{0}" using GSM-7 encoding'.format(char)) plainStopPtr = plainStopPtr + 1 diff --git a/test/test_modem.py b/test/test_modem.py index c5d715a..0f03ae7 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -1340,7 +1340,15 @@ def test_sendSmsLeaveTextModeOnInvalidCharacter(self): [('0061900A91103254769800088C05000390020100480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002000480065006C006C006F00200077006F0072006C00640021000A002D003E002000480065006C006C00F300200077006F0072', 152, 144), ('0061900A91103254769800080E0500039002020142006400210020', 26, 144)], 'SM', - 'UCS2'),) + 'UCS2'), +('+0123456789', '12345-010 12345-020 12345-030 12345-040 12345-050 12345-060 12345-070 12345-080 12345-090 12345-100 12345-110 12345-120 12345-130 12345-140 12345-150 12345-160-Hello word!', + 5, + datetime(2013, 3, 8, 15, 2, 16, tzinfo=SimpleOffsetTzInfo(2)), + '82913593', + [('0061910A9110325476980000A005000391020162B219ADD682C560A0986C46ABB560321828269BD16A2DD80C068AC966B45A0B46838162B219ADD682D560A0986C46ABB560361828269BD16A2DD80D068AC966B45A0B86838162B219ADD682E560A0986C46ABB562301828269BD16AAD580C068AC966B45A2B26838162B219ADD68ACD60A0986C46ABB562341828269BD16AAD580D068AC966', 152, 145), +('0061910A91103254769800001905000391020268B556CC066B21CB6CF61B747FCBC921', 34, 145)], + 'SM', + 'GSM'),) for number, message, index, smsTime, smsc, pdus, mem, encoding in tests: def writeCallbackFunc(data): From ef52f5ba80ed6b1216ac9b121b6201be13670171 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 17:11:14 +0100 Subject: [PATCH 109/133] Unittest: add tests for smsEncoding and smsSupportedEncoding properties --- test/test_modem.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/test/test_modem.py b/test/test_modem.py index 0f03ae7..06831b1 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -361,6 +361,39 @@ def test_errorTypes(self): self.assertEqual(e.type, 'CMS') self.assertEqual(e.code, 310) + def test_smsEncoding(self): + def writeCallbackFunc(data): + if type(data) == bytes: + data = data.decode() + self.assertEqual('AT+CSCS?\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS?', data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc + tests = [('UNKNOWN', '+CSCSERROR'), + ('UCS2', '+CSCS: "UCS2"'), + ('ISO', '+CSCS:"ISO"'), + ('IRA', '+CSCS: "IRA"'), + ('UNKNOWN', '+CSCS: ("GSM", "UCS2")'), + ('UNKNOWN', 'OK'),] + for name, toWrite in tests: + self.modem._smsEncoding = 'UNKNOWN' + self.modem.serial.responseSequence = ['{0}\r\n'.format(toWrite), 'OK\r\n'] + self.assertEqual(name, self.modem.smsEncoding) + + def test_smsSupportedEncoding(self): + def writeCallbackFunc(data): + if type(data) == bytes: + data = data.decode() + self.assertEqual('AT+CSCS=?\r', data, 'Invalid data written to modem; expected "{0}", got: "{1}"'.format('AT+CSCS?', data)) + self.modem.serial.writeCallbackFunc = writeCallbackFunc + tests = [(['GSM'], '+CSCS: ("GSM")'), + (['GSM', 'UCS2'], '+CSCS: ("GSM", "UCS2")'), + (['GSM', 'UCS2'], '+CSCS:("GSM","UCS2")'), + (['GSM', 'UCS2'], '+CSCS: ( "GSM" , "UCS2" )'), + (['GSM'], '+CSCS: ("GSM" "UCS2")'),] + for name, toWrite in tests: + self.modem._smsSupportedEncodingNames = None + self.modem.serial.responseSequence = ['{0}\r\n'.format(toWrite), 'OK\r\n'] + self.assertEqual(name, self.modem.smsSupportedEncoding) + class TestUssd(unittest.TestCase): """ Tests USSD session handling """ From 5bbb43cb5fbed5e4505c155efaaa358babad9240 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 17:11:47 +0100 Subject: [PATCH 110/133] Modem: raise an error if required encoding scheme is not supported --- gsmmodem/modem.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index b86f576..e6aee15 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -676,10 +676,12 @@ def smsEncoding(self, encoding): self._commands = self.supportedCommands if self._commands == None: - return False + if encoding != self._encoding: + raise ValueError('Unable to set SMS encoding (no supported commands)') if not '+CSCS' in self._commands: - return False + if encoding != self._encoding: + raise ValueError('Unable to set SMS encoding (+CSCS command not supported)') # Check if command is available if self._smsSupportedEncodingNames == None: @@ -694,7 +696,7 @@ def smsEncoding(self, encoding): self._smsEncoding = encoding return True - return False + raise ValueError('Unable to set SMS encoding (enocoding {0} not supported)'.format(encoding)) def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ From 51fa489b727b9e352a2d97d47acfeb0757c806d1 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 17:26:53 +0100 Subject: [PATCH 111/133] Modem: do not raise an error if modem does not support +CSCS command and wants to use GSM encoding --- gsmmodem/modem.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e6aee15..9c6cecf 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -623,6 +623,7 @@ def smsSupportedEncoding(self): # Check response length (should be 2 - list of options and command status) if len(response) != 2: self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + self._smsSupportedEncodingNames = [] raise NotImplementedError # Extract encoding names list @@ -636,6 +637,7 @@ def smsSupportedEncoding(self): enc_list = [x.split('"')[1] for x in enc_list] except: self.log.debug('Unhandled +CSCS response: {0}'.format(response)) + self._smsSupportedEncodingNames = [] raise NotImplementedError self._smsSupportedEncodingNames = enc_list @@ -678,10 +680,14 @@ def smsEncoding(self, encoding): if self._commands == None: if encoding != self._encoding: raise ValueError('Unable to set SMS encoding (no supported commands)') + else: + return True if not '+CSCS' in self._commands: if encoding != self._encoding: raise ValueError('Unable to set SMS encoding (+CSCS command not supported)') + else: + return True # Check if command is available if self._smsSupportedEncodingNames == None: @@ -696,7 +702,10 @@ def smsEncoding(self, encoding): self._smsEncoding = encoding return True - raise ValueError('Unable to set SMS encoding (enocoding {0} not supported)'.format(encoding)) + if encoding != self._encoding: + raise ValueError('Unable to set SMS encoding (enocoding {0} not supported)'.format(encoding)) + else: + return True def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ From 77e620c77d8dbd8e34980383a283e3e1f51f6971 Mon Sep 17 00:00:00 2001 From: Tomasz Chyrowicz Date: Wed, 8 Mar 2017 17:39:49 +0100 Subject: [PATCH 112/133] Modem: improved exceptions inside smsEncoding setter --- gsmmodem/modem.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 9c6cecf..7b37dbd 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -671,23 +671,24 @@ def smsEncoding(self): def smsEncoding(self, encoding): """ Set encoding for SMS inside PDU mode. - :return: True if encoding successfully set, otherwise False. """ - + :raise CommandError: if unable to set encoding + :raise ValueError: if encoding is not supported by modem + """ # Check if command is available if self._commands == None: self._commands = self.supportedCommands if self._commands == None: if encoding != self._encoding: - raise ValueError('Unable to set SMS encoding (no supported commands)') + raise CommandError('Unable to set SMS encoding (no supported commands)') else: - return True + return if not '+CSCS' in self._commands: if encoding != self._encoding: - raise ValueError('Unable to set SMS encoding (+CSCS command not supported)') + raise CommandError('Unable to set SMS encoding (+CSCS command not supported)') else: - return True + return # Check if command is available if self._smsSupportedEncodingNames == None: @@ -700,12 +701,12 @@ def smsEncoding(self, encoding): if len(response) == 1: if response[0].lower() == 'ok': self._smsEncoding = encoding - return True + return if encoding != self._encoding: raise ValueError('Unable to set SMS encoding (enocoding {0} not supported)'.format(encoding)) else: - return True + return def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ From 85994a819dab54645c7547766bbd814210de1dcc Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 15 Mar 2017 12:15:21 +0100 Subject: [PATCH 113/133] Add python 3.6 inside TravisCI configuration --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 6846889..4b9d14c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: python python: + - "3.6" - "3.5" - "3.4" - "3.3" From 4ef955e4e800f09fbeebe74a121c653f6b81a3c6 Mon Sep 17 00:00:00 2001 From: babca Date: Wed, 15 Mar 2017 12:47:39 +0100 Subject: [PATCH 114/133] v0.12 release --- ChangeLog | 6 ++++++ README.rst | 2 +- setup.py | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 68209f6..2703c83 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +* Wed Mar 15 2017 babca - 0.12 +– stable release +- unit tests fixed after rapid merging – credits to: tomchy +- python3.6 support added +– message concatenation fixes and more + * Thu Nov 10 2016 babca - 0.11 - added getter for SIM own number - added option for blocking incoming calls (GSMBUSY) diff --git a/README.rst b/README.rst index 91c4e39..8fe8fed 100644 --- a/README.rst +++ b/README.rst @@ -1,4 +1,4 @@ -python-gsmmodem-new v0.11 +python-gsmmodem-new v0.12 ========================= *GSM modem module for Python* diff --git a/setup.py b/setup.py index bc73f7d..abe244a 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ test_command = [sys.executable, '-m', 'unittest', 'discover'] coverage_command = ['coverage', 'run', '-m', 'unittest', 'discover'] -VERSION = "0.11" +VERSION = "0.12" class RunUnitTests(Command): """ run unit tests """ From 014ed002b91135055a656bac92b7a84bc3e7ed9f Mon Sep 17 00:00:00 2001 From: Mikhail Knyazev Date: Tue, 4 Apr 2017 13:54:56 +0300 Subject: [PATCH 115/133] empty write() removed --- gsmmodem/modem.py | 1 - 1 file changed, 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 7b37dbd..989af6d 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -712,7 +712,6 @@ def _setSmsMemory(self, readDelete=None, write=None): """ Set the current SMS memory to use for read/delete/write operations """ # Switch to the correct memory type if required if write != None and write != self._smsMemWrite: - self.write() readDel = readDelete or self._smsMemReadDelete self.write('AT+CPMS="{0}","{1}"'.format(readDel, write)) self._smsMemReadDelete = readDel From 1973c95021f0aefa123b7779a45087267a932fbf Mon Sep 17 00:00:00 2001 From: Ali Momen Sani Date: Wed, 7 Jun 2017 02:24:53 +0430 Subject: [PATCH 116/133] change wrong attribute _encoding to _smsEncoding --- gsmmodem/modem.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 7b37dbd..d075808 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -679,13 +679,13 @@ def smsEncoding(self, encoding): self._commands = self.supportedCommands if self._commands == None: - if encoding != self._encoding: + if encoding != self._smsEncoding: raise CommandError('Unable to set SMS encoding (no supported commands)') else: return if not '+CSCS' in self._commands: - if encoding != self._encoding: + if encoding != self._smsEncoding: raise CommandError('Unable to set SMS encoding (+CSCS command not supported)') else: return @@ -703,7 +703,7 @@ def smsEncoding(self, encoding): self._smsEncoding = encoding return - if encoding != self._encoding: + if encoding != self._smsEncoding: raise ValueError('Unable to set SMS encoding (enocoding {0} not supported)'.format(encoding)) else: return From b5e857157791de40cc037dd008faf02cb3beea94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isidro=20Mart=C3=ADnez?= Date: Tue, 27 Jun 2017 10:54:24 -0500 Subject: [PATCH 117/133] Unnecessary semicolon removed --- examples/sms_handler_demo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/sms_handler_demo.py b/examples/sms_handler_demo.py index bab17bf..1fbfdeb 100755 --- a/examples/sms_handler_demo.py +++ b/examples/sms_handler_demo.py @@ -34,7 +34,7 @@ def main(): try: modem.rxThread.join(2**31) # Specify a (huge) timeout so that it essentially blocks indefinitely, but still receives CTRL+C interrupt signal finally: - modem.close(); + modem.close() if __name__ == '__main__': main() From 81bdf5bb47882d03b30f9a947738d318d9dd944f Mon Sep 17 00:00:00 2001 From: Mikhail Knyazev Date: Fri, 4 Aug 2017 19:03:16 +0300 Subject: [PATCH 118/133] HUAWEI CEND notification format fix --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index c7ba6f7..435593b 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -291,7 +291,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): self.log.info('Loading Huawei call state update table') self._callStatusUpdates = ((re.compile('^\^ORIG:(\d),(\d)$'), self._handleCallInitiated), (re.compile('^\^CONN:(\d),(\d)$'), self._handleCallAnswered), - (re.compile('^\^CEND:(\d),(\d),(\d)+,(\d)+$'), self._handleCallEnded)) + (re.compile('^\^CEND:(\d),(\d+),(\d)+,(\d)+$'), self._handleCallEnded)) self._mustPollCallStatus = False # Huawei modems use ^DTMF to send DTMF tones; use that instead Call.DTMF_COMMAND_BASE = '^DTMF={cid},' From 72b088dde1a219b5bc514f98beaa6d4d036de4f2 Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 10 Nov 2017 12:45:36 +0100 Subject: [PATCH 119/133] smsStatusReportCallback was called twice (fixed) --- gsmmodem/modem.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 435593b..192bae9 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1379,9 +1379,6 @@ def _handleSmsStatusReport(self, notificationLine): except Exception: self.log.error('error in smsStatusReportCallback', exc_info=True) - - self.smsStatusReportCallback(report) - def _handleSmsStatusReportTe(self, length, notificationLine): """ Handler for TE SMS status reports """ self.log.debug('TE SMS status report received') From d5690151e7bbc7cebe0edea18456f664566e0bfc Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 10 Nov 2017 12:46:47 +0100 Subject: [PATCH 120/133] log smsStatusReportCallback errors in _handleSmsStatusReportTe too --- gsmmodem/modem.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 192bae9..8fe65f6 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1399,7 +1399,10 @@ def _handleSmsStatusReportTe(self, length, notificationLine): self._smsStatusReportEvent.set() else: # Nothing is waiting for this report directly - use callback - self.smsStatusReportCallback(report) + try: + self.smsStatusReportCallback(report) + except Exception: + self.log.error('error in smsStatusReportCallback', exc_info=True) def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index From 8bbd76cdcbcfcbeab2d12b1f3d3c519410958986 Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 10 Nov 2017 13:15:18 +0100 Subject: [PATCH 121/133] Callback fixes _placeHolderCallback removed. If there is no callback set, callback variable is None. That means it is now simple to test if the callback is set or not. Some parts of the code were using this method (if someCallbackFunc is None) for a longer period of time anyway. --- gsmmodem/modem.py | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 8fe65f6..14104a1 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -146,11 +146,11 @@ class GsmModem(SerialComms): CDSI_REGEX = re.compile('\+CDSI:\s*"([^"]+)",(\d+)$') CDS_REGEX = re.compile('\+CDS:\s*([0-9]+)"$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallbackFunc=None, requestDelivery=True, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) - self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback - self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback - self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback + self.incomingCallCallbackFunc = incomingCallCallbackFunc + self.smsReceivedCallbackFunc = smsReceivedCallbackFunc + self.smsStatusReportCallbackFunc = smsStatusReportCallbackFunc self.requestDelivery = requestDelivery self.AT_CNMI = AT_CNMI or "2,1,0,2" # Flag indicating whether caller ID for incoming call notification has been set up @@ -377,7 +377,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): del cpmsSupport del cpmsLine - if self._smsReadSupported and (self.smsReceivedCallback or self.smsStatusReportCallback): + if self._smsReadSupported and (self.smsReceivedCallbackFunc or self.smsStatusReportCallbackFunc): try: self.write('AT+CNMI=' + self.AT_CNMI) # Set message notifications except CommandError: @@ -1067,16 +1067,16 @@ def processStoredSms(self, unreadOnly=False): :param unreadOnly: If True, only process unread SMS messages :type unreadOnly: boolean """ - if self.smsReceivedCallback: + if self.smsReceivedCallbackFunc: states = [Sms.STATUS_RECEIVED_UNREAD] if not unreadOnly: states.insert(0, Sms.STATUS_RECEIVED_READ) for msgStatus in states: messages = self.listStoredSms(status=msgStatus, delete=True) for sms in messages: - self.smsReceivedCallback(sms) + self.smsReceivedCallbackFunc(sms) else: - raise ValueError('GsmModem.smsReceivedCallback not set') + raise ValueError('GsmModem.smsReceivedCallbackFunc not set') def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. @@ -1283,7 +1283,9 @@ def _handleIncomingCall(self, lines): callId = len(self.activeCalls) + 1; call = IncomingCall(self, callerNumber, ton, callerName, callId, callType) self.activeCalls[callId] = call - self.incomingCallCallback(call) + + if self.incomingCallCallbackFunc(incomingCallCallback): + self.incomingCallCallbackFunc(call) def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ @@ -1344,16 +1346,16 @@ def _handleCallRejected(self, regexMatch, callId=None): def _handleSmsReceived(self, notificationLine): """ Handler for "new SMS" unsolicited notification line """ self.log.debug('SMS message received') - if self.smsReceivedCallback is not None: + if self.smsReceivedCallbackFunc is not None: cmtiMatch = self.CMTI_REGEX.match(notificationLine) if cmtiMatch: msgMemory = cmtiMatch.group(1) msgIndex = cmtiMatch.group(2) sms = self.readStoredSms(msgIndex, msgMemory) try: - self.smsReceivedCallback(sms) + self.smsReceivedCallbackFunc(sms) except Exception: - self.log.error('error in smsReceivedCallback', exc_info=True) + self.log.error('error in smsReceivedCallbackFunc', exc_info=True) else: self.deleteStoredSms(msgIndex) @@ -1372,12 +1374,12 @@ def _handleSmsStatusReport(self, notificationLine): if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() - elif self.smsStatusReportCallback: + elif self.smsStatusReportCallbackFunc: # Nothing is waiting for this report directly - use callback try: - self.smsStatusReportCallback(report) + self.smsStatusReportCallbackFunc(report) except Exception: - self.log.error('error in smsStatusReportCallback', exc_info=True) + self.log.error('error in smsStatusReportCallbackFunc', exc_info=True) def _handleSmsStatusReportTe(self, length, notificationLine): """ Handler for TE SMS status reports """ @@ -1400,9 +1402,10 @@ def _handleSmsStatusReportTe(self, length, notificationLine): else: # Nothing is waiting for this report directly - use callback try: - self.smsStatusReportCallback(report) + self.smsStatusReportCallbackFunc(report) except Exception: - self.log.error('error in smsStatusReportCallback', exc_info=True) + self.log.error('error in smsStatusReportCallbackFunc', exc_info=True) + def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index @@ -1540,10 +1543,6 @@ def _parseCusdResponse(self, lines): message = cusdMatches[0].group(2) return Ussd(self, sessionActive, message) - def _placeHolderCallback(self, *args): - """ Does nothing """ - self.log.debug('called with args: {0}'.format(args)) - def _pollCallStatus(self, expectedState, callId=None, timeout=None): """ Poll the status of outgoing calls. This is used for modems that do not have a known set of call status update notifications. From bd7c54f3116643ffd68995481f033a424551b88c Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 10 Nov 2017 13:22:50 +0100 Subject: [PATCH 122/133] _placeholderCallback removed from serial_comms.py too This is not a fix and does not add any functionality. I made changes to a way of calling callback so it reflects recent changes in modem.py. --- gsmmodem/serial_comms.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index 22e722c..a7a82ff 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -39,8 +39,8 @@ def __init__(self, port, baudrate=115200, notifyCallbackFunc=None, fatalErrorCal # Reentrant lock for managing concurrent write access to the underlying serial port self._txLock = threading.RLock() - self.notifyCallback = notifyCallbackFunc or self._placeholderCallback - self.fatalErrorCallback = fatalErrorCallbackFunc or self._placeholderCallback + self.notifyCallbackFunc = notifyCallbackFunc + self.fatalErrorCallbackFunc = fatalErrorCallbackFunc self.com_args = args self.com_kwargs = kwargs @@ -78,12 +78,10 @@ def _handleLineRead(self, line, checkForResponseTerm=True): # No more chars on the way for this notification - notify higher-level callback #print 'notification:', self._notification self.log.debug('notification: %s', self._notification) - self.notifyCallback(self._notification) + if self.notifyCallbackFunc: + self.notifyCallbackFunc(self._notification) self._notification = [] - def _placeholderCallback(self, *args, **kwargs): - """ Placeholder callback function (does nothing) """ - def _readLoop(self): """ Read thread main loop @@ -119,7 +117,8 @@ def _readLoop(self): except Exception: #pragma: no cover pass # Notify the fatal error handler - self.fatalErrorCallback(e) + if self.fatalErrorCallbackFunc: + self.fatalErrorCallbackFunc(e) def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=None): data = data.encode() From 5f8b04773b03134d1495be644166f5da61123daf Mon Sep 17 00:00:00 2001 From: babca Date: Fri, 10 Nov 2017 13:50:05 +0100 Subject: [PATCH 123/133] condition bugfix/typo --- gsmmodem/modem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 14104a1..b0a9b78 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -1284,7 +1284,7 @@ def _handleIncomingCall(self, lines): call = IncomingCall(self, callerNumber, ton, callerName, callId, callType) self.activeCalls[callId] = call - if self.incomingCallCallbackFunc(incomingCallCallback): + if self.incomingCallCallbackFunc: self.incomingCallCallbackFunc(call) def _handleCallInitiated(self, regexMatch, callId=None, callType=1): From 0d0431446f998b6c94ae19ac6b04b016b6ad458f Mon Sep 17 00:00:00 2001 From: babca Date: Sat, 18 Nov 2017 13:35:05 +0100 Subject: [PATCH 124/133] reverted changes in callbacks, needs to be redone --- gsmmodem/modem.py | 41 ++++++++++++++++++++-------------------- gsmmodem/serial_comms.py | 13 +++++++------ 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index b0a9b78..8fe65f6 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -146,11 +146,11 @@ class GsmModem(SerialComms): CDSI_REGEX = re.compile('\+CDSI:\s*"([^"]+)",(\d+)$') CDS_REGEX = re.compile('\+CDS:\s*([0-9]+)"$') - def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallbackFunc=None, requestDelivery=True, AT_CNMI="", *a, **kw): + def __init__(self, port, baudrate=115200, incomingCallCallbackFunc=None, smsReceivedCallbackFunc=None, smsStatusReportCallback=None, requestDelivery=True, AT_CNMI="", *a, **kw): super(GsmModem, self).__init__(port, baudrate, notifyCallbackFunc=self._handleModemNotification, *a, **kw) - self.incomingCallCallbackFunc = incomingCallCallbackFunc - self.smsReceivedCallbackFunc = smsReceivedCallbackFunc - self.smsStatusReportCallbackFunc = smsStatusReportCallbackFunc + self.incomingCallCallback = incomingCallCallbackFunc or self._placeholderCallback + self.smsReceivedCallback = smsReceivedCallbackFunc or self._placeholderCallback + self.smsStatusReportCallback = smsStatusReportCallback or self._placeholderCallback self.requestDelivery = requestDelivery self.AT_CNMI = AT_CNMI or "2,1,0,2" # Flag indicating whether caller ID for incoming call notification has been set up @@ -377,7 +377,7 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): del cpmsSupport del cpmsLine - if self._smsReadSupported and (self.smsReceivedCallbackFunc or self.smsStatusReportCallbackFunc): + if self._smsReadSupported and (self.smsReceivedCallback or self.smsStatusReportCallback): try: self.write('AT+CNMI=' + self.AT_CNMI) # Set message notifications except CommandError: @@ -1067,16 +1067,16 @@ def processStoredSms(self, unreadOnly=False): :param unreadOnly: If True, only process unread SMS messages :type unreadOnly: boolean """ - if self.smsReceivedCallbackFunc: + if self.smsReceivedCallback: states = [Sms.STATUS_RECEIVED_UNREAD] if not unreadOnly: states.insert(0, Sms.STATUS_RECEIVED_READ) for msgStatus in states: messages = self.listStoredSms(status=msgStatus, delete=True) for sms in messages: - self.smsReceivedCallbackFunc(sms) + self.smsReceivedCallback(sms) else: - raise ValueError('GsmModem.smsReceivedCallbackFunc not set') + raise ValueError('GsmModem.smsReceivedCallback not set') def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. @@ -1283,9 +1283,7 @@ def _handleIncomingCall(self, lines): callId = len(self.activeCalls) + 1; call = IncomingCall(self, callerNumber, ton, callerName, callId, callType) self.activeCalls[callId] = call - - if self.incomingCallCallbackFunc: - self.incomingCallCallbackFunc(call) + self.incomingCallCallback(call) def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ @@ -1346,16 +1344,16 @@ def _handleCallRejected(self, regexMatch, callId=None): def _handleSmsReceived(self, notificationLine): """ Handler for "new SMS" unsolicited notification line """ self.log.debug('SMS message received') - if self.smsReceivedCallbackFunc is not None: + if self.smsReceivedCallback is not None: cmtiMatch = self.CMTI_REGEX.match(notificationLine) if cmtiMatch: msgMemory = cmtiMatch.group(1) msgIndex = cmtiMatch.group(2) sms = self.readStoredSms(msgIndex, msgMemory) try: - self.smsReceivedCallbackFunc(sms) + self.smsReceivedCallback(sms) except Exception: - self.log.error('error in smsReceivedCallbackFunc', exc_info=True) + self.log.error('error in smsReceivedCallback', exc_info=True) else: self.deleteStoredSms(msgIndex) @@ -1374,12 +1372,12 @@ def _handleSmsStatusReport(self, notificationLine): if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() - elif self.smsStatusReportCallbackFunc: + elif self.smsStatusReportCallback: # Nothing is waiting for this report directly - use callback try: - self.smsStatusReportCallbackFunc(report) + self.smsStatusReportCallback(report) except Exception: - self.log.error('error in smsStatusReportCallbackFunc', exc_info=True) + self.log.error('error in smsStatusReportCallback', exc_info=True) def _handleSmsStatusReportTe(self, length, notificationLine): """ Handler for TE SMS status reports """ @@ -1402,10 +1400,9 @@ def _handleSmsStatusReportTe(self, length, notificationLine): else: # Nothing is waiting for this report directly - use callback try: - self.smsStatusReportCallbackFunc(report) + self.smsStatusReportCallback(report) except Exception: - self.log.error('error in smsStatusReportCallbackFunc', exc_info=True) - + self.log.error('error in smsStatusReportCallback', exc_info=True) def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index @@ -1543,6 +1540,10 @@ def _parseCusdResponse(self, lines): message = cusdMatches[0].group(2) return Ussd(self, sessionActive, message) + def _placeHolderCallback(self, *args): + """ Does nothing """ + self.log.debug('called with args: {0}'.format(args)) + def _pollCallStatus(self, expectedState, callId=None, timeout=None): """ Poll the status of outgoing calls. This is used for modems that do not have a known set of call status update notifications. diff --git a/gsmmodem/serial_comms.py b/gsmmodem/serial_comms.py index a7a82ff..22e722c 100644 --- a/gsmmodem/serial_comms.py +++ b/gsmmodem/serial_comms.py @@ -39,8 +39,8 @@ def __init__(self, port, baudrate=115200, notifyCallbackFunc=None, fatalErrorCal # Reentrant lock for managing concurrent write access to the underlying serial port self._txLock = threading.RLock() - self.notifyCallbackFunc = notifyCallbackFunc - self.fatalErrorCallbackFunc = fatalErrorCallbackFunc + self.notifyCallback = notifyCallbackFunc or self._placeholderCallback + self.fatalErrorCallback = fatalErrorCallbackFunc or self._placeholderCallback self.com_args = args self.com_kwargs = kwargs @@ -78,10 +78,12 @@ def _handleLineRead(self, line, checkForResponseTerm=True): # No more chars on the way for this notification - notify higher-level callback #print 'notification:', self._notification self.log.debug('notification: %s', self._notification) - if self.notifyCallbackFunc: - self.notifyCallbackFunc(self._notification) + self.notifyCallback(self._notification) self._notification = [] + def _placeholderCallback(self, *args, **kwargs): + """ Placeholder callback function (does nothing) """ + def _readLoop(self): """ Read thread main loop @@ -117,8 +119,7 @@ def _readLoop(self): except Exception: #pragma: no cover pass # Notify the fatal error handler - if self.fatalErrorCallbackFunc: - self.fatalErrorCallbackFunc(e) + self.fatalErrorCallback(e) def write(self, data, waitForResponse=True, timeout=5, expectedResponseTermSeq=None): data = data.encode() From 5bccf975e9169f0aeaafac1c9e3dcd3e6029b761 Mon Sep 17 00:00:00 2001 From: malanovo <34949989+malanovo@users.noreply.github.com> Date: Tue, 16 Jan 2018 14:09:21 -0800 Subject: [PATCH 125/133] Update modem.py Fix for issue #51, which was also affecting my environment. This modifies the ReceivedSms class so that there's access to the message index, which makes it possible to call things like deleteStoredSms without having to guess at the index. --- gsmmodem/modem.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 8fe65f6..f4ebce6 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -54,12 +54,13 @@ def __init__(self, number, text, smsc=None): class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - def __init__(self, gsmModem, status, number, time, text, smsc=None, udh=[]): + def __init__(self, gsmModem, status, number, time, text, smsc=None, udh=[], index=None): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time self.udh = udh + self.index = index def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ @@ -1114,7 +1115,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): if msgIndex != None and len(msgLines) > 0: msgText = '\n'.join(msgLines) msgLines = [] - messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText)) + messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText, None, [], msgIndex)) delMessages.add(int(msgIndex)) msgIndex, msgStatus, number, msgTime = cmglMatch.groups() msgLines = [] @@ -1124,7 +1125,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): if msgIndex != None and len(msgLines) > 0: msgText = '\n'.join(msgLines) msgLines = [] - messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText)) + messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText, None, [], msgIndex)) delMessages.add(int(msgIndex)) else: cmglRegex = re.compile('^\+CMGL:\s*(\d+),\s*(\d+),.*$') @@ -1148,7 +1149,7 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): # todo: make better fix else: if smsDict['type'] == 'SMS-DELIVER': - sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', [])) + sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', []), msgIndex) elif smsDict['type'] == 'SMS-STATUS-REPORT': sms = StatusReport(self, int(msgStat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: From 3e775b715f50f5e1bf8e93aec6993dd9c71686a5 Mon Sep 17 00:00:00 2001 From: chen Date: Fri, 13 Apr 2018 20:21:57 +0800 Subject: [PATCH 126/133] add long sms concat info support for recived sms add `concat` property for received sms //get Concantion from pdu `smsDict['udh']` --- examples/sms_handler_demo.py | 4 +++- gsmmodem/modem.py | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/examples/sms_handler_demo.py b/examples/sms_handler_demo.py index ef1cb69..5118fd3 100755 --- a/examples/sms_handler_demo.py +++ b/examples/sms_handler_demo.py @@ -18,7 +18,9 @@ from gsmmodem.modem import GsmModem def handleSms(sms): - print(u'== SMS message received ==\nFrom: {0}\nTime: {1}\nMessage:\n{2}\n'.format(sms.number, sms.time, sms.text)) + # long sms Concatenation support: reference, parts, number + concat = sms.concat.__dict__ if sms.concat else {} + print(u'== SMS message received ==\nFrom: {0}\nTime: {1}\nconcat: {2}\nMessage:\n{3}\n'.format(sms.number, sms.time, concat, sms.text)) print('Replying to SMS...') sms.reply(u'SMS received: "{0}{1}"'.format(sms.text[:20], '...' if len(sms.text) > 20 else '')) print('SMS sent.\n') diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..6b7c543 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -7,7 +7,7 @@ from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError -from .pdu import encodeSmsSubmitPdu, decodeSmsPdu +from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, Concatenation from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr from . import compat # For Python 2.6 compatibility @@ -49,11 +49,12 @@ def __init__(self, number, text, smsc=None): class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - def __init__(self, gsmModem, status, number, time, text, smsc=None): + def __init__(self, gsmModem, status, number, time, text, smsc=None, concat=None): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time + self.concat = concat def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ @@ -761,6 +762,15 @@ def processStoredSms(self, unreadOnly=False): for sms in messages: self.smsReceivedCallback(sms) + def _getConcat(self, smsDict): + concat = None + if smsDict.has_key('udh'): + for i in smsDict['udh']: + if isinstance(i, Concatenation): + concat = i + break + return concat + def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. @@ -827,7 +837,8 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self.log.debug('Discarding line from +CMGL response: %s', line) else: if smsDict['type'] == 'SMS-DELIVER': - sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + concat = self._getConcat(smsDict) + sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], concat) elif smsDict['type'] == 'SMS-STATUS-REPORT': sms = StatusReport(self, int(msgStat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: @@ -1066,7 +1077,8 @@ def readStoredSms(self, index, memory=None): pdu = msgData[1] smsDict = decodeSmsPdu(pdu) if smsDict['type'] == 'SMS-DELIVER': - return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + concat = self._getConcat(smsDict) + return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], concat) elif smsDict['type'] == 'SMS-STATUS-REPORT': return StatusReport(self, int(stat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: From 9c7ae29b47acccda264d98b7115e228fab1d9b36 Mon Sep 17 00:00:00 2001 From: chen Date: Fri, 13 Apr 2018 20:21:57 +0800 Subject: [PATCH 127/133] Add long sms concat info for received sms Add `concat` property for `ReceivedSms`: - Get Concantion from pdu `smsDict['udh']` - Update examples/sms_handler_demo.py --- examples/sms_handler_demo.py | 4 +++- gsmmodem/modem.py | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/examples/sms_handler_demo.py b/examples/sms_handler_demo.py index ef1cb69..5118fd3 100755 --- a/examples/sms_handler_demo.py +++ b/examples/sms_handler_demo.py @@ -18,7 +18,9 @@ from gsmmodem.modem import GsmModem def handleSms(sms): - print(u'== SMS message received ==\nFrom: {0}\nTime: {1}\nMessage:\n{2}\n'.format(sms.number, sms.time, sms.text)) + # long sms Concatenation support: reference, parts, number + concat = sms.concat.__dict__ if sms.concat else {} + print(u'== SMS message received ==\nFrom: {0}\nTime: {1}\nconcat: {2}\nMessage:\n{3}\n'.format(sms.number, sms.time, concat, sms.text)) print('Replying to SMS...') sms.reply(u'SMS received: "{0}{1}"'.format(sms.text[:20], '...' if len(sms.text) > 20 else '')) print('SMS sent.\n') diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index e468f34..6b7c543 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -7,7 +7,7 @@ from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError -from .pdu import encodeSmsSubmitPdu, decodeSmsPdu +from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, Concatenation from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr from . import compat # For Python 2.6 compatibility @@ -49,11 +49,12 @@ def __init__(self, number, text, smsc=None): class ReceivedSms(Sms): """ An SMS message that has been received (MT) """ - def __init__(self, gsmModem, status, number, time, text, smsc=None): + def __init__(self, gsmModem, status, number, time, text, smsc=None, concat=None): super(ReceivedSms, self).__init__(number, text, smsc) self._gsmModem = weakref.proxy(gsmModem) self.status = status self.time = time + self.concat = concat def reply(self, message): """ Convenience method that sends a reply SMS to the sender of this message """ @@ -761,6 +762,15 @@ def processStoredSms(self, unreadOnly=False): for sms in messages: self.smsReceivedCallback(sms) + def _getConcat(self, smsDict): + concat = None + if smsDict.has_key('udh'): + for i in smsDict['udh']: + if isinstance(i, Concatenation): + concat = i + break + return concat + def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): """ Returns SMS messages currently stored on the device/SIM card. @@ -827,7 +837,8 @@ def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): self.log.debug('Discarding line from +CMGL response: %s', line) else: if smsDict['type'] == 'SMS-DELIVER': - sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + concat = self._getConcat(smsDict) + sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], concat) elif smsDict['type'] == 'SMS-STATUS-REPORT': sms = StatusReport(self, int(msgStat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: @@ -1066,7 +1077,8 @@ def readStoredSms(self, index, memory=None): pdu = msgData[1] smsDict = decodeSmsPdu(pdu) if smsDict['type'] == 'SMS-DELIVER': - return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc']) + concat = self._getConcat(smsDict) + return ReceivedSms(self, int(stat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], concat) elif smsDict['type'] == 'SMS-STATUS-REPORT': return StatusReport(self, int(stat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status']) else: From 8f594f95ec5a536faf504f6f3fbb90252625cc01 Mon Sep 17 00:00:00 2001 From: Sergey Ninua Date: Thu, 12 Jul 2018 16:18:52 +0300 Subject: [PATCH 128/133] Fix supportedCommands property for Siemens modems --- gsmmodem/modem.py | 4 ++-- gsmmodem/util.py | 14 ++++++++++++++ test/test_modem.py | 2 ++ test/test_util.py | 8 +++++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index 8fe65f6..4dd6b06 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -9,7 +9,7 @@ from .serial_comms import SerialComms from .exceptions import CommandError, InvalidStateException, CmeError, CmsError, InterruptedException, TimeoutException, PinRequiredError, IncorrectPinError, SmscNumberUnknownError from .pdu import encodeSmsSubmitPdu, decodeSmsPdu, encodeGsm7, encodeTextMode -from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr +from .util import SimpleOffsetTzInfo, lineStartingWith, allLinesMatchingPattern, parseTextModeTimeStr, removeAtPrefix #from . import compat # For Python 2.6 compatibility from gsmmodem.util import lineMatching @@ -554,7 +554,7 @@ def supportedCommands(self): commands = commands[6:] # remove the +CLAC: prefix before splitting return commands.split(',') elif len(response) > 2: # Multi-line response - return [cmd.strip() for cmd in response[:-1]] + return [removeAtPrefix(cmd.strip()) for cmd in response[:-1]] else: self.log.debug('Unhandled +CLAC response: {0}'.format(response)) return None diff --git a/gsmmodem/util.py b/gsmmodem/util.py index 1008e5c..6bf7cf3 100644 --- a/gsmmodem/util.py +++ b/gsmmodem/util.py @@ -108,3 +108,17 @@ def allLinesMatchingPattern(pattern, lines): if m: result.append(m) return result + + +def removeAtPrefix(string): + """ Remove AT prefix from a specified string. + + :param string: An original string + :type string: str + + :return: A string with AT prefix removed + :rtype: str + """ + if string.startswith('AT'): + return string[2:] + return string diff --git a/test/test_modem.py b/test/test_modem.py index 2a20b5b..9d9adb5 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -207,6 +207,8 @@ def writeCallbackFunc(data): (['FGH,RTY,UIO\r\n', 'OK\r\n'], ['FGH', 'RTY', 'UIO']), # nasty, but possible # ZTE-like response: do not start with +CLAC, and use multiple lines (['A\r\n', 'BCD\r\n', 'EFGH\r\n', 'OK\r\n'], ['A', 'BCD', 'EFGH']), + # Siemens response: like ZTE but each command has AT prefix + (['AT&F\r\n', 'AT&V\r\n', 'AT&W\r\n', 'AT+CACM\r\n', 'OK\r\n'], ['&F', '&V', '&W', '+CACM']), # Some Huawei modems have a ZTE-like response, but add an addition \r character at the end of each listed command (['Q\r\r\n', 'QWERTY\r\r\n', '^DTMF\r\r\n', 'OK\r\n'], ['Q', 'QWERTY', '^DTMF'])) for responseSequence, expected in tests: diff --git a/test/test_util.py b/test/test_util.py index 7e2b0f8..184e2c5 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -9,7 +9,7 @@ from . import compat # For Python 2.6 compatibility -from gsmmodem.util import allLinesMatchingPattern, lineMatching, lineStartingWith, lineMatchingPattern, SimpleOffsetTzInfo +from gsmmodem.util import allLinesMatchingPattern, lineMatching, lineStartingWith, lineMatchingPattern, SimpleOffsetTzInfo, removeAtPrefix class TestUtil(unittest.TestCase): """ Tests misc utilities from gsmmodem.util """ @@ -74,6 +74,12 @@ def test_SimpleOffsetTzInfo(self): self.assertEqual(tz.dst(None), timedelta(0)) self.assertIsInstance(tz.__repr__(), str) + def test_removeAtPrefix(self): + tests = (('AT+CLAC', '+CLAC'), ('ATZ', 'Z'), ('+CLAC', '+CLAC'), ('Z', 'Z')) + for src, dst in tests: + res = removeAtPrefix(src) + self.assertEqual(res, dst) + if __name__ == "__main__": logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) From 4abcc93e9d43e84062be0132b59633a5dfb8b5bd Mon Sep 17 00:00:00 2001 From: Sergey Ninua Date: Fri, 30 Nov 2018 15:55:57 +0300 Subject: [PATCH 129/133] Fix brand mistake. It's actually Teleofis, not Siemens. Add test docstring. --- test/test_modem.py | 2 +- test/test_util.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_modem.py b/test/test_modem.py index 9d9adb5..420b827 100644 --- a/test/test_modem.py +++ b/test/test_modem.py @@ -207,7 +207,7 @@ def writeCallbackFunc(data): (['FGH,RTY,UIO\r\n', 'OK\r\n'], ['FGH', 'RTY', 'UIO']), # nasty, but possible # ZTE-like response: do not start with +CLAC, and use multiple lines (['A\r\n', 'BCD\r\n', 'EFGH\r\n', 'OK\r\n'], ['A', 'BCD', 'EFGH']), - # Siemens response: like ZTE but each command has AT prefix + # Teleofis response: like ZTE but each command has AT prefix (['AT&F\r\n', 'AT&V\r\n', 'AT&W\r\n', 'AT+CACM\r\n', 'OK\r\n'], ['&F', '&V', '&W', '+CACM']), # Some Huawei modems have a ZTE-like response, but add an addition \r character at the end of each listed command (['Q\r\r\n', 'QWERTY\r\r\n', '^DTMF\r\r\n', 'OK\r\n'], ['Q', 'QWERTY', '^DTMF'])) diff --git a/test/test_util.py b/test/test_util.py index 184e2c5..71ecd65 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -75,6 +75,7 @@ def test_SimpleOffsetTzInfo(self): self.assertIsInstance(tz.__repr__(), str) def test_removeAtPrefix(self): + """ Tests function: removeAtPrefix""" tests = (('AT+CLAC', '+CLAC'), ('ATZ', 'Z'), ('+CLAC', '+CLAC'), ('Z', 'Z')) for src, dst in tests: res = removeAtPrefix(src) From c459b6362c6aa93d56dd07d1041f265c759c25de Mon Sep 17 00:00:00 2001 From: Christoph Klaffl Date: Fri, 15 Feb 2019 09:19:09 +0100 Subject: [PATCH 130/133] fix connect for modem's which don't support AT+DDET command --- gsmmodem/modem.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py index f4ebce6..6b6410e 100644 --- a/gsmmodem/modem.py +++ b/gsmmodem/modem.py @@ -274,7 +274,11 @@ def connect(self, pin=None, waitingForModemToStartInSeconds=0): if callUpdateTableHint == 0: if 'simcom' in self.manufacturer.lower() : #simcom modems support DTMF and don't support AT+CLAC Call.dtmfSupport = True - self.write('AT+DDET=1') # enable detect incoming DTMF + try: + self.write('AT+DDET=1') # enable detect incoming DTMF + except CommandError: + # simcom 7000E for example doesn't support the DDET command + Call.dtmfSupport = False if self.manufacturer.lower() == 'huawei': callUpdateTableHint = 1 # huawei From ae0afb6737f614777c6e9454a006876c598c51c0 Mon Sep 17 00:00:00 2001 From: babca Date: Mon, 11 Mar 2019 10:17:31 +0100 Subject: [PATCH 131/133] README.md very short How to use section added --- README.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.rst b/README.rst index 8fe8fed..2e057e1 100644 --- a/README.rst +++ b/README.rst @@ -28,6 +28,12 @@ Bundled utilities: - **identify-modem.py**: simple utility to identify attached modem. Can also be used to provide debug information used for development of python-gsmmodem. +How to use this package +----------------------- + +Go to `examples/` directory in this repo. + + Requirements ------------ @@ -119,6 +125,7 @@ For true isolation, you may wish to run the above commands within a `virtualenv `_, which will help you manage this development installation. + License information ------------------- From 26faba4e8e38fcd63913f1cb2b76b7e5a7697eea Mon Sep 17 00:00:00 2001 From: babca Date: Mon, 11 Mar 2019 18:18:31 +0100 Subject: [PATCH 132/133] simple FAQ --- README.rst | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.rst b/README.rst index 2e057e1..99aec86 100644 --- a/README.rst +++ b/README.rst @@ -134,3 +134,19 @@ See AUTHORS for all authors and contact information. License: GNU Lesser General Public License, version 3 or later; see COPYING included in this archive for details. + +FAQ +--- + +List all modem ports +~~~~~~~~~~~~~~~~~~~~ + +You can simply list all ttyUSB devices before and after pluging the modem in. + + ls /dev/ttyUSB* + + +Device or resource busy error +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Check running processes. The device could be occupied by another program or another instance of gsmmodem which is still running in the background. Run ``sudo lsof | grep tty``, try to locate the problematic process and ``sudo kill ``. From 2d397769256d6d120e4adb8d1d08c9879234a1cc Mon Sep 17 00:00:00 2001 From: babca Date: Tue, 19 Mar 2019 18:39:13 +0100 Subject: [PATCH 133/133] Updated URL to pyserial library --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 99aec86..66aff24 100644 --- a/README.rst +++ b/README.rst @@ -71,7 +71,7 @@ Download a ``python-gsmmodem-new`` archive from `PyPI python setup.py install Note that ``python-gsmmodem-new`` package relies on ``pyserial`` for serial communications: -http://pyserial.sourceforge.net +https://github.com/pyserial/pyserial Installation of the latest commit from GitHub ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -83,7 +83,7 @@ Clone from GitHub:: python setup.py install Note that ``python-gsmmodem-new`` package relies on ``pyserial`` for serial communications: -http://pyserial.sourceforge.net +https://github.com/pyserial/pyserial Testing the package -------------------