Utils Module API

Module containing various functions/modules used throughout the SPSDK.

Utils easy enum

EasyEnum allows numerical value, string tag and description to an enum element.

class spsdk.utils.easy_enum.Enum

Bases: object

Enum Type Class.

classmethod desc(default='')

Description of the specified value.

Parameters
  • key (Union[str, int]) – either value or name (name is case INSENSITIVE)

  • default (str) – value in case key does not exist

Return type

str

Returns

description of the value; empty string if description was not specified

Raises

TypeError – Key is nor string or int

classmethod from_int()

Converts integer value into enumeration.

Note: the method does two things: - checks whether given integer value is defined within the enumeration - formally converts value into enumeration (for type hints), even the returned value is same as input :type value: int :param value: integer value to be converted :rtype: Enum :return: corresponding enumeration :raises SPSDKError: If specified value does not match any enumeration value

classmethod get(default=None)

Converts enumeration value to name OR name to enumeration value.

Parameters
  • key (Union[str, int]) – either value or name (name is case INSENSITIVE)

  • default (Union[str, int, None]) – value in case key does not exist

Return type

str

Returns

name for value; value for name

classmethod name(default=None)

Returns name of selected enumeration tag.

Parameters
  • key (int) – enumeration tag

  • default (Optional[str]) – value to return of tag not found; if not defined, KeyError exception will be raised

Return type

str

Returns

name of the corresponding enumeration tag

Raises

KeyError – if tag not supported and default value not provided

classmethod tags()

Return sequence of all enumerations tags.

Return type

Sequence[int]

Utils crypto

Module for cryptographic utilities.

class spsdk.utils.crypto.BackendClass

Bases: abc.ABC

Abstract Class for Security Backend.

abstract aes_ctr_decrypt(key, encrypted_data, nonce)

Decrypt encrypted data with AES in CTR mode.

Parameters
  • key (bytes) – The key for data decryption

  • encrypted_data (bytes) – Input data

  • nonce (bytes) – Nonce data with counter value

Return type

bytes

abstract aes_ctr_encrypt(key, plain_data, nonce)

Encrypt plain data with AES in CTR mode.

Parameters
  • key (bytes) – The key for data encryption

  • plain_data (bytes) – Input data

  • nonce (bytes) – Nonce data with counter value

Return type

bytes

abstract aes_key_unwrap(kek, wrapped_key)

Unwraps a key using a key-encrypting key (KEK).

Parameters
  • kek (bytes) – The key-encrypting key

  • wrapped_key (bytes) – Encrypted data

Return type

bytes

abstract aes_key_wrap(kek, key_to_wrap)

Wraps a key using a key-encrypting key (KEK).

Parameters
  • kek (bytes) – The key-encrypting key

  • key_to_wrap (bytes) – Plain data

Return type

bytes

ecc_sign(private_key, data, algorithm=None)

Sign data using (EC)DSA.

Parameters
  • private_key (bytes) – ECC private key

  • data (bytes) – Data to sign

  • algorithm (Optional[str]) – Hash algorithm, if None the hash length is determined from ECC curve size

Return type

bytes

Returns

Signature, r and s coordinates as bytes

ecc_verify(public_key, signature, data, algorithm=None)

Verify (EC)DSA signature.

Parameters
  • public_key (bytes) – ECC public key

  • signature (bytes) – Signature to verify, r and s coordinates as bytes

  • data (bytes) – Data to validate

  • algorithm (Optional[str]) – Hash algorithm, if None the hash length is determined from ECC curve size

Return type

bool

Returns

True if the signature is valid

Raises

SPSDKError – Signature length is invalid

abstract hash(data, algorithm='sha256')

Return a HASH from input data with specified algorithm.

Parameters
  • data (bytes) – Input data in bytes

  • algorithm (str) – Algorithm type for HASH function

Return type

bytes

abstract hmac(key, data, algorithm='sha256')

Return a HMAC from data with specified key and algorithm.

Parameters
  • key (bytes) – The key in bytes format

  • data (bytes) – Input data in bytes format

  • algorithm (str) – Algorithm type for HASH function (sha256, sha384, sha512, …)

Return type

bytes

abstract property name

Backend Name.

Return type

str

abstract random_bytes(length)

Return a random byte string with specified length.

Parameters

length (int) – The length in bytes

Return type

bytes

rsa_public_key(modulus, exponent)

Create RSA public key object from modulus and exponent.

Parameters
  • modulus (int) – The RSA public key modulus

  • exponent (int) – The RSA public key exponent

Return type

Any

rsa_sign(private_key, data, algorithm='sha256')

Sign input data.

Parameters
  • private_key (bytes) – The private key

  • data (bytes) – Input data

  • algorithm (str) – Used algorithm

Return type

bytes

rsa_verify(pub_key_mod, pub_key_exp, signature, data, algorithm='sha256')

Verify input data.

Parameters
  • pub_key_mod (int) – The private key modulus

  • pub_key_exp (int) – The private key exponent

  • signature (bytes) – The signature of input data

  • data (bytes) – Input data

  • algorithm (str) – Used algorithm

Return type

bool

abstract property version

Backend Version.

Return type

str

class spsdk.utils.crypto.CertBlockV2(version='1.0', flags=0, build_number=0)

Bases: spsdk.utils.crypto.cert_blocks.CertBlock

Certificate block.

Shared for SB file and for MasterBootImage

Constructor.

Parameters
  • version (str) – of the certificate in format n.n

  • flags (int) – Flags for the Certificate Block Header

  • build_number (int) – of the certificate

DEFAULT_ALIGNMENT = 16
RKHT_SIZE = 4
RKH_SIZE = 32
add_certificate(cert)

Add certificate.

First call adds root certificate. Additional calls add chain certificates.

Parameters

cert (Union[bytes, Certificate]) – The certificate itself in DER format

