desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Instance initialiation. Arguments: dbf: A `Dbf.Dbf` instance this record belonogs to. index: An integer record index or None. If this value is None, record will be appended to the DBF. deleted: Boolean flag indicating whether this record is a deleted record. data: A sequence or None. This is a data of the fields. If t...
def __init__(self, dbf, index=None, deleted=False, data=None):
self.dbf = dbf self.index = index self.deleted = deleted if (data is None): self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields] else: self.fieldData = list(data)
'Return raw record contents read from the stream. Arguments: dbf: A `Dbf.Dbf` instance containing the record. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is a string containing record data in DBF format.'
def rawFromStream(cls, dbf, index):
dbf.stream.seek((dbf.header.headerLength + (index * dbf.header.recordLength))) return dbf.stream.read(dbf.header.recordLength)
'Return a record read from the stream. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is an instance of the current class.'
def fromStream(cls, dbf, index):
return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
'Return record read from the string object. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. string: A string new record should be created from. index: Index of the record in the container. If this argument is None, record will be appended. Return value is an instance of the current class.'
def fromString(cls, dbf, string, index=None):
return cls(dbf, index, (string[0] == '*'), [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
'Write data to the dbf stream. Note: This isn\'t a public method, it\'s better to use \'store\' instead publically. Be design ``_write`` method should be called only from the `Dbf` instance.'
def _write(self):
self._validateIndex(False) self.dbf.stream.seek(self.position) self.dbf.stream.write(bytes(self.toString(), sys.getfilesystemencoding())) if (self.index == len(self.dbf)): self.dbf.stream.write('\x1a')
'Valid ``self.index`` value. If ``allowUndefined`` argument is True functions does nothing in case of ``self.index`` pointing to None object.'
def _validateIndex(self, allowUndefined=True, checkRange=False):
if (self.index is None): if (not allowUndefined): raise ValueError('Index is undefined') elif (self.index < 0): raise ValueError(("Index can't be negative (%s)" % self.index)) elif (checkRange and (self.index <= self.dbf.header.recordCount)): raise Value...
'Store current record in the DBF. If ``self.index`` is None, this record will be appended to the records of the DBF this records belongs to; or replaced otherwise.'
def store(self):
self._validateIndex() if (self.index is None): self.index = len(self.dbf) self.dbf.append(self) else: self.dbf[self.index] = self
'Mark method as deleted.'
def delete(self):
self.deleted = True
'Return string packed record values.'
def toString(self):
return ''.join(([' *'[self.deleted]] + [_def.encodeValue(_dat) for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData)]))
'Return a flat list of fields. Note: Change of the list\'s values won\'t change real values stored in this object.'
def asList(self):
return self.fieldData[:]
'Return a dictionary of fields. Note: Change of the dicts\'s values won\'t change real values stored in this object.'
def asDict(self):
return dict([_i for _i in zip(self.dbf.fieldNames, self.fieldData)])
'Return value by field name or field index.'
def __getitem__(self, key):
if isinstance(key, int): return self.fieldData[key] return self.fieldData[self.dbf.indexOfFieldName(key)]
'Set field value by integer index of the field or string name.'
def __setitem__(self, key, value):
if isinstance(key, int): return self.fieldData[key] self.fieldData[self.dbf.indexOfFieldName(key)] = value
'Append the actual tags to content.'
def render(self, tag, single, between, kwargs):
out = (u'<%s' % tag) for (key, value) in kwargs.iteritems(): if (value is not None): key = key.strip('_') if (key in ['http_equiv', 'accept_charset']): key.replace('_', '-') out = (u'%s %s="%s"' % (out, key, escape(value))) else: ...
'Append a closing tag unless element has only opening tag.'
def close(self):
if (self.tag in self.parent.twotags): self.parent.content.append(('</%s>' % self.tag)) elif (self.tag in self.parent.onetags): raise ClosingError(self.tag) elif ((self.parent.mode == 'strict_html') and (self.tag in self.parent.deptags)): raise DeprecationError(self.tag)
'Append an opening tag.'
def open(self, **kwargs):
if ((self.tag in self.parent.twotags) or (self.tag in self.parent.onetags)): self.render(self.tag, False, None, kwargs) elif ((self.mode == 'strict_html') and (self.tag in self.parent.deptags)): raise DeprecationError(self.tag)
'Stuff that effects the whole document. mode -- \'strict_html\' for HTML 4.01 (default) \'html\' alias for \'strict_html\' \'loose_html\' to allow some deprecated elements \'xml\' to allow arbitrary elements case -- \'lower\' element names will be printed in lower case (default) \'upper\...
def __init__(self, mode='strict_html', case='lower', onetags=None, twotags=None, separator='\n', class_=None):
valid_onetags = ['AREA', 'BASE', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'LINK', 'META', 'PARAM'] valid_twotags = ['A', 'ABBR', 'ACRONYM', 'ADDRESS', 'B', 'BDO', 'BIG', 'BLOCKQUOTE', 'BODY', 'BUTTON', 'CAPTION', 'CITE', 'CODE', 'COLGROUP', 'DD', 'DEL', 'DFN', 'DIV', 'DL', 'DT', 'EM', 'FIELDSET', 'FORM', 'FR...
'Return the document as a string. escape -- False print normally True replace < and > by &lt; and &gt; the default escape sequences in most browsers'
def __call__(self, escape=False):
if escape: return _escape(self.__str__()) else: return self.__str__()
'This is an alias to addcontent.'
def add(self, text):
self.addcontent(text)
'Add some text to the bottom of the document'
def addfooter(self, text):
self.footer.append(text)
'Add some text to the top of the document'
def addheader(self, text):
self.header.append(text)
'Add some text to the main part of the document'
def addcontent(self, text):
self.content.append(text)
'This method is used for complete documents with appropriate doctype, encoding, title, etc information. For an HTML/XML snippet omit this method. lang -- language, usually a two character string, will appear as <html lang=\'en\'> in html mode (ignored in xml mode) css -- Cascading Style Sheet filename as a str...
def init(self, lang='en', css=None, metainfo=None, title=None, header=None, footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None):
self._full = True if ((self.mode == 'strict_html') or (self.mode == 'loose_html')): if (doctype is None): doctype = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>" self.header.append(doctype) self.html(lang=lang) self.head() ...
'This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.'
def css(self, filelist):
if isinstance(filelist, basestring): self.link(href=filelist, rel='stylesheet', type='text/css', media='all') else: for file in filelist: self.link(href=file, rel='stylesheet', type='text/css', media='all')
'This convenience function is only useful for html. It adds meta information via the <meta> element, the argument is a dictionary of the form { \'name\':\'content\' }.'
def metainfo(self, mydict):
if isinstance(mydict, dict): for (name, content) in mydict.iteritems(): self.meta(name=name, content=content) else: raise TypeError('Metainfo should be called with a dictionary argument of name:content pairs.')
'Only useful in html, mydict is dictionary of src:type pairs will be rendered as <script type=\'text/type\' src=src></script>'
def scripts(self, mydict):
if isinstance(mydict, dict): for (src, type) in mydict.iteritems(): self.script('', src=src, type=('text/%s' % type)) else: raise TypeError('Script should be given a dictionary of src:type pairs.')
'Return `DbfFieldDef` instance from the current definition.'
def getDbfField(self):
return self.cls(self.name, self.len, self.dec)
'Create a `DbfFieldDef` instance and append it to the dbf header. Arguments: dbfh: `DbfHeader` instance.'
def appendToHeader(self, dbfh):
_dbff = self.getDbfField() dbfh.addField(_dbff)
'Add field definition. Arguments: name: field name (str object). field name must not contain ASCII NULs and it\'s length shouldn\'t exceed 10 characters. typ: type of the field. this must be a single character from the "CNLMDT" set meaning character, numeric, logical, memo, date and date/time respectively. len: length ...
def add_field(self, name, typ, len, dec=0):
self.fields.append(self.FieldDefinitionClass(name, typ, len, dec))
'Create empty .DBF file using current structure.'
def write(self, filename):
_dbfh = DbfHeader() _dbfh.setCurrentDate() for _fldDef in self.fields: _fldDef.appendToHeader(_dbfh) _dbfStream = file(filename, 'wb') _dbfh.write(_dbfStream) _dbfStream.close()
'Initialize instance.'
def __init__(self, name, length=None, decimalCount=None, start=None, stop=None, ignoreErrors=False):
assert (self.typeCode is not None), 'Type code must be overriden' assert (self.defaultValue is not None), 'Default value must be overriden' if (len(name) > 10): raise ValueError(('Field name "%s" is too long' % name)) name = str(name).upper() if (self._...
'Decode dbf field definition from the string data. Arguments: string: a string, dbf definition is decoded from. length of the string must be 32 bytes. start: position in the database file. ignoreErrors: initial error processing mode for the new field (boolean)'
def fromString(cls, string, start, ignoreErrors=False):
assert (len(string) == 32) _length = ord(string[16]) return cls(utils.unzfill(string)[:11], _length, ord(string[17]), start, (start + _length), ignoreErrors=ignoreErrors)
'Return encoded field definition. Return: Return value is a string object containing encoded definition of this field.'
def toString(self):
if (sys.version_info < (2, 4)): _name = (self.name[:11] + ('\x00' * (11 - len(self.name)))) else: _name = self.name.ljust(11, '\x00') return (((((_name + self.typeCode) + (chr(0) * 4)) + chr(self.length)) + chr(self.decimalCount)) + (chr(0) * 14))
'Return field information. Return: Return value is a (name, type, length, decimals) tuple.'
def fieldInfo(self):
return (self.name, self.typeCode, self.length, self.decimalCount)
'Return a "raw" field value from the record string.'
def rawFromRecord(self, record):
return record[self.start:self.end]
'Return decoded field value from the record string.'
def decodeFromRecord(self, record):
try: return self.decodeValue(self.rawFromRecord(record)) except: if self.ignoreErrors: return utils.INVALID_VALUE else: raise
'Return decoded value from string value. This method shouldn\'t be used publicly. It\'s called from the `decodeFromRecord` method. This is an abstract method and it must be overridden in child classes.'
def decodeValue(self, value):
raise NotImplementedError
'Return str object containing encoded field value. This is an abstract method and it must be overriden in child classes.'
def encodeValue(self, value):
raise NotImplementedError
'Return string object. Return value is a ``value`` argument with stripped right spaces.'
def decodeValue(self, value):
return value.rstrip(' ')
'Return raw data string encoded from a ``value``.'
def encodeValue(self, value):
return str(value)[:self.length].ljust(self.length)
'Return a number decoded from ``value``. If decimals is zero, value will be decoded as an integer; or as a float otherwise. Return: Return value is a int (long) or float instance.'
def decodeValue(self, value):
value = value.strip(' \x00') if ('.' in value): return float(value) elif value: return int(value) else: return 0
'Return string containing encoded ``value``.'
def encodeValue(self, value):
_rv = ('%*.*f' % (self.length, self.decimalCount, value)) if (len(_rv) > self.length): _ppos = _rv.find('.') if (0 <= _ppos <= self.length): _rv = _rv[:self.length] else: raise ValueError(('[%s] Numeric overflow: %s (field width: %i)' % (self.nam...
'Return an integer number decoded from ``value``.'
def decodeValue(self, value):
return struct.unpack('<i', value)[0]
'Return string containing encoded ``value``.'
def encodeValue(self, value):
return struct.pack('<i', int(value))
'Return float number decoded from ``value``.'
def decodeValue(self, value):
return (struct.unpack('<q', value)[0] / 10000.0)
'Return string containing encoded ``value``.'
def encodeValue(self, value):
return struct.pack('<q', round((value * 10000)))
'Return True, False or -1 decoded from ``value``.'
def decodeValue(self, value):
if (value == '?'): return (-1) if (value in 'NnFf '): return False if (value in 'YyTt'): return True raise ValueError(('[%s] Invalid logical value %r' % (self.name, value)))
'Return a character from the "TF?" set. Return: Return value is "T" if ``value`` is True "?" if value is -1 or False otherwise.'
def encodeValue(self, value):
if (value is True): return 'T' if (value == (-1)): return '?' return 'F'
'Return int .dbt block number decoded from the string object.'
def decodeValue(self, value):
raise NotImplementedError
'Return raw data string encoded from a ``value``. Note: this is an internal method.'
def encodeValue(self, value):
raise NotImplementedError
'Return a ``datetime.date`` instance decoded from ``value``.'
def decodeValue(self, value):
if value.strip(): return utils.getDate(value) else: return None
'Return a string-encoded value. ``value`` argument should be a value suitable for the `utils.getDate` call. Return: Return value is a string in format "yyyymmdd".'
def encodeValue(self, value):
if value: return utils.getDate(value).strftime('%Y%m%d') else: return (' ' * self.length)
'Return a `datetime.datetime` instance.'
def decodeValue(self, value):
assert (len(value) == self.length) (_jdn, _msecs) = struct.unpack('<2I', value) if (_jdn >= 1): _rv = datetime.datetime.fromordinal((_jdn - self.JDN_GDN_DIFF)) _rv += datetime.timedelta(0, (_msecs / 1000.0)) else: _rv = None return _rv
'Return a string-encoded ``value``.'
def encodeValue(self, value):
if value: value = utils.getDateTime(value) _rv = struct.pack('<2I', (value.toordinal() + self.JDN_GDN_DIFF), ((((value.hour * 3600) + (value.minute * 60)) + value.second) * 1000)) else: _rv = ('\x00' * self.length) assert (len(_rv) == self.length) return _rv
'Initialize instance. Arguments: fields: a list of field definitions; recordLength: size of the records; headerLength: size of the header; recordCount: number of records stored in DBF; signature: version number (aka signature). using 0x03 as a default meaning "File without DBT". for more information about this field vi...
def __init__(self, fields=None, headerLength=0, recordLength=0, recordCount=0, signature=3, lastUpdate=None, ignoreErrors=False):
self.signature = signature if (fields is None): self.fields = [] else: self.fields = list(fields) self.lastUpdate = utils.getDate(lastUpdate) self.recordLength = recordLength self.headerLength = headerLength self.recordCount = recordCount self.ignoreErrors = ignoreErrors ...
'Return header instance from the string object.'
def fromString(cls, string):
return cls.fromStream(cStringIO.StringIO(str(string)))
'Return header object from the stream.'
def fromStream(cls, stream):
stream.seek(0) _data = stream.read(32) (_cnt, _hdrLen, _recLen) = struct.unpack('<I2H', _data[4:12]) _year = ord(_data[1]) if (_year < 80): _year += 2000 else: _year += 1900 _obj = cls(None, _hdrLen, _recLen, _cnt, ord(_data[0]), (_year, ord(_data[2]), ord(_data[3]))) _po...
'Update `ignoreErrors` flag on self and all fields'
def ignoreErrors(self, value):
self._ignore_errors = value = bool(value) for _field in self.fields: _field.ignoreErrors = value
'Internal variant of the `addField` method. This method doesn\'t set `self.changed` field to True. Return value is a length of the appended records. Note: this method doesn\'t modify ``recordLength`` and ``headerLength`` fields. Use `addField` instead of this method if you don\'t exactly know what you\'re doing.'
def _addField(self, *defs):
_defs = [] _recordLength = 0 for _def in defs: if isinstance(_def, fields.DbfFieldDef): _obj = _def else: (_name, _type, _len, _dec) = (tuple(_def) + ((None,) * 4))[:4] _cls = fields.lookupFor(_type) _obj = _cls(_name, _len, _dec, ignoreErrors=...
'Add field definition to the header. Examples: dbfh.addField( ("name", "C", 20), dbf.DbfCharacterFieldDef("surname", 20), dbf.DbfDateFieldDef("birthdate"), ("member", "L"), dbfh.addField(("price", "N", 5, 2)) dbfh.addField(dbf.DbfNumericFieldDef("origprice", 5, 2))'
def addField(self, *defs):
_oldLen = self.recordLength self.recordLength += self._addField(*defs) if (not _oldLen): self.recordLength += 1 self.headerLength = ((32 + (32 * len(self.fields))) + 1) self.changed = True
'Encode and write header to the stream.'
def write(self, stream):
stream.seek(0) stream.write(self.toString()) stream.write(''.join([_fld.toString() for _fld in self.fields])) stream.write(chr(13)) self.changed = False
'Returned 32 chars length string with encoded header.'
def toString(self):
return (struct.pack('<4BI2H', self.signature, (self.year - 1900), self.month, self.day, self.recordCount, self.headerLength, self.recordLength) + ('\x00' * 20))
'Update ``self.lastUpdate`` field with current date value.'
def setCurrentDate(self):
self.lastUpdate = datetime.date.today()
'Return a field definition by numeric index or name string'
def __getitem__(self, item):
if isinstance(item, basestring): _name = item.upper() for _field in self.fields: if (_field.name == _name): return _field else: raise KeyError(item) else: return self.fields[item]
'Initialize instance. Arguments: f: Filename or file-like object. new: True if new data table must be created. Assume data table exists if this argument is False. readOnly: if ``f`` argument is a string file will be opend in read-only mode; in other cases this argument is ignored. This argument is ignored even if ``new...
def __init__(self, f, readOnly=False, new=False, ignoreErrors=False):
if isinstance(f, basestring): self.name = f if new: self.stream = file(f, 'w+b') else: self.stream = file(f, ('r+b', 'rb')[bool(readOnly)]) else: self.name = getattr(f, 'name', '') self.stream = f if new: self.header = self.HeaderClass(...
'Update `ignoreErrors` flag on the header object and self'
def ignoreErrors(self, value):
self.header.ignoreErrors = self._ignore_errors = bool(value)
'Return fixed index. This method fails if index isn\'t a numeric object (long or int). Or index isn\'t in a valid range (less or equal to the number of records in the db). If ``index`` is a negative number, it will be treated as a negative indexes for list objects. Return: Return value is numeric object maning valid in...
def _fixIndex(self, index):
if (not isinstance(index, (int, long))): raise TypeError('Index must be a numeric object') if (index < 0): index += (len(self) + 1) if (index >= len(self)): raise IndexError('Record index out of range') return index
'Flush data to the associated stream.'
def flush(self):
if self.changed: self.header.setCurrentDate() self.header.write(self.stream) self.stream.flush() self._changed = False
'Index of field named ``name``.'
def indexOfFieldName(self, name):
return self.header.fields.index(name)
'Return new record, which belong to this table.'
def newRecord(self):
return self.RecordClass(self)
'Append ``record`` to the database.'
def append(self, record):
record.index = self.header.recordCount record._write() self.header.recordCount += 1 self._changed = True self._new = False
'Add field definitions. For more information see `header.DbfHeader.addField`.'
def addField(self, *defs):
if self._new: self.header.addField(*defs) else: raise TypeError("At least one record was added, structure can't be changed")
'Return number of records.'
def __len__(self):
return self.recordCount
'Return `DbfRecord` instance.'
def __getitem__(self, index):
return self.RecordClass.fromStream(self, self._fixIndex(index))
'Write `DbfRecord` instance to the stream.'
def __setitem__(self, index, record):
record.index = self._fixIndex(index) record._write() self._changed = True self._new = False
'Instance initialiation. Arguments: dbf: A `Dbf.Dbf` instance this record belonogs to. index: An integer record index or None. If this value is None, record will be appended to the DBF. deleted: Boolean flag indicating whether this record is a deleted record. data: A sequence or None. This is a data of the fields. If t...
def __init__(self, dbf, index=None, deleted=False, data=None):
self.dbf = dbf self.index = index self.deleted = deleted if (data is None): self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields] else: self.fieldData = list(data)
'Return raw record contents read from the stream. Arguments: dbf: A `Dbf.Dbf` instance containing the record. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is a string containing record data in DBF format.'
def rawFromStream(cls, dbf, index):
dbf.stream.seek((dbf.header.headerLength + (index * dbf.header.recordLength))) return dbf.stream.read(dbf.header.recordLength)
'Return a record read from the stream. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is an instance of the current class.'
def fromStream(cls, dbf, index):
return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
'Return record read from the string object. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. string: A string new record should be created from. index: Index of the record in the container. If this argument is None, record will be appended. Return value is an instance of the current class.'
def fromString(cls, dbf, string, index=None):
return cls(dbf, index, (string[0] == '*'), [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
'Write data to the dbf stream. Note: This isn\'t a public method, it\'s better to use \'store\' instead publically. Be design ``_write`` method should be called only from the `Dbf` instance.'
def _write(self):
self._validateIndex(False) self.dbf.stream.seek(self.position) self.dbf.stream.write(self.toString()) if (self.index == len(self.dbf)): self.dbf.stream.write('\x1a')
'Valid ``self.index`` value. If ``allowUndefined`` argument is True functions does nothing in case of ``self.index`` pointing to None object.'
def _validateIndex(self, allowUndefined=True, checkRange=False):
if (self.index is None): if (not allowUndefined): raise ValueError('Index is undefined') elif (self.index < 0): raise ValueError(("Index can't be negative (%s)" % self.index)) elif (checkRange and (self.index <= self.dbf.header.recordCount)): raise Value...
'Store current record in the DBF. If ``self.index`` is None, this record will be appended to the records of the DBF this records belongs to; or replaced otherwise.'
def store(self):
self._validateIndex() if (self.index is None): self.index = len(self.dbf) self.dbf.append(self) else: self.dbf[self.index] = self
'Mark method as deleted.'
def delete(self):
self.deleted = True
'Return string packed record values.'
def toString(self):
return ''.join(([' *'[self.deleted]] + [_def.encodeValue(_dat) for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)]))
'Return a flat list of fields. Note: Change of the list\'s values won\'t change real values stored in this object.'
def asList(self):
return self.fieldData[:]
'Return a dictionary of fields. Note: Change of the dicts\'s values won\'t change real values stored in this object.'
def asDict(self):
return dict([_i for _i in izip(self.dbf.fieldNames, self.fieldData)])
'Return value by field name or field index.'
def __getitem__(self, key):
if isinstance(key, (long, int)): return self.fieldData[key] return self.fieldData[self.dbf.indexOfFieldName(key)]
'Set field value by integer index of the field or string name.'
def __setitem__(self, key, value):
if isinstance(key, (int, long)): return self.fieldData[key] self.fieldData[self.dbf.indexOfFieldName(key)] = value
'Init Result Event.'
def __init__(self, data):
wx.PyEvent.__init__(self) self.SetEventType(EVT_DEBUG_ID) self.data = data
'Initializes port by resetting device and gettings supported PIDs.'
def __init__(self, portnum, _notify_window, SERTIMEOUT, RECONNATTEMPTS):
baud = 9600 databits = 8 par = serial.PARITY_NONE sb = 1 to = SERTIMEOUT self.ELMver = 'Unknown' self.State = 1 self._notify_window = _notify_window wx.PostEvent(self._notify_window, DebugEvent([1, 'Opening interface (serial port)'])) try: self.port = serial.Seri...
'Resets device and closes all associated filehandles'
def close(self):
if ((self.port != None) and (self.State == 1)): self.send_command('atz') self.port.close() self.port = None self.ELMver = 'Unknown'
'Internal use only: not a public interface'
def send_command(self, cmd):
if self.port: self.port.flushOutput() self.port.flushInput() for c in cmd: self.port.write(c) self.port.write('\r\n') wx.PostEvent(self._notify_window, DebugEvent([3, ('Send command:' + cmd)]))
'Internal use only: not a public interface'
def interpret_result(self, code):
if (len(code) < 7): print ('boguscode?' + code) code = string.split(code, '\r') code = code[0] code = string.split(code) code = string.join(code, '') if (code[:6] == 'NODATA'): return 'NODATA' code = code[4:] return code
'Internal use only: not a public interface'
def get_result(self):
time.sleep(0.1) if self.port: buffer = '' while 1: c = self.port.read(1) if ((c == '\r') and (len(buffer) > 0)): break elif ((buffer != '') or (c != '>')): buffer = (buffer + c) wx.PostEvent(self._notify_window, DebugEve...
'Internal use only: not a public interface'
def get_sensor_value(self, sensor):
cmd = sensor.cmd self.send_command(cmd) data = self.get_result() if data: data = self.interpret_result(data) if (data != 'NODATA'): data = sensor.value(data) else: return 'NORESPONSE' return data
'Returns 3-tuple of given sensors. 3-tuple consists of (Sensor Name (string), Sensor Value (string), Sensor Unit (string) )'
def sensor(self, sensor_index):
sensor = obd_sensors.SENSORS[sensor_index] r = self.get_sensor_value(sensor) return (sensor.name, r, sensor.unit)
'Internal use only: not a public interface'
def sensor_names(self):
names = [] for s in obd_sensors.SENSORS: names.append(s.name) return names
'Returns a list of all pending DTC codes. Each element consists of a 2-tuple: (DTC code (string), Code description (string) )'
def get_dtc(self):
dtcLetters = ['P', 'C', 'B', 'U'] r = self.sensor(1)[1] dtcNumber = r[0] mil = r[1] DTCCodes = [] print ((('Number of stored DTC:' + str(dtcNumber)) + ' MIL: ') + str(mil)) for i in range(0, ((dtcNumber + 2) / 3)): self.send_command(GET_DTC_COMMAND) res = self....
'Clears all DTCs and freeze frame data'
def clear_dtc(self):
self.send_command(CLEAR_DTC_COMMAND) r = self.get_result() return r
'Download packages, packges must be list in format of [url, path, package name]'
def download(self, packages):
for package in packages: url = package[0] filename = package[1] pkg_name = package[2] try: directory = os.path.dirname(filename) if (not os.path.exists(directory)): os.makedirs(directory) Log.info(self, 'Downloading {0:20}'.forma...