iotile.core.utilities.intelhex

Intel HEX format manipulation library.

Package Contents

__docformat__ = javadoc
total_size(o, handlers={}, verbose=False)

Returns the approximate memory footprint an object and all of its contents.

Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers to iterate over their contents:

handlers = {SomeContainerClass: iter,
OtherContainerClass: OtherContainerClass.get_elements}
class _DeprecatedParam

Bases:object

_DEPRECATED
class IntelHex(source=None)

Bases:object

Intel HEX file reader.

fromfile
_get_eol_textfile
_decode_record(self, s, line=0)

Decode one record of HEX file.

@param s line with HEX record. @param line line number (for error messages).

@raise EndOfFile if EOF record encountered.

loadhex(self, fobj)

Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized.

@param fobj file name or file-like object

loadbin(self, fobj, offset=0)

Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized.

@param fobj file name or file-like object @param offset starting address offset

loadfile(self, fobj, format)

Load data file into internal buffer. Preferred wrapper over loadbin or loadhex.

@param fobj file name or file-like object @param format file format (“hex” or “bin”)

fromdict(self, dikt)

Load data from dictionary. Dictionary should contain int keys representing addresses. Values should be the data to be stored in those addresses in unsigned char form (i.e. not strings). The dictionary may contain the key, start_addr to indicate the starting address of the data as described in README.

The contents of the dict will be merged with this object and will overwrite any conflicts. This function is not necessary if the object was initialized with source specified.

frombytes(self, bytes, offset=0)

Load data from array or list of bytes. Similar to loadbin() method but works directly with iterable bytes.

_get_start_end(self, start=None, end=None, size=None)

Return default values for start and end if they are None. If this IntelHex object is empty then it’s error to invoke this method with both start and end as None.

tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None)

Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead]

fill empty spaces with this value (if pad is None then this method uses self.padding).

@param size size of the block, used with start or end parameter. @return array of unsigned char data.

_tobinarray_really(self, start, end, pad, size)

Return binary array.

tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None)

Convert to binary form and return as binary string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead]

fill empty spaces with this value (if pad is None then this method uses self.padding).

@param size size of the block, used with start or end parameter. @return bytes string of binary data.

_tobinstr_really(self, start, end, pad, size)
tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None)

Convert to binary and write to file.

@param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead]

fill empty spaces with this value (if pad is None then this method uses self.padding).

@param size size of the block, used with start or end parameter.

todict(self)

Convert to python dictionary.

@return dict suitable for initializing another IntelHex object.

addresses(self)

Returns all used addresses in sorted order. @return list of occupied data addresses in sorted order.

minaddr(self)

Get minimal address of HEX content. @return minimal address or None if no data

maxaddr(self)

Get maximal address of HEX content. @return maximal address or None if no data

__getitem__(self, addr)

Get requested byte from address. @param addr address of byte. @return byte if address exists in HEX file, or self.padding

if no data found.
__setitem__(self, addr, byte)

Set byte at address.

__delitem__(self, addr)

Delete byte at address.

__len__(self)

Return count of bytes with real values.

static _get_eol_textfile(eolstyle, platform)
write_hex_file(self, f, write_start_addr=True, eolstyle='native', byte_count=16)

Write data to file f in HEX format.

@param f filename or file-like object for writing @param write_start_addr enable or disable writing start address

record to file (enabled by default). If there is no start address in obj, nothing will be written regardless of this setting.
@param eolstyle can be used to force CRLF line-endings
for output file on different platforms. Supported eol styles: ‘native’, ‘CRLF’.

@param byte_count number of bytes in the data field

tofile(self, fobj, format)

Write data to hex or bin file. Preferred method over tobin or tohex.

@param fobj file name or file-like object @param format file format (“hex” or “bin”)

gets(self, addr, length)

Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used.

puts(self, addr, s)

Put string of bytes at given address. Will overwrite any previous entries.

getsz(self, addr)

Get zero-terminated bytes string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0.

putsz(self, addr, s)

Put bytes string in object at addr and append terminating zero at end.

dump(self, tofile=None, width=16, withpadding=False)

Dump object content to specified file object or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right.

@param tofile file-like object to dump to @param width number of bytes per line (i.e. columns) @param withpadding print padding character instead of ‘–’ @raise ValueError if width is not a positive integer

merge(self, other, overlap='error')

Merge content of other IntelHex object into current object (self). @param other other IntelHex object. @param overlap action on overlap of data or starting addr:

  • error: raising OverlapError;

  • ignore: ignore other data and keep current data

    in overlapping region;

  • replace: replace data with other data

    in overlapping region.

@raise TypeError if other is not instance of IntelHex @raise ValueError if other is the same object as self

(it can’t merge itself)

@raise ValueError if overlap argument has incorrect value @raise AddressOverlapError on overlapped data

segments(self)

Return a list of ordered tuple objects, representing contiguous occupied data addresses. Each tuple has a length of two and follows the semantics of the range and xrange objects. The second entry of the tuple is always an integer greater than the first entry.

get_memory_size(self)

Returns the approximate memory footprint for data.

class IntelHex16bit(source=None)

Bases:iotile.core.utilities.intelhex.IntelHex

Access to data as 16-bit words. Intended to use with Microchip HEX files.

__getitem__(self, addr16)

Get 16-bit word from address. Raise error if only one byte from the pair is set. We assume a Little Endian interpretation of the hex file.

@param addr16 address of word (addr8 = 2 * addr16). @return word if bytes exists in HEX file, or self.padding

if no data found.
__setitem__(self, addr16, word)

Sets the address at addr16 to word assuming Little Endian mode.