Raises

SPSDKError – If certificate cannot be added

Return type

None

property alignment

Alignment of the binary output, by default it is DEFAULT_ALIGNMENT but can be customized.

Return type

int

property certificates

List of certificates in header.

First certificate is root certificate and followed by optional chain certificates

Return type

List[Certificate]

export()

Serialize Certificate Block V2 object.

Return type

bytes

property header

Certificate block header.

Return type

CertBlockHeader

property image_length

Image length in bytes.

Return type

int

info()

Text info about certificate block.

Return type

str

classmethod parse(data, offset=0)

Deserialize CertBlockV2 from binary file.

Parameters
  • data (bytes) – Binary data

  • offset (int) – Offset within the data, where the Certificate block begins, defaults to 0

Return type

CertBlockV2

Returns

Certificate Block instance

Raises

Exception – Length of the data doesn’t match Certificate Block length

property raw_size

Aligned size of the certificate block.

Return type

int

property rkh

List of root keys hashes (SHA-256), each hash as 32 bytes.

Return type

List[bytes]

property rkh_index

Index of the hash that matches the certificate; None if does not match.

Return type

Optional[int]

property rkht

32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys.

Return type

bytes

property rkht_fuses

List of RKHT fuses, ordered from highest bit to lowest.

Note: Returned values are in format that should be passed for blhost

Return type

List[int]

set_root_key_hash(index, key_hash)

Add Root Key Hash into RKH at specified index.

Note: Multiple root public keys are supported to allow for key revocation.

Parameters
  • index (int) – The index of Root Key Hash in the table

  • key_hash (Union[bytes, bytearray, Certificate]) – The Root Key Hash value (32 bytes, SHA-256); or Certificate where the hash can be created from public key

Raises
  • SPSDKError – When there is invalid index of root key hash in the table

  • SPSDKError – When there is invalid length of key hash

Return type

None

property signature_size

Size of the signature in bytes.

Return type

int

verify_data(signature, data)

Signature verification.

Parameters
  • signature (bytes) – to be verified

  • data (bytes) – that has been signed

Return type

bool

Returns

True if the data signature can be confirmed using the certificate; False otherwise

verify_private_key(private_key_pem_data)

Verify that given private key matches the public certificate.

Parameters

private_key_pem_data (bytes) – to be tested; decrypted binary data in PEM format

Return type

bool

Returns

True if yes; False otherwise

class spsdk.utils.crypto.Certificate(certificate)

Bases: object

Internally used representation of a Certificate.

Initialize the Certificate object.

Parameters

certificate (bytes) – Certificate bytes (read from file)

property ca

Certification Authority flag.

Return type

bool

export()

Serialized Certificate data.

Return type

bytes

property hash_algo

HASH algorithm used in the Certificate.

Return type

str

info()

Text information about the Certificate.

Return type

str

property issuer

Certificate issuer.

Return type

Dict[str, str]

property max_path_length

Maximum length of derived Certificate chain.

Return type

int

property not_valid_after

End of the Certificate valid period.

Return type

datetime

property not_valid_before

Begging of the Certificate valid period.

Return type

datetime

property public_key_exponent

Exponent of the public key of the certificate.

Return type

int

property public_key_hash

32 bytes hash (SHA-256) of public key (modulus and exponent).

Return type

bytes

property public_key_modulus

Modulus of the public key of the certificate.

Return type

int

property public_key_usage

Usage of the Certificate.

Return type

Set[str]

property raw_size

Size of the Certificate data (aligned to 4 bytes).

Return type

int

property self_issued

Is the Certificate self-issued (subject and issuer are the same).

Return type

bool

property self_signed

Indication whether the Certificate is self-signed.

A unicode string of “no” or “maybe”. The “maybe” result will be returned if the certificate issuer and subject are the same. If a key identifier and authority key identifier are present, they will need to match otherwise “no” will be returned.

To verify is a certificate is truly self-signed, the signature will need to be verified. See the certvalidator package for one possible solution.

Return type

str

property serial_number

Serial number of the Certificate.

Return type

int

property signature

Certificate signature.

Return type

bytes

property signature_algo

Certificate signature algorithm.

Return type

str

verify(public_key_modulus, public_key_exponent)

Use given public key to verify the certificate is signed.

Parameters
  • public_key_modulus (int) – modulus of the public key to be verified

  • public_key_exponent (int) – exponent of the public key to be verified

Return type

bool

Returns

True if verification pass; False otherwise

property version

Version of the Certificate.

Return type

str

class spsdk.utils.crypto.Counter(nonce, ctr_value=None, ctr_byteorder_encoding='little')

Bases: object

AES counter with specified counter byte ordering and customizable increment.

Constructor.

Parameters
  • nonce (bytes) – last for bytes are used as initial value for counter

  • ctr_value (Optional[int]) – counter initial value; it is added to counter value retrieved from nonce

  • ctr_byteorder_encoding (str) – way how the counter is encoded into output value: either ‘little’ or ‘big’

Raises

SPSDKError – When invalid byteorder is provided

increment(value=1)

Increment counter by specified value.

Parameters

value (int) – to add to counter

Return type

None

property value

Initial vector for AES encryption.

Return type

bytes

spsdk.utils.crypto.crypto_backend()

Return default crypto backend instance.

Return type

BackendClass

spsdk.utils.crypto.matches_key_and_cert(priv_key, cert)

Verify that given private key matches the public certificate.

Parameters
  • priv_key (bytes) – to be tested; decrypted binary data in PEM format

  • cert (Certificate) – to be used for verification

Return type

bool

Returns

True if yes; False otherwise

General utils

Miscellaneous functions used throughout the SPSDK.

class spsdk.utils.misc.DebugInfo(enabled=True)

Bases: object

The class is used to provide detailed information about export process and exported data.

It is handy for analyzing content and debugging changes in the exported binary output.

