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: str

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

static sign_size(key)

Get size of signature for loaded private key.

Parameters

key (Union[RSAPrivateKey, EllipticCurvePrivateKey]) – Private key used to sign data.

Return type

int

Returns

Size of signature in bytes for the private key.

Raises

SPSDKError – Invalid key type.

abstract property version: str

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: int

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

Return type

int

property certificates: List[spsdk.utils.crypto.certificate.Certificate]

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

classmethod from_config(config, search_paths=None)

Creates an instance of CertBlockV2 from configuration.

Parameters
  • config (Dict[str, Any]) – Input standard configuration.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type

CertBlockV2

Returns

Instance of CertBlockV2

Raises

SPSDKError – Invalid certificates detected.

classmethod get_validation_schemas()

Create the list of validation schemas.

Return type

List[Dict[str, Any]]

Returns

List of validation schemas.

property header: spsdk.utils.crypto.cert_blocks.CertBlockHeader

Certificate block header.

Return type

CertBlockHeader

property image_length: int

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: int

Aligned size of the certificate block.

Return type

int

property rkh: List[bytes]

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

Return type

List[bytes]

property rkh_index: Optional[int]

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

Return type

Optional[int]

property rkht: bytes

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

Return type

bytes

property rkht_fuses: List[int]

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: int

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: bool

Certification Authority flag.

Return type

bool

dump(force=False)

Encodes the value using DER.

Parameters

force (bool) – If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format

Return type

bytes

Returns

A byte string of the DER-encoded value

export()

Serialized Certificate data.

Return type

bytes

property hash_algo: str

HASH algorithm used in the Certificate.

Return type

str

info()

Text information about the Certificate.

Return type

str

property issuer: Dict[str, str]

Certificate issuer.

Return type

Dict[str, str]

property max_path_length: int

Maximum length of derived Certificate chain.

Return type

int

property not_valid_after: datetime.datetime

End of the Certificate valid period.

Return type

datetime

property not_valid_before: datetime.datetime

Begging of the Certificate valid period.

Return type

datetime

property public_key_exponent: int

Exponent of the public key of the certificate.

Return type

int

property public_key_hash: bytes

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

Return type

bytes

property public_key_modulus: int

Modulus of the public key of the certificate.

Return type

int

property public_key_usage: Set[str]

Usage of the Certificate.

Return type

Set[str]

property raw_size: int

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

Return type

int

property self_issued: bool

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

Return type

bool

property self_signed: str

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: int

Serial number of the Certificate.

Return type

int

property signature: bytes

Certificate signature.

Return type

bytes

property signature_algo: str

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: str

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: bytes

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.BinaryPattern(pattern)

Bases: object

Binary pattern class.

Supported patterns:
  • rand: Random Pattern

  • zeros: Filled with zeros

  • ones: Filled with all ones

  • inc: Filled with repeated numbers incremented by one 0-0xff

  • any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.

Constructor of pattern class.

Parameters

pattern (str) – Supported patterns: - rand: Random Pattern - zeros: Filled with zeros - ones: Filled with all ones - inc: Filled with repeated numbers incremented by one 0-0xff - any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.

Raises

SPSDKValueError – Unsupported pattern detected.

SPECIAL_PATTERNS = ['rand', 'zeros', 'ones', 'inc']
get_block(size)

Get block filled with pattern.

Parameters

size (int) – Size of block to return.

Return type

bytes

Returns

Filled up block with specified pattern.

property pattern: str

Get the pattern.

Return type

str

Returns

Pattern in string representation.

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: bool
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: Iterable[str]
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 timeout 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 timeout 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=None)

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

Parameters
  • data (Union[bytes, bytearray]) – to be aligned

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

  • padding (Union[int, BinaryPattern, None]) – byte to be added or BinaryPattern

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_endianness(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 endianness).

Raises

SPSDKError – Invalid value on input.

spsdk.utils.misc.check_range(x, start=0, end=4294967295)

Check if the number is in range.

Parameters
  • x (int) – Number to check.

  • start (int) – Lower border of range, default is 0.

  • end (int) – Upper border of range, default is unsigned 32-bit range.

Return type

bool

Returns

True if fits, False otherwise.

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_file(file_path, use_cwd=True, search_paths=None, raise_exc=True)

Return a full path to the file.

search_paths takes precedence over CWD if used (default)

Parameters
  • file_path (str) – File name, part of file path or full path

  • use_cwd (bool) – Try current working directory to find the file, defaults to True

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

  • raise_exc (bool) – Raise exception if file is not found, defaults to True

Return type

str

Returns

Full path to the file

Raises

SPSDKError – File not found

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

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

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

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

Return type

Optional[TypeVar(T)]

Returns

found element; None if not found

