Library API

When mcbootflash is used as a library, the main object of intereset is the BootloaderConnection. It provides methods for flashing new firmware, erasing existing firmware, reading metadata from the connected device, and resetting the device.

The flashing module also offers a command-line interface which other applications can hook into to set their own defaults, add or remove parameters, set help messages, etc. See Command-line interface.

connection

class mcbootflash.connection.BootloaderConnection(**kwargs: str)[source]

Bases: Serial

Communication interface to device running MCC 16-bit bootloader.

BootloaderConnection subclasses serial.Serial from pyserial. When creating a new BootloaderConnection instance, you will typically need to specify at least the ‘port’ and ‘baudrate’ arguments from the parent class. See pyserial’s documentation for detailed information about the serial.Serial class.

flash(hexfile: str, quiet: bool = False) None[source]

Flash application firmware.

Parameters
  • hexfile (str) – Path to a HEX-file containing application firmware.

  • quiet (bool (optional)) – If true, don’t print a progressbar while flashing. False by default.

Raises
read_version() Tuple[int, int, int, int, int][source]

Read bootloader version and some other useful information.

Returns

  • version (int)

  • max_packet_length (int) – The maximum size of a single packet sent to the bootloader, including both the command and associated data.

  • device_id (int)

  • erase_size (int) – Flash page size. When erasing flash memory, the number of bytes to be erased must align with a flash page.

  • write_size (int) – Write block size. When writing to flash, the number of bytes to be written must align with a write block.

erase_flash(erase_size: Union[None, int] = None, erase_range: Union[None, range] = None, force: bool = False, verify: bool = True) None[source]

Erase program memory area.

Parameters
  • erase_size (int, optional) – Size of an erase flash page in bytes. Read from connected device if not specified.

  • erase_range (range, optional) – Address range to erase. By default the entire program memory is erased.

  • force (bool, optional) – By default, flash erase will be skipped if no program is detected in the program memory area. Setting force to True skips program detection and erases regardless of whether a program is present or not.

  • verify (bool, optional) – The ERASE_FLASH command may fail silently if the unlock_sequence field of the command packet is incorrect. By default, this method verifies that the erase was successful by checking that no application is detected after the erase. Set verify to False to skip this check.

reset() None[source]

Reset device.

protocol

See also Protocol specification.

Definitions and representations for data sent to and from the bootloader.

class mcbootflash.protocol.BootCommand(value)[source]

Bases: IntEnum

The MCC 16-bit bootloader supports these commands.

READ_VERSION = 0
READ_FLASH = 1
WRITE_FLASH = 2
ERASE_FLASH = 3
CALC_CHECKSUM = 8
RESET_DEVICE = 9
SELF_VERIFY = 10
GET_MEMORY_ADDRESS_RANGE = 11
class mcbootflash.protocol.BootResponse(value)[source]

Bases: IntEnum

Sent by the bootloader in response to a command.

UNDEFINED = 0
SUCCESS = 1
UNSUPPORTED_COMMAND = 255
BAD_ADDRESS = 254
BAD_LENGTH = 253
VERIFY_FAIL = 252
class mcbootflash.protocol.ChecksumPacket(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0, success: BootResponse = BootResponse.UNDEFINED, checksum: int = 0)[source]

Bases: ResponsePacket

Response to CALCULATE_CHECKSUM command.

Layout:

| [ResponsePacket] | uint16   |
| [ResponsePacket] | checksum |
Parameters

checksum (int) – Checksum of data_length bytes starting from address.

checksum: int = 0
FORMAT: ClassVar[str] = '=BH2IBH'
class mcbootflash.protocol.CommandPacket(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0)[source]

Bases: Packet

Base class for packets sent to the bootloader.

Layout is identical to Packet.

command: BootCommand
class mcbootflash.protocol.Packet(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0)[source]

Bases: object

Base class for communication packets to and from the bootloader.

Layout:

| uint8   | uint16      | uint32          | uint32   |
| command | data_length | unlock_sequence | address  |
Parameters
  • command (BootCommand) – Command code which specifies which command should be executed by the bootloader.

  • data_length (int) –

    Meaning depends on value of ‘command’-field:

    WRITE_FLASH: Number of bytes following the command packet.
    ERASE_FLASH: Number of flash pages to be erased.
    CALC_CHECKSUM: Number of bytes to checksum.
    

    For other commands this field is ignored.

  • unlock_sequence (uint32) – Key to unlock flash memory for writing. Write operations (WRITE_FLASH, ERASE_FLASH) will fail SILENTLY if this key is incorrect.

  • address (uint32) – Address at which to perform command.

  • FORMAT (ClassVar[str]) – Format string for struct which specifies types and layout of the data fields.

Note

No error is raised if the key is incorrect. A failed WRITE_FLASH operation can be detected by comparing checksums of the written bytes and the flash area they were written to. A failed ERASE_FLASH operation can be detected by issuing a SELF_VERIFY command. If the erase succeeded, SELF_VERIFY should return VERIFY_FAIL.

command: BootCommand
data_length: int = 0
unlock_sequence: int = 0
address: int = 0
FORMAT: ClassVar[str] = '=BH2I'
classmethod from_bytes(data: bytes) _P[source]

Create a Packet instance from a bytes-like object.

classmethod from_serial(interface: Serial) _P[source]

Create a Packet instance by reading from a serial interface.

classmethod get_size() int[source]

Get the size of Packet in bytes.

class mcbootflash.protocol.MemoryRangePacket(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0, success: BootResponse = BootResponse.UNDEFINED, program_start: int = 0, program_end: int = 0)[source]