Constructor.

Parameters

enabled (bool) – True if logging enabled; False otherwise

append(line)

Appends the line to the log.

Parameters

line (str) – text to be added

Raises

SPSDKError – When there is nothing to append

Return type

None

append_binary_data(data_name, data)

Append short section with binary data.

Parameters
  • data_name (str) – the name

  • data (bytes) – binary data (up to 8 bytes)

Raises

SPSDKError – When the data has incorrect length

Return type

None

append_binary_section(section_name, data)

Append section and binary data.

Parameters
  • section_name (str) – the name

  • data (bytes) – binary data

Return type

None

append_hex_data(data)

Append binary data in HEX form.

Parameters

data (bytes) – to be logged

Return type

None

append_section(name)

Append new section to the debug log.

Parameters

name (str) – of the section

Return type

None

classmethod disabled()

Return an instance of DebugInfo with disabled message collecting.

Return type

DebugInfo

property enabled
Return type

bool

Returns

whether debugging enabled.

info()
Return type

str

Returns

multi-line text with log; empty string if nothing logged or log disabled.

property lines
Return type

Iterable[str]

Returns

list of logged lines; empty list if nothing logged or log disabled.

class spsdk.utils.misc.Timeout(timeout, units='s')

Bases: object

Simple timout handle class.

Simple timeout class constructor.

Parameters
  • timeout (int) – Timeout value.

  • units (str) – Timeout units (MUST be from the UNITS list)

Raises

SPSDKValueError – Invalid input value.

UNITS = {'ms': 1000, 's': 1000000, 'us': 1}
get_consumed_time()

Returns consumed time since start of timeouted operation.

Return type

int

Returns

Consumed time in units as the class was constructed

get_consumed_time_ms()

Returns consumed time since start of timeouted operation in milliseconds.

Return type

int

Returns

Consumed time in milliseconds

get_rest_time(raise_exc=False)

Returns rest time to timeout overflow.

Parameters

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type

int

Returns

Rest time in units as the class was constructed

Raises

SPSDKTimeoutError – In case of overflow

get_rest_time_ms(raise_exc=False)

Returns rest time to timeout overflow.

Parameters

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type

int

Returns

Rest time in milliseconds

Raises

SPSDKTimeoutError – In case of overflow

overflow(raise_exc=False)

Check the the timer has been overflowed.

Parameters

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type

bool

Returns

True if timeout overflowed, False otherwise.

Raises

SPSDKTimeoutError – In case of overflow

spsdk.utils.misc.align(number, alignment=4)

Align number (size or address) size to specified alignment, typically 4, 8 or 16 bytes boundary.

Parameters
  • number (int) – input to be aligned

  • alignment (int) – the boundary to align; typical value is power of 2

Return type

int

Returns

aligned number; result is always >= size (e.g. aligned up)

Raises

SPSDKError – When there is wrong alignment

spsdk.utils.misc.align_block(data, alignment=4, padding=0)

Align binary data block length to specified boundary by adding padding bytes to the end.

Parameters
  • data (bytes) – to be aligned

  • alignment (int) – boundary alignment (typically 2, 4, 16, 64 or 256 boundary)

  • padding (int) – byte to be added, use -1 to fill with random data

Return type

bytes

Returns

aligned block

Raises

SPSDKError – When there is wrong alignment

spsdk.utils.misc.align_block_fill_random(data, alignment=4)

Same as align_block, just parameter padding is fixed to -1 to fill with random data.

Return type

bytes

spsdk.utils.misc.change_endianism(bin_data)

Convert binary format used in files to binary used in register object.

Parameters

bin_data (bytes) – input binary array.

Return type

bytes

Returns

Converted array (practically little to big endianism).

Raises

SPSDKError – Invalid value on input.

spsdk.utils.misc.extend_block(data, length, padding=0)

Add padding to the binary data block to extend the length to specified value.

Parameters
  • data (bytes) – block to be extended

  • length (int) – requested block length; the value must be >= current block length

  • padding (int) – 8-bit value value to be used as a padding

Return type

bytes

Returns

block extended with padding

Raises

SPSDKError – When the length is incorrect

spsdk.utils.misc.find_first(iterable, predicate)

Find first element from the list, that matches the condition.

Parameters
  • iterable (Iterable[~T]) – list of elements

  • predicate (Callable[[~T], bool]) – function for selection of the element

Return type

Optional[~T]

Returns

found element; None if not found

spsdk.utils.misc.format_value(value, size, delimeter='_', use_prefix=True)

Convert the ‘value’ into either BIN or HEX string, depending on ‘size’.

if ‘size’ is divisible by 8, function returns HEX, BIN otherwise digits in result string are grouped by 4 using ‘delimeter’ (underscore)

Return type

str

spsdk.utils.misc.get_bytes_cnt_of_int(value, align_to_2n=True)

Returns count of bytes needed to store handled integer.

Parameters
  • value (int) – Input integer value.

  • align_to_2n (bool) – The result will be aligned to standard sizes 1,2,4,8,12,16,20.

Return type

int

Returns

Number of bytes needed to store integer.

spsdk.utils.misc.load_binary(*args)

Loads binary file into bytes.

Parameters

args (str) – list that consists of: - absolute path - optional sub-directory (any number) - file name including file extension All the fields together represents absolute path to the file

Return type

bytes

Returns

content of the binary file as bytes

spsdk.utils.misc.load_file(*path_segments, mode='r')

Loads a file into bytes.

Parameters
  • path_segments (str) – list that consists of: - absolute path - optional sub-directory (any number) - file name including file extension All the fields together represents absolute path to the file

  • mode (str) – mode for reading the file ‘r’/’rb’

Return type

Union[str, bytes]

Returns

content of the binary file as bytes or str (based on mode)

spsdk.utils.misc.load_text(*path_segments)