spsdk.utils.misc.format_value(value, size, delimiter='_', 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 ‘delimiter’ (underscore)

Return type

str

spsdk.utils.misc.get_abs_path(file_path, base_dir=None)

Return a full path to the file.

param base_dir: Base directory to create absolute path, if not specified the system CWD is used. return: Absolute file path.

Return type

str

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

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.

  • byte_cnt (Optional[int]) – The result count of bytes.

Raises

SPSDKValueError – The integer input value doesn’t fit into byte_cnt.

Return type

int

Returns

Number of bytes needed to store integer.

spsdk.utils.misc.get_key_by_val(value, dictionary)

Return key by its value.

Parameters
  • value (str) – Value to find.

  • dictionary (Dict[str, List[str]]) – Dictionary to find in.

Raises

SPSDKValueError – Value is not present in dictionary.

Return type

str

Returns

Key name

spsdk.utils.misc.load_binary(path, search_paths=None)

Loads binary file into bytes.

Parameters
  • path (str) – Path to the file.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type

bytes

Returns

content of the binary file as bytes

spsdk.utils.misc.load_configuration(path)

Load configuration from yml/json file.

Parameters

path (str) – Path to configuration file

Raises

SPSDKError – When unsupported file is provided

Return type

dict

Returns

Content of configuration as dictionary

spsdk.utils.misc.load_file(path, mode='r', search_paths=None)

Loads a file into bytes.

Parameters
  • path (str) – Path to the file.

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

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type

Union[str, bytes]

Returns

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

spsdk.utils.misc.load_text(path, search_paths=None)

Loads binary file into bytes.

Parameters
  • path (str) – Path to the file.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type

str

Returns

content of the binary file as bytes

spsdk.utils.misc.numberify_version(version, separator='.', valid_numbers=3)

Turn version string into a number.

Each group is weighted by a multiple of 1000

1.2.3 -> 1 * 1_000_000 + 2 * 1_000 + 3 * 1 = 1_002_003 21.100.9 -> 21 * 1_000_000 + 100 * 1_000 + 9 * 1 = 21_100_009

Parameters
  • version (str) – Version string numbers separated by separator

  • separator (str) – Separator used in the version string, defaults to “.”

  • valid_numbers (int) – Amount of numbers to sanitize to consider, defaults to 3

Return type

int

Returns

Number representing the version

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.sanitize_version(version, separator='.', valid_numbers=3)

Sanitize version string.

Append ‘.0’ in case version string has fewer parts than valid_numbers Remove right-most version parts after valid_numbers amount of parts

1.2 -> 1.2.0 1.2.3.4 -> 1.2.3

Parameters
  • version (str) – Original version string

  • separator (str) – Separator used in the version string, defaults to “.”

  • valid_numbers (int) – Amount of numbers to sanitize, defaults to 3

Return type

str

Returns

Sanitized version string

spsdk.utils.misc.size_fmt(num, use_kibibyte=True)

Size format.

Return type

str

spsdk.utils.misc.swap16(x)

Swap bytes in half word (16bit).

Parameters

x (int) – Original number

Return type

int

Returns

Number with swapped bytes

Raises

SPSDKError – When incorrect number to be swapped is provided

spsdk.utils.misc.swap32(x)

Swap 32 bit integer.

Parameters

x (int) – integer to be swapped

Return type

int

Returns

swapped value

Raises

SPSDKError – When incorrect number to be swapped is provided

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, byte_cnt=None, endianness='big')

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.

  • byte_cnt (Optional[int]) – The result count of bytes.

  • endianness (str) – The result bytes endianness [‘big’, ‘little’].

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, mode='w', encoding=None)

Writes data into a file.

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

  • path (str) – Path to the file.

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

  • encoding (Optional[str]) – Encoding of written file (‘ascii’, ‘utf-8’).

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 resetting input buffer.

Return type

None

reset_output_buffer()

