signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def _handleCtrlZ(self): | if self._typingSms:<EOL><INDENT>self.serial.write('<STR_LIT>'.join(self.inputBuffer))<EOL>self.serial.write(self.CTRL_Z_CHARACTER)<EOL>self._typingSms = False<EOL>self.inputBuffer = []<EOL>self.cursorPos = <NUM_LIT:0><EOL>sys.stdout.write('<STR_LIT:\n>')<EOL>self._refreshInputPrompt()<EOL><DEDENT> | Handler for CTRL+Z keypresses | f2337:c1:m7 |
def _handleEsc(self): | if self._typingSms:<EOL><INDENT>self.serial.write(self.ESC_CHARACTER)<EOL>self._typingSms = False<EOL>self.inputBuffer = []<EOL>self.cursorPos = <NUM_LIT:0><EOL><DEDENT> | Handler for CTRL+Z keypresses | f2337:c1:m8 |
def _exit(self): | self._removeInputPrompt()<EOL>print(self._color(self.COLOR_YELLOW, '<STR_LIT>')) <EOL>self.stop()<EOL> | Shuts down the terminal (and app) | f2337:c1:m9 |
def _cursorLeft(self): | if self.cursorPos > <NUM_LIT:0>:<EOL><INDENT>self.cursorPos -= <NUM_LIT:1><EOL>sys.stdout.write(console.CURSOR_LEFT)<EOL>sys.stdout.flush()<EOL><DEDENT> | Handles "cursor left" events | f2337:c1:m10 |
def _cursorRight(self): | if self.cursorPos < len(self.inputBuffer):<EOL><INDENT>self.cursorPos += <NUM_LIT:1><EOL>sys.stdout.write(console.CURSOR_RIGHT)<EOL>sys.stdout.flush()<EOL><DEDENT> | Handles "cursor right" events | f2337:c1:m11 |
def _cursorUp(self): | if self.historyPos > <NUM_LIT:0>:<EOL><INDENT>self.historyPos -= <NUM_LIT:1><EOL>clearLen = len(self.inputBuffer)<EOL>self.inputBuffer = list(self.history[self.historyPos])<EOL>self.cursorPos = len(self.inputBuffer)<EOL>self._refreshInputPrompt(clearLen)<EOL><DEDENT> | Handles "cursor up" events | f2337:c1:m12 |
def _cursorDown(self): | if self.historyPos < len(self.history)-<NUM_LIT:1>:<EOL><INDENT>clearLen = len(self.inputBuffer)<EOL>self.historyPos += <NUM_LIT:1><EOL>self.inputBuffer = list(self.history[self.historyPos]) <EOL>self.cursorPos = len(self.inputBuffer)<EOL>self._refreshInputPrompt(clearLen)<EOL><DEDENT> | Handles "cursor down" events | f2337:c1:m13 |
def _handleBackspace(self): | if self.cursorPos > <NUM_LIT:0>:<EOL><INDENT>self.inputBuffer = self.inputBuffer[<NUM_LIT:0>:self.cursorPos-<NUM_LIT:1>] + self.inputBuffer[self.cursorPos:]<EOL>self.cursorPos -= <NUM_LIT:1><EOL>self._refreshInputPrompt(len(self.inputBuffer)+<NUM_LIT:1>)<EOL><DEDENT> | Handles backspace characters | f2337:c1:m14 |
def _handleDelete(self): | if self.cursorPos < len(self.inputBuffer):<EOL><INDENT>self.inputBuffer = self.inputBuffer[<NUM_LIT:0>:self.cursorPos] + self.inputBuffer[self.cursorPos+<NUM_LIT:1>:] <EOL>self._refreshInputPrompt(len(self.inputBuffer)+<NUM_LIT:1>)<EOL><DEDENT> | Handles "delete" characters | f2337:c1:m15 |
def _handleHome(self): | self.cursorPos = <NUM_LIT:0><EOL>self._refreshInputPrompt(len(self.inputBuffer))<EOL> | Handles "home" character | f2337:c1:m16 |
def _handleEnd(self): | self.cursorPos = len(self.inputBuffer)<EOL>self._refreshInputPrompt(len(self.inputBuffer))<EOL> | Handles "end" character | f2337:c1:m17 |
def _doCommandCompletion(self): | prefix = '<STR_LIT>'.join(self.inputBuffer).strip().upper()<EOL>matches = self.completion.keys(prefix)<EOL>matchLen = len(matches) <EOL>if matchLen == <NUM_LIT:0> and prefix[-<NUM_LIT:1>] == '<STR_LIT:=>':<EOL><INDENT>try: <EOL><INDENT>command = prefix[:-<NUM_LIT:1>]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>self.__printCommandSyntax(command)<EOL><DEDENT><DEDENT>elif matchLen > <NUM_LIT:0>: <EOL><INDENT>if matchLen == <NUM_LIT:1>:<EOL><INDENT>if matches[<NUM_LIT:0>] == prefix:<EOL><INDENT>self.__printCommandSyntax(prefix)<EOL><DEDENT>else:<EOL><INDENT>self.inputBuffer = list(matches[<NUM_LIT:0>])<EOL>self.cursorPos = len(self.inputBuffer)<EOL>self._refreshInputPrompt(len(self.inputBuffer))<EOL><DEDENT>return<EOL><DEDENT>else:<EOL><INDENT>commonPrefix = self.completion.longestCommonPrefix('<STR_LIT>'.join(self.inputBuffer))<EOL>self.inputBuffer = list(commonPrefix)<EOL>self.cursorPos = len(self.inputBuffer)<EOL>if matchLen > <NUM_LIT:20>:<EOL><INDENT>matches = matches[:<NUM_LIT:20>]<EOL>matches.append('<STR_LIT>'.format(matchLen - <NUM_LIT:20>))<EOL><DEDENT><DEDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>for match in matches:<EOL><INDENT>sys.stdout.write('<STR_LIT>'.format(match))<EOL><DEDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>sys.stdout.flush()<EOL>self._refreshInputPrompt(len(self.inputBuffer))<EOL><DEDENT> | Command-completion method | f2337:c1:m21 |
def __printCommandSyntax(self, command): | commandHelp = self.completion[command]<EOL>if commandHelp != None and len(commandHelp) > <NUM_LIT:2>:<EOL><INDENT>commandValues = commandHelp[<NUM_LIT:2>]<EOL>displayHelp = [self._color(self.COLOR_WHITE, command)]<EOL>if commandValues != None:<EOL><INDENT>valuesIsEnum = len(commandHelp) >= <NUM_LIT:6><EOL>if '<STR_LIT:+>' in command or command.upper() in ['<STR_LIT>']:<EOL><INDENT>displayHelp.append(self._color(self.COLOR_WHITE, '<STR_LIT:=>'))<EOL><DEDENT>displayHelp.append(('<STR_LIT:|>' if valuesIsEnum else '<STR_LIT:U+002C>').join([value[<NUM_LIT:0>] for value in commandValues]))<EOL><DEDENT>sys.stdout.write('<STR_LIT>'.format(self._color(self.COLOR_WHITE, '<STR_LIT>'.join(displayHelp))))<EOL>sys.stdout.flush()<EOL>self._refreshInputPrompt(len(self.inputBuffer))<EOL><DEDENT> | Command-completion helper method: print command syntax | f2337:c1:m22 |
def _allKeys(self, prefix): | global dictItemsIter<EOL>result = [prefix + self.key] if self.key != None else []<EOL>for key, trie in dictItemsIter(self.slots): <EOL><INDENT>result.extend(trie._allKeys(prefix + key)) <EOL><DEDENT>return result<EOL> | Private implementation method. Use keys() instead. | f2339:c0:m7 |
def keys(self, prefix=None): | if prefix == None:<EOL><INDENT>return self._allKeys('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self._filteredKeys(prefix, '<STR_LIT>')<EOL><DEDENT> | 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 | f2339:c0:m8 |
def longestCommonPrefix(self, prefix='<STR_LIT>'): | return self._longestCommonPrefix(prefix, '<STR_LIT>')<EOL> | Return the longest common prefix shared by all keys that start with prefix
(note: the return value will always start with the specified prefix) | f2339:c0:m10 |
def parseArgs(): | from argparse import ArgumentParser<EOL>parser = ArgumentParser(description='<STR_LIT>') <EOL>parser.add_argument('<STR_LIT:port>', metavar='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=None, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>') <EOL>return parser.parse_args()<EOL> | Argument parser for Python 2.7 and above | f2341:m0 |
def parseArgsPy26(): | from gsmtermlib.posoptparse import PosOptionParser, Option <EOL>parser = PosOptionParser(description='<STR_LIT>') <EOL>parser.add_positional_argument(Option('<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>'))<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=None, help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>options, args = parser.parse_args()<EOL>if len(args) != <NUM_LIT:1>: <EOL><INDENT>parser.error('<STR_LIT>'.format(sys.argv[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>options.port = args[<NUM_LIT:0>]<EOL>return options<EOL><DEDENT> | Argument parser for Python 2.6 | f2341:m1 |
def parseArgs(): | from argparse import ArgumentParser<EOL>parser = ArgumentParser(description='<STR_LIT>') <EOL>parser.add_argument('<STR_LIT:port>', metavar='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>') <EOL>return parser.parse_args()<EOL> | Argument parser for Python 2.7 and above | f2342:m0 |
def parseArgsPy26(): | from gsmtermlib.posoptparse import PosOptionParser, Option <EOL>parser = PosOptionParser(description='<STR_LIT>') <EOL>parser.add_positional_argument(Option('<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>'))<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>') <EOL>options, args = parser.parse_args()<EOL>if len(args) != <NUM_LIT:1>: <EOL><INDENT>parser.error('<STR_LIT>'.format(sys.argv[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>options.port = args[<NUM_LIT:0>]<EOL>return options<EOL><DEDENT> | Argument parser for Python 2.6 | f2342:m1 |
def parseArgs(): | from argparse import ArgumentParser<EOL>parser = ArgumentParser(description='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=None, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>') <EOL>return parser.parse_args()<EOL> | Argument parser for Python 2.7 and above | f2343:m0 |
def parseArgsPy26(): | from gsmtermlib.posoptparse import PosOptionParser, Option<EOL>parser = PosOptionParser(description='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=<NUM_LIT>, help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', metavar='<STR_LIT>', default=None, help='<STR_LIT>')<EOL>parser.add_option('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>parser.add_positional_argument(Option('<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>')) <EOL>options, args = parser.parse_args()<EOL>if len(args) != <NUM_LIT:1>: <EOL><INDENT>parser.error('<STR_LIT>'.format(sys.argv[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>options.destination = args[<NUM_LIT:0>]<EOL>return options<EOL><DEDENT> | Argument parser for Python 2.6 | f2343:m1 |
def parseTextModeTimeStr(timeStr): | msgTime = timeStr[:-<NUM_LIT:3>]<EOL>tzOffsetHours = int(int(timeStr[-<NUM_LIT:3>:]) * <NUM_LIT>)<EOL>return datetime.strptime(msgTime, '<STR_LIT>').replace(tzinfo=SimpleOffsetTzInfo(tzOffsetHours))<EOL> | Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an hour])
:param timeStr: The time string to parse
:type timeStr: str
:return: datetime object representing the specified time string
:rtype: datetime.datetime | f2357:m0 |
def lineStartingWith(string, lines): | for line in lines:<EOL><INDENT>if line.startswith(string):<EOL><INDENT>return line<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Searches through the specified list of strings and returns the
first line starting with the specified search string, or None if not found | f2357:m1 |
def lineMatching(regexStr, lines): | regex = re.compile(regexStr)<EOL>for line in lines:<EOL><INDENT>m = regex.match(line)<EOL>if m:<EOL><INDENT>return m<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified regex string, or None if no match was found
Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead
:type regexStr: Regular expression string to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match | f2357:m2 |
def lineMatchingPattern(pattern, lines): | for line in lines:<EOL><INDENT>m = pattern.match(line)<EOL>if m:<EOL><INDENT>return m<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Searches through the specified list of strings and returns the regular expression
match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found
Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: the regular expression match for the first line that matches the specified regex, or None if no match was found
:rtype: re.Match | f2357:m3 |
def allLinesMatchingPattern(pattern, lines): | result = []<EOL>for line in lines:<EOL><INDENT>m = pattern.match(line)<EOL>if m:<EOL><INDENT>result.append(m)<EOL><DEDENT><DEDENT>return result<EOL> | Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if none matched
:rtype: list | f2357:m4 |
def __init__(self, offsetInHours=None): | if offsetInHours != None: <EOL><INDENT>self.offsetInHours = offsetInHours<EOL><DEDENT> | Constructs a new tzinfo instance using an amount of hours as an offset
:param offsetInHours: The timezone offset, in hours (may be negative)
:type offsetInHours: int or float | f2357:c0:m0 |
def encodeSmsSubmitPdu(number, text, reference=<NUM_LIT:0>, validity=None, smsc=None, requestStatusReport=True, rejectDuplicates=False, sendFlash=False): | tpduFirstOctet = <NUM_LIT> <EOL>if validity != None:<EOL><INDENT>if type(validity) == timedelta:<EOL><INDENT>tpduFirstOctet |= <NUM_LIT> <EOL>validityPeriod = [_encodeRelativeValidityPeriod(validity)]<EOL><DEDENT>elif type(validity) == datetime:<EOL><INDENT>tpduFirstOctet |= <NUM_LIT> <EOL>validityPeriod = _encodeTimestamp(validity) <EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>') <EOL><DEDENT><DEDENT>else:<EOL><INDENT>validityPeriod = None<EOL><DEDENT>if rejectDuplicates:<EOL><INDENT>tpduFirstOctet |= <NUM_LIT> <EOL><DEDENT>if requestStatusReport:<EOL><INDENT>tpduFirstOctet |= <NUM_LIT> <EOL><DEDENT>try:<EOL><INDENT>encodedText = encodeGsm7(text)<EOL><DEDENT>except ValueError:<EOL><INDENT>alphabet = <NUM_LIT> <EOL><DEDENT>else:<EOL><INDENT>alphabet = <NUM_LIT> <EOL><DEDENT>if len(text) > MAX_MESSAGE_LENGTH[alphabet]:<EOL><INDENT>concatHeaderPrototype = Concatenation()<EOL>concatHeaderPrototype.reference = reference<EOL>pduCount = int(len(text) / MAX_MESSAGE_LENGTH[alphabet]) + <NUM_LIT:1><EOL>concatHeaderPrototype.parts = pduCount<EOL>tpduFirstOctet |= <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>concatHeaderPrototype = None<EOL>pduCount = <NUM_LIT:1><EOL><DEDENT>pdus = [] <EOL>for i in xrange(pduCount):<EOL><INDENT>pdu = bytearray()<EOL>if smsc:<EOL><INDENT>pdu.extend(_encodeAddressField(smsc, smscField=True))<EOL><DEDENT>else:<EOL><INDENT>pdu.append(<NUM_LIT>) <EOL><DEDENT>udh = bytearray()<EOL>if concatHeaderPrototype != None:<EOL><INDENT>concatHeader = copy(concatHeaderPrototype)<EOL>concatHeader.number = i + <NUM_LIT:1><EOL>if alphabet == <NUM_LIT>:<EOL><INDENT>pduText = text[i*<NUM_LIT>:(i+<NUM_LIT:1>) * <NUM_LIT>]<EOL><DEDENT>elif alphabet == <NUM_LIT>:<EOL><INDENT>pduText = text[i * <NUM_LIT> : (i + <NUM_LIT:1>) * <NUM_LIT>]<EOL><DEDENT>udh.extend(concatHeader.encode())<EOL><DEDENT>else:<EOL><INDENT>pduText = text<EOL><DEDENT>udhLen = len(udh) <EOL>pdu.append(tpduFirstOctet)<EOL>pdu.append(reference) <EOL>pdu.extend(_encodeAddressField(number))<EOL>pdu.append(<NUM_LIT>) <EOL>pdu.append(alphabet if not sendFlash else (<NUM_LIT> if alphabet == <NUM_LIT> else <NUM_LIT>))<EOL>if validityPeriod:<EOL><INDENT>pdu.extend(validityPeriod)<EOL><DEDENT>if alphabet == <NUM_LIT>: <EOL><INDENT>encodedText = encodeGsm7(pduText)<EOL>userDataLength = len(encodedText) <EOL>if udhLen > <NUM_LIT:0>:<EOL><INDENT>shift = ((udhLen + <NUM_LIT:1>) * <NUM_LIT:8>) % <NUM_LIT:7> <EOL>userData = packSeptets(encodedText, padBits=shift)<EOL>if shift > <NUM_LIT:0>:<EOL><INDENT>userDataLength += <NUM_LIT:1> <EOL><DEDENT><DEDENT>else:<EOL><INDENT>userData = packSeptets(encodedText)<EOL><DEDENT><DEDENT>elif alphabet == <NUM_LIT>: <EOL><INDENT>userData = encodeUcs2(pduText)<EOL>userDataLength = len(userData)<EOL><DEDENT>if udhLen > <NUM_LIT:0>: <EOL><INDENT>userDataLength += udhLen + <NUM_LIT:1> <EOL>pdu.append(userDataLength)<EOL>pdu.append(udhLen)<EOL>pdu.extend(udh) <EOL><DEDENT>else:<EOL><INDENT>pdu.append(userDataLength)<EOL><DEDENT>pdu.extend(userData) <EOL>tpdu_length = len(pdu) - <NUM_LIT:1><EOL>pdus.append(Pdu(pdu, tpdu_length))<EOL><DEDENT>return pdus<EOL> | 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
:type text: str
:param reference: message reference number (see also: rejectDuplicates parameter)
:type reference: int
:param validity: message validity period (absolute or relative)
:type validity: datetime.timedelta (relative) or datetime.datetime (absolute)
:param smsc: SMSC number to use (leave None to use default)
: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 | f2358:m0 |
def decodeSmsPdu(pdu): | try:<EOL><INDENT>pdu = toByteArray(pdu)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise EncodingError(e)<EOL><DEDENT>result = {}<EOL>pduIter = iter(pdu)<EOL>smscNumber, smscBytesRead = _decodeAddressField(pduIter, smscField=True)<EOL>result['<STR_LIT>'] = smscNumber<EOL>result['<STR_LIT>'] = len(pdu) - smscBytesRead<EOL>tpduFirstOctet = next(pduIter) <EOL>pduType = tpduFirstOctet & <NUM_LIT> <EOL>if pduType == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT:type>'] = '<STR_LIT>'<EOL>result['<STR_LIT>'] = _decodeAddressField(pduIter)[<NUM_LIT:0>]<EOL>result['<STR_LIT>'] = next(pduIter)<EOL>dataCoding = _decodeDataCoding(next(pduIter))<EOL>result['<STR_LIT:time>'] = _decodeTimestamp(pduIter)<EOL>userDataLen = next(pduIter)<EOL>udhPresent = (tpduFirstOctet & <NUM_LIT>) != <NUM_LIT:0><EOL>ud = _decodeUserData(pduIter, userDataLen, dataCoding, udhPresent)<EOL>result.update(ud)<EOL><DEDENT>elif pduType == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT:type>'] = '<STR_LIT>'<EOL>result['<STR_LIT>'] = next(pduIter) <EOL>result['<STR_LIT>'] = _decodeAddressField(pduIter)[<NUM_LIT:0>]<EOL>result['<STR_LIT>'] = next(pduIter)<EOL>dataCoding = _decodeDataCoding(next(pduIter))<EOL>validityPeriodFormat = (tpduFirstOctet & <NUM_LIT>) >> <NUM_LIT:3> <EOL>if validityPeriodFormat == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT>'] = _decodeRelativeValidityPeriod(next(pduIter))<EOL><DEDENT>elif validityPeriodFormat == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT>'] = _decodeTimestamp(pduIter)<EOL><DEDENT>userDataLen = next(pduIter)<EOL>udhPresent = (tpduFirstOctet & <NUM_LIT>) != <NUM_LIT:0><EOL>ud = _decodeUserData(pduIter, userDataLen, dataCoding, udhPresent)<EOL>result.update(ud)<EOL><DEDENT>elif pduType == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT:type>'] = '<STR_LIT>'<EOL>result['<STR_LIT>'] = next(pduIter)<EOL>result['<STR_LIT>'] = _decodeAddressField(pduIter)[<NUM_LIT:0>]<EOL>result['<STR_LIT:time>'] = _decodeTimestamp(pduIter)<EOL>result['<STR_LIT>'] = _decodeTimestamp(pduIter)<EOL>result['<STR_LIT:status>'] = next(pduIter) <EOL><DEDENT>else:<EOL><INDENT>raise EncodingError('<STR_LIT>'.format(pduType, tpduFirstOctet))<EOL><DEDENT>return result<EOL> | 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 | f2358:m1 |
def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent): | result = {}<EOL>if udhPresent:<EOL><INDENT>result['<STR_LIT>'] = []<EOL>udhLen = next(byteIter)<EOL>ieLenRead = <NUM_LIT:0><EOL>while ieLenRead < udhLen:<EOL><INDENT>ie = InformationElement.decode(byteIter)<EOL>ieLenRead += len(ie)<EOL>result['<STR_LIT>'].append(ie)<EOL><DEDENT>del ieLenRead<EOL>if dataCoding == <NUM_LIT>: <EOL><INDENT>shift = ((udhLen + <NUM_LIT:1>) * <NUM_LIT:8>) % <NUM_LIT:7> <EOL>prevOctet = next(byteIter)<EOL>shift += <NUM_LIT:1><EOL><DEDENT><DEDENT>if dataCoding == <NUM_LIT>: <EOL><INDENT>if udhPresent:<EOL><INDENT>userDataSeptets = unpackSeptets(byteIter, userDataLen, prevOctet, shift)<EOL><DEDENT>else:<EOL><INDENT>userDataSeptets = unpackSeptets(byteIter, userDataLen)<EOL><DEDENT>result['<STR_LIT:text>'] = decodeGsm7(userDataSeptets)<EOL><DEDENT>elif dataCoding == <NUM_LIT>: <EOL><INDENT>result['<STR_LIT:text>'] = decodeUcs2(byteIter, userDataLen)<EOL><DEDENT>else: <EOL><INDENT>userData = []<EOL>for b in byteIter:<EOL><INDENT>userData.append(unichr(b))<EOL><DEDENT>result['<STR_LIT:text>'] = '<STR_LIT>'.join(userData)<EOL><DEDENT>return result<EOL> | Decodes PDU user data (UDHI (if present) and message text) | f2358:m2 |
def _decodeRelativeValidityPeriod(tpVp): | if tpVp <= <NUM_LIT>:<EOL><INDENT>return timedelta(minutes=((tpVp + <NUM_LIT:1>) * <NUM_LIT:5>))<EOL><DEDENT>elif <NUM_LIT> <= tpVp <= <NUM_LIT>:<EOL><INDENT>return timedelta(hours=<NUM_LIT:12>, minutes=((tpVp - <NUM_LIT>) * <NUM_LIT:30>))<EOL><DEDENT>elif <NUM_LIT> <= tpVp <= <NUM_LIT>:<EOL><INDENT>return timedelta(days=(tpVp - <NUM_LIT>))<EOL><DEDENT>elif <NUM_LIT> <= tpVp <= <NUM_LIT:255>:<EOL><INDENT>return timedelta(weeks=(tpVp - <NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta | f2358:m3 |
def _encodeRelativeValidityPeriod(validityPeriod): | <EOL>seconds = validityPeriod.seconds + (validityPeriod.days * <NUM_LIT> * <NUM_LIT>)<EOL>if seconds <= <NUM_LIT>: <EOL><INDENT>tpVp = int(seconds / <NUM_LIT>) - <NUM_LIT:1> <EOL><DEDENT>elif seconds <= <NUM_LIT>: <EOL><INDENT>tpVp = int((seconds - <NUM_LIT>) / <NUM_LIT>) + <NUM_LIT> <EOL><DEDENT>elif validityPeriod.days <= <NUM_LIT:30>: <EOL><INDENT>tpVp = validityPeriod.days + <NUM_LIT> <EOL><DEDENT>elif validityPeriod.days <= <NUM_LIT>: <EOL><INDENT>tpVp = int(validityPeriod.days / <NUM_LIT:7>) + <NUM_LIT> <EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return tpVp<EOL> | 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 | f2358:m4 |
def _decodeTimestamp(byteIter): | dateStr = decodeSemiOctets(byteIter, <NUM_LIT:7>)<EOL>timeZoneStr = dateStr[-<NUM_LIT:2>:] <EOL>return datetime.strptime(dateStr[:-<NUM_LIT:2>], '<STR_LIT>').replace(tzinfo=SmsPduTzInfo(timeZoneStr))<EOL> | Decodes a 7-octet timestamp | f2358:m5 |
def _encodeTimestamp(timestamp): | if timestamp.tzinfo == None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>tzDelta = timestamp.utcoffset()<EOL>if tzDelta.days >= <NUM_LIT:0>:<EOL><INDENT>tzValStr = '<STR_LIT>'.format(int(tzDelta.seconds / <NUM_LIT> / <NUM_LIT:15>))<EOL><DEDENT>else: <EOL><INDENT>tzVal = int((tzDelta.days * -<NUM_LIT> * <NUM_LIT> - tzDelta.seconds) / <NUM_LIT> / <NUM_LIT:15>) <EOL>tzVal = int('<STR_LIT>'.format(tzVal), <NUM_LIT:16>) | <NUM_LIT><EOL>tzValStr = '<STR_LIT>'.format(tzVal)<EOL><DEDENT>dateStr = timestamp.strftime('<STR_LIT>') + tzValStr<EOL>return encodeSemiOctets(dateStr)<EOL> | 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 | f2358:m6 |
def _decodeAddressField(byteIter, smscField=False, log=False): | addressLen = next(byteIter)<EOL>if addressLen > <NUM_LIT:0>:<EOL><INDENT>toa = next(byteIter)<EOL>ton = (toa & <NUM_LIT>) <EOL>if ton == <NUM_LIT>: <EOL><INDENT>addressLen = int(math.ceil(addressLen / <NUM_LIT>))<EOL>septets = unpackSeptets(byteIter, addressLen)<EOL>addressValue = decodeGsm7(septets)<EOL>return (addressValue, (addressLen + <NUM_LIT:2>))<EOL><DEDENT>else:<EOL><INDENT>if smscField:<EOL><INDENT>addressValue = decodeSemiOctets(byteIter, addressLen-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>if addressLen % <NUM_LIT:2>:<EOL><INDENT>addressLen = int(addressLen / <NUM_LIT:2>) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>addressLen = int(addressLen / <NUM_LIT:2>) <EOL><DEDENT>addressValue = decodeSemiOctets(byteIter, addressLen)<EOL>addressLen += <NUM_LIT:1> <EOL><DEDENT>if ton == <NUM_LIT>: <EOL><INDENT>addressValue = '<STR_LIT:+>' + addressValue<EOL><DEDENT>return (addressValue, (addressLen + <NUM_LIT:1>))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return (None, <NUM_LIT:1>)<EOL><DEDENT> | Decodes the address field at the current position of the bytearray iterator
:param byteIter: Iterator over 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 | f2358:m8 |
def _encodeAddressField(address, smscField=False): | <EOL>toa = <NUM_LIT> | <NUM_LIT> | <NUM_LIT> <EOL>alphaNumeric = False <EOL>if address.isalnum():<EOL><INDENT>if address.isdigit():<EOL><INDENT>toa |= <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>toa |= <NUM_LIT><EOL>toa &= <NUM_LIT> <EOL>alphaNumeric = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if address[<NUM_LIT:0>] == '<STR_LIT:+>' and address[<NUM_LIT:1>:].isdigit():<EOL><INDENT>toa |= <NUM_LIT><EOL>address = address[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>toa |= <NUM_LIT><EOL>toa &= <NUM_LIT> <EOL>alphaNumeric = True<EOL><DEDENT><DEDENT>if alphaNumeric:<EOL><INDENT>addressValue = packSeptets(encodeGsm7(address, False))<EOL>addressLen = len(addressValue) * <NUM_LIT:2> <EOL><DEDENT>else:<EOL><INDENT>addressValue = encodeSemiOctets(address)<EOL>if smscField: <EOL><INDENT>addressLen = len(addressValue) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>addressLen = len(address)<EOL><DEDENT><DEDENT>result = bytearray()<EOL>result.append(addressLen)<EOL>result.append(toa)<EOL>result.extend(addressValue)<EOL>return result<EOL> | 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 | f2358:m9 |
def encodeSemiOctets(number): | if len(number) % <NUM_LIT:2> == <NUM_LIT:1>:<EOL><INDENT>number = number + '<STR_LIT:F>' <EOL><DEDENT>octets = [int(number[i+<NUM_LIT:1>] + number[i], <NUM_LIT:16>) for i in xrange(<NUM_LIT:0>, len(number), <NUM_LIT:2>)]<EOL>return bytearray(octets)<EOL> | Semi-octet encoding algorithm (e.g. for phone numbers)
:return: bytearray containing the encoded octets
:rtype: bytearray | f2358:m10 |
def decodeSemiOctets(encodedNumber, numberOfOctets=None): | number = []<EOL>if type(encodedNumber) in (str, bytes):<EOL><INDENT>encodedNumber = bytearray(codecs.decode(encodedNumber, '<STR_LIT>'))<EOL><DEDENT>i = <NUM_LIT:0><EOL>for octet in encodedNumber: <EOL><INDENT>hexVal = hex(octet)[<NUM_LIT:2>:].zfill(<NUM_LIT:2>) <EOL>number.append(hexVal[<NUM_LIT:1>])<EOL>if hexVal[<NUM_LIT:0>] != '<STR_LIT:f>':<EOL><INDENT>number.append(hexVal[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT>if numberOfOctets != None:<EOL><INDENT>i += <NUM_LIT:1><EOL>if i == numberOfOctets:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'.join(number)<EOL> | 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 | f2358:m11 |
def encodeGsm7(plaintext, discardInvalid=False): | result = bytearray()<EOL>if PYTHON_VERSION >= <NUM_LIT:3>: <EOL><INDENT>plaintext = str(plaintext)<EOL><DEDENT>for char in plaintext:<EOL><INDENT>idx = GSM7_BASIC.find(char)<EOL>if idx != -<NUM_LIT:1>:<EOL><INDENT>result.append(idx)<EOL><DEDENT>elif char in GSM7_EXTENDED:<EOL><INDENT>result.append(<NUM_LIT>) <EOL>result.append(ord(GSM7_EXTENDED[char]))<EOL><DEDENT>elif not discardInvalid:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(char))<EOL><DEDENT><DEDENT>return result<EOL> | 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
: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 | f2358:m12 |
def decodeGsm7(encodedText): | result = []<EOL>if type(encodedText) == str:<EOL><INDENT>encodedText = rawStrToByteArray(encodedText) <EOL><DEDENT>iterEncoded = iter(encodedText)<EOL>for b in iterEncoded:<EOL><INDENT>if b == <NUM_LIT>: <EOL><INDENT>c = chr(next(iterEncoded))<EOL>for char, value in dictItemsIter(GSM7_EXTENDED):<EOL><INDENT>if c == value:<EOL><INDENT>result.append(char)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>result.append(GSM7_BASIC[b])<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(result)<EOL> | 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 | f2358:m13 |
def packSeptets(octets, padBits=<NUM_LIT:0>): | result = bytearray() <EOL>if type(octets) == str:<EOL><INDENT>octets = iter(rawStrToByteArray(octets))<EOL><DEDENT>elif type(octets) == bytearray:<EOL><INDENT>octets = iter(octets)<EOL><DEDENT>shift = padBits<EOL>if padBits == <NUM_LIT:0>:<EOL><INDENT>prevSeptet = next(octets)<EOL><DEDENT>else:<EOL><INDENT>prevSeptet = <NUM_LIT><EOL><DEDENT>for octet in octets:<EOL><INDENT>septet = octet & <NUM_LIT>;<EOL>if shift == <NUM_LIT:7>:<EOL><INDENT>shift = <NUM_LIT:0> <EOL>prevSeptet = septet<EOL>continue <EOL><DEDENT>b = ((septet << (<NUM_LIT:7> - shift)) & <NUM_LIT>) | (prevSeptet >> shift)<EOL>prevSeptet = septet<EOL>shift += <NUM_LIT:1><EOL>result.append(b) <EOL><DEDENT>if shift != <NUM_LIT:7>:<EOL><INDENT>result.append(prevSeptet >> shift)<EOL><DEDENT>return result<EOL> | 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 | f2358:m14 |
def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=<NUM_LIT:7>): | result = bytearray() <EOL>if type(septets) == str:<EOL><INDENT>septets = iter(rawStrToByteArray(septets))<EOL><DEDENT>elif type(septets) == bytearray:<EOL><INDENT>septets = iter(septets) <EOL><DEDENT>if numberOfSeptets == None: <EOL><INDENT>numberOfSeptets = MAX_INT <EOL><DEDENT>i = <NUM_LIT:0><EOL>for octet in septets:<EOL><INDENT>i += <NUM_LIT:1><EOL>if shift == <NUM_LIT:7>:<EOL><INDENT>shift = <NUM_LIT:1><EOL>if prevOctet != None: <EOL><INDENT>result.append(prevOctet >> <NUM_LIT:1>) <EOL><DEDENT>if i <= numberOfSeptets:<EOL><INDENT>result.append(octet & <NUM_LIT>)<EOL>prevOctet = octet <EOL><DEDENT>if i == numberOfSeptets:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>b = ((octet << shift) & <NUM_LIT>) | (prevOctet >> (<NUM_LIT:8> - shift))<EOL>prevOctet = octet <EOL>result.append(b)<EOL>shift += <NUM_LIT:1><EOL>if i == numberOfSeptets:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if shift == <NUM_LIT:7>:<EOL><INDENT>b = prevOctet >> (<NUM_LIT:8> - shift)<EOL>if b:<EOL><INDENT>result.append(b) <EOL><DEDENT><DEDENT>return result<EOL> | 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 | f2358:m15 |
def decodeUcs2(byteIter, numBytes): | userData = []<EOL>i = <NUM_LIT:0><EOL>try:<EOL><INDENT>while i < numBytes:<EOL><INDENT>userData.append(unichr((next(byteIter) << <NUM_LIT:8>) | next(byteIter)))<EOL>i += <NUM_LIT:2><EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT>return '<STR_LIT>'.join(userData)<EOL> | Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes | f2358:m16 |
def encodeUcs2(text): | result = bytearray()<EOL>for b in map(ord, text):<EOL><INDENT>result.append(b >> <NUM_LIT:8>)<EOL>result.append(b & <NUM_LIT>)<EOL><DEDENT>return result<EOL> | 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 | f2358:m17 |
def __init__(self, pduOffsetStr=None): | self._offset = None<EOL>if pduOffsetStr != None:<EOL><INDENT>self._setPduOffsetStr(pduOffsetStr)<EOL><DEDENT> | :param pduOffset: 2 semi-octet timezone offset as specified by PDU (see GSM 03.40 spec)
: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) | f2358:c0:m0 |
def dst(self, dt): | return timedelta(<NUM_LIT:0>)<EOL> | We do not have enough info in the SMS PDU to implement daylight savings time | f2358:c0:m3 |
def __new__(cls, *args, **kwargs): | if len(args) > <NUM_LIT:0>:<EOL><INDENT>targetClass = IEI_CLASS_MAP.get(args[<NUM_LIT:0>], cls)<EOL><DEDENT>elif '<STR_LIT>' in kwargs:<EOL><INDENT>targetClass = IEI_CLASS_MAP.get(kwargs['<STR_LIT>'], cls)<EOL><DEDENT>else:<EOL><INDENT>return super(InformationElement, cls).__new__(cls)<EOL><DEDENT>return super(InformationElement, targetClass).__new__(targetClass)<EOL> | Causes a new InformationElement class, or subclass
thereof, to be created. If the IEI is recognized, a specific
subclass of InformationElement is returned | f2358:c1:m0 |
@classmethod<EOL><INDENT>def decode(cls, byteIter):<DEDENT> | iei = next(byteIter)<EOL>ieLen = next(byteIter)<EOL>ieData = []<EOL>for i in xrange(ieLen):<EOL><INDENT>ieData.append(next(byteIter))<EOL><DEDENT>return InformationElement(iei, ieLen, ieData)<EOL> | Decodes a single IE at the current position in the specified
byte iterator
:return: An InformationElement (or subclass) instance for the decoded IE
:rtype: InformationElement, or subclass thereof | f2358:c1:m2 |
def encode(self): | result = bytearray()<EOL>result.append(self.id)<EOL>result.append(self.dataLength)<EOL>result.extend(self.data)<EOL>return result<EOL> | Encodes this IE and returns the resulting bytes | f2358:c1:m3 |
def __len__(self): | return self.dataLength + <NUM_LIT:2><EOL> | Exposes the IE's total length (including the IEI and IE length octet) in octets | f2358:c1:m4 |
def __init__(self, data, tpduLength): | self.data = data<EOL>self.tpduLength = tpduLength<EOL> | Constructor
:param data: the raw PDU data (as bytes)
:type data: bytearray
:param tpduLength: Length (in bytes) of the TPDU
:type tpduLength: int | f2358:c4:m0 |
def reply(self, message): | return self._gsmModem.sendSms(self.number, message)<EOL> | Convenience method that sends a reply SMS to the sender of this message | f2360:c1:m1 |
@property<EOL><INDENT>def status(self):<DEDENT> | if self.report == None:<EOL><INDENT>return SentSms.ENROUTE<EOL><DEDENT>else:<EOL><INDENT>return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED<EOL><DEDENT> | 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' | f2360:c2:m1 |
def connect(self, pin=None): | self.log.info('<STR_LIT>', self.port, self.baudrate) <EOL>super(GsmModem, self).connect()<EOL>try: <EOL><INDENT>self.write('<STR_LIT>') <EOL><DEDENT>except CommandError:<EOL><INDENT>self.write('<STR_LIT>', parseError=False) <EOL>self._unlockSim(pin)<EOL>pinCheckComplete = True<EOL>self.write('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>pinCheckComplete = False<EOL><DEDENT>self.write('<STR_LIT>') <EOL>try:<EOL><INDENT>cfun = int(lineStartingWith('<STR_LIT>', self.write('<STR_LIT>'))[<NUM_LIT:7>:]) <EOL>if cfun != <NUM_LIT:1>:<EOL><INDENT>self.write('<STR_LIT>')<EOL><DEDENT><DEDENT>except CommandError:<EOL><INDENT>pass <EOL><DEDENT>self.write('<STR_LIT>') <EOL>if not pinCheckComplete:<EOL><INDENT>self._unlockSim(pin)<EOL><DEDENT>commands = self.supportedCommands<EOL>callUpdateTableHint = <NUM_LIT:0> <EOL>enableWind = False<EOL>if commands != None:<EOL><INDENT>if '<STR_LIT>' in commands:<EOL><INDENT>self.write('<STR_LIT>', parseError=False) <EOL><DEDENT>if '<STR_LIT>' in commands: <EOL><INDENT>Call.dtmfSupport = True<EOL><DEDENT>elif '<STR_LIT>' in commands:<EOL><INDENT>callUpdateTableHint = <NUM_LIT:1> <EOL><DEDENT>if '<STR_LIT>' in commands:<EOL><INDENT>self.write('<STR_LIT>', parseError=False)<EOL><DEDENT>if '<STR_LIT>' in commands:<EOL><INDENT>callUpdateTableHint = <NUM_LIT:2> <EOL>enableWind = True<EOL><DEDENT>elif '<STR_LIT>' in commands:<EOL><INDENT>callUpdateTableHint = <NUM_LIT:3> <EOL><DEDENT><DEDENT>else:<EOL><INDENT>enableWind = True<EOL><DEDENT>if enableWind:<EOL><INDENT>try:<EOL><INDENT>wind = lineStartingWith('<STR_LIT>', self.write('<STR_LIT>')) <EOL><DEDENT>except CommandError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if int(wind[<NUM_LIT:7>:]) != <NUM_LIT:50>:<EOL><INDENT>self.write('<STR_LIT>')<EOL><DEDENT>callUpdateTableHint = <NUM_LIT:2> <EOL><DEDENT><DEDENT>if callUpdateTableHint == <NUM_LIT:0>:<EOL><INDENT>if self.manufacturer.lower() == '<STR_LIT>':<EOL><INDENT>callUpdateTableHint = <NUM_LIT:1> <EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>self.write('<STR_LIT>')<EOL><DEDENT>except CommandError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>callUpdateTableHint = <NUM_LIT:3> <EOL><DEDENT><DEDENT><DEDENT>if callUpdateTableHint == <NUM_LIT:1>:<EOL><INDENT>self.log.info('<STR_LIT>')<EOL>self._callStatusUpdates = ((re.compile(r'<STR_LIT>'), self._handleCallInitiated),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallAnswered),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallEnded))<EOL>self._mustPollCallStatus = False<EOL>Call.DTMF_COMMAND_BASE = '<STR_LIT>'<EOL>Call.dtmfSupport = True<EOL><DEDENT>elif callUpdateTableHint == <NUM_LIT:2>:<EOL><INDENT>self.log.info('<STR_LIT>')<EOL>self._callStatusUpdates = ((re.compile(r'<STR_LIT>'), self._handleCallInitiated),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallAnswered),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallEnded))<EOL>self._waitForAtdResponse = False <EOL>self._mustPollCallStatus = False<EOL>if commands == None: <EOL><INDENT>Call.dtmfSupport = True<EOL><DEDENT><DEDENT>elif callUpdateTableHint == <NUM_LIT:3>: <EOL><INDENT>self.log.info('<STR_LIT>')<EOL>self._callStatusUpdates = ((re.compile(r'<STR_LIT>'), self._handleCallAnswered),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallEnded),<EOL>(re.compile(r'<STR_LIT>'), self._handleCallRejected))<EOL>self._waitForAtdResponse = False <EOL>self._mustPollCallStatus = False<EOL>self._waitForCallInitUpdate = False <EOL>if commands == None: <EOL><INDENT>Call.dtmfSupport = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info('<STR_LIT>')<EOL>self._mustPollCallStatus = True<EOL>self._pollCallStatusRegex = re.compile('<STR_LIT>')<EOL>self._waitForAtdResponse = True <EOL><DEDENT>self.write('<STR_LIT>', parseError=False) <EOL>self.write('<STR_LIT>'.format(<NUM_LIT:1> if self._smsTextMode else <NUM_LIT:0>)) <EOL>self._compileSmsRegexes()<EOL>if self._smscNumber != None:<EOL><INDENT>self.write('<STR_LIT>'.format(self._smscNumber)) <EOL>currentSmscNumber = self._smscNumber<EOL><DEDENT>else:<EOL><INDENT>currentSmscNumber = self.smsc<EOL><DEDENT>if currentSmscNumber != None:<EOL><INDENT>self._smscNumber = None <EOL><DEDENT>self.write('<STR_LIT>', parseError=False) <EOL>if currentSmscNumber != None and self.smsc != currentSmscNumber:<EOL><INDENT>self.smsc = currentSmscNumber<EOL><DEDENT>try:<EOL><INDENT>cpmsLine = lineStartingWith('<STR_LIT>', self.write('<STR_LIT>'))<EOL><DEDENT>except CommandError:<EOL><INDENT>self._smsReadSupported = False<EOL>self.log.warning('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>cpmsSupport = cpmsLine.split('<STR_LIT:U+0020>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT>')<EOL>for memItem in cpmsSupport:<EOL><INDENT>if len(memItem) == <NUM_LIT:0>:<EOL><INDENT>self._smsReadSupported = False<EOL>self.log.warning('<STR_LIT>', cpmsLine)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>preferredMemoryTypes = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>cpmsItems = ['<STR_LIT>'] * len(cpmsSupport)<EOL>for i in xrange(len(cpmsSupport)):<EOL><INDENT>for memType in preferredMemoryTypes:<EOL><INDENT>if memType in cpmsSupport[i]:<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>self._smsMemReadDelete = memType<EOL><DEDENT>cpmsItems[i] = memType<EOL>break<EOL><DEDENT><DEDENT><DEDENT>self.write('<STR_LIT>'.format('<STR_LIT:U+002C>'.join(cpmsItems))) <EOL><DEDENT>del cpmsSupport<EOL>del cpmsLine<EOL><DEDENT>if self._smsReadSupported:<EOL><INDENT>try:<EOL><INDENT>self.write('<STR_LIT>') <EOL><DEDENT>except CommandError:<EOL><INDENT>self._smsReadSupported = False<EOL>self.log.warning('<STR_LIT>')<EOL><DEDENT><DEDENT>try:<EOL><INDENT>self.write('<STR_LIT>') <EOL><DEDENT>except CommandError as clipError:<EOL><INDENT>self._callingLineIdentification = False<EOL>self.log.warning('<STR_LIT>'.format(clipError))<EOL><DEDENT>else:<EOL><INDENT>self._callingLineIdentification = True<EOL>try:<EOL><INDENT>self.write('<STR_LIT>') <EOL><DEDENT>except CommandError as crcError:<EOL><INDENT>self._extendedIncomingCallIndication = False<EOL>self.log.warning('<STR_LIT>'.format(crcError))<EOL><DEDENT>else:<EOL><INDENT>self._extendedIncomingCallIndication = True <EOL><DEDENT><DEDENT>self.write('<STR_LIT>', parseError=False)<EOL> | 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 | f2360:c4:m1 |
def _unlockSim(self, pin): | <EOL>try:<EOL><INDENT>cpinResponse = lineStartingWith('<STR_LIT>', self.write('<STR_LIT>', timeout=<NUM_LIT>))<EOL><DEDENT>except TimeoutException as timeout:<EOL><INDENT>if timeout.data != None:<EOL><INDENT>cpinResponse = lineStartingWith('<STR_LIT>', timeout.data)<EOL>if cpinResponse == None:<EOL><INDENT>raise timeout<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise timeout<EOL><DEDENT><DEDENT>if cpinResponse != '<STR_LIT>':<EOL><INDENT>if pin != None:<EOL><INDENT>self.write('<STR_LIT>'.format(pin))<EOL><DEDENT>else:<EOL><INDENT>raise PinRequiredError('<STR_LIT>')<EOL><DEDENT><DEDENT> | Unlocks the SIM card using the specified PIN (if necessary, else does nothing) | f2360:c4:m2 |
def write(self, data, waitForResponse=True, timeout=<NUM_LIT:5>, parseError=True, writeTerm='<STR_LIT:\r>', expectedResponseTermSeq=None): | self.log.debug('<STR_LIT>', data)<EOL>responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq)<EOL>if self._writeWait > <NUM_LIT:0>: <EOL><INDENT>time.sleep(self._writeWait)<EOL><DEDENT>if waitForResponse:<EOL><INDENT>cmdStatusLine = responseLines[-<NUM_LIT:1>]<EOL>if parseError:<EOL><INDENT>if '<STR_LIT>' in cmdStatusLine:<EOL><INDENT>cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine)<EOL>if cmErrorMatch:<EOL><INDENT>errorType = cmErrorMatch.group(<NUM_LIT:1>)<EOL>errorCode = int(cmErrorMatch.group(<NUM_LIT:2>))<EOL>if errorCode == <NUM_LIT> or errorCode == <NUM_LIT>:<EOL><INDENT>self._writeWait += <NUM_LIT> <EOL>self.log.debug('<STR_LIT>', self._writeWait)<EOL>time.sleep(self._writeWait)<EOL>result = self.write(data, waitForResponse, timeout, parseError, writeTerm, expectedResponseTermSeq)<EOL>self.log.debug('<STR_LIT>')<EOL>if errorCode == <NUM_LIT>:<EOL><INDENT>self._writeWait = <NUM_LIT:0.1> <EOL><DEDENT>else:<EOL><INDENT>self._writeWait = <NUM_LIT:0> <EOL><DEDENT>return result<EOL><DEDENT>if errorType == '<STR_LIT>':<EOL><INDENT>raise CmeError(data, int(errorCode))<EOL><DEDENT>else: <EOL><INDENT>raise CmsError(data, int(errorCode))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise CommandError(data)<EOL><DEDENT><DEDENT>elif cmdStatusLine == '<STR_LIT>': <EOL><INDENT>raise CommandError(data + '<STR_LIT>'.format(cmdStatusLine))<EOL><DEDENT><DEDENT>return responseLines<EOL><DEDENT> | Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be written to the modem
:type data: str
:param waitForResponse: Whether this method should block and return the response from the modem or not
:type waitForResponse: bool
:param timeout: Maximum amount of time in seconds to wait for a response from the modem
:type timeout: int
:param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is)
:type parseError: bool
:param writeTerm: The terminating sequence to append to the written data
:type writeTerm: str
:param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``)
:type expectedResponseTermSeq: str
:raise CommandError: if the command returns an error (only if parseError parameter is True)
:raise TimeoutException: if no response to the command was received from the modem
:return: A list containing the response lines from the modem, or None if waitForResponse is False
:rtype: list | f2360:c4:m3 |
@property<EOL><INDENT>def signalStrength(self):<DEDENT> | csq = self.CSQ_REGEX.match(self.write('<STR_LIT>')[<NUM_LIT:0>])<EOL>if csq:<EOL><INDENT>ss = int(csq.group(<NUM_LIT:1>))<EOL>return ss if ss != <NUM_LIT> else -<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise CommandError()<EOL><DEDENT> | 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 | f2360:c4:m4 |
@property<EOL><INDENT>def manufacturer(self):<DEDENT> | return self.write('<STR_LIT>')[<NUM_LIT:0>]<EOL> | :return: The modem's manufacturer's name | f2360:c4:m5 |
@property<EOL><INDENT>def model(self):<DEDENT> | return self.write('<STR_LIT>')[<NUM_LIT:0>]<EOL> | :return: The modem's model name | f2360:c4:m6 |
@property<EOL><INDENT>def revision(self):<DEDENT> | try:<EOL><INDENT>return self.write('<STR_LIT>')[<NUM_LIT:0>]<EOL><DEDENT>except CommandError:<EOL><INDENT>return None<EOL><DEDENT> | :return: The modem's software revision, or None if not known/supported | f2360:c4:m7 |
@property<EOL><INDENT>def imei(self):<DEDENT> | return self.write('<STR_LIT>')[<NUM_LIT:0>]<EOL> | :return: The modem's serial number (IMEI number) | f2360:c4:m8 |
@property<EOL><INDENT>def imsi(self):<DEDENT> | return self.write('<STR_LIT>')[<NUM_LIT:0>]<EOL> | :return: The IMSI (International Mobile Subscriber Identity) of the SIM card. The PIN may need to be entered before reading the IMSI | f2360:c4:m9 |
@property<EOL><INDENT>def networkName(self):<DEDENT> | copsMatch = lineMatching(r'<STR_LIT>', self.write('<STR_LIT>')) <EOL>if copsMatch:<EOL><INDENT>return copsMatch.group(<NUM_LIT:3>)<EOL><DEDENT> | :return: the name of the GSM Network Operator to which the modem is connected | f2360:c4:m10 |
@property<EOL><INDENT>def supportedCommands(self):<DEDENT> | try:<EOL><INDENT>response = self.write('<STR_LIT>')<EOL>if len(response) == <NUM_LIT:2>: <EOL><INDENT>commands = response[<NUM_LIT:0>]<EOL>if commands.startswith('<STR_LIT>'):<EOL><INDENT>commands = commands[<NUM_LIT:6>:] <EOL><DEDENT>return commands.split('<STR_LIT:U+002C>')<EOL><DEDENT>elif len(response) > <NUM_LIT:2>: <EOL><INDENT>return [cmd.strip() for cmd in response[:-<NUM_LIT:1>]]<EOL><DEDENT>else:<EOL><INDENT>self.log.debug('<STR_LIT>'.format(response))<EOL>return None<EOL><DEDENT><DEDENT>except CommandError:<EOL><INDENT>return None<EOL><DEDENT> | :return: list of AT commands supported by this modem (without the AT prefix). Returns None if not known | f2360:c4:m11 |
@property<EOL><INDENT>def smsTextMode(self):<DEDENT> | return self._smsTextMode<EOL> | :return: True if the modem is set to use text mode for SMS, False if it is set to use PDU mode | f2360:c4:m12 |
@smsTextMode.setter<EOL><INDENT>def smsTextMode(self, textMode):<DEDENT> | if textMode != self._smsTextMode:<EOL><INDENT>if self.alive:<EOL><INDENT>self.write('<STR_LIT>'.format(<NUM_LIT:1> if textMode else <NUM_LIT:0>))<EOL><DEDENT>self._smsTextMode = textMode<EOL>self._compileSmsRegexes()<EOL><DEDENT> | Set to True for the modem to use text mode for SMS, or False for it to use PDU mode | f2360:c4:m13 |
def _setSmsMemory(self, readDelete=None, write=None): | <EOL>if write != None and write != self._smsMemWrite:<EOL><INDENT>self.write()<EOL>readDel = readDelete or self._smsMemReadDelete<EOL>self.write('<STR_LIT>'.format(readDel, write))<EOL>self._smsMemReadDelete = readDel<EOL>self._smsMemWrite = write<EOL><DEDENT>elif readDelete != None and readDelete != self._smsMemReadDelete:<EOL><INDENT>self.write('<STR_LIT>'.format(readDelete))<EOL>self._smsMemReadDelete = readDelete<EOL><DEDENT> | Set the current SMS memory to use for read/delete/write operations | f2360:c4:m14 |
def _compileSmsRegexes(self): | if self._smsTextMode:<EOL><INDENT>if self.CMGR_SM_DELIVER_REGEX_TEXT == None:<EOL><INDENT>self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'<STR_LIT>')<EOL>self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'<STR_LIT>')<EOL><DEDENT><DEDENT>elif self.CMGR_REGEX_PDU == None:<EOL><INDENT>self.CMGR_REGEX_PDU = re.compile(r'<STR_LIT>')<EOL><DEDENT> | Compiles regular expression used for parsing SMS messages based on current mode | f2360:c4:m15 |
@property<EOL><INDENT>def smsc(self):<DEDENT> | if self._smscNumber == None:<EOL><INDENT>try:<EOL><INDENT>readSmsc = self.write('<STR_LIT>')<EOL><DEDENT>except SmscNumberUnknownError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>cscaMatch = lineMatching(r'<STR_LIT>', readSmsc)<EOL>if cscaMatch:<EOL><INDENT>self._smscNumber = cscaMatch.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>return self._smscNumber<EOL> | :return: The default SMSC number stored on the SIM card | f2360:c4:m16 |
@smsc.setter<EOL><INDENT>def smsc(self, smscNumber):<DEDENT> | if smscNumber != self._smscNumber:<EOL><INDENT>if self.alive:<EOL><INDENT>self.write('<STR_LIT>'.format(smscNumber))<EOL><DEDENT>self._smscNumber = smscNumber<EOL><DEDENT> | Set the default SMSC number to use when sending SMS messages | f2360:c4:m17 |
def waitForNetworkCoverage(self, timeout=None): | block = [True]<EOL>if timeout != None:<EOL><INDENT>def _cancelBlock(): <EOL><INDENT>block[<NUM_LIT:0>] = False <EOL><DEDENT>t = threading.Timer(timeout, _cancelBlock)<EOL>t.start()<EOL><DEDENT>ss = -<NUM_LIT:1><EOL>checkCreg = True<EOL>while block[<NUM_LIT:0>]:<EOL><INDENT>if checkCreg:<EOL><INDENT>cregResult = lineMatching(r'<STR_LIT>', self.write('<STR_LIT>', parseError=False)) <EOL>if cregResult:<EOL><INDENT>status = int(cregResult.group(<NUM_LIT:2>))<EOL>if status in (<NUM_LIT:1>, <NUM_LIT:5>):<EOL><INDENT>checkCreg = False<EOL><DEDENT>elif status == <NUM_LIT:3>:<EOL><INDENT>raise InvalidStateException('<STR_LIT>')<EOL><DEDENT>elif status == <NUM_LIT:0>:<EOL><INDENT>raise InvalidStateException('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info('<STR_LIT>')<EOL>checkCreg = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ss = self.signalStrength<EOL>if ss > <NUM_LIT:0>:<EOL><INDENT>return ss<EOL><DEDENT><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise TimeoutException()<EOL><DEDENT> | Block until the modem has GSM network coverage.
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
:raise TimeoutException: if a timeout was specified and reached
:raise InvalidStateException: if the modem is not going to receive network coverage (SIM blocked, etc)
:return: the current signal strength
:rtype: int | f2360:c4:m18 |
def sendSms(self, destination, text, waitForDeliveryReport=False, deliveryTimeout=<NUM_LIT:15>, sendFlash=False): | if self._smsTextMode:<EOL><INDENT>self.write('<STR_LIT>'.format(destination), timeout=<NUM_LIT:3>, expectedResponseTermSeq='<STR_LIT>')<EOL>result = lineStartingWith('<STR_LIT>', self.write(text, timeout=<NUM_LIT:15>, writeTerm=chr(<NUM_LIT>)))<EOL><DEDENT>else:<EOL><INDENT>pdus = encodeSmsSubmitPdu(destination, text, reference=self._smsRef, sendFlash=sendFlash)<EOL>for pdu in pdus:<EOL><INDENT>self.write('<STR_LIT>'.format(pdu.tpduLength), timeout=<NUM_LIT:3>, expectedResponseTermSeq='<STR_LIT>')<EOL>result = lineStartingWith('<STR_LIT>', self.write(str(pdu), timeout=<NUM_LIT:15>, writeTerm=chr(<NUM_LIT>))) <EOL><DEDENT><DEDENT>if result == None:<EOL><INDENT>raise CommandError('<STR_LIT>')<EOL><DEDENT>reference = int(result[<NUM_LIT:7>:])<EOL>self._smsRef = reference + <NUM_LIT:1><EOL>if self._smsRef > <NUM_LIT:255>:<EOL><INDENT>self._smsRef = <NUM_LIT:0><EOL><DEDENT>sms = SentSms(destination, text, reference)<EOL>self.sentSms[reference] = sms<EOL>if waitForDeliveryReport:<EOL><INDENT>self._smsStatusReportEvent = threading.Event()<EOL>if self._smsStatusReportEvent.wait(deliveryTimeout):<EOL><INDENT>self._smsStatusReportEvent = None<EOL><DEDENT>else: <EOL><INDENT>self._smsStatusReportEvent = None<EOL>raise TimeoutException()<EOL><DEDENT><DEDENT>return sms<EOL> | Send an SMS text message
:param destination: the recipient's phone number
:type destination: str
:param text: the message text
: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)
:type deliveryTimeout: int or float
:raise CommandError: if an error occurs while attempting to send the message
:raise TimeoutException: if the operation times out | f2360:c4:m19 |
def sendUssd(self, ussdString, responseTimeout=<NUM_LIT:15>): | self._ussdSessionEvent = threading.Event()<EOL>try:<EOL><INDENT>cusdResponse = self.write('<STR_LIT>'.format(ussdString), timeout=responseTimeout) <EOL><DEDENT>except Exception:<EOL><INDENT>self._ussdSessionEvent = None <EOL>raise<EOL><DEDENT>if len(cusdResponse) > <NUM_LIT:1>:<EOL><INDENT>cusdResponseFound = lineStartingWith('<STR_LIT>', cusdResponse) != None<EOL>if cusdResponseFound:<EOL><INDENT>self._ussdSessionEvent = None <EOL>return self._parseCusdResponse(cusdResponse)<EOL><DEDENT><DEDENT>if self._ussdSessionEvent.wait(responseTimeout):<EOL><INDENT>self._ussdSessionEvent = None<EOL>return self._ussdResponse<EOL><DEDENT>else: <EOL><INDENT>self._ussdSessionEvent = None <EOL>raise TimeoutException()<EOL><DEDENT> | 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 | f2360:c4:m20 |
def dial(self, number, timeout=<NUM_LIT:5>, callStatusUpdateCallbackFunc=None): | if self._waitForCallInitUpdate:<EOL><INDENT>self._dialEvent = threading.Event()<EOL>try:<EOL><INDENT>self.write('<STR_LIT>'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)<EOL><DEDENT>except Exception:<EOL><INDENT>self._dialEvent = None <EOL>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.write('<STR_LIT>'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse)<EOL>self.log.debug("<STR_LIT>")<EOL>callId = len(self.activeCalls) + <NUM_LIT:1><EOL>callType = <NUM_LIT:0> <EOL>call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)<EOL>self.activeCalls[callId] = call<EOL>return call<EOL><DEDENT>if self._mustPollCallStatus:<EOL><INDENT>threading.Thread(target=self._pollCallStatus, kwargs={'<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': timeout}).start()<EOL><DEDENT>if self._dialEvent.wait(timeout):<EOL><INDENT>self._dialEvent = None<EOL>callId, callType = self._dialResponse<EOL>call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc)<EOL>self.activeCalls[callId] = call<EOL>return call<EOL><DEDENT>else: <EOL><INDENT>self._dialEvent = None<EOL>raise TimeoutException()<EOL><DEDENT> | 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
remote events (i.e. when it is answered, the call is ended by the remote party)
:return: The outgoing call
:rtype: gsmmodem.modem.Call | f2360:c4:m21 |
def processStoredSms(self, unreadOnly=False): | states = [Sms.STATUS_RECEIVED_UNREAD]<EOL>if not unreadOnly:<EOL><INDENT>states.insert(<NUM_LIT:0>, Sms.STATUS_RECEIVED_READ)<EOL><DEDENT>for msgStatus in states:<EOL><INDENT>messages = self.listStoredSms(status=msgStatus, delete=True)<EOL>for sms in messages:<EOL><INDENT>self.smsReceivedCallback(sms)<EOL><DEDENT><DEDENT> | 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
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 | f2360:c4:m22 |
def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False): | self._setSmsMemory(readDelete=memory)<EOL>messages = []<EOL>delMessages = set()<EOL>if self._smsTextMode:<EOL><INDENT>cmglRegex= re.compile(r'<STR_LIT>')<EOL>for key, val in dictItemsIter(Sms.TEXT_MODE_STATUS_MAP):<EOL><INDENT>if status == val:<EOL><INDENT>statusStr = key<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(status))<EOL><DEDENT>result = self.write('<STR_LIT>'.format(statusStr))<EOL>msgLines = []<EOL>msgIndex = msgStatus = number = msgTime = None<EOL>for line in result:<EOL><INDENT>cmglMatch = cmglRegex.match(line) <EOL>if cmglMatch:<EOL><INDENT>if msgIndex != None and len(msgLines) > <NUM_LIT:0>:<EOL><INDENT>msgText = '<STR_LIT:\n>'.join(msgLines)<EOL>msgLines = []<EOL>messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText))<EOL>delMessages.add(int(msgIndex))<EOL><DEDENT>msgIndex, msgStatus, number, msgTime = cmglMatch.groups()<EOL>msgLines = []<EOL><DEDENT>else:<EOL><INDENT>if line != '<STR_LIT:OK>':<EOL><INDENT>msgLines.append(line)<EOL><DEDENT><DEDENT><DEDENT>if msgIndex != None and len(msgLines) > <NUM_LIT:0>:<EOL><INDENT>msgText = '<STR_LIT:\n>'.join(msgLines)<EOL>msgLines = []<EOL>messages.append(ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText))<EOL>delMessages.add(int(msgIndex))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cmglRegex = re.compile(r'<STR_LIT>')<EOL>readPdu = False<EOL>result = self.write('<STR_LIT>'.format(status))<EOL>for line in result:<EOL><INDENT>if not readPdu:<EOL><INDENT>cmglMatch = cmglRegex.match(line)<EOL>if cmglMatch:<EOL><INDENT>msgIndex = int(cmglMatch.group(<NUM_LIT:1>))<EOL>msgStat = int(cmglMatch.group(<NUM_LIT:2>))<EOL>readPdu = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>smsDict = decodeSmsPdu(line)<EOL><DEDENT>except EncodingError:<EOL><INDENT>self.log.debug('<STR_LIT>', line)<EOL><DEDENT>else:<EOL><INDENT>if smsDict['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>sms = ReceivedSms(self, int(msgStat), smsDict['<STR_LIT>'], smsDict['<STR_LIT:time>'], smsDict['<STR_LIT:text>'], smsDict['<STR_LIT>'])<EOL><DEDENT>elif smsDict['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>sms = StatusReport(self, int(msgStat), smsDict['<STR_LIT>'], smsDict['<STR_LIT>'], smsDict['<STR_LIT:time>'], smsDict['<STR_LIT>'], smsDict['<STR_LIT:status>'])<EOL><DEDENT>else:<EOL><INDENT>raise CommandError('<STR_LIT>'.format(smsDict['<STR_LIT:type>']))<EOL><DEDENT>messages.append(sms)<EOL>delMessages.add(msgIndex)<EOL>readPdu = False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if delete:<EOL><INDENT>if status == Sms.STATUS_ALL:<EOL><INDENT>self.deleteMultipleStoredSms()<EOL><DEDENT>else:<EOL><INDENT>for msgIndex in delMessages:<EOL><INDENT>self.deleteStoredSms(msgIndex)<EOL><DEDENT><DEDENT><DEDENT>return messages<EOL> | 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 | f2360:c4:m23 |
def _handleModemNotification(self, lines): | threading.Thread(target=self.__threadedHandleModemNotification, kwargs={'<STR_LIT>': lines}).start()<EOL> | 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 | f2360:c4:m24 |
def __threadedHandleModemNotification(self, lines): | for line in lines:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>self._handleIncomingCall(lines)<EOL>return<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>self._handleSmsReceived(line)<EOL>return<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>self._handleUssd(lines)<EOL>return<EOL><DEDENT>elif line.startswith('<STR_LIT>'):<EOL><INDENT>self._handleSmsStatusReport(line)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>for updateRegex, handlerFunc in self._callStatusUpdates:<EOL><INDENT>match = updateRegex.match(line)<EOL>if match:<EOL><INDENT>handlerFunc(match)<EOL>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.log.debug('<STR_LIT>', lines)<EOL> | Implementation of _handleModemNotification() to be run in a separate thread
:param lines The lines that were read | f2360:c4:m25 |
def _handleCallInitiated(self, regexMatch, callId=None, callType=<NUM_LIT:1>): | if self._dialEvent:<EOL><INDENT>if regexMatch:<EOL><INDENT>groups = regexMatch.groups()<EOL>if len(groups) >= <NUM_LIT:2>:<EOL><INDENT>self._dialResponse = (int(groups[<NUM_LIT:0>]) , int(groups[<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>self._dialResponse = (int(groups[<NUM_LIT:0>]), <NUM_LIT:1>) <EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._dialResponse = callId, callType<EOL><DEDENT>self._dialEvent.set()<EOL><DEDENT> | Handler for "outgoing call initiated" event notification line | f2360:c4:m27 |
def _handleCallAnswered(self, regexMatch, callId=None): | if regexMatch:<EOL><INDENT>groups = regexMatch.groups()<EOL>if len(groups) > <NUM_LIT:1>:<EOL><INDENT>callId = int(groups[<NUM_LIT:0>])<EOL>self.activeCalls[callId].answered = True<EOL><DEDENT>else:<EOL><INDENT>for call in dictValuesIter(self.activeCalls):<EOL><INDENT>if call.answered == False and type(call) == Call:<EOL><INDENT>call.answered = True<EOL>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.activeCalls[callId].answered = True<EOL><DEDENT> | Handler for "outgoing call answered" event notification line | f2360:c4:m28 |
def _handleCallRejected(self, regexMatch, callId=None): | return self._handleCallEnded(regexMatch, callId, True)<EOL> | Handler for rejected (unanswered calls being ended)
Most modems use _handleCallEnded for handling both call rejections and remote hangups.
This method does the same, but filters for unanswered calls only. | f2360:c4:m30 |
def _handleSmsReceived(self, notificationLine): | self.log.debug('<STR_LIT>')<EOL>cmtiMatch = self.CMTI_REGEX.match(notificationLine)<EOL>if cmtiMatch:<EOL><INDENT>msgMemory = cmtiMatch.group(<NUM_LIT:1>)<EOL>msgIndex = cmtiMatch.group(<NUM_LIT:2>)<EOL>sms = self.readStoredSms(msgIndex, msgMemory)<EOL>self.deleteStoredSms(msgIndex)<EOL>self.smsReceivedCallback(sms)<EOL><DEDENT> | Handler for "new SMS" unsolicited notification line | f2360:c4:m31 |
def _handleSmsStatusReport(self, notificationLine): | self.log.debug('<STR_LIT>')<EOL>cdsiMatch = self.CDSI_REGEX.match(notificationLine)<EOL>if cdsiMatch:<EOL><INDENT>msgMemory = cdsiMatch.group(<NUM_LIT:1>)<EOL>msgIndex = cdsiMatch.group(<NUM_LIT:2>)<EOL>report = self.readStoredSms(msgIndex, msgMemory)<EOL>self.deleteStoredSms(msgIndex)<EOL>if report.reference in self.sentSms: <EOL><INDENT>self.sentSms[report.reference].report = report<EOL><DEDENT>if self._smsStatusReportEvent: <EOL><INDENT>self._smsStatusReportEvent.set()<EOL><DEDENT>else:<EOL><INDENT>self.smsStatusReportCallback(report)<EOL><DEDENT><DEDENT> | Handler for SMS status reports | f2360:c4:m32 |
def readStoredSms(self, index, memory=None): | <EOL>self._setSmsMemory(readDelete=memory)<EOL>msgData = self.write('<STR_LIT>'.format(index))<EOL>if self._smsTextMode:<EOL><INDENT>cmgrMatch = self.CMGR_SM_DELIVER_REGEX_TEXT.match(msgData[<NUM_LIT:0>])<EOL>if cmgrMatch:<EOL><INDENT>msgStatus, number, msgTime = cmgrMatch.groups()<EOL>msgText = '<STR_LIT:\n>'.join(msgData[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL>return ReceivedSms(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], number, parseTextModeTimeStr(msgTime), msgText)<EOL><DEDENT>else:<EOL><INDENT>cmgrMatch = self.CMGR_SM_REPORT_REGEXT_TEXT.match(msgData[<NUM_LIT:0>])<EOL>if cmgrMatch:<EOL><INDENT>msgStatus, reference, number, sentTime, deliverTime, deliverStatus = cmgrMatch.groups()<EOL>if msgStatus.startswith('<STR_LIT:">'):<EOL><INDENT>msgStatus = msgStatus[<NUM_LIT:1>:-<NUM_LIT:1>] <EOL><DEDENT>if len(msgStatus) == <NUM_LIT:0>:<EOL><INDENT>msgStatus = "<STR_LIT>"<EOL><DEDENT>return StatusReport(self, Sms.TEXT_MODE_STATUS_MAP[msgStatus], int(reference), number, parseTextModeTimeStr(sentTime), parseTextModeTimeStr(deliverTime), int(deliverStatus))<EOL><DEDENT>else:<EOL><INDENT>raise CommandError('<STR_LIT>'.format(msgData))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>cmgrMatch = self.CMGR_REGEX_PDU.match(msgData[<NUM_LIT:0>])<EOL>if not cmgrMatch:<EOL><INDENT>raise CommandError('<STR_LIT>'.format(msgData))<EOL><DEDENT>stat, alpha, length = cmgrMatch.groups()<EOL>try:<EOL><INDENT>stat = int(stat)<EOL><DEDENT>except Exception:<EOL><INDENT>stat = Sms.STATUS_RECEIVED_UNREAD<EOL><DEDENT>pdu = msgData[<NUM_LIT:1>]<EOL>smsDict = decodeSmsPdu(pdu)<EOL>if smsDict['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return ReceivedSms(self, int(stat), smsDict['<STR_LIT>'], smsDict['<STR_LIT:time>'], smsDict['<STR_LIT:text>'], smsDict['<STR_LIT>'])<EOL><DEDENT>elif smsDict['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return StatusReport(self, int(stat), smsDict['<STR_LIT>'], smsDict['<STR_LIT>'], smsDict['<STR_LIT:time>'], smsDict['<STR_LIT>'], smsDict['<STR_LIT:status>'])<EOL><DEDENT>else:<EOL><INDENT>raise CommandError('<STR_LIT>'.format(smsDict['<STR_LIT:type>']))<EOL><DEDENT><DEDENT> | 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) | f2360:c4:m33 |
def deleteStoredSms(self, index, memory=None): | self._setSmsMemory(readDelete=memory)<EOL>self.write('<STR_LIT>'.format(index))<EOL> | 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 | f2360:c4:m34 |
def deleteMultipleStoredSms(self, delFlag=<NUM_LIT:4>, memory=None): | if <NUM_LIT:0> < delFlag <= <NUM_LIT:4>:<EOL><INDENT>self._setSmsMemory(readDelete=memory)<EOL>self.write('<STR_LIT>'.format(delFlag))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | 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 | f2360:c4:m35 |
def _handleUssd(self, lines): | if self._ussdSessionEvent:<EOL><INDENT>self._ussdResponse = self._parseCusdResponse(lines)<EOL>self._ussdSessionEvent.set()<EOL><DEDENT> | Handler for USSD event notification line(s) | f2360:c4:m36 |
def _parseCusdResponse(self, lines): | if len(lines) > <NUM_LIT:1>:<EOL><INDENT>cusdMatches = list(self.CUSD_REGEX.finditer('<STR_LIT:\r\n>'.join(lines)))<EOL><DEDENT>else:<EOL><INDENT>cusdMatches = [self.CUSD_REGEX.match(lines[<NUM_LIT:0>])]<EOL><DEDENT>message = None<EOL>sessionActive = True<EOL>if len(cusdMatches) > <NUM_LIT:1>:<EOL><INDENT>self.log.debug('<STR_LIT>')<EOL>for cusdMatch in cusdMatches:<EOL><INDENT>if cusdMatch.group(<NUM_LIT:1>) == '<STR_LIT:2>':<EOL><INDENT>self.log.debug('<STR_LIT>', cusdMatch.group(<NUM_LIT:2>))<EOL>sessionActive = False<EOL><DEDENT>else:<EOL><INDENT>message = cusdMatch.group(<NUM_LIT:2>)<EOL>if sessionActive and cusdMatch.group(<NUM_LIT:1>) != '<STR_LIT:1>':<EOL><INDENT>sessionActive = False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>sessionActive = cusdMatches[<NUM_LIT:0>].group(<NUM_LIT:1>) == '<STR_LIT:1>'<EOL>message = cusdMatches[<NUM_LIT:0>].group(<NUM_LIT:2>)<EOL><DEDENT>return Ussd(self, sessionActive, message)<EOL> | Parses one or more +CUSD notification lines (for USSD)
:return: USSD response object
:rtype: gsmmodem.modem.Ussd | f2360:c4:m37 |
def _placeHolderCallback(self, *args): | self.log.debug('<STR_LIT>'.format(args))<EOL> | Does nothing | f2360:c4:m38 |
def _pollCallStatus(self, expectedState, callId=None, timeout=None): | callDone = False<EOL>timeLeft = timeout or <NUM_LIT><EOL>while self.alive and not callDone and timeLeft > <NUM_LIT:0>:<EOL><INDENT>time.sleep(<NUM_LIT:0.5>)<EOL>if expectedState == <NUM_LIT:0>: <EOL><INDENT>timeLeft -= <NUM_LIT:0.5><EOL><DEDENT>try:<EOL><INDENT>clcc = self._pollCallStatusRegex.match(self.write('<STR_LIT>')[<NUM_LIT:0>])<EOL><DEDENT>except TimeoutException as timeout:<EOL><INDENT>clcc = None<EOL><DEDENT>if clcc:<EOL><INDENT>direction = int(clcc.group(<NUM_LIT:2>))<EOL>if direction == <NUM_LIT:0>: <EOL><INDENT>stat = int(clcc.group(<NUM_LIT:3>))<EOL>if expectedState == <NUM_LIT:0>: <EOL><INDENT>if stat == <NUM_LIT:2> or stat == <NUM_LIT:3>: <EOL><INDENT>callId = int(clcc.group(<NUM_LIT:1>))<EOL>callType = int(clcc.group(<NUM_LIT:4>))<EOL>self._handleCallInitiated(None, callId, callType) <EOL>expectedState = <NUM_LIT:1> <EOL><DEDENT><DEDENT>elif expectedState == <NUM_LIT:1>: <EOL><INDENT>if stat == <NUM_LIT:0>: <EOL><INDENT>callId = int(clcc.group(<NUM_LIT:1>))<EOL>self._handleCallAnswered(None, callId)<EOL>expectedState = <NUM_LIT:2> <EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif expectedState == <NUM_LIT:2> : <EOL><INDENT>callDone = True<EOL>self._handleCallEnded(None, callId=callId)<EOL><DEDENT>elif expectedState == <NUM_LIT:1>: <EOL><INDENT>callDone = True<EOL>self._handleCallRejected(None, callId=callId)<EOL><DEDENT><DEDENT>if timeLeft <= <NUM_LIT:0>:<EOL><INDENT>raise TimeoutException()<EOL><DEDENT> | 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 | f2360:c4:m39 |
def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallbackFunc=None): | self._gsmModem = weakref.proxy(gsmModem)<EOL>self._callStatusUpdateCallbackFunc = callStatusUpdateCallbackFunc<EOL>self.id = callId<EOL>self.type = callType <EOL>self.number = number <EOL>self._answered = False<EOL>self.active = True<EOL> | :param gsmModem: GsmModem instance that created this object
:param number: The number that is being called | f2360:c5:m0 |
def sendDtmfTone(self, tones): | if self.answered:<EOL><INDENT>dtmfCommandBase = self.DTMF_COMMAND_BASE.format(cid=self.id)<EOL>toneLen = len(tones)<EOL>if len(tones) > <NUM_LIT:1>:<EOL><INDENT>cmd = ('<STR_LIT>' + '<STR_LIT>'.join(tones[<NUM_LIT:1>:])).format(dtmfCommandBase, tones[<NUM_LIT:0>]) <EOL><DEDENT>else:<EOL><INDENT>cmd = '<STR_LIT>'.format(dtmfCommandBase, tones)<EOL><DEDENT>try:<EOL><INDENT>self._gsmModem.write(cmd, timeout=(<NUM_LIT:5> + toneLen))<EOL><DEDENT>except CmeError as e:<EOL><INDENT>if e.code == <NUM_LIT:30>:<EOL><INDENT>raise InterruptedException('<STR_LIT>', e)<EOL><DEDENT>elif e.code == <NUM_LIT:3>:<EOL><INDENT>raise InterruptedException('<STR_LIT>', e)<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise InvalidStateException('<STR_LIT>')<EOL><DEDENT> | 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 InvalidStateException: if the call has not been answered, or is ended while the command is still executing | f2360:c5:m3 |
def hangup(self): | if self.active:<EOL><INDENT>self._gsmModem.write('<STR_LIT>')<EOL>self.answered = False<EOL>self.active = False<EOL><DEDENT>if self.id in self._gsmModem.activeCalls:<EOL><INDENT>del self._gsmModem.activeCalls[self.id]<EOL><DEDENT> | End the phone call.
Does nothing if the call is already inactive. | f2360:c5:m4 |
def __init__(self, gsmModem, number, ton, callerName, callId, callType): | if type(callType) == str:<EOL><INDENT>callType = self.CALL_TYPE_MAP[callType] <EOL><DEDENT>super(IncomingCall, self).__init__(gsmModem, callId, callType, number) <EOL>self.ton = ton<EOL>self.callerName = callerName <EOL>self.ringing = True <EOL>self.ringCount = <NUM_LIT:1><EOL> | :param gsmModem: GsmModem instance that created this object
:param number: Caller number
:param ton: TON (type of number/address) in integer format
:param callType: Type of the incoming call (VOICE, FAX, DATA, etc) | f2360:c6:m0 |
def answer(self): | if self.ringing:<EOL><INDENT>self._gsmModem.write('<STR_LIT>')<EOL>self.ringing = False<EOL>self.answered = True<EOL><DEDENT>return self<EOL> | Answer the phone call.
:return: self (for chaining method calls) | f2360:c6:m1 |
def hangup(self): | self.ringing = False<EOL>super(IncomingCall, self).hangup()<EOL> | End the phone call. | f2360:c6:m2 |
def reply(self, message): | if self.sessionActive:<EOL><INDENT>return self._gsmModem.sendUssd(message)<EOL><DEDENT>else:<EOL><INDENT>raise InvalidStateException('<STR_LIT>')<EOL><DEDENT> | 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) | f2360:c7:m1 |
def cancel(self): | if self.sessionActive:<EOL><INDENT>self._gsmModem.write('<STR_LIT>')<EOL><DEDENT> | Terminates/cancels the USSD session (without sending a reply)
Does nothing if the USSD session is inactive. | f2360:c7:m2 |
def __init__(self, port, baudrate=<NUM_LIT>, notifyCallbackFunc=None, fatalErrorCallbackFunc=None, *args, **kwargs): | self.alive = False<EOL>self.port = port<EOL>self.baudrate = baudrate<EOL>self._responseEvent = None <EOL>self._expectResponseTermSeq = None <EOL>self._response = None <EOL>self._notification = [] <EOL>self._txLock = threading.RLock()<EOL>self.notifyCallback = notifyCallbackFunc or self._placeholderCallback <EOL>self.fatalErrorCallback = fatalErrorCallbackFunc or self._placeholderCallback<EOL> | Constructor
:param fatalErrorCallbackFunc: function to call if a fatal error occurs in the serial device reading thread
:type fatalErrorCallbackFunc: func | f2362:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.