Loads binary file into bytes.

Parameters

path_segments (str) – list that consists of: - absolute path - optional sub-directory (any number) - file name including file extension All the fields together represents absolute path to the file

Return type

str

Returns

content of the binary file as bytes

spsdk.utils.misc.reverse_bytes_in_longs(arr)

The function reverse byte order in longs from input bytes.

Parameters

arr (bytes) – Input array.

Return type

bytes

Returns

New array with reversed bytes.

Raises

SPSDKError – Raises when invalid value is in input.

spsdk.utils.misc.use_working_directory(path)

Execute the block in given directory.

Cd into specific directory. Execute the block. Change the directory back into the original one.

Parameters

path (str) – the path, where the current directory will be changed to

Return type

Iterator[None]

spsdk.utils.misc.value_to_bool(value)

Function decode bool value from various formats.

Parameters

value (Union[bool, int, str]) – Input value.

Return type

bool

Returns

Boolean value.

Raises

SPSDKError – Unsupported input type.

spsdk.utils.misc.value_to_bytes(value, align_to_2n=True)

Function loads value from lot of formats.

Parameters
  • value (Union[bytes, bytearray, int, str]) – Input value.

  • align_to_2n (bool) – When is set, the function aligns length of return array to 1,2,4,8,12 etc.

Return type

bytes

Returns

Value in bytes.

spsdk.utils.misc.value_to_int(value, default=None)

Function loads value from lot of formats to integer.

Parameters
  • value (Union[bytes, bytearray, int, str]) – Input value.

  • default (Optional[int]) – Default Value in case of invalid input.

Return type

int

Returns

Value in Integer.

Raises

SPSDKError – Unsupported input type.

spsdk.utils.misc.write_file(data, *path_segments, mode='w')

Writes data into a file.

Parameters
  • data (Union[str, bytes]) – data to write

  • path_segments (str) – pieces of path to the file, might be just a single str

  • mode (str) – writing mode, ‘w’ for text, ‘wb’ for binary data, defaults to ‘w’

Return type

int

Returns

number of written elements

Serial Proxy

SerialProxy serves as patch replacement for serial.Serial class.

class spsdk.utils.serial_proxy.SerialProxy(port, timeout, baudrate)

Bases: object

SerialProxy is used to simulate communication with serial device.

It can be used as mock.patch for serial.Serial class. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))

Basic initialization for serial.Serial class.

__init__ signature must accommodate instantiation of serial.Serial

Parameters
  • port (str) – Serial port name

  • timeout (int) – timeout (does nothing)

  • baudrate (int) – Serial port speed (does nothing)

close()

Simulates closing a serial port.

Return type

None

flush()

Simulates flushing input buffer.

Return type

None

ignore_ack: bool = False
info()

Text information about the interface.

Return type

str

classmethod init_proxy(data, ignore_ack=False)

Initialized response dictionary of write and read bytes.

Parameters
  • data (Dict[bytes, bytes]) – Dictionary of write and read bytes

  • ignore_ack (bool) – Don’t modify internal buffer upon receiving a ACK packet

Return type

Type[SerialProxy]

Returns

SerialProxy class with configured data

open()

Simulates opening a serial port.

Return type

None

read(length)

Read portion of pre-configured data.

Parameters

length (int) – Amount of data to read from buffer

Return type

bytes

Returns

Data read

reset_input_buffer()

Simulates reseting input buffer.

Return type

None

reset_output_buffer()

Simulates reseting output buffer.

Return type

None

responses: Dict[bytes, bytes] = {}
write(data)

Simulates a write, currently just pick up response from responses.

Parameters

data (bytes) – Bytes to write, key in responses

Return type

None

class spsdk.utils.serial_proxy.SimpleReadSerialProxy(port, timeout, baudrate)

Bases: spsdk.utils.serial_proxy.SerialProxy

SimpleReadSerialProxy is used to simulate communication with serial device.

It simplifies reading method. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))

Basic initialization for serial.Serial class.

__init__ signature must accommodate instantiation of serial.Serial

Parameters
  • port (str) – Serial port name

  • timeout (int) – timeout (does nothing)

  • baudrate (int) – Serial port speed (does nothing)

FULL_BUFFER = b''
classmethod init_data_proxy(data)

Initialized response dictionary of write and read bytes.

Parameters

data (bytes) – Dictionary of write and read bytes

Return type

Type[SimpleReadSerialProxy]

Returns

SerialProxy class with configured data

write(data)

Simulates a write method, but it does nothing.

Parameters

data (bytes) – Bytes to write, key in responses

Return type

None

USB Filter

Module defining a USB filtering class.

class spsdk.utils.usbfilter.NXPUSBDeviceFilter(usb_id=None, nxp_device_names=None)

Bases: spsdk.utils.usbfilter.USBDeviceFilter

NXP Device Filtering class.

Extension of the generic USB device filter class to support filtering based on NXP devices. Modifies the way, how single number is handled. By default, if single value is provided, it’s content is expected to be VID. However, legacy tooling were expecting PID, so from this perspective if a single number is provided, we expect that VID is out of range NXP_VIDS.

Initialize the USB Device Filtering.

Parameters
  • usb_id (Optional[str]) – usb_id string

  • nxp_device_names (Optional[Dict[str, Tuple[int, int]]]) – Dictionary holding NXP device vid/pid {“device_name”: [vid(int), pid(int)]}

NXP_VIDS = [8137, 5538]
compare(usb_device_object)

Compares the internal usb_id with provided usb_device_object.

Extends the comparison by USB names - dictionary of device name and corresponding VID/PID.

Parameters

usb_device_object (Any) – lpcusbsio USB HID device object

Return type

bool

Returns

True on match, False otherwise

class spsdk.utils.usbfilter.USBDeviceFilter(usb_id=None, search_by_pid=False)

Bases: object