Bases: ResponsePacket

Response to GET_MEMORY_RANGE command.

Layout:

| [ResponsePacket] | uint32        | uint32      |
| [ResponsePacket] | program_start | program_end |
Parameters
  • program_start (int) – Low end of address space to which application firmware can be flashed.

  • program_end (int) – High end of address space to which application firmware can be flashed.

program_start: int = 0
program_end: int = 0
FORMAT: ClassVar[str] = '=BH2IB2I'
class mcbootflash.protocol.ResponsePacket(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0, success: BootResponse = BootResponse.UNDEFINED)[source]

Bases: Packet

Base class for most packets received from the bootloader.

Layout:

| [Packet] | uint8   |
| [Packet] | success |

The exception is READ_VERSION, in response to which a VersionResponsePacket is received instead.

Parameters

success (BootResponse) – Success or failure status of the command this packet is sent in response to.

success: BootResponse = 0
FORMAT: ClassVar[str] = '=BH2IB'
class mcbootflash.protocol.VersionResponsePacket(command: BootCommand, data_length: int = 0, unlock_sequence: int = 0, address: int = 0, version: int = 0, max_packet_length: int = 0, device_id: int = 0, erase_size: int = 0, write_size: int = 0)[source]

Bases: Packet

Response to a READ_VERSION command.

Layout:

| [Packet] | uint16  | uint16            | uint16    | uint16    | ...
| [Packet] | version | max_packet_length | (ignored) | device_id | ...

... | uint16    | uint16     | uint16     | uint32    | uint32    | uint32    |
... | (ignored) | erase_size | write_size | (ignored) | (ignored) | (ignored) |
Parameters
  • version (uint16) – Bootloader version number.

  • max_packet_length (int16) – Maximum number of bytes which can be sent to the bootloader per packet. Includes the size of the packet itself plus associated data.

  • device_id (uint16) – A device-specific identifier.

  • erase_size (uint16) – Size of a flash erase page in bytes. When erasing flash, the size of the memory area which should be erased is given in number of erase pages.

  • write_size (uint16) – Size of a write block in bytes. When writing to flash, the data must align with a write block.

version: int = 0
max_packet_length: int = 0
device_id: int = 0
erase_size: int = 0
write_size: int = 0
FORMAT: ClassVar[str] = '=BH2I2H2xH2x2H12x'

flashing

See also Command-line interface.

Command line tool for flashing firmware.

mcbootflash.flashing.flash(parsed_args: Union[None, Namespace] = None) None[source]

Entry point for console_script.

Parameters

parsed_args (argparse.Namespace, optional) – Pre-parsed arguments. If not specified, arguments will be parsed from the command line.

mcbootflash.flashing.get_parser() ArgumentParser[source]

Return a populated ArgumentParser instance.

This function is meant to be used by applications which want to create their own CLI while using mcbootflash in the background.

Returns

The returned ArgumentParser has the following arguments already added:

file           (str,   required)
-p, --port     (str,   required)
-b, --baudrate (int,   required)
-t, --timeout  (float, default=5)
-v, --verbose  (bool,  default=False)
-q, --quiet    (bool,  default=False)

These arguments can be overridden by adding a new argument with the same option string. For example, an application which only needs to communicate with a specific device with a known serial baudrate could override the ‘baudrate’ option to make it optional:

import mcbootflash
parser = mcbootflash.get_parser()
parser.add_argument("-b", "--baudrate", default=460800)
mcbootflash.flash(parser.parse_args())

Return type

argparse.ArgumentParser

error

Exceptions raised by mcbootflash.

exception mcbootflash.error.BadAddress[source]

Bases: BootloaderError

Raised if ResponsePacket.success is BootResponse.BAD_ADDRESS.

This means an operation was attempted outside of the program memory range.

exception mcbootflash.error.BadLength[source]

Bases: BootloaderError

Raised if ResponsePacket.success is BootResponse.BAD_LENGTH.

This means that the size of the command packet plus associated data was greater than permitted.

exception mcbootflash.error.BootloaderError[source]

Bases: McbootflashException

Base class for exceptions that map to a specific BootResponse error code.

exception mcbootflash.error.ChecksumError[source]

Bases: McbootflashException

Raised in case of mismatch between local and remote checksums.

exception mcbootflash.error.ConnectionFailure[source]

Bases: McbootflashException

Raised if the connection to the bootloader cannot be established or is lost.

exception mcbootflash.error.FlashEraseFail[source]

Bases: McbootflashException

Raised if a program is still detected in flash memory after an erase attempt.

exception mcbootflash.error.McbootflashException[source]

Bases: Exception

Base class for mcbootflash exceptions.

exception mcbootflash.error.NoData[source]

Bases: McbootflashException

Raised if asked to flash a HEX file which contains no suitable data.

Specifically, the HEX file must contain at least one memory segment that fits entirely within the program memory range specified by the bootloader.

exception mcbootflash.error.UnexpectedResponse[source]

Bases: McbootflashException

Raised if the command fields of a Command/Response packet pair do not match.

exception mcbootflash.error.UnsupportedCommand[source]

Bases: BootloaderError

Raised if ResponsePacket.success is BootResponse.UNSUPPORTED_COMMAND.

This means that the bootloader did not recognize the most recently sent command.

exception mcbootflash.error.VerifyFail[source]

Bases: BootloaderError

Raised if ResponsePacket.success is BootResponse.VERIFY_FAIL.

This means that no program was detected in the program memory range.