Utils Module API#
Module containing various functions/modules used throughout the SPSDK.
Abstract class template#
Module for base abstract classes.
- class spsdk.utils.abstract.BaseClass#
Bases:
RawBaseClassSPSDK abstract class for Data Classes.
- abstract export()#
Export object into bytes array.
- Return type:
bytes
- abstract classmethod parse(data)#
Parse object from bytes array.
- Return type:
Self
- post_export(output_path)#
Post export method.
- Parameters:
output_path (
str) – Path to store the data files of configuration.- Return type:
list[str]- Returns:
List of created file paths.
- class spsdk.utils.abstract.RawBaseClass#
Bases:
ABCSPSDK raw abstract class for general Classes.
Utils easy enum#
Custom enum extension.
- class spsdk.utils.spsdk_enum.SpsdkEnum(tag, label, description=None)#
Bases:
SpsdkEnumMember,EnumSPSDK Enum type.
- classmethod contains(obj)#
Check if given member with given tag/label exists in enum.
- Parameters:
obj (
Union[int,str]) – Label or tag of enum- Return type:
bool- Returns:
True if exists False otherwise
- classmethod create_from_dict(name, config)#
Create the Enum in runtime from the Dictionary where is instead.
- Parameters:
name (
str) – Name of new Classconfig (
dict[str,Union[tuple,list]]) – Configuration with the enum
- Return type:
Type[Self]- Returns:
Enum class
- classmethod from_attr(attribute)#
Get enum member with given tag/label attribute.
- Parameters:
attribute (
Union[int,str]) – Attribute value of enum member- Return type:
Self- Returns:
Found enum member
- classmethod from_label(label)#
Get enum member with given label.
- Parameters:
label (
str) – Label to be used for searching- Raises:
SPSDKKeyError – If enum with given label is not found
- Return type:
Self- Returns:
Found enum member
- classmethod from_tag(tag)#
Get enum member with given tag.
- Parameters:
tag (
int) – Tag to be used for searching- Raises:
SPSDKKeyError – If enum with given label is not found
- Return type:
Self- Returns:
Found enum member
- classmethod get_description(tag, default=None)#
Get description of enum member with given tag.
- Parameters:
tag (
int) – Tag to be used for searchingdefault (
Optional[str]) – Default value if member contains no description
- Return type:
Optional[str]- Returns:
Description of found enum member
- classmethod get_label(tag)#
Get label of enum member with given tag.
- Parameters:
tag (
int) – Tag to be used for searching- Return type:
str- Returns:
Label of found enum member
- classmethod get_tag(label)#
Get tag of enum member with given label.
- Parameters:
label (
str) – Label to be used for searching- Return type:
int- Returns:
Tag of found enum member
- classmethod labels()#
Get list of labels of all enum members.
- Return type:
list[str]- Returns:
List of all labels
- classmethod tags()#
Get list of tags of all enum members.
- Return type:
list[int]- Returns:
List of all tags
- class spsdk.utils.spsdk_enum.SpsdkEnumMember(tag, label, description=None)#
Bases:
objectSPSDK Enum member.
-
description:
Optional[str] = None#
-
label:
str#
-
tag:
int#
-
description:
- class spsdk.utils.spsdk_enum.SpsdkSoftEnum(tag, label, description=None)#
Bases:
SpsdkEnumSPSDK Soft Enum type.
It has API with default values for labels and descriptions with defaults for non existing members.
- classmethod from_tag(tag)#
Get enum member with given tag.
- Parameters:
tag (
int) – Tag to be used for searching- Raises:
SPSDKKeyError – If enum with given label is not found
- Return type:
Self- Returns:
Found enum member
- classmethod get_description(tag, default=None)#
Get description of enum member with given tag.
- Parameters:
tag (
int) – Tag to be used for searchingdefault (
Optional[str]) – Default value if member contains no description
- Return type:
Optional[str]- Returns:
Description of found enum member
- classmethod get_label(tag)#
Get label of enum member with given tag.
If member not found and default is specified, the default is returned.
- Parameters:
tag (
int) – Tag to be used for searching- Return type:
str- Returns:
Label of found enum member
General utils#
Miscellaneous functions used throughout the SPSDK.
- class spsdk.utils.misc.BinaryPattern(pattern)#
Bases:
objectBinary 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.
- Returns:
Pattern in string representation.
- class spsdk.utils.misc.Endianness(value)#
Bases:
str,EnumEndianness enum.
- BIG = 'big'#
- LITTLE = 'little'#
- classmethod values()#
Get enumeration values.
- Return type:
list[str]
- class spsdk.utils.misc.SingletonMeta#
Bases:
typeSingleton metaclass.
- class spsdk.utils.misc.Timeout(timeout, units='s')#
Bases:
objectSimple 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 timed out 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 alignedalignment (
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 alignedalignment (
int) – boundary alignment (typically 2, 4, 16, 64 or 256 boundary)padding (
Union[int,str,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.bytes_to_print(data, max_size=128)#
Prints bytes to hex string and shorten it if needed.
- Parameters:
data (
bytes) – Input data in bytesmax_size (
int) – maximal count of bytes to be printed, defaults to 128
- Return type:
str- Returns:
Hex string of input data
- 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.clean_up_file_name(original_name)#
Clean up the file name.
- Parameters:
original_name (
str) – Input file name- Return type:
str- Returns:
Sanitized name.
- spsdk.utils.misc.deep_update(d, u)#
Deep update nested dictionaries.
- Parameters:
d (
dict) – Dictionary that will be updatedu (
dict) – Dictionary with update information
- Return type:
dict- Returns:
Updated dictionary.
- 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 extendedlength (
int) – requested block length; the value must be >= current block lengthpadding (
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_dir(dir_path, use_cwd=True, search_paths=None, raise_exc=True)#
Return a full path to the directory.
search_paths takes precedence over CWD if used (default)
- Parameters:
dir_path (
str) – Directory name, part of directory path or full pathuse_cwd (
bool) – Try current working directory to find the directory, defaults to Truesearch_paths (
Optional[list[str]]) – List of paths where to search for the directory, defaults to Noneraise_exc (
bool) – Raise exception if directory is not found, defaults to True
- Return type:
str- Returns:
Full path to the directory
- Raises:
SPSDKError – File not found
- 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 pathuse_cwd (
bool) – Try current working directory to find the file, defaults to Truesearch_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to Noneraise_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 elementspredicate (
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_hash(text)#
Returns hash of given text.
- Return type:
str
- 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.get_printable_path(path)#
Get path to the file.
If the JUPYTER_SPSDK environment variable is set to 1, the path is relative to the current working directory.
- Parameters:
path (
str) – Path to the file.- Return type:
str- Returns:
Path to the file.
- spsdk.utils.misc.get_spsdk_version()#
Get SPSDK version.
- Return type:
Version
- 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, search_paths=None)#
Load configuration from yml/json file.
- Parameters:
path (
str) – Path to configuration filesearch_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None
- 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_hex_string(source, expected_size, search_paths=None, name='key')#
Get the HEX string from the command line parameter (Keys, digests, etc).
- Parameters:
source (
Union[str,int,bytes,None]) – File path to key file or hexadecimal value. If not specified random value is used.expected_size (
int) – Expected size of key in bytes.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to Nonename (
Optional[str]) – Name for the key/data to load
- Raises:
SPSDKError – Invalid key
- Return type:
bytes- Returns:
Key in bytes.
- spsdk.utils.misc.load_secret(value, search_paths=None)#
Load secret text from the configuration value.
- Parameters:
value (
str) – Input string to be used for loading the secretsearch_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None
There are several options how the secret is loaded from the input string 1. If the value is an existing path, first line of file is read and returned 2. If the value has format ‘$ENV_VAR’, the value of environment variable ENV_VAR is returned 3. If the value has format ‘$ENV_VAR’ and the value contains a valid path to a file, the first line of a file is returned 4. If the value does not match any options above, the input value itself is returned
Note, that the value with an initial component of ~ or ~user is replaced by that user’s home directory.
- Return type:
str- Returns:
The actual secret value
- spsdk.utils.misc.load_text(path, search_paths=None)#
Loads text file into string.
- 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 text file as string
- 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 separatorseparator (
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_bits(x, bits_cnt=32)#
Reverse bits in integer.
- Parameters:
x (
int) – Integer to be bit reversedbits_cnt (
int) – Count of bits to reverse
- Return type:
int- Returns:
Reversed value value
- 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 stringseparator (
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.split_data(data, size)#
Split data into chunks of size.
- Parameters:
data (bytearray) – array of bytes to be split
size (int) – size of splitted array
- Return Generator[bytes]:
splitted array
- Return type:
Generator[bytes,None,None]
- 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.swap_bytes(data)#
Swap individual bytes as following: b’abcd’ -> b’badc’.
- Return type:
bytes
- 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,None]) – 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=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 (
Endianness) – 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.wrap_text(text, max_line=100)#
Wrap text in SPSDK standard.
Count with new lines in input string and do wrapping after that.
- Parameters:
text (
str) – Text to wrapmax_line (
int) – Max line in output, defaults to 100
- Return type:
str- Returns:
Wrapped text (added new lines characters on right places)
- spsdk.utils.misc.write_file(data, path, mode='w', encoding='utf-8', overwrite=True)#
Writes data into a file.
- Parameters:
data (
Union[str,bytes]) – data to writepath (
str) – Path to the file.mode (
str) – writing mode, ‘w’ for text, ‘wb’ for binary data, defaults to ‘w’encoding (
str) – Encoding of written file (‘ascii’, ‘utf-8’), default is ‘utf-8’.overwrite (
bool) – If False, doesn’t overwrite existing file but creates new one with appended number
- Return type:
int- Returns:
number of written elements
Binary Image utils#
Module to keep additional utilities for binary images.
- class spsdk.utils.binary_image.BinaryImage(name, size=0, offset=0, description=None, binary=None, pattern=None, alignment=1, parent=None, execution_start_address=None)#
Bases:
objectBinary Image class.
Binary Image class constructor.
- Parameters:
name (
str) – Name of Image.size (
int) – Image size.offset (
int) – Image offset in parent image, defaults to 0description (
Optional[str]) – Text description of image, defaults to Nonebinary (
Optional[bytes]) – Optional binary content.pattern (
Optional[BinaryPattern]) – Optional binary pattern.alignment (
int) – Optional alignment of result imageparent (
Optional[BinaryImage]) – Handle to parent object, defaults to Noneexecution_start_address (
Optional[int]) – Execution start address, defaults to None
- MINIMAL_DRAW_WIDTH = 30#
- property absolute_address: int#
Image absolute address relative to base parent.
- Returns:
Absolute address relative to base parent
- add_image(image)#
Add new sub image information.
- Parameters:
image (
BinaryImage) – Image object.- Return type:
None
- aligned_length(alignment=4)#
Returns aligned length for erasing purposes.
- Parameters:
alignment (
int) – The alignment value, defaults to 4.- Return type:
int- Returns:
Ceil alignment length.
- aligned_start(alignment=4)#
Returns aligned start address.
- Parameters:
alignment (
int) – The alignment value, defaults to 4.- Return type:
int- Returns:
Floor alignment address.
- append_image(image)#
Append new sub image at the end of the parent.
This function use the size of the parent as a offset for new appended image.
- Parameters:
image (
BinaryImage) – Image object.- Return type:
None
- draw(include_sub_images=True, width=0, color='', no_color=False, use_unicode=True)#
Draw the image into the ASCII/Unicode graphics.
- Parameters:
include_sub_images (
bool) – Include also sub images into, defaults to Truewidth (
int) – Fixed width of table, 0 means autosize.color (
str) – Color of this block, None means automatic color.no_color (
bool) – Disable adding colors into output.use_unicode (
bool) – Use Unicode box drawing characters instead of ASCII, defaults to True
- Raises:
SPSDKValueError – In case of invalid width.
- Return type:
str- Returns:
ASCII/Unicode art representation of image.
- export()#
Export represented binary image.
- Return type:
bytes- Returns:
Byte array of binary image.
- find_sub_image(name)#
Find sub image by its name.
- Parameters:
name (
str) – Name of sub image- Raises:
SPSDKValueError – The sub image with requested name doesn’t exists
- Return type:
- Returns:
Sub Image object
- static get_config_template()#
Generate configuration template.
- Return type:
str- Returns:
Template to create binary merge.
- get_image_by_absolute_address(address)#
Get Binary Image object that contains the provided absolute address.
- Parameters:
address (
int) – Absolute address to image- Raises:
SPSDKValueError – Exception when the address doesn’t fit into address space
- Return type:
- Returns:
Binary image object that contains the data.
- get_min_draw_width(include_sub_images=True)#
Get minimal width of table for draw function.
- Parameters:
include_sub_images (
bool) – Include also sub images into, defaults to True- Return type:
int- Returns:
Minimal width in characters.
- static get_validation_schemas()#
Get validation schemas list to check a supported configuration.
- Return type:
list[dict[str,Any]]- Returns:
Validation schemas.
- property image_name: str#
Image name including all parents.
- Returns:
Full Image name
- join_images()#
Join all sub images into main binary block.
- Return type:
None
- static load_binary_image(path, name=None, size=0, offset=None, description=None, pattern=None, search_paths=None, alignment=1, load_bin=True, parent_image=None)#
Load binary data file.
Supported formats are ELF, HEX, SREC and plain binary
- Parameters:
path (
str) – Path to the file.name (
Optional[str]) – Name of Image, defaults to file name.size (
int) – Image size, defaults to 0.offset (
Optional[int]) – Additional image offset in parent image, defaults to Nonedescription (
Optional[str]) – Text description of image, defaults to Nonepattern (
Optional[BinaryPattern]) – Optional binary pattern.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to Nonealignment (
int) – Optional alignment of result imageload_bin (
bool) – Load as binary in case of every other format load failsparent_image (
Optional[BinaryImage]) – Optional parent image reference, it will be used to compute optional offset
- Raises:
SPSDKError – The binary file cannot be loaded.
- Return type:
- Returns:
Binary data represented in BinaryImage class.
- classmethod load_from_config(config)#
Converts the configuration option into an Binary Image object.
- Parameters:
config (
Config) – Description of binary image.- Return type:
Self- Returns:
Initialized Binary Image.
- property min_offset: int#
Offset of first subimage.
- post_export(output_path)#
Perform post export steps like saving the script files.
- Parameters:
output_path (
str) – Path to the output directory- Return type:
list[str]
- save_binary_image(path, file_format='BIN')#
Save binary data file.
- Parameters:
path (
str) – Path to the file.file_format (
str) – Format of saved file (‘BIN’, ‘HEX’, ‘S19’), defaults to ‘BIN’.
- Raises:
SPSDKValueError – The file format is invalid.
- Return type:
None
- property size: int#
Size property.
- update_offsets()#
Update offsets from the sub images into main offset value begin offsets.
- Return type:
None
- validate()#
Validate if the images doesn’t overlaps each other.
- Return type:
None
- class spsdk.utils.binary_image.ColorPicker#
Bases:
objectSimple class to get each time when ask different color from list.
Constructor of ColorPicker.
- COLORS = ['\x1b[90m', '\x1b[34m', '\x1b[32m', '\x1b[36m', '\x1b[33m', '\x1b[35m', '\x1b[37m', '\x1b[94m', '\x1b[96m', '\x1b[92m', '\x1b[95m', '\x1b[97m', '\x1b[93m']#
- get_color(unwanted_color=None)#
Get new color from list.
- Parameters:
unwanted_color (
Optional[str]) – Color that should be omitted.- Return type:
str- Returns:
Color
Interfaces utils#
Device Interfaces.
Serial Proxy#
SerialProxy serves as patch replacement for serial.Serial class.
- class spsdk.utils.serial_proxy.SerialProxy(port, timeout, baudrate, write_timeout=None)#
Bases:
objectSerialProxy 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 nametimeout (
int) – timeout (does nothing)write_timeout (
Optional[int]) – does nothingbaudrate (
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#
- 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 bytesignore_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, write_timeout=None)#
Bases:
SerialProxySimpleReadSerialProxy 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 nametimeout (
int) – timeout (does nothing)write_timeout (
Optional[int]) – does nothingbaudrate (
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:
USBDeviceFilterNXP 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 stringnxp_device_names (
Optional[dict[str,list[UsbId]]]) – 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:
objectGeneric 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 stringsearch_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
- static 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
Registers descriptions#
Module to handle registers descriptions.
- class spsdk.utils.registers.Access(tag, label, description=None)#
Bases:
SpsdkEnumAccess mode enum.
- NONE = (0, 'none', 'Not applicable')#
- RO = (1, 'RO', 'Read-only')#
- RW = (2, 'RW', 'Read/Write')#
- WO = (3, 'WO', 'Write-only')#
- WRITE_CONST = (4, 'WRITE_CONST', 'Accepts only default value')#
- classmethod from_label(label)#
Get enum member with given label.
- Parameters:
label (
str) – Label to be used for searching- Return type:
Self- Returns:
Found enum member
- property is_readable: bool#
Return True if the object is readable.
- property is_writable: bool#
Return True if the object is writeable.
- class spsdk.utils.registers.ConfigProcessor(description='')#
Bases:
objectBase class for processing configuration data.
Initialize the processor.
- NAME = 'NOP'#
- classmethod from_spec(spec)#
Create config processor from JSON data entry.
- Return type:
Optional[ConfigProcessor]
- classmethod from_str(config_string)#
Create config processor instance from configuration string.
- Return type:
- classmethod get_description(config_string)#
Return extra description for config processor.
- Return type:
str
- classmethod get_method_name(config_string)#
Return config processor method name.
- Return type:
str
- classmethod get_params(config_string)#
Return config processor method parameters.
- Return type:
dict[str,int]
- post_process(value)#
Post-process value going to config file.
- Return type:
int
- pre_process(value)#
Pre-process value coming from config file.
- Return type:
int
- width_update(value)#
Update bit-width of value going to config file.
- Return type:
int
- class spsdk.utils.registers.Register(name, offset, width, uid, description=None, reverse=False, access=Access(tag=2, label='RW', description='Read/Write'), config_as_hexstring=False, reverse_subregs_order=False, base_endianness=Endianness.BIG, alt_widths=None, hidden=False, no_yaml_comments=False)#
Bases:
objectInitialization 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.uid (
str) – Register unique ID.description (
Optional[str]) – Text description of register.reverse (
bool) – Multi byte register value could be printed in reverse order.access (
Access) – Access type of register.config_as_hexstring (
bool) – Config is stored as a hex string.reverse_subregs_order (
bool) – Reverse order of sub registers.base_endianness (
Endianness) – Base endianness for bytes import/export of value.alt_widths (
Optional[list[int]]) – List of alternative widths.hidden (
bool) – The register will be hidden from standard searches.no_yaml_comments (
bool) – Disable yaml comments for this register.
- add_alias(alias)#
Add alias name to register.
- Parameters:
alias (
str) – Register name alias.- Return type:
None
- add_bitfield(bitfield)#
Add register bitfield.
- Parameters:
bitfield (
RegsBitField) – New bitfield value for register.- Return type:
None
- classmethod create_from_spec(spec)#
Initialization register by specification.
- Parameters:
spec (
dict[str,Any]) – Input specification with register data.- Return type:
Self- Returns:
The instance of this class.
- create_spec()#
Creates the register specification structure.
- Return type:
dict[str,Any]- Returns:
The register specification.
- find_bitfield(name)#
Returns the instance of the bitfield by its name.
- Parameters:
name (
str) – The name of the bitfield.- Return type:
- Returns:
Instance of the bitfield.
- Raises:
SPSDKRegsErrorBitfieldNotFound – The bitfield doesn’t exist.
- get_alt_width(value)#
Get alternative width of register.
- Parameters:
value (
int) – Input value to recognize width- Return type:
int- Returns:
Current width
- get_bitfield(uid)#
Returns the instance of the bitfield by its UID.
- Parameters:
uid (
str) – The uid of the bitfield.- Return type:
- Returns:
Instance of the bitfield.
- Raises:
SPSDKRegsErrorBitfieldNotFound – The bitfield doesn’t exist.
- 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(raw=False)#
Get the bytes value of register.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
bytes- Returns:
Register value in bytes.
- get_hex_value(raw=False)#
Get the value of register in string hex format.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
str- Returns:
Hexadecimal value of register.
- get_reset_value()#
Returns reset value of the register.
- Return type:
int- Returns:
Reset value of register.
- get_value(raw=False)#
Get the value of register.
- Parameters:
raw (
bool) – Do not use any modification hooks.- 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.
- property has_reset_value: bool#
Test if the current value is reset value.
- Returns:
True if the value has not been changed, 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
- class spsdk.utils.registers.Registers(family, feature, base_key=None, base_endianness=Endianness.BIG, just_standard_library_data=False, do_not_raise_exception=False)#
Bases:
_RegistersBase[Register]SPSDK class for registers handling.
Initialization of Registers class.
- Parameters:
family (
FamilyRevision) – Family revision object.feature (
str) – Feature namebase_key (
Union[list[str],str,None]) – Base item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]base_endianness (
Endianness) – The base endianness of registers in binary formjust_standard_library_data (
bool) – The specification is gets from embedded library if True, otherwise Restricted data takes in countdo_not_raise_exception (
bool) – Enable debug mode - not raising exception in case of error during database load.
- class spsdk.utils.registers.RegsBitField(parent, name, offset, width, uid, description=None, reset_val=None, access=Access(tag=2, label='RW', description='Read/Write'), hidden=False, config_processor=None, no_yaml_comments=False)#
Bases:
objectStorage for register bitfields.
Constructor of RegsBitField class. Used to store bitfield information.
- Parameters:
parent (
Register) – Parent register of bitfield.name (
str) – Name of bitfield.offset (
int) – Bit offset of bitfield.width (
int) – Bit width of bitfield.uid (
str) – Bitfield unique IDdescription (
Optional[str]) – Text description of bitfield.reset_val (
Optional[Any]) – Reset value of bitfield if available.access (
Access) – Access type of bitfield.hidden (
bool) – The bitfield will be hidden from standard searches.no_yaml_comments (
bool) – Disable yaml comments for this register.
- add_enum(enum)#
Add bitfield enum.
- Parameters:
enum (
RegsEnum) – New enumeration value for bitfield.- Return type:
None
- classmethod create_from_spec(spec, offset, parent)#
Initialization bitfield by specification.
- Parameters:
spec (
dict[str,Any]) – Input subelement with bitfield data.offset (
int) – Bitfield offset.parent (
Register) – Reference to parent Register object.
- Return type:
- Returns:
The instance of this class.
- create_spec()#
Creates the register specification structure.
- Return type:
dict[str,Any]- Returns:
The specification of Register bitfield.
- 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_hex_value()#
Get the value of register in string hex format.
- Return type:
str- Returns:
Hexadecimal value of register.
- 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.
NOTE: The input value can be either string enum or integer. If string is used, the method tries to decode it Special RAW unprocessed values can be passed as string prefixed with RAW:.
- Parameters:
new_val (
Union[str,int]) – 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, no_preprocess=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.no_preprocess (
bool) – If set, no pre-processing of value is applied.
- Raises:
SPSDKValueError – The input value is out of range.
- Return type:
None
- class spsdk.utils.registers.RegsEnum(name, value, description, max_width=0)#
Bases:
objectStorage 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.
- classmethod create_from_spec(spec, maxwidth=0)#
Initialization Enum from specification.
- Parameters:
spec (
dict[str,Any]) – Input specification with enumeration data.maxwidth (
int) – The maximal width of bitfield for this enum (used for formatting).
- Return type:
Self- Returns:
The instance of this class.
- Raises:
SPSDKRegsError – Error during JSON data parsing.
- create_spec()#
Creates the enumeration specification.
- Return type:
dict[str,Union[str,int]]- Returns:
The specification dictionary of enum.
- 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.ShiftRightConfigProcessor(count, description='')#
Bases:
ConfigProcessorConfig processor performing the right-shift operation.
Initialize the right-shift config processor.
- Parameters:
count (
int) – Count of bit for shift operationdescription (
str) – Extra description for config processor, defaults to “”
- NAME = 'SHIFT_RIGHT'#
- classmethod from_str(config_string)#
Create config processor instance from configuration string.
- Return type:
- post_process(value)#
Post-process value going to config file.
- Return type:
int
- pre_process(value)#
Pre-process value coming from config file.
- Return type:
int
- width_update(value)#
Update bit-width of value going to config file.
- Return type:
int
USB Device Scanner#
NXP USB Device Scanner API.
- spsdk.utils.nxpdevscan.filter_uart_devices(ports, real_devices)#
Filter UART devices.
- Ports:
ListPortInfo from pyserial
- Real_devices:
Scan for real devices using ioctl TIOCGSERIAL.
- Return type:
list[ListPortInfo]
- spsdk.utils.nxpdevscan.is_real_tty_device(device)#
Check if a /dev/ttyS* device is a real serial device using ioctl.
Check only for Linux. Check is based on ioctl TIOCGSERIAL. If the device is not a real serial device, the ioctl will return PORT_UNKNOWN (0).
- Parameters:
device (
str) – The device path.- Return type:
bool- Returns:
True if the device is a real serial device, False otherwise.
- 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_sdio_devices()#
Searches all NXP SDIO devices based on their device path.
- Return type:
list[SDIODeviceDescription]- Returns:
list of SDIODeviceDescription corresponding to NXP devices
- spsdk.utils.nxpdevscan.search_nxp_uart_devices(scan=True, all_devices=True, scan_uboot=True, timeout=50, real_devices=False)#
Returns a list of all NXP devices connected via UART.
- Scan:
whether to scan for mboot and SDP devices
- All_devices:
whether to return all devices or only NXP devices
- Scan_uboot:
whether to scan for U-Boot console devices
- Timeout:
timeout for UART scan in ms
- Real_devices:
Check if the device is real using ioctl TIOCGSERIAL.
- 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
- spsdk.utils.nxpdevscan.search_uuu_usb_devices()#
Searches all UUU compatible USB devices.
- Return type:
list[UUUDeviceDescription]- Returns:
list of USBDeviceDescription corresponding to UUU devices
Device description#
Module for NXP device description classes.
- class spsdk.utils.devicedescription.DeviceDescription#
Bases:
ABCBase 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!
- class spsdk.utils.devicedescription.SDIODeviceDescription(vid, pid, path)#
Bases:
DeviceDescriptionSimple container holding information about SDIO device.
This container should be used instead of any SDIO API related objects, as this container will be the same all the time compared to specific SDIO API implementations.
Constructor.
- Parameters:
vid (
int) – Vendor IDpid (
int) – Product ID
See
get_usb_device_name()function to getg the name from VID and PID. Seeconvert_usb_path()function to provide a proper path string.
- class spsdk.utils.devicedescription.SIODeviceDescription(info)#
Bases:
DeviceDescriptionSimple container holding information about LIBUSBSIO device.
This container contains information about LIBUSBSIOdevice.
Constructor.
- Parameters:
info (
HIDAPI_DEVICE_INFO_T) – LIBUSBSIO device information class.
- class spsdk.utils.devicedescription.USBDeviceDescription(vid, pid, path, product_string, manufacturer_string, name, serial, original_path=None)#
Bases:
DeviceDescriptionSimple 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 IDpid (
int) – Product IDproduct_string (
str) – Product stringmanufacturer_string (
str) – Manufacturer stringname (
str) – Name(s) of NXP devices as defined under spsdk.mboot.interfaces.usb or spsdk.sdp.interfaces.usbserial (
str) – The serial number of device.
See
get_usb_device_name()function to get the name from VID and PID. Seeconvert_usb_path()function to provide a proper path string.
- class spsdk.utils.devicedescription.UUUDeviceDescription(path, chip, pro, vid, pid, bcd, serial_no)#
Bases:
objectSimple container holding information about UUU device.
This container should be used instead of any UUU API related objects, as this container will be the same all the time compared to specific UUU API implementations.
Constructor.
- Parameters:
path (
str) – The path to the USB device.chip (
str) – The chip of the USB device.pro (
str) – The product of the USB device.vid (
int) – The vendor ID of the USB device.pid (
int) – The product ID of the USB device.bcd (
int) – The device release number in binary-coded decimal.serial_no (
str) – The serial number of the USB device.
- class spsdk.utils.devicedescription.UartDeviceDescription(name=None, dev_type=None)#
Bases:
DeviceDescriptionSimple 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 namedev_type (
Optional[str]) – ‘mboot device’ or ‘SDP device’
- 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 inpid (
int) – Product ID we are interested indevice_names (
Optional[dict[str,list[UsbId]]]) – 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.CommentedConfig(main_title, schemas, note=None)#
Bases:
objectClass for generating commented config templates or custom configurations.
Constructor for Config templates.
- Parameters:
main_title (
str) – Main title of final template.schemas (
list[dict[str,Any]]) – Main description of final template.note (
Optional[str]) – Additional Note after title test.
- MAX_LINE_LENGTH = 118#
- static convert_cm_to_yaml(config)#
Convert Commented Map for into final YAML string.
- Parameters:
config (
CommentedMap) – Configuration in CM format.- Raises:
SPSDKError – If configuration is empty
- Return type:
str- Returns:
YAML string with configuration to use to store in file.
- export(config=None)#
Export configuration template into CommentedMap.
- Parameters:
config (
Optional[dict[str,Any]]) – Configuration to be applied to template.- Raises:
SPSDKError – Error
- Return type:
CommentedMap- Returns:
Configuration template in CM.
- get_config(config)#
Export Configuration directly into YAML string format.
- Return type:
str- Returns:
YAML string.
- static get_property_optional_required(key, block)#
Function to determine if the config property is required or not.
- Parameters:
key (
str) – Name of config recordblock (
dict[str,Any]) – Source data block
- Return type:
- Returns:
Final description.
- get_template()#
Export Configuration template directly into YAML string format.
- Return type:
str- Returns:
YAML string.
- property max_line: int#
Maximal line with current indent.
- class spsdk.utils.schema_validator.PropertyRequired(tag, label, description=None)#
Bases:
SpsdkEnumEnum describing if the property is required or optional.
- CONDITIONALLY_REQUIRED = (1, 'CONDITIONALLY_REQUIRED', 'Conditionally required')#
- OPTIONAL = (2, 'OPTIONAL', 'Optional')#
- REQUIRED = (0, 'REQUIRED', 'Required')#
- class spsdk.utils.schema_validator.SPSDKListStrategies(strategy_list)#
Bases:
ListStrategiesExtended List Strategies.
- static strategy_set(_config, _path, base, nxt)#
Use the set of both as a output.
- class spsdk.utils.schema_validator.SPSDKMerger(type_strategies=[(<class 'list'>[, 'set']), (<class 'dict'>[, 'merge']), (<class 'set'>[, 'union'])], fallback_strategies=['override'], type_conflict_strategies=['override'])#
Bases:
MergerModified Merger to add new list strategy ‘set’.
SPSDK Merger constructor.
- Parameters:
type_strategies (
list) – Type of merge strategies, defaults to [(list, [“set”]), (dict, [“merge”]), (set, [“union”])]fallback_strategies (
list) – Fallback strategies, defaults to [“override”]type_conflict_strategies (
list) – Conflict strategies, defaults to [“override”]
- PROVIDED_TYPE_STRATEGIES: dict[type, type[s.StrategyList]] = {<class 'dict'>: <class 'deepmerge.strategy.dict.DictStrategies'>, <class 'list'>: <class 'spsdk.utils.schema_validator.SPSDKListStrategies'>, <class 'set'>: <class 'deepmerge.strategy.set.SetStrategies'>}#
- spsdk.utils.schema_validator.check_config(config, schemas, extra_formatters=None, search_paths=None, check_unknown_props=False)#
Check the configuration by provided list of validation schemas.
- Parameters:
config (
dict[str,Any]) – Configuration to checkschemas (
list[dict[str,Any]]) – List of validation schemasextra_formatters (
Optional[dict[str,Callable[[str],bool]]]) – Additional custom formatterssearch_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to Nonecheck_unknown_props (
bool) – If True, check for unknown properties in config and print warnings
- Raises:
SPSDKError – Invalid validation schema or configuration
- Return type:
None
- spsdk.utils.schema_validator.check_unknown_properties(config_dict, schema_dict, path='')#
Recursively check for unknown properties in config.
- Return type:
None
- spsdk.utils.schema_validator.cmap_update(cmap, updater)#
Update CMap including comments.
- Parameters:
cmap (
CommentedMap) – Original CMap to be updated.updater (
CommentedMap) – CMap updater.
- Return type:
None
Utils Exceptions#
Module provides exceptions for SPSDK utilities.
- exception spsdk.utils.exceptions.SPSDKRegsError(desc=None)#
Bases:
SPSDKErrorGeneral Error group for utilities SPSDK registers module.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorBitfieldNotFound(desc=None)#
Bases:
SPSDKRegsErrorBitfield has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorEnumNotFound(desc=None)#
Bases:
SPSDKRegsErrorEnum has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterGroupMishmash(desc=None)#
Bases:
SPSDKRegsErrorRegister Group inconsistency problem.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterNotFound(desc=None)#
Bases:
SPSDKRegsErrorRegister has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKTimeoutError(desc=None)#
Bases:
SPSDKError,TimeoutErrorSPSDK Timeout.
Initialize the base SPSDK Exception.
Database#
Module to manage and interact with databases used in SPSDK.
This module provides utilities and classes for handling various databases used throughout the Secure Provisioning SDK (SPSDK). It includes functionality for loading, caching, and accessing device-specific data, features, and revisions.
- class spsdk.utils.database.Bootloader(protocol, interfaces, usb_id, protocol_params)#
Bases:
objectRepresents a bootloader with its protocol and interface details.
Initialize a Bootloader instance.
- Parameters:
protocol (
Optional[str]) – Name of the bootloader protocol (e.g., ‘mboot’, ‘sdp’, ‘sdps’, ‘lpc’)interfaces (
list) – List of supported interfacesusb_id (
UsbId) – USB identifier for the bootloaderprotocol_params (
dict) – Dictionary of protocol-specific parameters
- Raises:
SPSDKValueError – If an invalid protocol value is provided
- classmethod load(config)#
Create a Bootloader instance from a configuration dictionary.
- Parameters:
config (
dict) – Dictionary containing bootloader configuration- Return type:
Self- Returns:
New Bootloader instance
- update(config)#
Update the Bootloader instance from a configuration dictionary.
- Parameters:
config (
dict) – Dictionary containing updated bootloader configuration- Return type:
None
- class spsdk.utils.database.Database(path, restricted_data_path=None, addons_data_path=None, complete_load=False)#
Bases:
objectClass that helps manage used databases in SPSDK.
Register Configuration class constructor.
- Parameters:
path (
str) – The path to the base database.restricted_data_path (
Optional[str]) – The path to the restricted data database.addons_data_path (
Optional[str]) – The path to the addons data database.complete_load (
bool) – The database is fully loaded from database path without using cache.
- class DatabaseData(path, restricted_data_path=None, addons_data_path=None, complete_load=False)#
Bases:
objectDatabase data intended to be cached if possible.
Constructor of Database data object.
- static get_cache_filename(path)#
Get database cache folder and file name.
- Return type:
str- Returns:
Database cache file name.
- static hash_db_data(cached_configs, path, restricted_data_path=None, addons_data_path=None)#
Get hash of real files/data.
- Parameters:
cached_configs (
list[str]) – List of file names to be hashedpath (
str) – Path to databaserestricted_data_path (
Optional[str]) – Optional path to restricted data, defaults to Noneaddons_data_path (
Optional[str]) – Optional path to addons data, defaults to None
- Return type:
bytes- Returns:
Hash of all inputs including defaults content
- make_cache()#
Create cache file of itself.
- Return type:
None
- get_common_data_file_path(path)#
Get common data file path.
The method counts also with restricted data source and any other addons.
- Parameters:
path (
str) – Relative path in common data folder- Raises:
SPSDKValueError – Non existing file path.
- Return type:
str- Returns:
Final absolute path to data file.
- get_data_file_path(path, exc_enabled=True, just_standard_lib=False)#
Get data file path.
The method counts also with restricted data source and any other addons.
- Parameters:
path (
str) – Relative path in data folderexc_enabled (
bool) – Exception enabled in case of non existing file.just_standard_lib (
bool) – Use just standard library files (no restricted data, neither addons), defaults False.
- Raises:
SPSDKValueError – Non existing file path.
- Return type:
str- Returns:
Final absolute path to data file.
- get_defaults(feature)#
Gets feature defaults.
- Parameters:
feature (
str) – Feature name- Return type:
dict[str,Any]- Returns:
Dictionary with feature defaults.
- get_device_features(family, revision='latest')#
Get device features database.
- Parameters:
family (
str) – The family name.revision (
str) – The revision name.
- Raises:
SPSDKValueError – Unsupported feature
- Return type:
- Returns:
The feature data.
- get_schema_file(feature)#
Get JSON Schema file name for the requested feature.
- Parameters:
feature (
str) – Requested feature.- Return type:
dict[str,Any]- Returns:
Loaded dictionary of JSON Schema file.
- load_db_cfg_file(filename)#
Return load database config file (JSON/YAML). Use SingleTon behavior.
- Parameters:
filename (
str) – Path to config file.- Raises:
SPSDKError – Invalid config file.
- Return type:
dict[str,Any]- Returns:
Loaded file in dictionary.
- class spsdk.utils.database.DatabaseManager#
Bases:
objectMain SPSDK database manager implementing singleton pattern.
Manage SPSDK Database as a singleton class.
- Returns:
SPSDK_Database object
- AHAB = 'ahab'#
- BCA = 'bca'#
- BEE = 'bee'#
- BLHOST = 'blhost'#
- BOOTABLE_IMAGE = 'bootable_image'#
- CERT_BLOCK = 'cert_block'#
- COMM_BUFFER = 'comm_buffer'#
- DAT = 'dat'#
- DEVHSM = 'devhsm'#
- DICE = 'dice'#
- EL2GO_TP = 'el2go_tp'#
- ELE = 'ele'#
- FASTBOOT = 'fastboot'#
- FCB = 'fcb'#
- FCF = 'fcf'#
- FUSES = 'fuses'#
- HAB = 'hab'#
- IEE = 'iee'#
- LPCPROG = 'lpcprog'#
- MBI = 'mbi'#
- MEMCFG = 'memcfg'#
- NXPUUU = 'nxpuuu'#
- OTFAD = 'otfad'#
- PFR = 'pfr'#
- SB21 = 'sb21'#
- SB31 = 'sb31'#
- SBC = 'sbc'#
- SBX = 'sbx'#
- SHADOW_REGS = 'shadow_regs'#
- SHE_SCEC = 'she_scec'#
- SIGNED_MSG = 'signed_msg'#
- SIGNING = 'signing'#
- TP = 'tp'#
- TZ = 'tz'#
- WPC = 'wpc'#
- XMCD = 'xmcd'#
- static clear_cache()#
Clear SPSDK cache directory.
- Return type:
None
- classmethod get_db(complete_load=False)#
Get database, and handle the first time use.
- Parameters:
complete_load (
bool) – If True, the database will be completely loaded.- Return type:
- Returns:
Database instance.
- static get_quick_info_hash(paths)#
Calculate the hash of the real databases.
- Parameters:
paths (
list[Optional[str]]) – List of paths to database folders.- Return type:
bytes- Returns:
Calculated hash as bytes.
- static get_restricted_data()#
Get restricted data folder path, if applicable.
- Return type:
Optional[str]- Returns:
Optional restricted data folder path.
- property quick_info: QuickDatabase#
Get quick info Database instance.
- class spsdk.utils.database.Device(name, db, latest_rev, info, device_alias=None, revisions=[])#
Bases:
objectDevice dataclass represents a single device.
Constructor of SPSDK Device.
- Parameters:
- create_file_path(file_name, just_standard_lib=False)#
Create File path value for this device.
- Parameters:
file_name (
str) – File name to be enriched by device pathjust_standard_lib (
bool) – Use just standard library files (no restricted data, neither addons), defaults False.
- Return type:
str- Returns:
File path value for the device
- get_copy(new_name=None)#
Get copy of self.
- Parameters:
new_name (
Optional[str]) – Optionally the copy could has a new name.- Return type:
- Returns:
Copy of self.
- get_features(revision=None)#
Get the list of device features.
- Return type:
list[str]
- class spsdk.utils.database.DeviceInfo(use_in_doc, purpose, spsdk_predecessor_name, web, memory_map, isp)#
Bases:
objectDevice information dataclass.
Constructor of device information class.
- Parameters:
purpose (
str) – String description of purpose of MCU (in fact the device group)spsdk_predecessor_name (
Optional[str]) – Device sub series name (usually predecessor name in SPSDK)web (
str) – Web page with device infomemory_map (
dict[str,dict[str,Any]]) – Basic memory map of deviceisp (
IspCfg) – Information regarding ISP mode
- classmethod load(config, defaults)#
Loads the device from folder.
- Parameters:
config (
dict[str,Any]) – The name of device.defaults (
dict[str,Any]) – Device data defaults.
- Return type:
Self- Returns:
The Device object.
- update(config)#
Updates Device info by new configuration.
- Parameters:
config (
dict[str,Any]) – The new Device Info configuration- Return type:
None
- class spsdk.utils.database.DeviceQuickInfo(features, info, latest_rev)#
Bases:
objectDevice quick and short info.
Constructor of Device quick information.
- Parameters:
features (
Revisions) – Device features to get information frominfo (
DeviceInfo) – Device informationlatest_rev (
str) – Latest chip revision
- get_features(revision=None)#
List of all supported features of device.
- Return type:
list[str]
- is_feature_supported(feature, sub_feature=None, revision=None)#
Return True if the feature is supported by devices.
- Parameters:
feature (
str) – Feature namesub_feature (
Optional[str]) – Sub feature name to better granularity, defaults to Nonerevision (
Optional[str]) – Specific device revision to check, defaults to latest revision
- Return type:
bool- Returns:
True if the feature is supported by devices, False otherwise.
- property revisions: list[str]#
List of available revisions.
- class spsdk.utils.database.Devices(db)#
Bases:
objectList of devices.
Constructor of managed devices in database.
- Parameters:
db (
Database) – Whole database object.
- feature_items(feature, key)#
Iter the whole database for the feature items.
- Return type:
Iterator[tuple[str,str,Any]]- Returns:
Tuple of Device name, revision name and items value.
- get(name)#
Return database device structure.
- Parameters:
name (
str) – String Key with device name.- Raises:
SPSDKErrorMissingDevice – In case the device with given name does not exist
- Return type:
- Returns:
Dictionary device configuration structure or None:
- load_devices_from_path(devices_path)#
Loads the devices from SPSDK database path.
- Parameters:
devices_path (
str) – The devices path.- Return type:
None
- class spsdk.utils.database.DevicesQuickInfo#
Bases:
objectList of all devices with their quick information.
Constructor of devices quick information.
- static create(devices)#
Create quick info about devices.
- Parameters:
devices (
Devices) – Full devices description.- Return type:
- get_correct_name(family)#
Get correct(latest) device name.
- Parameters:
family (
str) – The CPU family name.- Return type:
str- Returns:
Current database device name as string.
- get_devices_with_feature(feature, sub_feature=None)#
Get the list of all families that supports requested feature.
- Parameters:
feature (
str) – Name of featuresub_feature (
Optional[str]) – Optional sub feature to better specify the families selection
- Return type:
dict[str,list]- Returns:
List of devices that supports requested feature.
- get_family_names()#
Get the list of all families supported by SPSDK.
- Return type:
list[str]
- get_feature_list(family, revision=None)#
Get features list.
If device is not used, the whole list of SPSDK features is returned
- Parameters:
family (
str) – Family namerevision (
Optional[str]) – Optional device revision
- Return type:
list[str]- Returns:
List of features.
- get_predecessors(families)#
Get the list of devices predecessors in previous SPSDK versions.
- Parameters:
families (
list[str]) – List of current family names- Return type:
dict[str,str]- Returns:
Dictionary mapping predecessor family names to current names
- is_predecessor_name(family)#
Check if device name is predecessor SPSDK device name.
- Parameters:
family (
str) – The CPU family name.- Return type:
bool- Returns:
True if it’s SPSDK predecessor name.
- class spsdk.utils.database.Features(name, is_latest, device, features)#
Bases:
objectRepresents a single device revision with its features.
Initialize a Features instance.
- Parameters:
name (
str) – Revision name.is_latest (
bool) – Flag indicating if this revision is the latest.device (
Device) – Reference to its device.features (
dict[str,dict[str,Any]]) – Dictionary of features.
- check_key(feature, key)#
Check if the key exists in the database.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).
- Raises:
SPSDKValueError – If the feature is unsupported.
- Return type:
bool- Returns:
True if the key exists, False otherwise.
- get_bool(feature, key, default=None)#
Get a boolean value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[bool]) – Default value if the key is missing.
- Return type:
bool- Returns:
Boolean value from the feature dictionary.
- get_dict(feature, key, default=None)#
Get a dictionary value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[dict]) – Default value if the key is missing.
- Return type:
dict- Returns:
Dictionary value from the feature dictionary.
- get_file_path(feature, key, default=None, just_standard_lib=False)#
Get a file path value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[str]) – Default value if the key is missing.just_standard_lib (
bool) – Use only standard library files (no restricted data or addons).
- Return type:
str- Returns:
File path value for the device.
- get_int(feature, key, default=None)#
Get an integer value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[int]) – Default value if the key is missing.
- Return type:
int- Returns:
Integer value from the feature dictionary.
- get_list(feature, key, default=None)#
Get a list value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[list]) – Default value if the key is missing.
- Return type:
list[Any]- Returns:
List value from the feature dictionary.
- get_str(feature, key, default=None)#
Get a string value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[str]) – Default value if the key is missing.
- Return type:
str- Returns:
String value from the feature dictionary.
- get_value(feature, key, default=None)#
Get a value from the feature dictionary.
- Parameters:
feature (
str) – Feature name.key (
Union[list[str],str]) – Item key or key path as a list (e.g., [‘grp1’, ‘grp2’, ‘key’]).default (
Optional[Any]) – Default value if the key is missing.
- Raises:
SPSDKValueError – If the feature is unsupported or the item is unavailable.
- Return type:
Any- Returns:
Value from the feature dictionary.
- class spsdk.utils.database.FeaturesEnum(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of all SPSDK database features.
- AHAB = (7, 'ahab', 'Boot container - Advanced High Assurance Boot')#
- BCA = (33, 'bca', 'Bootloader Configuration Area')#
- BEE = (14, 'bee', 'Bus Encryption Engine')#
- BLHOST = (1, 'blhost', 'BLHOST application / mBoot In-System Programming protocol')#
- BOOTABLE_IMAGE = (11, 'bootable_image', 'Bootable Image')#
- CERT_BLOCK = (3, 'cert_block', 'Certification Block')#
- COMM_BUFFER = (2, 'comm_buffer', 'Communication buffer in RAM memory')#
- DAT = (4, 'dat', 'Debug Authentication Protocol')#
- DEVHSM = (21, 'devhsm', 'Device HSM')#
- DICE = (30, 'dice', 'Device Identifier Composition Engine')#
- EL2GO_TP = (28, 'el2go_tp', 'EdgeLock 2 Go Trust Provisioning')#
- ELE = (24, 'ele', 'EdgeLock Enclave')#
- FASTBOOT = (31, 'fastboot', 'Fastboot protocol')#
- FCB = (12, 'fcb', 'Flash Configuration Block')#
- FCF = (34, 'fcf', 'Flash Configuration Field')#
- FUSES = (0, 'fuses', 'One-Time Programmable fuses')#
- HAB = (6, 'hab', 'Boot container - High Assurance Boot')#
- IEE = (15, 'iee', 'Inline Encryption Engine')#
- LPCPROG = (29, 'lpcprog', 'LPC devices programming')#
- MBI = (5, 'mbi', 'Boot container - Master Boot Image')#
- MEMCFG = (25, 'memcfg', 'Memory Configuration')#
- NXPUUU = (32, 'nxpuuu', 'NXP UUU')#
- OTFAD = (16, 'otfad', 'On-The-Fly AES Decryption')#
- PFR = (9, 'pfr', 'Protected Flash Region')#
- SB21 = (17, 'sb21', 'Secure Binary v2.1')#
- SB31 = (18, 'sb31', 'Secure Binary v3.1')#
- SBC = (35, 'sbc', 'sbc')#
- SBX = (19, 'sbx', 'Secure Binary X')#
- SHADOW_REGS = (20, 'shadow_regs', 'Shadow registers')#
- SHE_SCEC = (36, 'she_scec', 'Secure Hardware Extension')#
- SIGNED_MSG = (8, 'signed_msg', 'Signed Message')#
- SIGNING = (27, 'signing', 'Signing additional information')#
- TP = (22, 'tp', 'Trust Provisioning')#
- TZ = (23, 'tz', 'ARM TrustZone')#
- WPC = (26, 'wpc', 'Wireless Power Consortium')#
- XMCD = (13, 'xmcd', 'External Memory Configuration Data')#
- class spsdk.utils.database.FeaturesQuickData#
Bases:
objectGeneral quick data for features not depends on devices.
Constructor, just to keep members.
- classmethod create(devices)#
Create Quick data from the Database.
- Parameters:
devices (
Devices) – Database devices object to pick data from- Return type:
Self- Returns:
Quick features object.
- property get_all_features: list[str]#
Return list of all supported features.
- get_mem_types(feature)#
Get supported memory types in individual features per all devices.
- Parameters:
feature (
str) – Feature name- Return type:
list[str]
- class spsdk.utils.database.IspCfg(rom, flashloader)#
Bases:
objectISP configuration.
Constructor of ISP config class.
- Parameters:
rom (
Bootloader) – ROM objectflashloader (
Bootloader) – Flashloader object
- get_usb_ids(protocol)#
Get the usb params for interfaces supporting given protocol.
- Return type:
list[UsbId]
- is_protocol_supported(protocol)#
Returns true is any of interfaces supports given protocol.
- Return type:
bool
- classmethod load(config)#
Load from configuration.
- Return type:
Self
- update(config)#
Update the object from configuration.
- Return type:
None
- class spsdk.utils.database.MemBlock(name, desc)#
Bases:
objectOne memory block from memory map.
Initialize a MemBlock instance.
- Parameters:
name (
str) – Name of the memory blockdesc (
dict[str,Any]) – Dictionary containing the memory block description
- BLOCK_NAMES = ['dtcm', 'itcm', 'system-tcm', 'code-tcm', 'ram', 'dram', 'sdram', 'sram', 'sramx', 'sram-l', 'sram-u', 'ocram', 'ocram-ecc', 'usb-ram', 'flash-logical-window', 'flexspi', 'xspi', 'internal-flash', 'ifr-bank']#
- CORES = ['a55', 'cm7', 'cm4', 'cm33', 'cm0', 'cm0p']#
- SECURITY = ['s', 'ns']#
- property base_address: int#
Get the base address of the memory block.
- Returns:
Base address as an integer
- property block_name: str#
Get block name.
- property core: str | None#
Get core name if specified.
- classmethod create_name(block_name, core=None, instance=None, secure_access=None)#
Create full name of memory block.
- Parameters:
block_name (
str) – Name of memory blockcore (
Optional[str]) – Optional core name, defaults to Noneinstance (
Optional[int]) – Optional instance, defaults to Nonesecure_access (
Optional[bool]) – Optional specification if block has secure or non secure access, defaults to None
- Return type:
str- Returns:
Full block name.
- property external: bool#
Check if this is an external memory block.
- Returns:
True if external, False otherwise
- property instance: int | None#
Get instance if specified.
- classmethod parse_name(name)#
Parse name to base elements.
- Parameters:
name (
str) – Name of the memory block.- Return type:
tuple[Optional[str],str,Optional[int],Optional[bool]]- Returns:
Tuple of: - Optional Core name - Name of memory - Optional index of memory - Optional boolean if secure access
- property security_access: bool | None#
Get security access if specified.
- property size: int#
Get the size of the memory block.
- Returns:
Size in bytes as an integer
- class spsdk.utils.database.MemMap(mem_map)#
Bases:
objectDevice memory map configuration.
Device memory map configuration.
- Parameters:
mem_map_raw – Raw data of memory map loaded from database.
- get_memory(block_name, core=None, instance=None, secure=None)#
Get the one memory block by parameters.
- Parameters:
block_name (
str) – Core block namecore (
Optional[str]) – Optional core name, defaults to Noneinstance (
Optional[int]) – Optional instance, defaults to Nonesecure (
Optional[bool]) – optional selection of secure non secure memory access, defaults to False
- Return type:
- Returns:
Memory block if available
- Raises:
SPSDKError in case that block is not found.
- get_table()#
Get string table with memory map description.
- Return type:
str
- classmethod load(mem_map)#
Loads the Memory map from configuration.
- Parameters:
mem_map (
dict[str,dict[str,Any]]) – Dictionary with all blocks.- Return type:
Self
- class spsdk.utils.database.QuickDatabase#
Bases:
objectBase quick database class.
This class is intend to be loaded after startup of SPSDK to provides basic information to satisfy whole CLI information (like helps texts and enums for choices) without loading heavy database with all data.
Just constructor to held the internal members.
- classmethod create(database)#
Create Quick data from the Database.
- Parameters:
database (
Database) – Database object to pick data from- Return type:
Self- Returns:
Quick database object.
- split_devices_to_groups(devices)#
Sort given devices to groups by their purposes.
- Parameters:
devices (
list[str]) – Input list of devices.- Return type:
dict[str,list[str]]- Returns:
Dictionary where the key is name od group and value is list of devices.
- class spsdk.utils.database.Revisions(iterable=(), /)#
Bases:
list[Features]List of device revisions.
This class extends the built-in list to store and manage device revision Features.
- get(name=None)#
Get the revision by its name.
If name is not specified, or equal to ‘latest’, then the latest revision is returned.
- Parameters:
name (
Optional[str]) – The revision name to retrieve.- Return type:
- Returns:
The Features object for the specified revision.
- Raises:
SPSDKValueError – If the requested revision is not supported.
- revision_names(append_latest=False)#
Get a list of revision names.
- Parameters:
append_latest (
bool) – If True, append “latest” to the list of revision names.- Return type:
list[str]- Returns:
List of all supported device revision names.
- exception spsdk.utils.database.SPSDKErrorMissingDevice(desc=None, missing_device_name=None)#
Bases:
SPSDKErrorException raised when a device is missing from the database.
Initialize the SPSDKErrorMissingDevice exception.
- Parameters:
desc (
Optional[str]) – Description of the error.missing_device_name (
Optional[str]) – Name of the missing device.
- class spsdk.utils.database.UsbId(vid=None, pid=None)#
Bases:
objectUSB identifier for a given device.
Initialize a USB ID instance.
- Parameters:
vid (
Optional[int]) – USB Vendor IDpid (
Optional[int]) – USB Product ID
- is_valid()#
Check if the USB ID is valid.
- Return type:
bool- Returns:
True if both vid and pid are set, False otherwise
- classmethod load(usb_config)#
Create a UsbId instance from a configuration dictionary.
- Parameters:
usb_config (
dict) – Dictionary containing ‘vid’ and/or ‘pid’ keys- Return type:
Self- Returns:
New UsbId instance
- update(usb_config)#
Update the USB ID from a configuration dictionary.
- Parameters:
usb_config (
dict) – Dictionary containing ‘vid’ and/or ‘pid’ keys- Return type:
None
- spsdk.utils.database.get_common_data_file_path(path)#
Get common data file path.
The method counts also with restricted data source and any other addons.
- Parameters:
path (
str) – Relative path in common data folder.- Raises:
SPSDKValueError – Non existing file path.
- Return type:
str- Returns:
Final absolute path to data file.
- spsdk.utils.database.get_schema_file(feature)#
Get JSON Schema file name for the requested feature.
- Parameters:
feature (
str) – Requested feature.- Return type:
dict[str,Any]- Returns:
Loaded dictionary of JSON Schema file.
- spsdk.utils.database.get_spsdk_cache_dirname()#
Get database cache folder name.
Returns the path specified by SPSDK_CACHE_FOLDER if set and valid. Otherwise, returns the default user cache directory for SPSDK.
- Return type:
str
- Raises:
SPSDKValueError: If SPSDK_CACHE_FOLDER is set but not a valid absolute path.
- Returns:
str: The path to the SPSDK cache directory.