minaddr(self)

Get minimal address of HEX content in 16-bit mode.

@return minimal address used in this object

maxaddr(self)

Get maximal address of HEX content in 16-bit mode.

@return maximal address used in this object

tobinarray(self, start=None, end=None, size=None)

Convert this object to binary form as array (of 2-bytes word data). If start and end unspecified, they will be inferred from the data. @param start start address of output data. @param end end address of output data (inclusive). @param size size of the block (number of words),

used with start or end parameter.

@return array of unsigned short (uint16_t) data.

hex2bin(fin, fout, start=None, end=None, size=None, pad=None)

Hex-to-Bin convertor engine. @return 0 if all OK

@param fin input hex file (filename or file-like object) @param fout output bin file (filename or file-like object) @param start start of address range (optional) @param end end of address range (inclusive; optional) @param size size of resulting file (in bytes) (optional) @param pad padding byte (optional)

bin2hex(fin, fout, offset=0)

Simple bin-to-hex convertor. @return 0 if all OK

@param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin

diff_dumps(ih1, ih2, tofile=None, name1='a', name2='b', n_context=3)

Diff 2 IntelHex objects and produce unified diff output for their hex dumps.

@param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to write output @param name1 name of the first hex file to show in the diff header @param name2 name of the first hex file to show in the diff header @param n_context number of context lines in the unidiff output

class Record

Bases:object

Helper methods to build valid ihex records.

_from_bytes
data
eof
extended_segment_address
start_segment_address
extended_linear_address
start_linear_address
static _from_bytes(bytes)

Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum.

@param bytes list of byte values so far to pack into record. @return String representation of one HEX record

static data(offset, bytes)

Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset.

@param offset load offset of first byte. @param bytes list of byte values to pack into record.

@return String representation of one HEX record

static eof()

Return End of File record as a string. @return String representation of Intel Hex EOF record

static extended_segment_address(usba)

Return Extended Segment Address Record. @param usba Upper Segment Base Address.

@return String representation of Intel Hex USBA record.

static start_segment_address(cs, ip)

Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register.

@return String representation of Intel Hex SSA record.

static extended_linear_address(ulba)

Return Extended Linear Address Record. @param ulba Upper Linear Base Address.

@return String representation of Intel Hex ELA record.

static start_linear_address(eip)

Return Start Linear Address Record. @param eip 32-bit linear address for the EIP register.

@return String representation of Intel Hex SLA record.

exception _BadFileNotation

Bases:Exception

Special error class to use with _get_file_and_addr_range.

_get_file_and_addr_range(s, _support_drive_letter=None)

Special method for hexmerge.py script to split file notation into 3 parts: (filename, start, end)

@raise _BadFileNotation when string cannot be safely split.

exception IntelHexError(msg=None, **kw)

Bases:Exception

Base Exception class for IntelHex module

_fmt = IntelHex base error
__str__(self)

Return the message in this Exception.

exception _EndOfFile

Bases:iotile.core.utilities.intelhex.IntelHexError

Used for internal needs only.

_fmt = EOF record reached -- signal to stop read file
exception HexReaderError

Bases:iotile.core.utilities.intelhex.IntelHexError

_fmt = Hex reader base error
exception AddressOverlapError

Bases:iotile.core.utilities.intelhex.HexReaderError

_fmt = Hex file has data overlap at address 0x%(address)X on line %(line)d
exception HexRecordError

Bases:iotile.core.utilities.intelhex.HexReaderError

_fmt = Hex file contains invalid record at line %(line)d
exception RecordLengthError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = Record at line %(line)d has invalid length
exception RecordTypeError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = Record at line %(line)d has invalid record type
exception RecordChecksumError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = Record at line %(line)d has invalid checksum
exception EOFRecordError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = File has invalid End-of-File record
exception ExtendedAddressRecordError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = Base class for extended address exceptions
exception ExtendedSegmentAddressRecordError

Bases:iotile.core.utilities.intelhex.ExtendedAddressRecordError

_fmt = Invalid Extended Segment Address Record at line %(line)d
exception ExtendedLinearAddressRecordError

Bases:iotile.core.utilities.intelhex.ExtendedAddressRecordError

_fmt = Invalid Extended Linear Address Record at line %(line)d
exception StartAddressRecordError

Bases:iotile.core.utilities.intelhex.HexRecordError

_fmt = Base class for start address exceptions
exception StartSegmentAddressRecordError

Bases:iotile.core.utilities.intelhex.StartAddressRecordError

_fmt = Invalid Start Segment Address Record at line %(line)d
exception StartLinearAddressRecordError

Bases:iotile.core.utilities.intelhex.StartAddressRecordError

_fmt = Invalid Start Linear Address Record at line %(line)d
exception DuplicateStartAddressRecordError

Bases:iotile.core.utilities.intelhex.StartAddressRecordError

_fmt = Start Address Record appears twice at line %(line)d
exception InvalidStartAddressValueError

Bases:iotile.core.utilities.intelhex.StartAddressRecordError

_fmt = Invalid start address value: %(start_addr)s
exception NotEnoughDataError

Bases:iotile.core.utilities.intelhex.IntelHexError

_fmt = Bad access at 0x%(address)X: not enough data to read %(length)d contiguous bytes
exception BadAccess16bit

Bases:iotile.core.utilities.intelhex.NotEnoughDataError

_fmt = Bad access at 0x%(address)X: not enough data to read 16 bit value
exception EmptyIntelHexError

Bases:iotile.core.utilities.intelhex.IntelHexError

_fmt = Requested operation cannot be executed with empty object