Generic USB Device Filtering class.

Create a filtering instance. This instance holds the USB ID you are interested in during USB HID device search and allows you to compare, whether provided USB HID object is the one you are interested in. The allowed format of usb_id string is following:

vid or pid - vendor ID or product ID. String holding hex or dec number. Hex number must be preceded by 0x or 0X. Number of characters after 0x is 1 - 4. Mixed upper & lower case letters is allowed. e.g. “0xaB12”, “0XAB12”, “0x1”, “0x0001”. The decimal number is restrictred only to have 1 - 5 digits, e.g. “65535” It’s allowed to set the USB filter ID to decimal number “99999”, however, as the USB VID number is four-byte hex number (max value is 65535), this will lead to zero results. Leading zeros are not allowed e.g. 0001. This will result as invalid match.

The user may provide a single number as usb_id. In such a case the number may represent either VID or PID. By default, the filter expects this number to be a VID. In rare cases the user may want to filter based on PID. Initialize the search_by_pid parameter to True in such cases.

vid/pid - string of vendor ID & product ID separated by ‘:’ or ‘,’ Same rules apply to the number format as in VID case, except, that the string consists of two numbers separated by ‘:’ or ‘,’. It’s not allowed to mix hex and dec numbers, e.g. “0xab12:12345” is not allowed. Valid vid/pid strings: “0x12aB:0xabc”, “1,99999”

Windows specific: instance ID - String in following format “HIDVID_<HEX>&PID_<HEX><instance_id>”, see instance ID in device manager under Windows OS.

Linux specific: USB device path - HID API returns path in following form: ‘0003:0002:00’

The first number represents the Bus, the second Device and the third interface. The Bus:Device number is unique so interface is not necessary and Bus:Device should be sufficient.

The Bus:Device can be observed using ‘lsusb’ command. The interface can be observed using ‘lsusb -t’. lsusb returns the Bus and Device as a 3-digit number. It has been agreed, that the expected input is: <Bus in dec>#<Device in dec>, e.g. 3#11

Mac specific: USB device path - HID API returns path in roughly following form: ‘IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/XHC1@14/XHC1@14000000/HS01@14100000/SE Blank RT Family @14100000/IOUSBHostInterface@0/AppleUserUSBHostHIDDevice’

This path can be found using the ‘ioreg’ utility or using ‘IO Hardware Registry Explorer’ tool. However, using the system report from ‘About This MAC -> System Report -> USB’ a partial path can also be gathered. Using the name of USB device from the ‘USB Device Tree’ and appending the ‘Location ID’ should work. The name can be ‘SE Blank RT Family’ and the ‘Location ID’ is in form <hex> / <dec>, e.g. ‘0x14200000 / 18’. So the ‘usb_id’ name should be ‘SE Blank RT Family @14200000’ and the filter should be able to filter out such device.

Initialize the USB Device Filtering.

Parameters
  • usb_id (Optional[str]) – usb_id string

  • search_by_pid (bool) – if true, expects usb_id to be a PID number, VID otherwise.

compare(usb_device_object)

Compares the internal usb_id with provided usb_device_object.

The provided USB ID during initialization may be VID or PID, VID/PID pair, or a path. See private methods for details.

Parameters

usb_device_object (Any) – Libusbsio/HID_API device object (dictionary)

Return type

bool

Returns

True on match, False otherwise

Registers descriptions with support for XML files

Module to handle registers descriptions with support for XML files.

class spsdk.utils.registers.Registers(device_name)

Bases: object

SPSDK Class for registers handling.

Initialization of Registers class.

add_register(reg)

Adds register into register list.

Parameters

reg (RegsRegister) – Register to add to the class.

Raises
  • SPSDKError – Invalid type has been provided.

  • SPSDKRegsError – Cannot add register with same name

Return type

None

create_yml_config(exclude_regs=None, exclude_fields=None, ignored_fields=None, diff=False, indent=0)

The function creates the configuration YML file.

Parameters
  • exclude_regs (Optional[List[str]]) – List of excluded registers

  • exclude_fields (Optional[Dict[str, Dict[str, str]]]) – Dictionary with lists of excluded bitfields per register

  • ignored_fields (Optional[List[str]]) – List of ignored names in fields.

  • diff (bool) – Get only configuration with difference value to reset state.

  • indent (int) – Indent in space to generate YML.

Return type

Any

Returns

YAML commented map of registers value.

create_yml_config_white_list(white_list=None, diff=False, indent=0)

The function creates the configuration YML file.

Parameters
  • white_list (Optional[Dict[str, Any]]) – Dictionary with lists of registers and its bitfields

  • diff (bool) – Get only configuration with difference value to reset state.

  • indent (int) – Indent in space to generate YML.

Return type

Any

Returns

YAML commented map of registers value.

enable_backward_compatibility(bc_reg=None)

Enables support for basic backward compatibility with older name convention.

Parameters

bc_reg (Optional[Callable[[RegsRegister], List[str]]]) – Function to provide list of back compatibility names of register, defaults to None

Return type

None

enable_backward_compatibility_enums(bc_enum)

Enables support for basic backward compatibility with older name convention.

Parameters

bc_enum (Callable[[RegsRegister, RegsBitField, RegsEnum], List[str]]) – Function to provide list of back compatibility names of all enums, defaults to None

Return type

None

find_reg(name, include_group_regs=False)

Returns the instance of the register by its name.

Parameters
  • name (str) – The name of the register.

  • include_group_regs (bool) – The algorithm will check also group registers.

Return type

RegsRegister

Returns

The register instance.

Raises

SPSDKRegsErrorRegisterNotFound – The register doesn’t exists.

generate_html(heading1, heading2, regs_exclude=None, fields_exclude=None)

Generate describing HTML file with registers.

