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:<...
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:...
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>', '...
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_L...
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>', '...
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_L...
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>...
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...
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 ...
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 ...
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 patte...
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 = _encodeTimes...
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 re...
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) - smscBytesRe...
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_L...
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(da...
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.da...
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_L...
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 (addres...
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>] =...
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 h...
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 nu...
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>resul...
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 ValueE...
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 == val...
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>prevSepte...
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 oct...
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 ...
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(Informat...
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('<...
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 timeou...
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><INDEN...
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...
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...
: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._smsMemReadDe...
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_LI...
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><DEDE...
: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:<EO...
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 :...
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, ...
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 waitFor...
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 = lineStart...
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 res...
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.wr...
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...
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><DEDE...
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...
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...
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 Non...
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...
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><DEDEN...
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:<E...
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)<EO...
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.s...
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(msg...
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 CommandErr...
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 ...
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 me...
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.debu...
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_LI...
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...
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 = '<S...
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 ...
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>...
Constructor :param fatalErrorCallbackFunc: function to call if a fatal error occurs in the serial device reading thread :type fatalErrorCallbackFunc: func
f2362:c0:m0