Simulates resetting 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, 1137, 3368]
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 restricted 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 (Dict[str, 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.

export(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)

Export Registers into binary.

Parameters
  • size (int) – Result size of Image, 0 means automatic minimal size.

  • pattern (BinaryPattern) – Pattern of gaps, defaults to “zeros”

Return type

bytes

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_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.

get_validation_schema()

Get the JSON SCHEMA for registers.

Return type

Dict

Returns

JSON SCHEMA.

image_info(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)

Export Registers into binary information.

Parameters
  • size (int) – Result size of Image, 0 means automatic minimal size.

  • pattern (BinaryPattern) – Pattern of gaps, defaults to “zeros”

Return type

BinaryImage

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 occurs.

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

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', hidden=False)

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.

  • hidden (bool) – The bitfield will be hidden from standard searches.

add_enum(enum)

Add bitfield enum.

Parameters

enum (RegsEnum) – New enumeration value for bitfield.

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

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_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

Raises

SPSDKRegsError – Invalid input value.

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 formatting).

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 formatted value.

Return type

str

Returns

Formatted string with enum value.

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

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.

  • config_as_hexstring (bool) – Config is stored as a hex string.

  • otp_index (Optional[int]) – Index of OTP fuse.

  • reverse_subregs_order (bool) – Reverse order of sub registers.

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

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_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_bytes_value()

Get the bytes value of register.

The value indianness is returned by ‘reversed’ member. :rtype: bytes :return: Register value in bytes.

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_reset_value()

Returns reset value of the register.

Return type

int

Returns

Reset value of register.

get_value()

Get the value of register.

Return type

int

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: spsdk.utils.database.Database

Class that helps manage the registers configuration.

Register Configuration class constructor.

Parameters

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

get_address(device)

Get the area address in chip memory.

Parameters

device (str) – The device name.

Return type

int

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 dictionary of computed registers.

Parameters

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

Return type

Dict[str, Any]

Returns

The dictionary 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_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_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.

USB Device Scanner

NXP USB Device Scanner API.

spsdk.utils.nxpdevscan.search_libusbsio_devices()

Returns a list of all LIBUSBSIO devices.

Retval

list of UartDeviceDescription devices from devicedescription module

Raises

SPSDKError – In any case of LIBUSBSIO problems.

Return type

List[SIODeviceDescription]

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

List[UartDeviceDescription]

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

List[USBDeviceDescription]

Returns

list of USBDeviceDescription 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.SIODeviceDescription(info)

Bases: spsdk.utils.devicedescription.DeviceDescription

Simple container holding information about LIBUSBSIO device.

This container contains information about LIBUSBSIOdevice.

Constructor.

Parameters

info (HIDAPI_DEVICE_INFO_T) – LIBUSBSIO device information class.

info()

Returns a formatted device description string.

Return type

str

Returns

Text description of SIO device.

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

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.

Parameters
  • vid (int) – Vendor ID

  • pid (int) – Product ID

  • product_string (str) – Product string

  • manufacturer_string (str) – Manufacturer string

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

  • serial (str) – The serial number of device.

See get_usb_device_name() function to get 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

Returns

Text information of USB device.

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.

Constructor.

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

Parameters
  • name (Optional[str]) – COM port name

  • dev_type (Optional[str]) – ‘mboot device’ or ‘SDP device’

info()

Returns a formatted device description string.

Return type

str

Returns

Text information about UART device.

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.

Parameters

hid_api_usb_path (bytes) – 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.

Parameters
  • vid (int) – Vendor ID we are interested in

  • pid (int) – Product ID we are interested in

  • device_names (Optional[Dict[str, Tuple[int, int]]]) – 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

Module for schema-based configuration validation

Module for schema-based configuration validation.

class spsdk.utils.schema_validator.ConfigTemplate(main_title, schemas, override_values=None)

Bases: object

Class for generating commented config templates.

Constructor for Config templates.

Parameters
  • main_title (str) – Main title of final template.

  • schemas (List[Dict[str, Any]]) – Main description of final template.

  • override_values (Optional[Dict[str, Any]]) – Additional overriding default values.

static convert_cm_to_yaml(config)

Convert Commented Map for into final YAML string.

Parameters

config (CommentedMap) – Configuration in CM format.

Return type

str

Returns

YAML string with configuration to use to store in file.

export()

Export configuration template into CommentedMap.

Raises

SPSDKError – Error

Return type

CommentedMap

Returns

Configuration template in CM.

export_to_yaml()

Export Configuration template directly into YAML string format.

Return type

str

Returns

YAML string.

class spsdk.utils.schema_validator.SPSDK_ListStrategies(strategy_list)

Bases: deepmerge.strategy.list.ListStrategies

Extended List Strategies.

static strategy_set(config, path, base, nxt)

Use the set of both as a output.

class spsdk.utils.schema_validator.SPSDK_Merger(type_strategies, fallback_strategies, type_conflict_strategies)

Bases: deepmerge.merger.Merger

Modified Merger to add new list strategy ‘set’.

PROVIDED_TYPE_STRATEGIES = {<class 'list'>: <class 'spsdk.utils.schema_validator.SPSDK_ListStrategies'>, <class 'dict'>: <class 'deepmerge.strategy.dict.DictStrategies'>, <class 'set'>: <class 'deepmerge.strategy.set.SetStrategies'>}
class spsdk.utils.schema_validator.ValidationSchemas

Bases: object

Manager for validation schemas.

static get_schema_file(sch_file)

Return load schema file. Use SingleTon behavior.

Parameters

sch_file (str) – Path to schema config file.

Raises

SPSDKError – Invalid schema config file.

Return type

Dict[str, Any]

Returns

Loaded schema file.

spsdk.utils.schema_validator.check_config(config, schemas, extra_formaters=None, search_paths=None)

Check the configuration by provided list of validation schemas.

Parameters
  • config (Union[str, Dict[str, Any]]) – Configuration to check

  • schemas (List[Dict[str, Any]]) – List of validation schemas

  • extra_formaters (Optional[Dict[str, Callable[[str], bool]]]) – Additional custom formaters

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Raises

SPSDKError – Invalid validation schema or configuration

Return type

None

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.