Parameters
  • heading1 (str) – The main title in HTML.

  • heading2 (str) – The sub-title in HTML.

  • regs_exclude (Optional[List[str]]) – The exclude registers list.

  • fields_exclude (Optional[List[str]]) – The exclude bitfield list.

Return type

str

Returns

The content of HTML file.

get_bc_reg(old_name, regs=None)

Try to translate old name of register with the current one.

Parameters
  • old_name (str) – Old name to try to find

  • regs (Optional[List[str]]) – Optional set of regs name if the full list is not used.

Return type

Optional[str]

Returns

Name of current register

get_reg_names(exclude=None, include_group_regs=False)

Returns list of the register names.

Parameters
  • exclude (Optional[List[str]]) – Exclude list of register names if needed.

  • include_group_regs (bool) – The algorithm will check also group registers.

Return type

List[str]

Returns

List of register names.

get_registers(exclude=None, include_group_regs=False)

Returns list of the registers.

Method allows exclude some register by their names. :type exclude: Optional[List[str]] :param exclude: Exclude list of register names if needed. :type include_group_regs: bool :param include_group_regs: The algorithm will check also group registers. :rtype: List[RegsRegister] :return: List of register names.

load_registers_from_xml(xml, filter_reg=None, grouped_regs=None)

Function loads the registers from the given XML.

Parameters
  • xml (str) – Input XML data in string format.

  • filter_reg (Optional[List[str]]) – List of register names that should be filtered out.

  • grouped_regs (Optional[List[dict]]) – List of register prefixes names to be grouped int one.

Raises

SPSDKRegsError – XML parse problem occuress.

Return type

None

load_yml_config(yml_data, exclude_regs=None, exclude_fields=None)

The function loads the configuration from YML file.

Parameters
  • yml_data (Any) – The YAML commented data with register values.

  • exclude_regs (Optional[List[str]]) – List of excluded registers

  • exclude_fields (Optional[Dict[str, Dict[str, str]]]) – Dictionary with lists of excluded bitfields

Raises
Return type

None

remove_register(reg)

Remove register from register list by its instance reference.

Reg

Instance of register that should be removed.

Raises

SPSDKError – Invalid type has been provided.

Return type

None

remove_register_by_name(reg_names)

Removes register from register list by List of its names.

Reg_names

List of names of registers that should be removed.

Return type

None

reset_values(exclude=None)

The method reset values in registers.

Parameters

exclude (Optional[List[str]]) – The list of register names to be excluded.

Return type

None

run_hooks(exclude=None)

The method run hooks on all regular registers.

Parameters

exclude (Optional[List[str]]) – The list of register names to be excluded.

Return type

None

write_xml(file_name)

Write loaded register structures into XML file.

Parameters

file_name (str) – The name of XML file that should be created.

Return type

None

class spsdk.utils.registers.RegsBitField(parent, name, offset, width, description=None, reset_val='0', access='RW')

Bases: object

Storage for register bitfields.

Constructor of RegsBitField class. Used to store bitfield information.

Parameters
  • parent (RegsRegister) – Parent register of bitfield.

  • name (str) – Name of bitfield.

  • offset (int) – Bit offset of bitfield.

  • width (int) – Bit width of bitfield.

  • description (Optional[str]) – Text description of bitfield.

  • reset_val (Any) – Reset value of bitfield.

  • access (str) – Access type of bitfield.

add_enum(enum)

Add bitfield enum.

Parameters

enum (RegsEnum) – New enumeration value for bitfiled.

Return type

None

add_et_subelement(parent)

Creates the register XML structure in ElementTree.

Parameters

parent (Element) – The parent object of ElementTree.

Return type

None

enable_backward_compatibility(bc_enum)

Enables support for basic backward compatibility with older name convention.

Parameters

bc_enum (Callable[[RegsRegister, RegsBitField, RegsEnum], List[str]]) – Function to provide list of back compatibility names of enum, defaults to None

Return type

None

classmethod from_xml_element(xml_element, parent)

Initialization register by XML ET element.

Parameters
  • xml_element (Element) – Input XML subelement with register data.

  • parent (RegsRegister) – Reference to parent RegsRegister object.

Return type

RegsBitField

Returns

The instance of this class.

get_bc_enum(old_name)

Try to translate old name of enum with the current one.

Parameters

old_name (str) – Old name to try to find

Return type

Optional[str]

Returns

Name of current enum if exists

get_enum_constant(enum_name)

Returns constant representation of enum by its name.

Return type

int

Returns

Constant of enum.

Raises

SPSDKRegsErrorEnumNotFound – The enum has not been found.

get_enum_names()

Returns list of the enum strings.

Return type

List[str]

Returns

List of enum names.

get_enum_value()

Returns enum value of the bitfield.

Return type

Union[str, int]

Returns

Current value of bitfield.

get_enums()

Returns bitfield enums.

Return type

List[RegsEnum]

Returns

List of bitfield enumeration values.

get_html_data_element()

Returns HTML element of bitfield.

Return type

Mapping[str, Union[str, dict, list]]

Returns

HTML element.

get_reset_value()

Returns integer reset value of the bitfield.

Return type

int

Returns

Reset value of bitfield.

get_value()

Returns integer value of the bitfield.

Return type

int

Returns

Current value of bitfield.

has_enums()

Returns if the bitfields has enums.

Return type

bool

Returns

True is has enums, False otherwise.

set_enum_value(new_val, raw=False)

Updates the value of the bitfield by its enum value.

Parameters
  • new_val (str) – New enum value of bitfield.

  • raw (bool) – If set, no automatic modification of value is applied.

Raises

SPSDKRegsErrorEnumNotFound – Input value cannot be decoded.

Return type

None

set_value(new_val, raw=False)

Updates the value of the bitfield.

Parameters
  • new_val (Any) – New value of bitfield.

  • raw (bool) – If set, no automatic modification of value is applied.

Raises

SPSDKError – The input value is out of range.

Return type

None

class spsdk.utils.registers.RegsEnum(name, value, description, max_width=0)

Bases: object

Storage for register enumerations.

Constructor of RegsEnum class. Used to store enumeration information of bitfield.

Parameters
  • name (str) – Name of enumeration.

  • value (Any) – Value of enumeration.

  • description (str) – Text description of enumeration.

  • max_width (int) – Maximal width of enum value used to format output

add_et_subelement(parent)

Creates the register XML structure in ElementTree.

Parameters

parent (Element) – The parent object of ElementTree.

Return type

None

classmethod from_xml_element(xml_element, maxwidth=0)

Initialization Enum by XML ET element.

Parameters
  • xml_element (Element) – Input XML subelement with enumeration data.

  • maxwidth (int) – The maximal width of bitfield for this enum (used for formating).

Return type

RegsEnum

Returns

The instance of this class.

Raises

SPSDKRegsError – Error during enum XML parsing.

get_value_int()

Method returns Integer value of enum.

Return type

int

Returns

Integer value of Enum.

get_value_str()

Method returns formated value.

Return type

str

Returns

Formatted string with enum value.

class spsdk.utils.registers.RegsRegister(name, offset, width, description=None, reverse=False, access=None)

Bases: object

Initialization register by input information.

Constructor of RegsRegister class. Used to store register information.

Parameters
  • name (str) – Name of register.

  • offset (int) – Byte offset of register.

  • width (int) – Bit width of register.

  • description (Optional[str]) – Text description of register.

  • reverse (bool) – Multi register value is stored in reverse order.

  • access (Optional[str]) – Access type of register.

add_bitfield(bitfield)

Add register bitfield.

Parameters

bitfield (RegsBitField) – New bitfield value for register.

Return type

None

add_et_subelement(parent)

Creates the register XML structure in ElementTree.

Parameters

parent (Element) – The parent object of ElementTree.

Return type

None

add_group_reg(reg)

Add group element for this register.

Parameters

reg (RegsRegister) – Register member of this register group.

Raises

SPSDKRegsErrorRegisterGroupMishmash – When any inconsistency is detected.

Return type

None

add_setvalue_hook(hook, context=None)

Set the value hook for write operation.

Parameters
  • hook (Callable) – Callable hook for set value operation.

  • context (Optional[Any]) – Context data for this hook.

Return type

None

enable_backward_compatibility(bc_bitfield)

Enables support for basic backward compatibility with older name convention.

Parameters

bc_bitfield (Callable[[RegsRegister, RegsBitField], List[str]]) – Function to provide list of back compatibility names of bitfield, defaults to None

Return type

None

find_bitfield(name)

Returns the instance of the bitfield by its name.

Parameters

name (str) – The name of the bitfield.

Return type

RegsBitField

Returns

The bitfield instance.

Raises

SPSDKRegsErrorBitfieldNotFound – The register doesn’t exists.

classmethod from_xml_element(xml_element)

Initialization register by XML ET element.

Parameters

xml_element (Element) – Input XML subelement with register data.

Return type

RegsRegister

Returns

The instance of this class.

get_bc_bitfield(old_name)

Try to translate old name of bitfield with the current one.

Parameters

old_name (str) – Old name to try to find

Return type

Optional[str]

Returns

Name of current bitfield if exists

get_bitfield_names(exclude=None)

Returns list of the bitfield names.

Parameters

exclude (Optional[List[str]]) – Exclude list of bitfield names if needed.

Return type

List[str]

Returns

List of bitfield names.

get_bitfields(exclude=None)

Returns register bitfields.

Method allows exclude some bitfields by their names. :type exclude: Optional[List[str]] :param exclude: Exclude list of bitfield names if needed. :rtype: List[RegsBitField] :return: Returns List of register bitfields.

get_hex_value()

Get the value of register in string hex format.

Return type

str

get_html_data_element(exclude=None)

Returns HTML element of register.

Return type

Mapping[str, Union[str, dict, list]]

Returns

HTML element.

get_int_value()

Get the integer value of register.

Return type

int

get_reset_value()

Returns reset value of the register.

Return type

bytes

Returns

Reset value of register.

get_value()

Get the value of register.

Return type

bytes

has_group_registers()

Returns true if register is compounded from sub-registers.

Return type

bool

Returns

True if register has sub-registers, False otherwise.

reset_value(raw=False)

Reset the value of register.

Parameters

raw (bool) – Do not use any modification hooks.

Return type

None

set_value(val, raw=False)

Set the new value of register.

Parameters
  • val (Any) – The new value to set.

  • raw (bool) – Do not use any modification hooks.

Raises

SPSDKError – When invalid values is loaded into register

Return type

None

Register’s configuration

Module to handle registers configuration.

class spsdk.utils.reg_config.RegConfig(path)

Bases: object

Class that helps manage the registers configuration.

Register Configuration class constructor.

Parameters

path (str) – The path to configuration JSON file.

classmethod devices(path)

Classmethod to get list of suppported devices.

Parameters

path (str) – Path to database file.

Return type

List[str]

Returns

List of all supported devices.

get_address(device, remove_underscore=False)

Get the area address in chip memory.

Parameters
  • device (str) – The device name.

  • remove_underscore (bool) – Remove underscore from address if set.

Return type

str

Returns

Base address of registers.

get_antipole_regs(device=None)

Return the list of inverted registers.

Parameters

device (Optional[str]) – The device name.

Return type

Dict[str, str]

Returns

The dictionary of antipole registers.

get_computed_fields(device=None)

Return the list of computed fields (not used in config YML files).

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

Dict[str, Dict[str, str]]

Returns

The dictionary of computed fields.

get_computed_registers(device=None)

Return the list of computed registers.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

List[str]

Returns

The list of computed registers.

get_data_file(device, revision)

Return the full path to data file (xml).

Parameters
  • device (str) – The device name.

  • revision (str) – The chip revision.

Return type

str

Returns

The path to data file.

get_devices()

Get list of supported devices.

Return type

List[str]

Returns

List of supported device.

get_grouped_registers(device=None)

Return the list of grouped registers description.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

List[dict]

Returns

The list of grouped registers descriptions.

get_ignored_fields(device=None)

Return the list of ignored fields.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

List[str]

Returns

The list of ignored fields.

get_ignored_registers(device=None)

Return the list of ignored registers.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

List[str]

Returns

The list of ignored register.

get_latest_revision(device)

Get latest revision for device.

Parameters

device (str) – The device name.

Return type

str

Returns

The name of latest revision.

get_revisions(device)

Get list of revisions for given device.

Parameters

device (str) – The device name.

Return type

List[str]

Returns

List of all supported device version.

get_seal_count(device=None)

Return the seal count.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

Optional[int]

Returns

The seal count.

Raises

SPSDKError – When there is invalid seal count

get_seal_start_address(device=None)

Return the seal start address.

Parameters

device (Optional[str]) – The device name, if not specified, the general value is used.

Return type

Optional[str]

Returns

The seal start register name.

Raises

SPSDKError – When seal start address has invalid name

get_value(key, device=None, default=None)

Return any parameter by key.

Parameters
  • key (str) – The Key of the parameter to be returned.

  • device (Optional[str]) – The device name.

  • default (Optional[Any]) – The default Value in case that is not specified in config file.

Return type

Any

Returns

The Value of parameter by handled Key.

classmethod load_config(path)

Load config file.

Parameters

path (str) – The path to database file.

Return type

dict

Returns

The database.

USB Device Scanner

NXP USB Device Scanner API.

spsdk.utils.nxpdevscan.search_nxp_uart_devices()

Returns a list of all NXP devices connected via UART.

Retval

list of UartDeviceDescription devices from devicedescription module

Return type

Sequence[DeviceDescription]

spsdk.utils.nxpdevscan.search_nxp_usb_devices(extend_vid_list=None)

Searches all NXP USB devices based on their Vendor ID.

Extend_vid_list

list of VIDs, to extend the default NXP VID list (int)

Return type

Sequence[DeviceDescription]

Returns

list of dicts corresponding to NXP devices

Device description

Module for NXP device description classes.

class spsdk.utils.devicedescription.DeviceDescription

Bases: abc.ABC

Base class for all logical devices.

The intent is to have a generic container for providing info about devices of any type. Thus the class is named as ‘logical’, because it doesn’t allow you to control the device in any way.

This is just a base class and as such shouldn’t be used. If you want to use it, create your own class inheriting from this class and redefining the methods listed in this class!

abstract info()

Shall return a string describing the device, e.g. Name: <name>; ID: <id>.

Return type

str

class spsdk.utils.devicedescription.USBDeviceDescription(vid, pid, path, product_string, manufacturer_string, name)

Bases: spsdk.utils.devicedescription.DeviceDescription

Simple container holding information about USB device.

This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific USB API implementations.

Constructor.

Vid

Vendor ID

Pid

Product ID

Product_string

Product string

Manufacturer_string

Manufacturer string

Name

Name(s) of NXP devices as defined under spsdk.mboot.interfaces.usb or spsdk.sdp.interfaces.usb

See get_usb_device_name() function to getg the name from VID and PID. See convert_usb_path() function to provide a proper path string.

info()

Returns a formatted device description string.

Return type

str

class spsdk.utils.devicedescription.UartDeviceDescription(name=None, dev_type=None)

Bases: spsdk.utils.devicedescription.DeviceDescription

Simple container holding information about UART device.

This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific UART API implementations.

Construtor.

The ‘dev_type’ can be in general any string identifying the device type.

Name

COM port name

Dev_type

‘mboot device’ or ‘SDP device’

info()

Returns a formatted device description string.

Return type

str

spsdk.utils.devicedescription.convert_usb_path(hid_api_usb_path)

Converts the Libusbsio/HID_API path into string, which can be observed from OS.

DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided. Additionally, this method relies on the fact that the provided path comes from the Libusbsio/HID_API. This method will most probably fail or provide improper results in case path from different USB API is provided.

Hid_api_usb_path

USB device path from Libusbsio/HID_API

Return type

str

Returns

Libusbsio/HID_API path converted for given platform

spsdk.utils.devicedescription.get_usb_device_name(vid, pid, device_names=None)

Returns ‘name’ device identifier based on VID/PID, from dicts.

Searches provided dictionary for device name based on VID/PID. If the dict is None, the search happens on USB_DEVICES under mboot/interfaces/usb.py and sdphost/interfaces/usb.py

DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided.

Vid

Vendor ID we are interested in

Pid

Product ID we are interested in

Device_names

dict where str is device name, first int vid, second int pid

Return type

List[str]

Returns

list containing device names with corresponding VID/PID

Utils Exceptions

Module provides exceptions for SPSDK utilities.

exception spsdk.utils.exceptions.SPSDKRegsError(desc=None)

Bases: spsdk.exceptions.SPSDKError

General Error group for utilities SPSDK registers module.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorBitfieldNotFound(desc=None)

Bases: spsdk.utils.exceptions.SPSDKRegsError

Bitfield has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorEnumNotFound(desc=None)

Bases: spsdk.utils.exceptions.SPSDKRegsError

Enum has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterGroupMishmash(desc=None)

Bases: spsdk.utils.exceptions.SPSDKRegsError

Register Group inconsistency problem.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterNotFound(desc=None)

Bases: spsdk.utils.exceptions.SPSDKRegsError

Register has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKTimeoutError(desc=None)

Bases: spsdk.exceptions.SPSDKError

SPSDK Timeout.

Initialize the base SPSDK Exception.