Utils Module API#
SPSDK utilities package initialization module.
This module serves as the entry point for the SPSDK utilities package, providing access to common utility functions, classes, and exceptions used throughout the SPSDK library.
Abstract class template#
SPSDK abstract base classes for common functionality.
This module provides foundational abstract classes that define common interfaces and patterns used throughout the SPSDK library for consistent implementation across different components.
- class spsdk.utils.abstract.BaseClass#
Bases:
RawBaseClassSPSDK abstract base class for serializable data objects.
This class provides a common interface for data classes that need to be exported to and parsed from binary formats. It defines the essential methods for binary serialization and deserialization operations.
- abstract export()#
Export object into bytes array.
- Return type:
bytes- Returns:
Object representation as bytes.
- abstract classmethod parse(data)#
Parse object from bytes array.
- Parameters:
data (
bytes) – Byte array containing the serialized object data.- Return type:
Self- Returns:
Parsed object instance.
- post_export(output_path)#
Post export method to handle additional operations after data export.
This method is called after the main export process to perform any additional file operations or data processing that may be required.
- 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 abstract base class for common object operations.
This class provides a foundation for SPSDK classes with standardized equality comparison and string representation methods. It ensures consistent behavior across the SPSDK library by defining common object operations that derived classes must implement.
Utils easy enum#
SPSDK custom enumeration extensions with enhanced functionality.
This module provides extended enumeration classes that offer additional features beyond standard Python enums, including flexible member lookup, soft enums for dynamic values, and enhanced error handling tailored for SPSDK applications.
- class spsdk.utils.spsdk_enum.SpsdkEnum(tag, label, description=None)#
Bases:
SpsdkEnumMember,EnumSPSDK enhanced enumeration with extended functionality.
This class extends Python’s standard Enum to provide additional features for SPSDK operations including tag-based identification, label management, and flexible member lookup capabilities. It supports equality comparison by both tag and label values, and provides utility methods for member introspection and validation.
- classmethod contains(obj)#
Check if given member with given tag/label exists in enum.
- Parameters:
obj (
Union[int,str]) – Label or tag of enum member to check for existence.- Raises:
SPSDKTypeError – Object must be either string or integer.
- Return type:
bool- Returns:
True if member exists, False otherwise.
- classmethod create_from_dict(name, config)#
Create the Enum in runtime from the Dictionary configuration.
The method dynamically creates an Enum class using the provided name and configuration dictionary. All dictionary values are converted to tuples before creating the Enum.
- Parameters:
name (
str) – Name of the new Enum class to be created.config (
dict[str,Union[tuple,list]]) – Configuration dictionary containing enum definitions where values can be tuples or lists.
- Return type:
Type[Self]- Returns:
Dynamically created Enum class.
- classmethod from_attr(attribute)#
Get enum member with given tag/label attribute.
The method automatically determines whether to use tag (for int) or label (for str) based on the attribute type and delegates to the appropriate method.
- Parameters:
attribute (
Union[int,str]) – Tag value (int) or label value (str) of the enum member to find.- Return type:
Self- Returns:
Found enum member matching the given attribute.
- classmethod from_label(label)#
Get enum member with given label.
The method performs case-insensitive search through all enum members to find the one with matching label.
- Parameters:
label (
str) – Label to be used for searching- Raises:
SPSDKKeyError – If enum with given label is not found or label is not string
- 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 tag 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 searching.default (
Optional[str]) – Default value if member contains no description.
- Return type:
Optional[str]- Returns:
Description of found enum member or default value if no description exists.
- 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.- Raises:
SPSDKValueError – If enum member with given label is not found.
- 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 representation.
This class represents a single member of an SPSDK enumeration, containing the numeric tag, human-readable label, and optional description for the enumeration value.
-
description:
Optional[str] = None#
-
label:
str#
-
tag:
int#
-
description:
- class spsdk.utils.spsdk_enum.SpsdkSoftEnum(tag, label, description=None)#
Bases:
SpsdkEnumSPSDK Soft Enum with graceful error handling.
This enum variant provides default fallback values for labels and descriptions when accessing non-existing enum members, preventing exceptions during lookup operations and returning descriptive “Unknown” values instead.
- classmethod from_tag(tag)#
Get enum member with given tag.
This method attempts to find an enum member by its tag value. If the tag is not found in the current enum, it creates a dynamic UnknownEnum placeholder to handle the unrecognized value gracefully while maintaining enum structure integrity.
- Parameters:
tag (
int) – Integer tag value to search for in the enum.- Raises:
SPSDKKeyError – If enum with given tag is not found in parent implementation.
- Return type:
Self- Returns:
Found enum member or dynamically created UnknownEnum placeholder.
- classmethod get_description(tag, default=None)#
Get description of enum member with given tag.
The method searches for an enum member by tag and returns its description. If the member is not found, returns a formatted unknown message with the tag.
- Parameters:
tag (
int) – Tag to be used for searching the enum member.default (
Optional[str]) – Default value if member contains no description.
- Return type:
Optional[str]- Returns:
Description of found enum member or formatted unknown message.
- classmethod get_label(tag)#
Get label of enum member with given tag.
If member not found, returns a formatted string with the unknown tag value instead of raising an exception.
- Parameters:
tag (
int) – Tag value to search for in enum members.- Return type:
str- Returns:
Label of found enum member or “Unknown (tag)” if not found.
General utils#
SPSDK miscellaneous utilities and helper functions.
This module provides a collection of utility functions and classes used throughout the SPSDK library, including data manipulation, file operations, configuration loading, and various helper utilities for binary data processing.
- class spsdk.utils.misc.BinaryPattern(pattern)#
Bases:
objectBinary pattern generator for creating filled data blocks.
This class provides functionality to generate binary data blocks filled with various patterns including special patterns (random, zeros, ones, incremental) and custom numeric values that can be repeated to fill the entire block.
- 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.
- Variables:
SPECIAL_PATTERNS – List of supported special pattern names.
Initialize binary pattern generator.
Creates a new binary pattern generator that can produce data based on the specified pattern type. Supports predefined patterns (rand, zeros, ones, inc) and custom numeric values that will be repeated to fill the target data.
- Parameters:
pattern (
str) – Pattern specification - predefined patterns (rand, zeros, ones, inc) or numeric value in decimal/hexadecimal/bytes format to be repeated- Raises:
SPSDKValueError – Unsupported pattern detected.
- SPECIAL_PATTERNS = ['rand', 'zeros', 'ones', 'inc']#
- get_block(size)#
Get block filled with pattern.
Generate a block of bytes with the specified size using the configured pattern. Supports predefined patterns (zeros, ones, rand, inc) and custom byte patterns.
- Parameters:
size (
int) – Size of block to return in bytes.- Return type:
bytes- Returns:
Block of bytes filled with the specified pattern.
- property pattern: str#
Get the pattern in string representation.
Converts the internal pattern to hexadecimal format if it’s a numeric value, otherwise returns the pattern as-is.
- Returns:
Pattern as hexadecimal string if numeric, otherwise original string pattern.
- class spsdk.utils.misc.Endianness(value)#
Bases:
str,EnumEndianness enumeration for byte order specification.
This enumeration defines the byte order options used throughout SPSDK for data processing and binary operations.
- Variables:
BIG – Big-endian byte order representation.
LITTLE – Little-endian byte order representation.
- BIG = 'big'#
- LITTLE = 'little'#
- classmethod values()#
Get enumeration values.
- Return type:
list[str]- Returns:
List of all enumeration values as strings.
- class spsdk.utils.misc.SecretManager(*args: Any, **kwargs: Any)#
Bases:
objectSPSDK Secret Manager for secure configuration data handling.
This singleton class manages secrets loaded from YAML configuration files with lazy loading and caching capabilities. It provides secure access to sensitive configuration data across the SPSDK library while ensuring secrets are loaded only when needed and cached for performance.
- Variables:
secrets_path – Path to the secrets YAML file location.
- get_secret(key)#
Get a secret by key, loading the secrets file if needed.
- Parameters:
key (
str) – The key of the secret to retrieve.- Raises:
ValueError – If the secret key is not found.
- Return type:
Any- Returns:
The secret value.
- secrets_path = '/home/docs/.spsdk/secrets.yaml'#
- class spsdk.utils.misc.SecretsLoader(stream)#
Bases:
SafeLoaderYAML loader for SPSDK configuration files with secret tag support.
This custom YAML loader extends SafeLoader to handle special !secret tags in configuration files, enabling secure loading of sensitive data like passwords, keys, and tokens from external sources.
Initialize the scanner.
- yaml_constructors = {'!secret': <function secret_constructor>, 'tag:yaml.org,2002:binary': <function SafeConstructor.construct_yaml_binary>, 'tag:yaml.org,2002:bool': <function SafeConstructor.construct_yaml_bool>, 'tag:yaml.org,2002:float': <function SafeConstructor.construct_yaml_float>, 'tag:yaml.org,2002:int': <function SafeConstructor.construct_yaml_int>, 'tag:yaml.org,2002:map': <function SafeConstructor.construct_yaml_map>, 'tag:yaml.org,2002:null': <function SafeConstructor.construct_yaml_null>, 'tag:yaml.org,2002:omap': <function SafeConstructor.construct_yaml_omap>, 'tag:yaml.org,2002:pairs': <function SafeConstructor.construct_yaml_pairs>, 'tag:yaml.org,2002:seq': <function SafeConstructor.construct_yaml_seq>, 'tag:yaml.org,2002:set': <function SafeConstructor.construct_yaml_set>, 'tag:yaml.org,2002:str': <function SafeConstructor.construct_yaml_str>, 'tag:yaml.org,2002:timestamp': <function SafeConstructor.construct_yaml_timestamp>, None: <function SafeConstructor.construct_undefined>}#
- class spsdk.utils.misc.SingletonMeta#
Bases:
typeSingleton metaclass for ensuring single instance creation.
This metaclass implements the singleton pattern by overriding the class instantiation process to ensure only one instance of a class exists throughout the application lifecycle.
- Variables:
_instance – Stores the single instance of the class.
- class spsdk.utils.misc.Timeout(timeout, units='s')#
Bases:
objectTimeout handler for SPSDK operations.
This class provides timeout functionality with configurable time units and methods to track elapsed time and remaining time during operations. It supports microseconds, milliseconds, and seconds as time units.
- Variables:
UNITS – Supported time units and their conversion factors to microseconds.
Initialize timeout class with specified timeout value and units.
- Parameters:
timeout (
int) – Timeout value in specified units.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()#
Get consumed time since start of timeout operation.
- Return type:
int- Returns:
Consumed time in units as the class was constructed.
- get_consumed_time_ms()#
Get consumed time since start of timed out operation in milliseconds.
- Return type:
int- Returns:
Consumed time in milliseconds.
- get_rest_time(raise_exc=False)#
Get remaining time until timeout expiration.
The method calculates how much time is left before the timeout occurs. If the timeout has already expired and raise_exc is True, an exception will be raised.
- Parameters:
raise_exc (
bool) – If True, raises SPSDKTimeoutError when timeout has expired.- Return type:
int- Returns:
Remaining time in the same units used during class construction.
- Raises:
SPSDKTimeoutError – When timeout has expired and raise_exc is True.
- get_rest_time_ms(raise_exc=False)#
Get remaining time until timeout overflow.
- Parameters:
raise_exc (
bool) – If set, the function raises SPSDKTimeoutError in case of overflow.- Return type:
int- Returns:
Remaining time in milliseconds.
- Raises:
SPSDKTimeoutError – In case of timeout overflow when raise_exc is True.
- overflow(raise_exc=False)#
Check if the timer has overflowed.
The method verifies whether the timer has exceeded its configured timeout period. It can optionally raise an exception when overflow is detected.
- Parameters:
raise_exc (
bool) – If True, raises SPSDKTimeoutError when overflow occurs.- Return type:
bool- Returns:
True if timeout has overflowed, False otherwise.
- Raises:
SPSDKTimeoutError – When overflow occurs and raise_exc is True.
- spsdk.utils.misc.align(number, alignment=4)#
Align number to specified byte boundary.
The function aligns the input number up to the nearest multiple of the specified alignment value. This is commonly used for memory alignment requirements where data must be positioned at specific byte boundaries.
- Parameters:
number (
int) – The number to be aligned (size or address).alignment (
int) – The boundary alignment value, typically a power of 2 (4, 8, 16).
- Return type:
int- Returns:
Aligned number that is always greater than or equal to the input number.
- Raises:
SPSDKError – When alignment is non-positive or number is negative.
- 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]) – Binary data to be aligned.alignment (
int) – Boundary alignment in bytes (typically 2, 4, 16, 64 or 256).padding (
Union[int,str,BinaryPattern,None]) – Padding byte value, string pattern, or BinaryPattern instance to use.
- Return type:
bytes- Returns:
Aligned binary data block.
- Raises:
SPSDKError – When alignment value is invalid.
- spsdk.utils.misc.align_block_fill_random(data, alignment=4)#
Align block data to specified boundary using random padding.
This function extends align_block functionality by automatically using random data for padding instead of requiring a padding parameter.
- Parameters:
data (
bytes) – Input binary data to be aligned.alignment (
int) – Byte boundary for alignment, defaults to 4 bytes.
- Return type:
bytes- Returns:
Aligned binary data with random padding if needed.
- spsdk.utils.misc.align_block_iso7816(data, alignment=16)#
Align data block using ISO7816-4 padding.
ISO7816-4 padding adds a mandatory 0x80 byte followed by zero or more 0x00 bytes to reach the desired alignment. This is commonly used in smart card applications.
- Parameters:
data (
bytes) – Input data to be paddedalignment (
int) – Block size alignment in bytes, defaults to 16
- Return type:
bytes- Returns:
Padded data aligned to the specified block size
- spsdk.utils.misc.bytes_to_print(data, max_length=32, unavailable_text='Not available')#
Format bytes data for display with length-based truncation.
Converts bytes data to hexadecimal string representation with optional truncation for long data. Returns unavailable text when data is None or empty.
- Parameters:
data (
Optional[bytes]) – Bytes data to format, can be None or empty.max_length (
int) – Maximum number of bytes to display before truncation.unavailable_text (
str) – Text to show when data is None or empty.
- Return type:
str- Returns:
Formatted string representation of the bytes data.
- spsdk.utils.misc.change_endianness(bin_data)#
Convert binary format used in files to binary used in register object.
The method handles endianness conversion for different data lengths. Single bytes are returned unchanged, 2-byte values are reversed, 3-byte values are not supported, and longer values use specialized long word reversal.
- Parameters:
bin_data (
bytes) – Input binary array to convert endianness.- Return type:
bytes- Returns:
Converted array with changed endianness (little to big endian conversion).
- Raises:
SPSDKError – Unsupported length (3 bytes) for endianness conversion.
- 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 by removing invalid characters.
Removes characters that are not allowed in file names on Windows systems including: < > : “ | ? * :type original_name:
str:param original_name: Input file name to be sanitized. :rtype:str:return: Sanitized file name with invalid characters removed.
- spsdk.utils.misc.deep_update(d, u)#
Deep update nested dictionaries and lists.
Recursively merges two dictionaries, updating the first dictionary with values from the second. For nested dictionaries, the merge is performed recursively rather than replacing the entire nested dictionary. For lists containing dictionaries, the dictionaries are also merged recursively.
- Parameters:
d (
dict) – Dictionary that will be updated.u (
dict) – Dictionary with update information.
- Return type:
dict- Returns:
Updated dictionary.
- spsdk.utils.misc.extend_block(data, length, padding=0)#
Extend binary data block with padding to reach specified length.
Add padding bytes to the end of a binary data block to extend its length to the specified value. If the target length equals current length, returns the original data unchanged.
- Parameters:
data (
bytes) – Binary block to be extended.length (
int) – Requested block length; must be >= current block length.padding (
int) – 8-bit value to be used as padding (default: 0).
- Return type:
bytes- Returns:
Block extended with padding bytes.
- Raises:
SPSDKError – When the length is smaller than current block length.
- spsdk.utils.misc.file_extension(output_format='bin', add_dot=True)#
Get the file extension based on output format.
Converts the output format string to the corresponding file extension. Supported formats include binary, hex, S-record, and sparse image formats.
- Parameters:
output_format (
str) – Output format type [“bin”, “hex”, “srec”, “sparse”], defaults to “bin”add_dot (
bool) – Whether to include the dot prefix in the extension, defaults to True
- Return type:
str- Returns:
File extension string (e.g., “.bin”, “.hex”, “.srec”, “.simg” with dot, or “bin”, “hex”, “srec”, “simg” without)
- spsdk.utils.misc.find_dir(dir_path, use_cwd=True, search_paths=None, raise_exc=True)#
Find directory path with flexible search options.
The method searches for a directory using multiple strategies: absolute path check, current working directory search, and custom search paths. Search paths take precedence over current working directory when both are specified.
- 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 – Directory not found
- spsdk.utils.misc.find_file(file_path, use_cwd=True, search_paths=None, raise_exc=True)#
Find file in filesystem using multiple search strategies.
The method searches for a file by checking the provided path directly, then optionally searching in the current working directory and additional search paths. Search paths take precedence over current working directory when both are enabled.
- Parameters:
file_path (
str) – File name, part of file path or full path to search for.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 absolute path to the found file.
- Raises:
SPSDKError – File not found in any of the search locations.
- spsdk.utils.misc.find_first(iterable, predicate)#
Find first element from iterable that matches the given condition.
- Parameters:
iterable (
Iterable[TypeVar(T)]) – Iterable collection of elements to search through.predicate (
Callable[[TypeVar(T)],bool]) – Function that takes an element and returns True if it matches the condition.
- Return type:
Optional[TypeVar(T)]- Returns:
First matching element or None if no element matches the predicate.
- spsdk.utils.misc.format_value(value, size, delimiter='_', use_prefix=True)#
Convert integer value to formatted binary or hexadecimal string representation.
The function automatically selects binary format when size is not divisible by 8, otherwise uses hexadecimal format. Digits are grouped by 4 characters using the specified delimiter for better readability.
- Parameters:
value (
int) – Integer value to be converted.size (
int) – Bit size that determines output format and padding.delimiter (
str) – Character used to separate digit groups, defaults to underscore.use_prefix (
bool) – Whether to include format prefix (0b/0x), defaults to True.
- Return type:
str- Returns:
Formatted string representation of the value.
- spsdk.utils.misc.get_abs_path(file_path, base_dir=None)#
Convert relative or absolute file path to normalized absolute path.
The method handles both relative and absolute paths, normalizing path separators to forward slashes for cross-platform compatibility.
- Parameters:
file_path (
str) – File path to be converted to absolute path.base_dir (
Optional[str]) – Base directory to create absolute path, if not specified the system CWD is used.
- Return type:
str- Returns:
Absolute file path with normalized separators.
- spsdk.utils.misc.get_bytes_cnt_of_int(value, align_to_2n=True, byte_cnt=None)#
Calculate the minimum number of bytes needed to store an integer value.
The method determines the byte count required for integer storage with optional alignment to standard sizes and validation against a specified byte count.
- Parameters:
value (
int) – Input integer value to analyze.align_to_2n (
bool) – If True, align result to standard sizes (1,2,4,8,12,16,20…).byte_cnt (
Optional[int]) – Optional fixed byte count to validate against and return.
- Raises:
SPSDKValueError – The integer input value doesn’t fit into byte_cnt.
- Return type:
int- Returns:
Number of bytes needed to store the integer.
- spsdk.utils.misc.get_hash(text)#
Get hash of given text.
Computes SHA256 hash of the input text and returns first 8 characters of the hexadecimal digest.
- Parameters:
text (
Union[str,bytes]) – Input text to be hashed, either as string or bytes.- Return type:
str- Returns:
First 8 characters of SHA256 hash in hexadecimal format.
- spsdk.utils.misc.get_key_by_val(value, dictionary)#
Return key by its value from dictionary.
The method performs case-insensitive search through dictionary values to find the corresponding key.
- Parameters:
value (
str) – Value to find in dictionary values.dictionary (
dict[str,list[str]]) – Dictionary with string keys and list of strings as values.
- Raises:
SPSDKValueError – Value is not present in dictionary.
- Return type:
str- Returns:
Key name corresponding to the found value.
- spsdk.utils.misc.get_printable_path(path)#
Get printable path for file display purposes.
Converts file path to a format suitable for display, with special handling for Jupyter notebook environments. When JUPYTER_SPSDK environment variable is set to “1”, returns relative path from current working directory using POSIX format. Otherwise returns the original path unchanged.
- Parameters:
path (
str) – Absolute or relative file path to convert.- Return type:
str- Returns:
Display-friendly file path string.
- spsdk.utils.misc.load_binary(path, search_paths=None)#
Load binary file into bytes.
The method loads a binary file from the specified path or searches for it in the provided search paths if the direct path doesn’t exist.
- Parameters:
path (
str) – Path to the binary file to load.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 YAML or JSON file.
The method attempts to parse the file content as JSON first, then falls back to YAML parsing if JSON parsing fails. It uses SecretsLoader for YAML parsing to handle sensitive data securely.
- Parameters:
path (
str) – Path to configuration file (relative or absolute).search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.
- Raises:
SPSDKError – When file cannot be loaded, parsed, or contains invalid format.
- Return type:
dict- Returns:
Content of configuration as dictionary.
- spsdk.utils.misc.load_file(path, mode='r', search_paths=None)#
Load file content from specified path.
The method searches for the file in provided search paths and loads its content either as text or binary data based on the specified mode.
- Parameters:
path (
str) – Path to the file to be loaded.mode (
str) – File reading mode, ‘r’ for text or ‘rb’ for binary.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.
- Return type:
Union[str,bytes]- Returns:
File content as string (text mode) or bytes (binary mode).
- spsdk.utils.misc.load_hex_string(source, expected_size, search_paths=None, name='key')#
Load hexadecimal data from various sources.
The method supports loading from file paths, direct hexadecimal strings, bytes, or integers. If no source is provided, a random value of the expected size is generated. The method handles both text files containing hex strings and binary files.
- Parameters:
source (
Union[str,int,bytes,None]) – File path, hexadecimal string, bytes, or integer. Random value if None.expected_size (
int) – Expected size of the data in bytes.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.name (
Optional[str]) – Name for the key/data to load, defaults to “key”.
- Raises:
SPSDKError – Invalid input data or size mismatch.
- Return type:
bytes- Returns:
Data in bytes with the expected size.
- spsdk.utils.misc.load_secret(value, search_paths=None)#
Load secret text from the configuration value.
The method supports multiple input formats for flexible secret loading: 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.
- Parameters:
value (
str) – Input string to be used for loading the secret.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.
- Return type:
str- Returns:
The actual secret value.
- spsdk.utils.misc.load_text(path, search_paths=None)#
Load text file content into string.
The method loads a text file and returns its content as a string. It supports searching for the file in multiple directories if search paths are provided.
- Parameters:
path (
str) – Path to the text file to load.search_paths (
Optional[list[str]]) – List of directories 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)#
Convert version string into a numerical representation.
Each version component is weighted by powers of 1000 to create a comparable integer. This allows for easy version comparison and sorting operations.
- Examples:
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 with numbers separated by separator.separator (
str) – Character used to separate version components.valid_numbers (
int) – Maximum number of version components to process.
- Return type:
int- Returns:
Integer representation of the version string.
- spsdk.utils.misc.reverse_bits(x, bits_cnt=32)#
Reverse bits in integer.
- Parameters:
x (
int) – Integer to be bit reversed.bits_cnt (
int) – Count of bits to reverse, defaults to 32.
- Return type:
int- Returns:
Integer with reversed bit order.
- spsdk.utils.misc.reverse_bytes_in_longs(arr)#
Reverse byte order in 32-bit words from input bytes array.
The function processes the input bytes array in 4-byte chunks (32-bit words) and reverses the byte order within each word. The input array length must be divisible by 4.
- Parameters:
arr (
bytes) – Input bytes array to process, must be divisible by 4.- Raises:
SPSDKError – Input array length is not divisible by 4.
- Return type:
bytes- Returns:
New bytes array with reversed byte order in each 32-bit word.
- spsdk.utils.misc.sanitize_version(version, separator='.', valid_numbers=3)#
Sanitize version string to ensure consistent format.
The method normalizes version strings by padding with ‘.0’ when there are fewer parts than required, or truncating when there are more parts than needed.
- Examples:
1.2 -> 1.2.0 1.2.3.4 -> 1.2.3
- Parameters:
version (
str) – Original version string to be sanitized.separator (
str) – Separator used in the version string, defaults to “.”.valid_numbers (
int) – Number of version parts to maintain, defaults to 3.
- Return type:
str- Returns:
Sanitized version string with the specified number of parts.
- spsdk.utils.misc.secret_constructor(loader, node)#
Custom YAML constructor to load secrets from the secrets file.
- Parameters:
loader (
SafeLoader) – YAML loader instance.node (
ScalarNode) – YAML node representing the secret key.
- Return type:
Any- Returns:
Secret value corresponding to the key.
- Raises:
ValueError – If the secret key is not found.
- spsdk.utils.misc.size_fmt(num, use_kibibyte=True)#
Format byte size into human-readable string representation.
Converts a numeric byte value into a formatted string with appropriate unit suffix (B, kB/KiB, MB/MiB, etc.) for better readability.
- Parameters:
num (
Union[float,int]) – The byte size value to format.use_kibibyte (
bool) – If True, use binary prefixes (1024-based) with ‘iB’ suffix, if False, use decimal prefixes (1000-based) with ‘B’ suffix.
- Return type:
str- Returns:
Formatted size string with value and unit (e.g., “1.5 MiB”, “1024 B”).
- spsdk.utils.misc.split_data(data, size)#
Split data into chunks of specified size.
- Parameters:
data (
Union[bytearray,bytes]) – Array of bytes to be split into chunks.size (
int) – Size of each chunk in bytes.
- Return type:
Generator[bytes,None,None]- Returns:
Generator yielding byte chunks of the specified size.
- spsdk.utils.misc.swap16(x)#
Swap bytes in half word (16-bit).
Takes a 16-bit integer value and swaps its high and low bytes, converting between little-endian and big-endian byte order.
- Parameters:
x (
int) – 16-bit integer value to swap (0x0000 to 0xFFFF).- Return type:
int- Returns:
Integer with swapped bytes.
- Raises:
SPSDKError – When input value is outside valid 16-bit range.
- spsdk.utils.misc.swap32(x)#
Swap 32-bit integer byte order.
Converts a 32-bit integer from big-endian to little-endian byte order or vice versa.
- Parameters:
x (
int) – Integer value to be byte-swapped (0 to 0xFFFFFFFF).- Return type:
int- Returns:
Integer with swapped byte order.
- Raises:
SPSDKError – When the input value is outside the valid 32-bit range.
- spsdk.utils.misc.swap_bytes(data)#
Swap individual bytes in pairs.
Swaps adjacent bytes in the input data. For example, b’abcd’ becomes b’badc’. If the input has an odd number of bytes, the last byte remains unchanged.
- Parameters:
data (
bytes) – Input bytes to swap.- Return type:
bytes- Returns:
Bytes with adjacent pairs swapped.
- spsdk.utils.misc.swap_endianness(data, word_size=4)#
Convert between little-endian and big-endian byte order for data consisting of fixed-size words.
The method swaps the endianness of input data by treating it as a sequence of words of the specified size. Supports 16-bit, 32-bit, and 64-bit word sizes.
- Parameters:
data (
bytes) – Input data bytes to swap endianness.word_size (
int) – Size of each word in bytes (default: 4 for 32-bit words).
- Return type:
bytes- Returns:
Data with swapped endianness.
- Raises:
SPSDKError – If word_size is not supported or data length is not a multiple of word_size.
- spsdk.utils.misc.use_working_directory(path)#
Execute the block in given directory.
Changes current directory to the specified path, executes the block, and restores the original directory afterwards.
- Parameters:
path (
str) – The path where the current directory will be changed to.- Return type:
Iterator[None]- Returns:
Iterator for context manager usage.
- spsdk.utils.misc.value_to_bool(value)#
Convert various input formats to boolean value.
The function accepts boolean, integer, string, or None values and converts them to boolean. For strings, it recognizes “True”, “true”, “T”, and “1” as True, all other strings as False. For other types, uses Python’s built-in bool() conversion.
- Parameters:
value (
Union[bool,int,str,None]) – Input value to convert (bool, int, str, or None).- Return type:
bool- Returns:
Boolean representation of the input value.
- Raises:
SPSDKError – Unsupported input type.
- spsdk.utils.misc.value_to_bytes(value, align_to_2n=True, byte_cnt=None, endianness=Endianness.BIG)#
Convert value from multiple formats to bytes representation.
The function accepts various input types (bytes, bytearray, int, str) and converts them to a standardized bytes format with configurable alignment and endianness.
- Parameters:
value (
Union[bytes,bytearray,int,str]) – Input value to be converted to bytes.align_to_2n (
bool) – When True, aligns the output length to powers of 2 (1,2,4,8,16…).byte_cnt (
Optional[int]) – Specific number of bytes for the result, overrides alignment.endianness (
Endianness) – Byte order for the result (‘big’ or ‘little’ endian).
- Return type:
bytes- Returns:
Value converted to bytes format.
- spsdk.utils.misc.value_to_int(value, default=None)#
Convert value from multiple formats to integer.
Supports conversion from integers, bytes, bytearrays, and string representations (including binary, octal, decimal, and hexadecimal formats with optional prefixes).
- Parameters:
value (
Union[bytes,bytearray,int,str]) – Input value to convert (int, bytes, bytearray, or str).default (
Optional[int]) – Default value returned when conversion fails.
- Return type:
int- Returns:
Converted integer value.
- Raises:
SPSDKError – Unsupported input type or invalid conversion without default.
- spsdk.utils.misc.wrap_text(text, max_line=100)#
Wrap text according to SPSDK formatting standards.
Processes input text by preserving existing line breaks and applying text wrapping to each line individually to ensure consistent formatting across the SPSDK project.
- Parameters:
text (
str) – Input text to be wrapped.max_line (
int) – Maximum line length for wrapped output, defaults to 100.
- Return type:
str- Returns:
Formatted text with appropriate line breaks inserted.
- spsdk.utils.misc.write_file(data, path, mode='w', encoding='utf-8', overwrite=True)#
Write data to a file with automatic directory creation and overwrite protection.
The method automatically creates parent directories if they don’t exist and supports both text and binary modes. When overwrite is disabled, it generates a unique filename by appending a counter to avoid conflicts.
- Parameters:
data (
Union[str,bytes]) – Data to write to the file.path (
str) – Path to the target file.mode (
str) – File writing mode (‘w’ for text, ‘wb’ for binary), defaults to ‘w’.encoding (
str) – Text encoding (‘ascii’, ‘utf-8’), defaults to ‘utf-8’.overwrite (
bool) – Whether to overwrite existing files, defaults to True.
- Return type:
int- Returns:
Number of characters or bytes written to the file.
Binary Image utils#
SPSDK binary image utilities and visualization tools.
This module provides functionality for handling binary images, including color picking utilities and binary image processing capabilities for SPSDK applications.
- 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 representation and manipulation utility.
This class provides functionality for creating, managing, and manipulating binary images with support for hierarchical sub-images, alignment, patterns, and memory layout operations. It serves as a foundation for building complex binary structures used in embedded systems and firmware development.
- Variables:
MINIMAL_DRAW_WIDTH – Minimum width for image visualization output.
Initialize a new BinaryImage instance.
Creates a binary image object that can contain binary data, patterns, or sub-images. The image can be part of a hierarchical structure with parent-child relationships.
- Parameters:
name (
str) – Name identifier for the image.size (
int) – Size of the image in bytes, will be aligned according to alignment parameter.offset (
int) – Byte offset position within the parent image.description (
Optional[str]) – Human-readable description of the image purpose.binary (
Optional[bytes]) – Raw binary data content for the image.pattern (
Optional[BinaryPattern]) – Binary pattern to fill the image with.alignment (
int) – Byte alignment requirement for the image size.parent (
Optional[BinaryImage]) – Parent BinaryImage object in the hierarchy.execution_start_address (
Optional[int]) – Memory address where execution should start.
- MINIMAL_DRAW_WIDTH = 30#
- property absolute_address: int#
Get image absolute address relative to base parent.
Calculates the absolute address by traversing up the parent hierarchy and accumulating offsets from the base parent.
- Returns:
Absolute address relative to base parent.
- add_image(image)#
Add new sub image to the binary image container.
The method inserts the sub-image at the correct position based on its offset, maintaining the sorted order of sub-images within the container. The added image’s parent reference is automatically set to this container.
- Parameters:
image (
BinaryImage) – Binary image object to be added as a sub-image.- Return type:
None
- aligned_length(alignment=4)#
Calculate aligned length for memory erasing operations.
The method computes the total length needed when considering alignment requirements for both start and end addresses, typically used for flash memory operations.
- Parameters:
alignment (
int) – Memory alignment boundary in bytes, defaults to 4- Return type:
int- Returns:
Total aligned length in bytes from aligned start to aligned end
- aligned_start(alignment=4)#
Calculate aligned start address based on specified alignment.
The method performs floor division to align the absolute address to the nearest lower boundary that is divisible by the alignment value.
- Parameters:
alignment (
int) – The alignment value in bytes, defaults to 4.- Return type:
int- Returns:
Floor-aligned absolute address.
- append_image(image)#
Append new sub image at the end of the parent.
This function uses the size of the parent as an offset for the new appended image.
- Parameters:
image (
BinaryImage) – Binary image object to append.- Return type:
None
- static detect_file_format(path)#
Detect the format of a binary file.
- Parameters:
path (
str) – Path to the file to detect.- Return type:
str- Returns:
Format_type in string and is one of ‘SPARSE’, ‘ELF’, ‘SREC’, ‘HEX’, or ‘BIN’.
- Raises:
SPSDKError – If file cannot be read.
- draw(include_sub_images=True, width=0, color='', no_color=False, use_unicode=True)#
Draw the image into ASCII/Unicode graphics representation.
Creates a visual representation of the binary image with address information, size details, description, and optionally includes sub-images in a structured box-drawing format.
- Parameters:
include_sub_images (
bool) – Include also sub images into output, defaults to Truewidth (
int) – Fixed width of table, 0 means autosizecolor (
str) – Color of this block, empty string means automatic colorno_color (
bool) – Disable adding colors into outputuse_unicode (
bool) – Use Unicode box drawing characters instead of ASCII, defaults to True
- Raises:
SPSDKValueError – In case of invalid width or text longer than specified width
- Return type:
str- Returns:
ASCII/Unicode art representation of binary image
- export()#
Export the binary image as a byte array.
The method handles various scenarios including direct binary export, empty images, pattern-filled images, and recursive export of sub-images. Sub-images are merged into the parent image at their specified offsets with proper alignment.
- Raises:
SPSDKValueError – When sub-image cannot be merged into parent image due to size or offset conflicts.
- Return type:
bytes- Returns:
Byte array representation of the complete binary image with all sub-images merged and proper alignment applied.
- export_sparse(calculate_crc=False)#
Create sparse image from BinaryImage object.
This method efficiently converts a BinaryImage by analyzing its structure. If the image has sub-images, it processes them individually to create optimized chunks. RAW sub-images with binary data become RAW chunks, sub-images with non-zero patterns become FILL chunks, and gaps between sub-images or zero-pattern sub-images become DONT_CARE chunks.
- Parameters:
calculate_crc (
bool) – If True, calculate and add CRC32 checksum to the sparse image.- Return type:
SparseImage- Returns:
SparseImage object representing the binary image in sparse format.
- find_sub_image(name)#
Find sub image by its name.
- Parameters:
name (
str) – Name of sub image to search for.- Raises:
SPSDKValueError – The sub image with requested name doesn’t exist.
- Return type:
- Returns:
Sub Image object with the specified name.
- static get_config_template()#
Generate configuration template for binary image.
The method creates a template configuration that can be used to define binary merge operations with proper validation schemas.
- Return type:
str- Returns:
Template string to create binary merge configuration.
- 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.
The method calculates the minimum character width needed to properly display the binary image table, considering the image name, size information, and optionally any sub-images with their borders.
- Parameters:
include_sub_images (
bool) – Include sub-images in width calculation, 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:
List of validation schema dictionaries for binary image configuration.
- property image_name: str#
Get image name including all parent names.
The method constructs a hierarchical path by concatenating parent image names with the current image name using ‘=>’ as separator.
- Returns:
Full hierarchical image name with parent chain.
- info(no_color=False)#
Get comprehensive information about the binary image.
Provides detailed information including image structure, size, addresses, sub-images count, and visual representation.
- Parameters:
no_color (
bool) – Disable color output in the visual representation.- Return type:
str- Returns:
Formatted string with complete image information and visual diagram.
- iter_blocks(block_size=4096)#
Iterate over the binary image data in blocks without loading entire image into memory.
This method generates the binary image data block by block, allowing for memory-efficient processing of large images. Each block is constructed on-the-fly by determining which sub-images or patterns contribute to that specific block range.
- Usage example:
- for block in binary_image.iter_blocks(block_size=8192):
process(block)
- Parameters:
block_size (
int) – Size of each block in bytes, defaults to 4096.- Raises:
SPSDKValueError – When block_size is less than or equal to 0.
- Return type:
Generator[bytes,None,None]- Returns:
Generator yielding bytes objects of up to block_size length.
- join_images()#
Join all sub images into main binary block.
This method exports all sub-images into a single binary representation, clears the sub-images collection, and updates the main binary data with the consolidated result.
- Return type:
None
- static load_binary_image(path, name=None, size=0, offset=None, description=None, pattern=None, search_paths=None, alignment=1, parent_image=None)#
Load binary data file into BinaryImage object.
Supported formats are ELF, HEX, SREC, SPARSE and plain binary. The method automatically detects the file format and loads it accordingly. If format detection fails, it can fallback to binary loading if enabled.
- Parameters:
path (
str) – Path to the binary file to load.name (
Optional[str]) – Name of the image, defaults to file name if not provided.size (
int) – Expected image size in bytes, defaults to 0 for auto-detection.offset (
Optional[int]) – Additional image offset in parent image, defaults to None.description (
Optional[str]) – Text description of the image, defaults to auto-generated.pattern (
Optional[BinaryPattern]) – Optional binary pattern to apply to the image.search_paths (
Optional[list[str]]) – List of paths where to search for the file.alignment (
int) – Alignment requirement for the result image in bytes.parent_image (
Optional[BinaryImage]) – Optional parent image reference for offset computation.
- Raises:
SPSDKError – The binary file cannot be loaded or accessed.
- Return type:
- Returns:
Binary data represented as BinaryImage object.
- classmethod load_from_config(config)#
Create Binary Image object from configuration data.
The method processes configuration options to initialize a Binary Image with specified name, size, pattern, and alignment. It also handles optional regions containing binary files or binary blocks that are added as sub-images.
- Parameters:
config (
Config) – Configuration object containing binary image description with optional regions for binary files and blocks.- Return type:
Self- Returns:
Initialized Binary Image object with all configured sub-images.
- static load_sparse(sparse, name='Sparse Image')#
Convert sparse image to BinaryImage object.
This method efficiently converts the sparse image by creating sub-images for each chunk without reconstructing the full binary data in memory. Consecutive RAW chunks are merged into single sub-images, consecutive FILL chunks with the same pattern are merged, and DONT_CARE chunks are represented as gaps (filled by parent’s zero pattern).
- Parameters:
sparse (
SparseImage) – SparseImage object to convert.name (
str) – Name for the resulting BinaryImage.
- Raises:
SPSDKError – If conversion fails or no header/chunks available.
- Return type:
- Returns:
BinaryImage object containing the sparse image structure.
- property min_offset: int#
Get the offset of the first subimage in the binary image.
Calculates the minimum offset among all sub images. If no sub images exist, returns 0 as the default offset.
- Returns:
Minimum offset value from all sub images, or 0 if no sub images exist.
- post_export(output_path)#
Perform post export steps like saving the script files.
The method iterates through all sub-images and calls their post_export methods if available, collecting all generated files from the export process.
- Parameters:
output_path (
str) – Path to the output directory where files will be saved.- Return type:
list[str]- Returns:
List of paths to all generated files during the post-export process.
- save_binary_image(path, file_format='BIN')#
Save binary data file.
The method supports multiple output formats including binary, Intel HEX, and Motorola S-record formats. For non-binary formats, it handles empty binaries and uses execution start address if available.
- Parameters:
path (
str) – Path to the output file.file_format (
str) – Format of saved file (‘BIN’, ‘HEX’, ‘S19’, ‘SREC’), defaults to ‘BIN’.
- Raises:
SPSDKValueError – The file format is invalid.
- Return type:
None
- property size: int#
Get the size of the binary image.
- Returns:
Size of the binary image in bytes.
- update_offsets()#
Update offsets from the sub images into main offset value begin offsets.
This method normalizes the offset values by adjusting all sub-image offsets relative to the minimum offset found among them, and updates the main image offset accordingly. The minimum offset among sub-images becomes the new base (0), and the main offset is increased by this minimum value.
- Return type:
None
- validate()#
Validate binary image structure and detect overlaps.
Performs comprehensive validation of the binary image including: - Checks that image offset is non-negative - Verifies that image size is non-negative - Recursively validates all sub-images - Ensures sub-images fit within parent image boundaries - Detects overlapping sub-images at the same level
- Raises:
SPSDKValueError – When image offset or size is negative.
SPSDKOverlapError – When sub-image exceeds parent boundaries or overlaps with sibling.
- Return type:
None
- class spsdk.utils.binary_image.ColorPicker#
Bases:
objectColor picker utility for cycling through predefined terminal colors.
This class provides a simple mechanism to sequentially select different colors from a predefined list, useful for colorizing terminal output with distinct colors for different elements.
- Variables:
COLORS – List of available colorama foreground colors for selection.
Initialize ColorPicker with default settings.
Sets the color index to the total number of available colors in the COLORS collection.
- 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 next color from the color list.
The method cycles through available colors and skips any unwanted color if specified. When reaching the end of the color list, it wraps around to the beginning.
- Parameters:
unwanted_color (
Optional[str]) – Color that should be omitted from selection.- Return type:
str- Returns:
Selected color string.
Interfaces utils#
SPSDK device communication interfaces.
This module provides a unified interface layer for communicating with various NXP devices across different connection types including USB, UART, SPI, and network protocols.
Serial Proxy#
SPSDK Serial communication proxy utilities.
This module provides proxy classes that serve as replacements for the standard serial.Serial class, enabling enhanced serial communication handling with additional functionality for SPSDK applications.
- class spsdk.utils.serial_proxy.SerialProxy(port, timeout, baudrate, write_timeout=None)#
Bases:
objectSerial communication proxy for testing and simulation.
This class provides a mock implementation of serial.Serial that can be used for testing serial communication without actual hardware. It uses pre-recorded request-response pairs to simulate device communication patterns.
- Variables:
responses – Dictionary mapping write data to corresponding read responses.
ignore_ack – Flag to control ACK packet handling in internal buffer.
Initialize serial proxy with connection parameters.
The initialization signature accommodates instantiation compatible with serial.Serial interface while providing proxy functionality for testing and simulation purposes.
- Parameters:
port (
str) – Serial port name or identifier.timeout (
int) – Read timeout value in seconds (stored but not actively used).baudrate (
int) – Serial communication speed in bits per second (stored but not used).write_timeout (
Optional[int]) – Write timeout value in seconds (stored but not actively used).
- close()#
Simulates closing a serial port.
This method sets the is_open flag to False to indicate that the serial port connection has been closed. No actual hardware communication occurs.
- Return type:
None
- flush()#
Simulates flushing input buffer.
This method provides a mock implementation of buffer flushing functionality for testing or simulation purposes. No actual buffer operations are performed.
- Return type:
None
-
ignore_ack:
bool= False#
- classmethod init_proxy(data, ignore_ack=False)#
Initialize response dictionary of write and read bytes.
Configures the SerialProxy class with predefined responses for write operations and sets ACK packet handling behavior.
- Parameters:
data (
dict[bytes,bytes]) – Dictionary mapping write bytes to corresponding read response bytes.ignore_ack (
bool) – Don’t modify internal buffer upon receiving an ACK packet.
- Return type:
Type[SerialProxy]- Returns:
SerialProxy class with configured response data.
- open()#
Simulates opening a serial port.
This method sets the internal state to indicate that the serial port connection is open and ready for communication.
- Return type:
None
- read(length)#
Read portion of pre-configured data from buffer.
The method extracts the requested amount of data from the internal buffer and removes the read data from the buffer.
- Parameters:
length (
int) – Amount of data to read from buffer in bytes.- Return type:
bytes- Returns:
Data segment read from buffer.
- reset_input_buffer()#
Simulates resetting input buffer.
This method clears the input buffer to simulate the behavior of a real serial port’s input buffer reset operation.
- Return type:
None
- reset_output_buffer()#
Simulates resetting output buffer.
This method clears the output buffer to simulate the behavior of a real serial port’s output buffer reset operation.
- Return type:
None
-
responses:
dict[bytes,bytes] = {}#
- write(data)#
Simulate a write operation by retrieving response from predefined responses.
The method simulates writing data to a serial interface by using the input data as a key to look up a corresponding response from the responses dictionary. If ignore_ack is enabled and the data is an ACK byte sequence, the operation is ignored.
- Parameters:
data (
bytes) – Bytes to write, used as key to lookup response in responses dict- Raises:
KeyError – If data key is not found in responses dictionary
- Return type:
None
- class spsdk.utils.serial_proxy.SimpleReadSerialProxy(port, timeout, baudrate, write_timeout=None)#
Bases:
SerialProxySerial proxy for simplified read-only communication simulation.
This class provides a streamlined approach to simulating serial device communication where only read operations need to be mocked. It maintains a static buffer of data that can be read sequentially, making it ideal for testing scenarios where write operations are ignored and only predetermined read responses are required.
- Variables:
FULL_BUFFER – Static buffer containing all data to be read sequentially.
Initialize serial proxy with specified communication parameters.
This constructor sets up the serial proxy by calling the parent serial.Serial constructor and initializes the internal buffer to its full capacity.
- Parameters:
port (
str) – Serial port name or device path.timeout (
int) – Read timeout value in seconds (unused in proxy mode).baudrate (
int) – Serial communication baud rate (unused in proxy mode).write_timeout (
Optional[int]) – Write timeout value in seconds (unused in proxy mode).
- FULL_BUFFER = b''#
- classmethod init_data_proxy(data)#
Initialize data proxy with response buffer.
This class method sets up the serial proxy with a predefined data buffer that will be used for simulating serial communication responses.
- Parameters:
data (
bytes) – Byte data to be used as the response buffer for read operations.- Return type:
Type[SimpleReadSerialProxy]- Returns:
SerialProxy class configured with the provided data buffer.
- write(data)#
Write data to the serial proxy.
This method simulates a write operation but performs no actual data transmission. It serves as a placeholder for testing and simulation purposes.
- Parameters:
data (
bytes) – The byte data to be written to the serial interface.- Return type:
None
USB Filter#
SPSDK USB device filtering utilities.
This module provides functionality for filtering and identifying USB devices, with specialized support for NXP USB devices. It includes classes for creating device filters based on various USB properties and NXP-specific device identification.
- class spsdk.utils.usbfilter.NXPUSBDeviceFilter(usb_id=None, nxp_device_names=None)#
Bases:
USBDeviceFilterNXP USB Device Filter for SPSDK operations.
Extension of the generic USB device filter class to support filtering based on NXP devices. Modifies the way single number filtering is handled - when a single value is provided, it checks if the VID is within NXP’s vendor ID range, maintaining compatibility with legacy tooling that expected PID-based filtering.
- Variables:
NXP_VIDS – List of official NXP vendor IDs for device identification.
Initialize the USB Device Filtering.
- Parameters:
usb_id (
Optional[str]) – USB device identifier string for filtering specific device.nxp_device_names (
Optional[dict[str,list[UsbId]]]) – Dictionary mapping NXP device names to their USB identifiers, format: {“device_name”: [UsbId objects]}.
- NXP_VIDS = [8137, 5538, 1137, 3368]#
- compare(usb_device_object)#
Compare USB device with internal USB ID and NXP device registry.
Extends the comparison by USB names - dictionary of device name and corresponding VID/PID. Falls back to checking if device is any NXP device when no specific USB ID is configured.
- Parameters:
usb_device_object (
Any) – USB HID device object containing vendor_id and product_id- Return type:
bool- Returns:
True if device matches internal USB ID or is recognized NXP device, False otherwise
- class spsdk.utils.usbfilter.USBDeviceFilter(usb_id=None, search_by_pid=False)#
Bases:
objectUSB device filtering utility for cross-platform device identification.
This class provides filtering capabilities for USB HID devices across different operating systems. It parses various USB identifier formats including VID/PID pairs, platform-specific device paths, and instance IDs to enable precise device matching during enumeration.
Supported USB ID formats:
VID or PID - Vendor ID or product ID as hex or decimal number: - Hex: “0x1234”, “0XAB12”, “0x1” (1-4 chars after 0x, case insensitive) - Decimal: “4660”, “65535” (1-5 digits, no leading zeros except “0”) - Single number defaults to VID unless search_by_pid=True
VID/PID pairs - Two numbers separated by ‘:’ or ‘,’: - “0x1fc9:0x0025”, “1234,5678” - Both numbers must use same format (hex or decimal)
Platform-specific formats:
Windows - Instance ID from Device Manager: - “HIDVID_<HEX>&PID_<HEX><instance_id>”
Linux - Bus and device numbers from lsusb: - “<bus>#<device>” format (e.g., “3#11”) - Bus:Device numbers are decimal, interface not required
macOS - IOService device path or partial path: - Full: “IOService:/AppleACPIPlatformExpert/PCI0@0/…” - Partial: “SE Blank RT Family @14200000” (device name + location ID)
The filter supports both vendor ID and product ID based filtering, with configurable search modes for single number inputs.
Initialize the USB Device Filtering.
- Parameters:
usb_id (
Optional[str]) – USB identifier string (VID or PID depending on search_by_pid flag).search_by_pid (
bool) – If True, usb_id is treated as PID number, otherwise as VID.
- compare(usb_device_object)#
Compare 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. The method performs matching against various device attributes including vendor ID, product ID, serial number, device name, and USB path.
- Parameters:
usb_device_object (
dict[str,Any]) – Libusbsio/HID_API device object dictionary containing device information such as vendor_id, product_id, serial_number, device_name, and path- Return type:
bool- Returns:
True if device matches the filter criteria, False otherwise
- static convert_usb_path(hid_api_usb_path)#
Convert USB device path from HID API format to OS-observable format.
Converts Libusbsio/HID_API USB device paths into platform-specific string formats that can be observed from the operating system. The conversion handles Windows, Linux, and macOS platforms differently based on their respective USB path conventions. Note: This function is designed specifically for Libusbsio/HID_API paths and may fail or provide incorrect results if used with paths from other USB APIs.
- Parameters:
hid_api_usb_path (
bytes) – Raw USB device path bytes from Libusbsio/HID_API- Return type:
str- Returns:
Platform-specific USB device path string, empty string for unsupported OS
Registers descriptions#
SPSDK register configuration and management utilities.
This module provides comprehensive functionality for handling register descriptions, configurations, and operations within the SPSDK framework. It includes support for register bit fields, access control, enumeration handling, and configuration processing with validation capabilities.
- class spsdk.utils.registers.Access(tag, label, description=None)#
Bases:
SpsdkEnumRegister access mode enumeration for SPSDK operations.
Defines access permissions for register and bitfield operations including read-only, write-only, read-write, and special access modes. Provides utility methods to check readability and writability of access modes.
- 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.
The method accepts labels with forward slashes (like R/W, R/O) by removing the slash characters before searching for the enum member.
- Parameters:
label (
str) – Label to be used for searching the enum member.- Return type:
Self- Returns:
Found enum member matching the processed label.
- property is_readable: bool#
Check if the access mode allows read operations.
- Returns:
True if the object has read access (RO or RW), False otherwise.
- property is_writable: bool#
Check if the access mode allows write operations.
- Returns:
True if the access mode is write-only, read-write, or write-constant, False otherwise.
- class spsdk.utils.registers.ConfigProcessor(description='')#
Bases:
objectSPSDK Configuration Processor base class.
This class provides a foundation for processing configuration data with support for value transformation, parameter parsing, and configuration string handling. It serves as a base class for implementing specific configuration processors that can pre-process and post-process values during configuration operations.
- Variables:
NAME – Processor identifier name used for registration and identification.
Initialize the processor.
- Parameters:
description (
str) – Description of the processor, defaults to empty string.
- NAME = 'NOP'#
- classmethod from_spec(spec)#
Create config processor from JSON data entry.
Factory method that creates appropriate ConfigProcessor subclass instance based on the method name extracted from the specification string.
- Parameters:
spec (
Optional[str]) – JSON specification string containing processor configuration, None if not specified.- Return type:
Optional[ConfigProcessor]- Returns:
ConfigProcessor instance of appropriate subclass, or None if spec is None or no matching processor found.
- classmethod from_str(config_string)#
Create config processor instance from configuration string.
- Parameters:
config_string (
str) – Configuration string to process.- Return type:
- Returns:
New ConfigProcessor instance.
- classmethod get_description(config_string)#
Extract description from configuration string.
Parses a configuration string to extract the description part that follows the DESC= prefix after a semicolon separator.
- Parameters:
config_string (
str) – Configuration string containing description after semicolon.- Return type:
str- Returns:
Extracted description with DESC= prefix removed.
- classmethod get_method_name(config_string)#
Get config processor method name from configuration string.
Extracts the method name portion from a configuration string by splitting on the first colon separator.
- Parameters:
config_string (
str) – Configuration string containing method name and parameters.- Return type:
str- Returns:
Method name extracted from the configuration string.
- classmethod get_params(config_string)#
Parse configuration string to extract processor method parameters.
Extracts parameters from a configuration string in the format ‘method:param1=value1,param2=value2’. The method name and parameters are separated by colon, individual parameters are separated by commas, and each parameter follows the ‘name=value’ format.
- Parameters:
config_string (
str) – Configuration string containing method and parameters- Raises:
SPSDKRegsError – Invalid parameter format in configuration string
- Return type:
dict[str,int]- Returns:
Dictionary with parameter names as keys and integer values
- post_process(value)#
Post-process value going to config file.
- Parameters:
value (
int) – The integer value to be post-processed.- Return type:
int- Returns:
The post-processed integer value.
- pre_process(value)#
Pre-process value coming from config file.
- Parameters:
value (
int) – Integer value from configuration file to be processed.- Return type:
int- Returns:
Processed integer value.
- width_update(value)#
Update bit-width of value going to config file.
- Parameters:
value (
int) – The input value to be processed.- Return type:
int- Returns:
The processed value with updated bit-width.
- class spsdk.utils.registers.Register(name, offset, width, uid, description=None, default_value=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, reserved=False, no_yaml_comments=False, deprecated_names=None)#
Bases:
objectSPSDK Register representation for hardware register management.
This class represents a hardware register with configurable properties including bit width, access permissions, endianness, and sub-register management. It provides functionality for register value manipulation, bitfield operations, and configuration export/import capabilities.
Initialize RegsRegister instance with register configuration.
Creates a new register object with specified properties including name, offset, width, and various configuration options for register behavior and display.
- 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.default_value (
Optional[int]) – Default value 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.reserved (
bool) – The register will be hidden from standard searches.no_yaml_comments (
bool) – Disable yaml comments for this register.deprecated_names (
Optional[list[str]]) – List of deprecated names for this register.
- Raises:
SPSDKValueError – Register width is not a multiple of 8 bits.
- add_bitfield(bitfield)#
Add register bitfield to the register.
- Parameters:
bitfield (
RegsBitField) – New bitfield value for register.- Return type:
None
- classmethod create_from_spec(spec, reg_mods=None)#
Create register instance from specification dictionary.
This class method creates a new register instance by parsing the provided specification dictionary and applying optional modifications. It handles register properties, bitfield creation, and default value initialization.
- Parameters:
spec (
dict[str,Any]) – Dictionary containing register specification with keys like ‘id’, ‘name’, ‘offset_int’, ‘reg_width’, ‘description’, ‘access’, etc.reg_mods (
Optional[dict[str,Any]]) – Optional dictionary with register-level modifications that override specification values.
- Return type:
Self- Returns:
New register instance configured according to the specification.
- create_spec()#
Creates the register specification structure.
The method generates a dictionary containing all register information including ID, offset, width, name, description, default value, and bitfields. Gaps between bitfields are automatically filled to maintain proper structure.
- Return type:
dict[str,Any]- Returns:
Dictionary containing the complete register specification with all metadata and bitfield definitions.
- find_bitfield(name)#
Find bitfield by name in the register.
The method searches for a bitfield using its name, UID, or deprecated names. Case-insensitive matching is performed. A warning is logged when deprecated names are used.
- Parameters:
name (
str) – The name of the bitfield (case insensitive).- Return type:
- Returns:
Instance of the bitfield.
- Raises:
SPSDKRegsErrorBitfieldNotFound – The bitfield doesn’t exist.
- find_config_key(cfg)#
Find which register name (current or deprecated) is in the config and return its key.
The method searches for the register name in the configuration dictionary using multiple strategies: exact match, case-insensitive match for current name, and then the same approaches for deprecated names.
- Parameters:
cfg (
Config) – Configuration dictionary to search in.- Return type:
Optional[str]- Returns:
Configuration key if found, None otherwise.
- get_alt_width(value)#
Get alternative width of register based on input value.
Determines the appropriate register width by analyzing the input value’s byte requirements and selecting the smallest suitable width from available alternatives.
- Parameters:
value (
int) – Input integer value used to determine the required register width.- Return type:
int- Returns:
Register width in bits, either the default width or smallest suitable alternative.
- get_bitfield(uid)#
Get bitfield instance by its unique identifier.
The method performs case-insensitive search through all bitfields in the register to find the one matching the provided UID.
- Parameters:
uid (
str) – The unique identifier of the bitfield to retrieve.- Return type:
- Returns:
Instance of the bitfield matching the provided UID.
- Raises:
SPSDKRegsErrorBitfieldNotFound – The bitfield with given UID doesn’t exist.
- get_bitfield_names(exclude=None)#
Get list of bitfield names.
- Parameters:
exclude (
Optional[list[str]]) – List of bitfield names to exclude from the result, defaults to None.- Return type:
list[str]- Returns:
List of bitfield names.
- get_bitfields(exclude=None)#
Get register bitfields with optional exclusion filtering.
Method allows excluding specific bitfields by their names using prefix matching. Non-reserved bitfields are included by default.
- Parameters:
exclude (
Optional[list[str]]) – List of bitfield name prefixes to exclude from results.- Return type:
list[RegsBitField]- Returns:
List of non-reserved register bitfields, filtered by exclusion criteria.
- get_bytes_value(raw=False)#
Get the bytes value of register.
Converts the register value to bytes representation using the register’s endianness and appropriate byte count based on the value’s bit width.
- Parameters:
raw (
bool) – Do not use any modification hooks when getting the value.- Return type:
bytes- Returns:
Register value converted to 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()#
Get reset value of the register.
- Return type:
int- Returns:
Reset value of register.
- get_value(raw=False)#
Get the value of register.
Retrieves the register value, handling sub-registers if present and applying endianness conversion when needed.
- Parameters:
raw (
bool) – Do not use any modification hooks, defaults to False.- Return type:
int- Returns:
The register value as integer.
- has_group_registers()#
Check 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 to its default reset value.
- Parameters:
raw (
bool) – Do not use any modification hooks, defaults to False.- Return type:
None
- set_value(val, raw=False)#
Set the new value of register.
The method validates the input value fits within the register width and handles endianness conversion if reverse mode is enabled. For group registers, it also updates all sub-registers with appropriate bit portions of the value.
- Parameters:
val (
Any) – The new value to set (integer or convertible to integer).raw (
bool) – Do not use any modification hooks if True.
- Raises:
SPSDKError – When invalid value is loaded into register or value exceeds register width.
- 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 Registers container for hardware register management.
This class provides a specialized container for managing Register objects, extending the base registers functionality with specific register handling capabilities for NXP MCU register operations.
- Variables:
register_class – The Register class used for creating register instances.
Initialize Registers class for managing device register specifications.
Loads register specifications from the device database, including grouped registers, modifications, and deprecated register names. Handles both standard library data and restricted data sources.
- Parameters:
family (
FamilyRevision) – Family revision object specifying the target device family.feature (
str) – Feature name to identify the register set.base_key (
Union[list[str],str,None]) – Base item key or key path as list like [‘grp1’, ‘grp2’, ‘key’].base_endianness (
Endianness) – The base endianness of registers in binary form.just_standard_library_data (
bool) – If True, uses only embedded library data, otherwise includes restricted data.do_not_raise_exception (
bool) – Enable debug mode to suppress exceptions during database load errors.
- Raises:
SPSDKError – When database loading fails and do_not_raise_exception is False.
- class spsdk.utils.registers.RegistersPreValidationHook(register_keys=None)#
Bases:
PreValidationHookPre-validation hook for register configuration processing.
This class handles the preprocessing of register configurations before validation, specifically converting register and bitfield keys to uppercase format to ensure consistency across different configuration formats and legacy compatibility.
Initialize the hook with specific register keys to process.
- Parameters:
register_keys (
Optional[list[str]]) – List of keys in the config that contain register configurations. If None, processes the entire config.
- process_registers(config)#
Process register keys in a dictionary, converting them to uppercase.
The method processes both top-level register keys and nested bitfield keys within register configurations. It handles both old format with ‘bitfields’ key and direct bitfield format. Registers with ‘value’ key are skipped from bitfield processing.
- Parameters:
config (
dict) – Dictionary containing register configurations to be processed in-place- Return type:
None
- class spsdk.utils.registers.RegsBitField(parent, name, offset, width, uid, description=None, access=Access(tag=2, label='RW', description='Read/Write'), reserved=False, config_processor=None, no_yaml_comments=False, deprecated_names=None)#
Bases:
objectRegister bitfield representation and management.
This class represents a single bitfield within a register, providing functionality to manage bitfield properties such as offset, width, access permissions, and enumerated values. It handles bitfield configuration, validation, and value operations within the SPSDK register framework.
Initialize RegsBitField instance.
Constructor for RegsBitField class used to store and manage bitfield information within a register structure.
- Parameters:
parent (
Register) – Parent register containing this bitfield.name (
str) – Name identifier of the bitfield.offset (
int) – Bit offset position within the register.width (
int) – Width of the bitfield in bits.uid (
str) – Unique identifier for the bitfield.description (
Optional[str]) – Optional text description of the bitfield functionality.access (
Access) – Access permissions for the bitfield (read/write/etc).reserved (
bool) – Flag to hide bitfield from standard searches if True.config_processor (
Optional[ConfigProcessor]) – Optional processor for configuration handling.no_yaml_comments (
bool) – Flag to disable YAML comments generation if True.deprecated_names (
Optional[list[str]]) – Optional list of deprecated names for this bitfield.
- add_enum(enum)#
Add bitfield enum.
- Parameters:
enum (
RegsEnum) – New enumeration value for bitfield.- Return type:
None
- classmethod create_from_spec(spec, offset, parent, bitfield_mods=None)#
Create register bitfield from specification dictionary.
The method parses the specification dictionary to extract bitfield properties and creates a new RegsBitField instance with optional modifications applied.
- Parameters:
spec (
dict[str,Any]) – Dictionary containing bitfield specification data including width, name, description.offset (
int) – Bit offset position within the parent register.parent (
Register) – Parent Register object that contains this bitfield.bitfield_mods (
Optional[dict[str,Any]]) – Optional dictionary with modifications to override spec values.
- Return type:
- Returns:
New RegsBitField instance created from the specification.
- create_spec()#
Creates the register specification structure.
The method builds a dictionary containing all register bitfield properties including offset, width, access type, description, and optional enumeration values.
- Return type:
dict[str,Any]- Returns:
Dictionary with register bitfield specification containing id, offset, width, access type, description and optional values/deprecated_names.
- find_config_key(cfg)#
Find which bitfield name (current or deprecated) is in the config and return its key.
The method searches for the bitfield name in the configuration dictionary using multiple strategies: exact match, case-insensitive match, and deprecated names matching.
- Parameters:
cfg (
Config) – Configuration dictionary to search in.- Return type:
Optional[str]- Returns:
Configuration key found in the dictionary, or None if not found.
- get_enum_constant(enum_name)#
Get constant representation of enum by its name or value.
The method searches through available enums to find a match by name (case-insensitive) or integer value. It also supports deprecated enum names with warning logging.
- Parameters:
enum_name (
Union[str,int]) – Name of the enum (string) or its integer value to search for.- Raises:
SPSDKRegsErrorEnumNotFound – The enum has not been found.
- Return type:
int- Returns:
Integer constant value of the found enum.
- get_enum_names()#
Get list of enumeration names.
- Return type:
list[str]- Returns:
List of enum names as strings.
- get_enum_value()#
Get enum value of the bitfield.
Retrieves the enumerated value corresponding to the current bitfield value. If the current value matches an enumeration entry, returns the enum name, otherwise returns the hexadecimal representation of the value.
- Return type:
Union[str,int]- Returns:
Enum name if value matches enumeration, otherwise hex value.
- get_enums()#
Get bitfield enums.
- Return type:
list[RegsEnum]- Returns:
List of bitfield enumeration values.
- get_hex_value()#
Get the value of register in string hex format.
The method formats the register value as a hexadecimal string with proper width based on the register’s configuration width and ‘0x’ prefix.
- Return type:
str- Returns:
Hexadecimal value of register as formatted string.
- get_reset_value()#
Get reset value of the bitfield.
Extracts and returns the reset value for this specific bitfield from the parent register’s reset value. The method applies bit shifting, masking, and post-processing to isolate the bitfield’s portion of the register.
- Return type:
int- Returns:
Reset value of the bitfield as an integer.
- get_value()#
Get integer value of the bitfield.
Extracts and returns the current value of this bitfield from its parent register. The method retrieves the parent register value, applies bit shifting and masking to extract the relevant bits, and processes the result through the configuration processor.
- Return type:
int- Returns:
Current integer value of the bitfield after post-processing.
- has_enums()#
Check if the bitfield has enumeration values defined.
- Return type:
bool- Returns:
True if enums are defined, False otherwise.
- set_enum_value(new_val, raw=False)#
Update bitfield value using enum value or integer.
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 (string enum name or integer value).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.
The method modifies the bitfield value within its parent register by applying proper masking and bit shifting operations. The value can be preprocessed and automatically modified unless explicitly disabled.
- Parameters:
new_val (
Any) – New value to set for the 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 bitfield range.
- Return type:
None
- class spsdk.utils.registers.RegsEnum(name, value, description, max_width=0, deprecated_names=None)#
Bases:
objectRegister enumeration value container for SPSDK register operations.
This class represents a single enumeration value within a register bitfield, storing the name, numeric value, description, and formatting information. It provides functionality to create enumerations from specifications and convert between different value representations.
Initialize RegsEnum with enumeration information for bitfield.
Used to store enumeration data including name, value, description and formatting options.
- 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.deprecated_names (
Optional[list[str]]) – Optional list of deprecated names for this enum.
- Raises:
SPSDKRegsError – Invalid input value.
- classmethod create_from_spec(spec, maxwidth=0)#
Create Enum instance from specification dictionary.
The method parses enumeration specification data and creates a new Enum instance with validated name, value, description, and optional deprecated names.
- Parameters:
spec (
dict[str,Any]) – Input specification dictionary containing enumeration data including ‘name’, ‘value’, ‘description’, and optionally ‘deprecated_names’.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 or invalid enum value.
- create_spec()#
Creates the enumeration specification.
The method builds a dictionary containing the enumeration’s name, value, description, and optionally deprecated names if they exist.
- Return type:
dict[str,Union[str,int]]- Returns:
The specification dictionary containing enum properties.
- get_value_int()#
Get integer value of the enum.
- Return type:
int- Returns:
Integer value of the enum.
- get_value_str()#
Get formatted string representation of the register value.
The method formats the current register value using the maximum width specification to ensure consistent string representation.
- Return type:
str- Returns:
Formatted string with the register value.
- class spsdk.utils.registers.ShiftRightConfigProcessor(count, description='')#
Bases:
ConfigProcessorSPSDK Configuration Processor for right-shift bit operations.
This processor handles bit-shifting operations on register values, shifting bits to the right during pre-processing and to the left during post-processing. It automatically adjusts bit width calculations to accommodate the shift operations.
- Variables:
NAME – Processor identifier string for configuration parsing.
Initialize the right-shift config processor.
- Parameters:
count (
int) – Count of bits for shift operation.description (
str) – Extra description for config processor, defaults to empty string.
- NAME = 'SHIFT_RIGHT'#
- classmethod from_str(config_string)#
Create config processor instance from configuration string.
Parses the configuration string to extract method name, parameters, and description, then creates a new ShiftRightConfigProcessor instance with the specified count value.
- Parameters:
config_string (
str) – Configuration string containing method name, parameters and description.- Raises:
SPSDKRegsError – Invalid method name or missing COUNT parameter.
- Return type:
- Returns:
New ShiftRightConfigProcessor instance configured with parsed parameters.
- post_process(value)#
Post-process value going to config file.
Shifts the input value left by the count of bits specified in the register configuration.
- Parameters:
value (
int) – The integer value to be post-processed.- Return type:
int- Returns:
The value shifted left by self.count bits.
- pre_process(value)#
Pre-process value coming from config file.
Performs a right bit shift operation on the input value by the count of bits specified in the register field configuration.
- Parameters:
value (
int) – The integer value to be pre-processed from config file.- Return type:
int- Returns:
The pre-processed value after right bit shift operation.
- width_update(value)#
Update bit-width of value going to config file.
- Parameters:
value (
int) – The input value to be updated.- Return type:
int- Returns:
Updated value with count added to it.
USB Device Scanner#
SPSDK NXP device discovery and scanning utilities.
This module provides functionality for discovering and scanning various NXP devices across different communication interfaces including USB, UART, SDIO, and LibUSBSIO. It offers device enumeration, filtering, and identification capabilities for NXP MCU development and provisioning workflows.
- spsdk.utils.nxpdevscan.filter_uart_devices(ports, real_devices)#
Filter UART devices based on platform-specific criteria.
The method filters serial ports to identify actual UART devices. On macOS, it filters for USB serial devices. On Linux with real_devices enabled, it uses ioctl to verify real TTY devices.
- Parameters:
ports (
list[ListPortInfo]) – List of serial port information objects from pyserial.real_devices (
bool) – Enable scanning for real devices using ioctl TIOCGSERIAL on Linux.
- Return type:
list[ListPortInfo]- Returns:
Filtered list of UART device port information.
- spsdk.utils.nxpdevscan.is_real_tty_device(device)#
Check if a /dev/ttyS* device is a real serial device using ioctl.
Linux-only function that uses TIOCGSERIAL ioctl to determine if a device is a real serial port. Non-real serial devices return PORT_UNKNOWN (0) from the ioctl call. Non-ttyS devices are considered real by default.
- Parameters:
device (
str) – The device path to check.- Raises:
SPSDKUnsupportedOperation – When called on non-Linux systems.
- Return type:
bool- Returns:
True if the device is a real serial device, False otherwise.
- spsdk.utils.nxpdevscan.search_libusbsio_devices()#
Search for all available LIBUSBSIO devices in the system.
Scans the system for LIBUSBSIO devices and creates device descriptions for each found device. The method initializes the LIBUSBSIO library and iterates through all available ports to gather device information.
- Return type:
list[SIODeviceDescription]- Returns:
List of SIODeviceDescription objects representing found LIBUSBSIO devices.
- Raises:
SPSDKError – When LIBUSBSIO library fails or device information cannot be retrieved.
- spsdk.utils.nxpdevscan.search_nxp_sdio_devices()#
Search for all available NXP SDIO devices.
Scans predefined device paths to discover NXP SDIO devices and creates device descriptions for each found device containing vendor ID, product ID, and device path information.
- Return type:
list[SDIODeviceDescription]- Returns:
List of SDIODeviceDescription objects representing discovered NXP SDIO devices.
- spsdk.utils.nxpdevscan.search_nxp_uart_devices(scan=True, all_devices=True, scan_uboot=True, timeout=50, real_devices=False)#
Search for NXP UART devices connected to the system.
This method scans available UART ports and identifies NXP devices by attempting to communicate using mboot, SDP, and U-Boot protocols. It can filter devices based on vendor ID and perform real device validation.
- Parameters:
scan (
bool) – Whether to scan for mboot and SDP devices, defaults to True.all_devices (
bool) – Whether to return all devices or only NXP devices, defaults to True.scan_uboot (
bool) – Whether to scan for U-Boot console devices, defaults to True.timeout (
int) – Timeout for UART scan in milliseconds, defaults to 50.real_devices (
bool) – Check if the device is real using ioctl TIOCGSERIAL, defaults to False.
- Return type:
list[UartDeviceDescription]- Returns:
List of UartDeviceDescription objects representing discovered devices.
- spsdk.utils.nxpdevscan.search_nxp_usb_devices(extend_vid_list=None)#
Search all NXP USB devices based on their Vendor ID.
The method enumerates all USB devices and filters them by NXP vendor IDs to identify NXP devices connected to the system.
- Parameters:
extend_vid_list (
Optional[list]) – Additional vendor IDs to extend the default NXP VID list.- Return type:
list[USBDeviceDescription]- Returns:
List of USBDeviceDescription objects corresponding to found NXP devices.
- spsdk.utils.nxpdevscan.search_uuu_usb_devices()#
Search for all UUU compatible USB devices.
The method uses SPSDK UUU library to enumerate and identify all connected USB devices that are compatible with the UUU (Universal Update Utility) protocol.
- Return type:
list[UUUDeviceDescription]- Returns:
List of UUUDeviceDescription objects representing found UUU devices.
Device description#
SPSDK device description classes for various communication interfaces.
This module provides abstract and concrete device description classes for different communication protocols used with NXP devices, including UART, USB, UUU, SDIO, and SIO interfaces.
- class spsdk.utils.devicedescription.DeviceDescription#
Bases:
ABCAbstract base class for device description containers.
This class provides a generic interface for representing information about devices of any type without providing device control capabilities. It serves as a foundation for creating concrete device description implementations that can store and present device metadata, identifiers, and properties. Subclasses must implement the abstract methods to provide device-specific string representations and information formatting.
- class spsdk.utils.devicedescription.SDIODeviceDescription(vid, pid, path)#
Bases:
DeviceDescriptionSDIO device description container.
This class provides a standardized representation of SDIO device information including vendor ID, product ID, and device path. It serves as a consistent interface across different SDIO API implementations, ensuring compatibility and reliability in device identification and management within SPSDK operations.
Initialize USB device descriptor.
Creates a new USB device descriptor with vendor ID, product ID, and device path.
- Parameters:
vid (
int) – Vendor ID of the USB device.pid (
int) – Product ID of the USB device.path (
str) – USB device path string.
- class spsdk.utils.devicedescription.SIODeviceDescription(info)#
Bases:
DeviceDescriptionLIBUSBSIO device description container.
This class provides a structured representation of LIBUSBSIO device information, including device identifiers, connection details, and hardware specifications. It serves as a standardized interface for accessing and displaying LIBUSBSIO device properties within the SPSDK framework.
Initialize USB device description from LIBUSBSIO device information.
Creates a device description object that extracts and stores relevant device information including vendor/product IDs, strings, path, and interface details.
- Parameters:
info (
HIDAPI_DEVICE_INFO_T) – LIBUSBSIO device information structure containing USB device details.
- class spsdk.utils.devicedescription.USBDeviceDescription(vid, pid, path, product_string, manufacturer_string, name, serial, original_path=None)#
Bases:
DeviceDescriptionUSB device description container for SPSDK operations.
This container provides a standardized representation of USB device information that remains consistent across different USB API implementations. It abstracts USB device details into a portable format suitable for device identification and management within SPSDK workflows.
Initialize USB device description.
Creates a new device description instance with USB device information including vendor/product IDs, device strings, and path information.
- Parameters:
vid (
int) – Vendor ID of the USB device.pid (
int) – Product ID of the USB device.path (
str) – Device path string for communication.product_string (
str) – Product name string from USB descriptor.manufacturer_string (
str) – Manufacturer name string from USB descriptor.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 the device.original_path (
Union[str,bytes,None]) – Original device path before conversion, used for hashing.
- class spsdk.utils.devicedescription.UUUDeviceDescription(path, chip, pro, vid, pid, bcd, serial_no)#
Bases:
objectUUU device description container.
This class provides a stable container for UUU device information that remains consistent across different UUU API implementations. It encapsulates USB device properties including identification, product details, and connection path for reliable device management in SPSDK operations.
Initialize USB device description with device properties.
- 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:
DeviceDescriptionUART device description container for SPSDK operations.
This container holds UART device information and provides a consistent interface across different UART API implementations, ensuring stable device representation regardless of the underlying UART library used.
Initialize device description with port name and device type.
The ‘dev_type’ can be in general any string identifying the device type.
- Parameters:
name (
Optional[str]) – COM port name, defaults to “Unknown port” if not provided.dev_type (
Optional[str]) – Device type identifier such as ‘mboot device’ or ‘SDP device’, defaults to “Unknown device type” if not provided.
- spsdk.utils.devicedescription.get_usb_device_name(vid, pid, device_names=None)#
Get USB device name based on VID/PID.
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 to search for.pid (
int) – Product ID to search for.device_names (
Optional[dict[str,list[UsbId]]]) – Dictionary mapping device names to USB ID lists, defaults to None.
- Return type:
list[str]- Returns:
List of device names matching the VID/PID combination.
Module for schema-based configuration validation#
SPSDK schema-based configuration validation utilities.
This module provides comprehensive functionality for validating configuration data against JSON schemas, merging configurations with different strategies, and handling commented YAML configurations within the SPSDK framework.
- class spsdk.utils.schema_validator.CommentedConfig(main_title, schemas, note=None)#
Bases:
objectSPSDK Configuration Template Generator.
This class generates commented YAML configuration templates and custom configurations with proper formatting, indentation, and documentation comments for SPSDK operations.
- Variables:
MAX_LINE_LENGTH – Maximum line length for generated comments and formatting.
Initialize configuration template generator.
Creates a new instance for generating configuration templates from JSON schemas. The generator processes multiple schemas to create comprehensive configuration documentation with proper formatting and structure.
- Parameters:
main_title (
str) – Main title of the generated configuration template.schemas (
list[dict[str,Any]]) – List of JSON schema dictionaries to process for template generation.note (
Optional[str]) – Optional additional note to display after the title section.
- MAX_LINE_LENGTH = 118#
- static convert_cm_to_yaml(config)#
Convert Commented Map into final YAML string.
The method converts a configuration in Commented Map format to a properly formatted YAML string with appropriate indentation and width settings for file storage.
- Parameters:
config (
CommentedMap) – Configuration in Commented Map format.- Raises:
SPSDKError – If configuration is empty.
- Return type:
str- Returns:
YAML string with configuration ready for file storage.
- export(config=None)#
Export configuration template into CommentedMap.
This method processes the schema configuration by merging multiple schemas, organizing properties into logical blocks, and generating a formatted configuration template with proper comments and structure.
- Parameters:
config (
Optional[dict[str,Any]]) – Optional configuration dictionary to be applied to template.- Raises:
SPSDKError – Template generation failed due to processing errors.
- Return type:
CommentedMap- Returns:
Configuration template as CommentedMap with proper formatting.
- get_config(config)#
Export Configuration directly into YAML string format.
- Parameters:
config (
dict[str,Any]) – Configuration dictionary to be exported.- Return type:
str- Returns:
YAML string representation of the configuration.
- static get_property_optional_required(key, block)#
Determine if a configuration property is required, optional, or conditionally required.
The method analyzes JSON schema blocks to classify property requirements by checking direct required arrays, nested conditional structures, and schema keywords like allOf, anyOf, oneOf, if/then/else constructs.
- Parameters:
key (
str) – Name of the configuration property to check.block (
dict[str,Any]) – JSON schema block containing property definitions and requirements.
- Return type:
- Returns:
PropertyRequired enum indicating if property is REQUIRED, OPTIONAL, or CONDITIONALLY_REQUIRED.
- get_template()#
Export configuration template directly into YAML string format.
The method converts the exported configuration model into a YAML formatted string that can be used as a template for configuration files.
- Return type:
str- Returns:
Configuration template as YAML formatted string.
- property max_line: int#
Get maximum line length adjusted for current indentation level.
Calculates the maximum allowed line length by subtracting the current indentation space from the base maximum line length constant.
- Returns:
Maximum line length accounting for current indent level.
- class spsdk.utils.schema_validator.PropertyRequired(tag, label, description=None)#
Bases:
SpsdkEnumProperty requirement level enumeration for schema validation.
This enumeration defines the different requirement levels that can be applied to properties in SPSDK schema validation, indicating whether a property must be present, conditionally 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:
ListStrategiesSPSDK List Strategies for configuration merging.
This class extends the base ListStrategies to provide custom list merging strategies for SPSDK configuration processing. It implements specialized handling for combining lists during configuration merges, including set-based deduplication with fallback mechanisms for unhashable objects.
- static strategy_set(_config, _path, base, nxt)#
Merge two lists using set strategy to create a unique sorted output.
This strategy combines two lists by creating a set union to remove duplicates, then sorts the result. Falls back to concatenation if items are unhashable, or override strategy if concatenation fails.
- Parameters:
base (
list) – Base list to merge from.nxt (
list) – Next list to merge with base.
- Returns:
Merged list with unique elements, sorted if possible.
- 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:
MergerSPSDK Configuration Merger with enhanced list strategies.
This class extends the base Merger functionality to provide additional merge strategies specifically for SPSDK configuration processing, including a new ‘set’ strategy for list merging operations.
- Variables:
PROVIDED_TYPE_STRATEGIES – Mapping of data types to their available merge strategies.
Initialize SPSDK Merger with configurable merge strategies.
The merger provides flexible data merging capabilities with customizable strategies for different data types and conflict resolution.
- Parameters:
type_strategies (
list) – List of tuples defining merge strategies for specific types, each tuple contains (type, [strategy_list]).fallback_strategies (
list) – List of fallback strategies to use when no type-specific strategy is defined.type_conflict_strategies (
list) – List of strategies for resolving type conflicts during merge operations.
- 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.
The method validates configuration data against multiple JSON schemas that are merged together. It supports custom formatters for file/directory validation and can optionally check for unknown properties in the configuration.
- Parameters:
config (
dict[str,Any]) – Configuration dictionary to validate.schemas (
list[dict[str,Any]]) – List of JSON schema dictionaries for validation.extra_formatters (
Optional[dict[str,Callable[[str],bool]]]) – Additional custom format validators for schema validation.search_paths (
Optional[list[str]]) – List of directory paths to search for files during validation.check_unknown_props (
bool) – Whether to check and warn about unknown properties in config.
- Raises:
SPSDKError – Invalid validation schema or configuration validation failed.
- Return type:
None
- spsdk.utils.schema_validator.check_unknown_properties(config_dict, schema_dict, path='')#
Recursively check for unknown properties in configuration against schema.
This method validates that all properties in the configuration dictionary are defined in the corresponding schema. It handles nested objects, arrays, and pattern properties. When unknown properties are found, it either raises an exception (in strict mode) or logs a warning.
- Parameters:
config_dict (
dict) – Configuration dictionary to validateschema_dict (
dict) – JSON schema dictionary defining allowed propertiespath (
str) – Current path in the configuration for error reporting
- Raises:
SPSDKError – When unknown property is found and strict mode is enabled
- Return type:
None
- spsdk.utils.schema_validator.cmap_update(cmap, updater)#
Update CMap including comments.
This method updates the original CMap with data from the updater CMap, ensuring that both the main data and comment annotations are properly merged.
- Parameters:
cmap (
CommentedMap) – Original CMap to be updated.updater (
CommentedMap) – CMap updater containing new data and comments to merge.
- Return type:
None
Utils Exceptions#
SPSDK utilities exception classes and error handling.
This module defines specialized exception classes for SPSDK utilities, extending the base SPSDKError for specific error scenarios in registers, bitfields, enums, and timeout operations.
- exception spsdk.utils.exceptions.SPSDKRegsError(desc=None)#
Bases:
SPSDKErrorSPSDK Registers Error Exception.
This exception class represents errors that occur during SPSDK register operations including register parsing, validation, and manipulation tasks.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorBitfieldNotFound(desc=None)#
Bases:
SPSDKRegsErrorSPSDK registers exception for missing bitfield operations.
This exception is raised when attempting to access or manipulate a bitfield that does not exist in the register definition or configuration.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorEnumNotFound(desc=None)#
Bases:
SPSDKRegsErrorSPSDK registers exception for missing enumeration definitions.
This exception is raised when attempting to access or reference an enumeration that cannot be found in the registers configuration or definition files.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterGroupMishmash(desc=None)#
Bases:
SPSDKRegsErrorSPSDK Register Group Mishmash Exception.
This exception is raised when there are inconsistencies or conflicts within register group configurations, such as overlapping registers, invalid group definitions, or mismatched register properties within the same group.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterNotFound(desc=None)#
Bases:
SPSDKRegsErrorSPSDK register lookup exception for missing registers.
This exception is raised when attempting to access or manipulate a register that cannot be found in the current register database or configuration.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.utils.exceptions.SPSDKTimeoutError(desc=None)#
Bases:
SPSDKError,TimeoutErrorSPSDK timeout exception for operations that exceed time limits.
This exception is raised when SPSDK operations fail to complete within the specified timeout period, combining standard timeout behavior with SPSDK-specific error handling.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
Database#
SPSDK database management and device information utilities.
This module provides comprehensive functionality for managing SPSDK databases containing device-specific information, features, revisions, and configurations. It handles database loading, caching, validation, and provides unified access to device data across the NXP MCU portfolio.
- class spsdk.utils.database.Bootloader(protocol, interfaces, usb_ids, protocol_params)#
Bases:
objectSPSDK Bootloader representation.
This class encapsulates bootloader configuration including protocol type, supported interfaces, USB identification, and protocol-specific parameters. It provides functionality for loading bootloader configurations from dictionaries and managing bootloader connection details across NXP MCU devices.
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_ids (
UsbIdArray) – USB identifiers 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 with keys like ‘protocol’, ‘interfaces’, ‘usb’, and ‘protocol_params’.- Return type:
Self- Returns:
New Bootloader instance configured with the provided parameters.
- update(config)#
Update the Bootloader instance from a configuration dictionary.
This method updates the bootloader’s protocol, interfaces, protocol parameters, and USB ID configuration based on the provided configuration dictionary.
- Parameters:
config (
dict) – Dictionary containing updated bootloader configuration with optional keys: ‘protocol’, ‘interfaces’, ‘protocol_params’, and ‘usb’.- Return type:
None
- class spsdk.utils.database.Database(path, restricted_data_path=None, addons_data_path=None, complete_load=False)#
Bases:
objectSPSDK database manager for device configuration and data files.
This class provides centralized access to device databases, configuration files, and related data across the NXP MCU portfolio. It handles database caching, loading device-specific configurations, and managing restricted or addon data paths for efficient SPSDK operations.
Initialize database configuration.
Creates a new database instance with base, restricted, and addon data sources. Optionally loads all device configurations immediately instead of using lazy loading.
- Parameters:
path (
str) – Path to the base database directory.restricted_data_path (
Optional[str]) – Path to the restricted data database directory.addons_data_path (
Optional[str]) – Path to the addons data database directory.complete_load (
bool) – Load all database content immediately without caching.
- class DatabaseData(path, restricted_data_path=None, addons_data_path=None, complete_load=False)#
Bases:
objectSPSDK Database Data Manager.
This class manages database configuration data with intelligent caching capabilities to improve performance across SPSDK operations. It handles loading, validation, and caching of database configurations from multiple data sources including main database path, restricted data, and addon configurations.
Initialize Database data object with configuration paths and caching options.
The constructor sets up the database with primary data path and optional restricted and addon data paths. It handles cache loading/validation and loads default configurations from YAML files.
- Parameters:
path (
str) – Primary path to database data folder.restricted_data_path (
Optional[str]) – Optional path to restricted data folder.addons_data_path (
Optional[str]) – Optional path to addons data folder.complete_load (
bool) – If True, forces complete database reload bypassing cache.
- Raises:
SPSDKError – Invalid cache file type or cache loading failure.
- static get_cache_filename(path)#
Get database cache filename based on path and version.
The method generates a unique cache filename using the provided path, SPSDK version, and a SHA1 hash for uniqueness. The cache file is stored in the SPSDK cache directory.
- Parameters:
path (
str) – Path to generate cache filename for.- Return type:
str- Returns:
Full path to the database cache file.
- static hash_db_data(cached_configs, path, restricted_data_path=None, addons_data_path=None)#
Generate SHA1 hash of database configuration files and paths.
The method creates a hash based on file modification times, sizes, and paths to detect changes in database configuration data including cached configs, database path, restricted data, addons data, and default configuration.
- Parameters:
cached_configs (
list[str]) – List of configuration file paths to be hashed.path (
str) – Base path to the database directory.restricted_data_path (
Optional[str]) – Optional path to restricted data directory.addons_data_path (
Optional[str]) – Optional path to addons data directory.
- Return type:
bytes- Returns:
SHA1 hash bytes of all input data and file metadata.
- make_cache()#
Create cache file of database data.
The method creates a pickled cache file to improve performance by storing processed database configurations. It handles concurrent access using file locks and merges data from parallel processes when needed. The cache is only created if the database hash has changed.
- Raises:
Exception – Any exception during cache file creation or access.
- Return type:
None
- property devices: Devices#
Get the list of devices stored in the database.
- Returns:
Collection of devices available in the 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.
- 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 folder.exc_enabled (
bool) – Exception enabled in case of non existing file, defaults to True.just_standard_lib (
bool) – Use just standard library files (no restricted data, neither addons), defaults to False.
- Raises:
SPSDKValueError – Non existing file path.
- Return type:
str- Returns:
Final absolute path to data file.
- get_defaults(feature)#
Get feature defaults from the database.
The method retrieves default configuration values for a specified feature from the database’s defaults section and returns a deep copy to prevent accidental modifications.
- Parameters:
feature (
str) – Name of the feature to get defaults for.- Raises:
SPSDKValueError – Invalid or non-existing feature name.
- Return type:
dict[str,Any]- Returns:
Dictionary containing the feature’s default configuration values.
- get_device_features(family, revision='latest')#
Get device features database for specified family and revision.
Retrieves the feature configuration data for a specific device family and revision from the internal database. If revision is not specified, returns the latest available.
- Parameters:
family (
str) – The device family name to look up.revision (
str) – The device revision name, defaults to “latest”.
- Raises:
SPSDKValueError – Unsupported family or revision.
- Return type:
- Returns:
The feature configuration data for the specified device.
- get_schema_file(feature)#
Get JSON Schema file for the requested feature.
The method loads and returns the JSON Schema configuration file for a specific feature from the database’s jsonschemas directory.
- Parameters:
feature (
str) – Name of the feature to get the schema for.- Raises:
SPSDKError – If the schema file cannot be found or loaded.
- Return type:
dict[str,Any]- Returns:
Loaded dictionary containing the JSON Schema configuration.
- load_db_cfg_file(filename)#
Load database configuration file with caching support.
Loads JSON or YAML configuration files and caches them using singleton behavior to avoid repeated file operations for the same file path.
- Parameters:
filename (
str) – Path to the configuration file to load.- Raises:
SPSDKError – Invalid or corrupted configuration file.
- Return type:
dict[str,Any]- Returns:
Loaded configuration data as dictionary.
- class spsdk.utils.database.DatabaseManager#
Bases:
objectSPSDK database manager implementing singleton pattern for unified data access.
This class provides centralized access to SPSDK database resources including device configurations, register definitions, and restricted data. It manages database initialization, caching, and ensures single instance access across the application lifecycle.
- Variables:
FUSES – Database category for fuse-related data.
BLHOST – Database category for bootloader host data.
COMM_BUFFER – Database category for communication buffer data.
CERT_BLOCK – Database category for certificate block data.
DAT – Database category for debug authentication data.
MBI – Database category for master boot image data.
HAB – Database category for high assurance boot data.
Create singleton instance of SPSDK Database manager.
This method implements the singleton pattern to ensure only one instance of the DatabaseManager exists. It also configures logging based on the SPSDK_DEBUG_DB environment variable.
- Returns:
DatabaseManager singleton instance.
- 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'#
- HSE = 'hse'#
- IEE = 'iee'#
- LPCPROG = 'lpcprog'#
- MBI = 'mbi'#
- MEMCFG = 'memcfg'#
- NXPUUU = 'nxpuuu'#
- OTFAD = 'otfad'#
- PFR = 'pfr'#
- SB21 = 'sb21'#
- SB31 = 'sb31'#
- SB40 = 'sb40'#
- SBC = 'sbc'#
- SBX = 'sbx'#
- SHADOW_REGS = 'shadow_regs'#
- SHE_SCEC = 'she_scec'#
- SIGNED_MSG = 'signed_msg'#
- SIGNING = 'signing'#
- TLV_BLOB = 'tlv_blob'#
- TP = 'tp'#
- TZ = 'tz'#
- WPC = 'wpc'#
- XMCD = 'xmcd'#
- static clear_cache()#
Clear SPSDK cache directory.
Removes the entire SPSDK cache directory and all its contents. If the cache directory does not exist, logs an error message. If removal fails due to permission or other OS-related issues, logs an error with details.
- Raises:
PermissionError – When insufficient permissions to remove cache directory.
OSError – When OS-level error occurs during directory removal.
- Return type:
None
- property db: Database#
Get Database instance.
Retrieves and validates the database instance from the internal storage.
- Raises:
AssertionError – If the retrieved object is not a Database instance.
- Returns:
The Database instance.
- classmethod get_db(complete_load=False)#
Get database instance with lazy initialization.
Creates and initializes the database on first access using SPSDK data folders and restricted data configuration.
- Parameters:
complete_load (
bool) – If True, the database will be completely loaded during initialization, otherwise loaded on demand.- Return type:
- Returns:
Database instance.
- static get_quick_info_hash(paths)#
Calculate hash for quick database validation.
This method generates a SHA1 hash based on modification times and sizes of database files to quickly detect changes in the database structure without full content comparison. The hash includes common defaults and all device-specific database files.
- Parameters:
paths (
list[Optional[str]]) – List of paths to database folders, None values are ignored.- Return type:
bytes- Returns:
SHA1 hash of database files as bytes.
- static get_restricted_data()#
Get restricted data folder path, if applicable.
Validates the restricted data folder by checking metadata version compatibility with current SPSDK version and verifying the data folder exists.
- Return type:
Optional[str]- Returns:
Path to restricted data folder if valid and compatible, None otherwise.
- property quick_info: QuickDatabase#
Get quick info Database instance.
- Returns:
Quick database instance containing essential device information.
- class spsdk.utils.database.Device(name, db, latest_rev, info, device_alias=None, revisions=[])#
Bases:
objectSPSDK Device representation for hardware configuration management.
This class represents a single device in the SPSDK database, managing device-specific information including revisions, features, and configuration data. It provides functionality for device identification, feature retrieval, and configuration file path resolution across different device revisions.
Initialize SPSDK Device instance.
Creates a new Device object with specified configuration including name, database reference, revision information, and optional device alias.
- Parameters:
name (
str) – Device name that will be converted to lowercase.db (
Database) – Parent Database object containing this device.latest_rev (
str) – Name of the latest available revision.info (
DeviceInfo) – Device information object containing device details.device_alias (
Optional[Device]) – Optional alias device reference, defaults to None.revisions (
Revisions) – Device revisions collection, defaults to empty Revisions().
- create_file_path(file_name, just_standard_lib=False)#
Create file path for the specified device.
The method searches for the file in the device-specific directory within the database. If the file is not found and a device alias exists, it attempts to find the file using the alias device path as fallback.
- Parameters:
file_name (
str) – File name to be enriched by device path.just_standard_lib (
bool) – Use just standard library files (no restricted data, neither addons), defaults to False.
- Raises:
SPSDKValueError – Non existing file in database.
- Return type:
str- Returns:
File path value for the device.
- get_copy(new_name=None)#
Create a deep copy of the Device instance.
This method creates a complete copy of the device including all its revisions, features, and metadata. The copy is independent of the original instance.
- Parameters:
new_name (
Optional[str]) – Optional new name for the copied device, defaults to original name.- Return type:
- Returns:
Deep copy of the Device instance with optionally updated name.
- get_features(revision=None)#
Get the list of device features.
- Parameters:
revision (
Optional[str]) – Device revision to get features for. If None, uses default revision.- Return type:
list[str]- Returns:
List of feature names available for the specified device revision.
- static load(name, db)#
Load device configuration from database folder.
Loads device configuration from the database folder structure, including base configuration and any addon data. Handles device aliases and builds complete device object with all revisions and features.
- Parameters:
name (
str) – The name of device to load (case insensitive).db (
Database) – Base database object containing device data.
- Raises:
SPSDKErrorMissingDevice – Device doesn’t exist in database.
SPSDKError – Latest revision not found in supported revisions.
- Return type:
- Returns:
The Device object with loaded configuration and revisions.
- class spsdk.utils.database.DeviceInfo(use_in_doc, purpose, spsdk_predecessor_name, web, memory_map, isp)#
Bases:
objectDevice information container for NXP MCU devices.
This class encapsulates comprehensive device information including purpose, memory mapping, ISP configuration, and web resources. It provides functionality to load device configurations from dictionaries and supports dynamic updates of device parameters.
Initialize device information class.
- Parameters:
use_in_doc (
bool) – Flag indicating if device should be used in documentation.purpose (
str) – String description of purpose of MCU (device group).spsdk_predecessor_name (
Optional[str]) – Device sub series name (predecessor name in SPSDK).web (
str) – Web page with device information.memory_map (
dict[str,dict[str,Any]]) – Basic memory map of device.isp (
IspCfg) – Information regarding ISP mode.
- classmethod load(config, defaults)#
Load device configuration from provided config and defaults.
The method merges configuration data with defaults using deep update strategy and creates a new device instance with the combined configuration.
- Parameters:
config (
dict[str,Any]) – Device configuration dictionary to override defaults.defaults (
dict[str,Any]) – Default device configuration values.
- Return type:
Self- Returns:
New Device instance with merged configuration.
- update(config)#
Update device information with new configuration data.
This method updates the current device instance with values from the provided configuration dictionary. Only specified fields in the config will be updated, while unspecified fields retain their current values.
- Parameters:
config (
dict[str,Any]) – Dictionary containing device configuration parameters to update.- Raises:
SPSDKError – If memory map configuration is invalid or cannot be loaded.
- Return type:
None
- class spsdk.utils.database.DeviceQuickInfo(features, info, latest_rev)#
Bases:
objectDevice quick information container for SPSDK operations.
This class provides a convenient interface for accessing device features, revisions, and capabilities. It manages feature availability across different device revisions and enables quick lookups for supported functionality during provisioning operations.
Initialize Device quick information.
Creates a new Device instance with features organized by revision for easy access.
- Parameters:
features (
Revisions) – Device features collection containing revision-specific feature data.info (
DeviceInfo) – Device information object with basic device details.latest_rev (
str) – Latest chip revision identifier string.
- get_features(revision=None)#
Get list of all supported features of device.
Retrieves all available features for the specified device revision or the latest revision if none is provided.
- Parameters:
revision (
Optional[str]) – Device revision to get features for, defaults to latest revision.- Return type:
list[str]- Returns:
List of supported feature names for the specified revision.
- is_feature_supported(feature, sub_feature=None, revision=None)#
Check if a feature is supported by the device.
The method verifies feature availability for a specific device revision, with optional sub-feature granularity checking.
- Parameters:
feature (
str) – Feature name to check for support.sub_feature (
Optional[str]) – Sub feature name for more granular checking, defaults to None.revision (
Optional[str]) – Specific device revision to check, defaults to latest revision.
- Return type:
bool- Returns:
True if the feature is supported by the device, False otherwise.
- property revisions: list[str]#
Get list of available revisions.
- Returns:
List of revision names that are available in the database.
- class spsdk.utils.database.Devices(db)#
Bases:
objectSPSDK device collection manager.
This class manages a collection of devices from the SPSDK database, providing functionality to load, store, and retrieve device configurations. It serves as a container for Device objects and handles device name resolution including legacy SPSDK device names.
Initialize managed devices container for database operations.
Creates a new instance to manage device collections within the database context.
- Parameters:
db (
Database) – Database instance containing device configurations and metadata.
- feature_items(feature, key)#
Iterate through the database to find feature items across all devices and revisions.
The method searches through all devices and their revisions for a specific feature, then extracts the specified key value from that feature’s configuration.
- Parameters:
feature (
str) – Name of the feature to search for in device configurations.key (
str) – Specific key within the feature to extract the value from.
- Raises:
SPSDKValueError – When the specified key is missing in the feature configuration.
- Return type:
Iterator[tuple[str,str,Any]]- Returns:
Iterator yielding tuples of (device name, revision name, feature value).
- get(name)#
Get device configuration from database.
Retrieves the device structure for the specified device name. The method handles device name normalization and lazy loading of device configurations.
- Parameters:
name (
str) – Device name or family identifier.- Raises:
SPSDKErrorMissingDevice – If the device name is not specified or not found in database.
- Return type:
- Returns:
Device configuration structure.
- load_devices_from_path(devices_path)#
Load devices from SPSDK database path.
Scans the specified directory for device folders and attempts to load each device into the database. If loading a device fails, an error is logged but the process continues with remaining devices.
- Parameters:
devices_path (
str) – Path to directory containing device folders to load.- Raises:
SPSDKError – When device loading fails (logged but not propagated).
- Return type:
None
- class spsdk.utils.database.DevicesQuickInfo#
Bases:
objectSPSDK device quick information manager.
This class provides fast access to device information and features across the NXP MCU portfolio. It maintains a lookup table of devices with their capabilities and supports feature-based device discovery and predecessor device mapping.
Initialize devices database for quick device information lookup.
Creates empty dictionaries for storing device information and predecessor relationships used for device compatibility and feature queries.
- static create(devices)#
Create quick info about devices.
Creates a DevicesQuickInfo object containing essential device information and predecessor lookup mapping from the full devices description.
- Parameters:
devices (
Devices) – Full devices description containing all device details.- Return type:
- Returns:
DevicesQuickInfo object with device quick info and predecessor lookup.
- get_correct_name(family)#
Get correct(latest) device name.
The method normalizes device family names by converting predecessor names to their current equivalents using the predecessor lookup table.
- Parameters:
family (
str) – The MCU/MPU family name to normalize.- Return type:
str- Returns:
Current database device name as string.
- get_devices_with_feature(feature, sub_feature=None)#
Get devices that support the requested feature.
Returns a dictionary mapping device names to lists of revisions that support the specified feature and optional sub-feature.
- Parameters:
feature (
str) – Name of feature to search for.sub_feature (
Optional[str]) – Optional sub feature to better specify the device selection.
- Return type:
dict[str,list]- Returns:
Dictionary with device names as keys and lists of supporting revisions as values.
- get_family_names()#
Get the list of all families supported by SPSDK.
Returns a sorted list of all device family names that are currently supported by the SPSDK library.
- Return type:
list[str]- Returns:
Sorted list of supported device family names.
- get_feature_list(family, revision=None)#
Get features list for specified device family.
If device database is empty, returns an empty list. Otherwise returns the list of supported features for the given family and optional revision.
- Parameters:
family (
str) – Device family name to get features for.revision (
Optional[str]) – Optional device revision to filter features.
- Return type:
list[str]- Returns:
List of supported feature names for the device.
- get_predecessors(families)#
Get the list of devices predecessors in previous SPSDK versions.
- Parameters:
families (
list[str]) – List of current family names to find predecessors for.- 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.
This method verifies whether the provided family name exists in the predecessor lookup table, indicating it’s a legacy device name format.
- Parameters:
family (
str) – The MCU/MPU family name to check.- Return type:
bool- Returns:
True if the family name is found in predecessor lookup, False otherwise.
- class spsdk.utils.database.Features(name, is_latest, device, features)#
Bases:
objectDevice revision feature container for SPSDK database operations.
This class encapsulates feature data for a specific device revision, providing methods to query and retrieve feature values with type safety and validation. It serves as the primary interface for accessing device-specific capabilities and configuration options within the SPSDK database system.
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.
Retrieves a dictionary value from the specified feature using the provided key or key path. The method ensures the returned value is a dictionary type through assertion.
- Parameters:
feature (
str) – Feature name to search in.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.
- Raises:
AssertionError – If the retrieved value is not a dictionary.
- 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.
The method retrieves a string value from the feature dictionary and converts it to an absolute file path using the device’s file path creation method.
- Parameters:
feature (
str) – Feature name to look up in the database.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:
Absolute file path 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.
This method retrieves a value from the specified feature and ensures it is a list type. If the retrieved value is not a list, an assertion error will be raised.
- Parameters:
feature (
str) – Feature name to look up in the database.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.
Retrieves a string value from the specified feature using the provided key or key path. The method ensures type safety by asserting the returned value is a string.
- Parameters:
feature (
str) – Feature name to search in.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.
The method supports both simple keys and nested key paths for accessing hierarchical data structures within feature dictionaries.
- Parameters:
feature (
str) – Feature name to access in the database.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.
This enumeration defines all supported features across the NXP MCU portfolio that can be managed through SPSDK. Each feature represents a specific functionality or component such as boot containers, security protocols, memory configurations, and programming interfaces. The enumeration provides a standardized way to identify and reference SPSDK capabilities in the database system.
- 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')#
- HSE = (39, 'hse', 'Hardware Security Engine')#
- 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')#
- SB40 = (35, 'sb40', 'Secure Binary v4.0')#
- SBC = (36, 'sbc', 'sbc')#
- SBX = (19, 'sbx', 'Secure Binary X')#
- SHADOW_REGS = (20, 'shadow_regs', 'Shadow registers')#
- SHE_SCEC = (37, 'she_scec', 'Secure Hardware Extension')#
- SIGNED_MSG = (8, 'signed_msg', 'Signed Message')#
- SIGNING = (27, 'signing', 'Signing additional information')#
- TLV_BLOB = (38, 'tlv_blob', 'Type-Length-Value blobs')#
- 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:
objectSPSDK Features Quick Data Manager.
This class manages aggregated feature data across multiple devices in the SPSDK database, providing fast access to consolidated feature information without device-specific dependencies. It extracts and consolidates features like memory types from all devices to enable quick lookups and feature validation.
Initialize the database object.
Sets up an empty features dictionary to store device and feature configurations. The features dictionary uses a nested structure where the outer key represents the device/family name and the inner dictionary contains feature definitions.
- classmethod create(devices)#
Create Quick data from the Database.
Extracts features from all devices in the database and consolidates them into a Quick features object. For each device, uses the latest revision and merges memory types while removing duplicates.
- Parameters:
devices (
Devices) – Database devices object to pick data from.- Return type:
Self- Returns:
Quick features object with consolidated device features.
- property get_all_features: list[str]#
Get all supported features from the database.
- Returns:
List of all feature names available in the database.
- get_mem_types(feature)#
Get supported memory types for a specific feature across all devices.
The method retrieves the list of memory types that are supported by the specified feature. If the feature doesn’t exist or has no memory types defined, an empty list is returned.
- Parameters:
feature (
str) – Name of the feature to query for supported memory types.- Return type:
list[str]- Returns:
List of supported memory type names, empty list if feature not found.
- class spsdk.utils.database.IspCfg(rom, flashloader)#
Bases:
objectISP Configuration Manager for NXP MCU bootloaders.
This class manages In-System Programming (ISP) configuration data for both ROM and flashloader bootloaders, providing unified access to protocol support, USB identification, and configuration management across the SPSDK framework.
Initialize ISP configuration with ROM and flashloader instances.
- Parameters:
rom (
Bootloader) – ROM bootloader instance for initial communication.flashloader (
Bootloader) – Flashloader bootloader instance for memory operations.
- get_usb_ids(protocol)#
Get USB parameters for interfaces supporting given protocol.
The method searches through ROM and flashloader interfaces to find USB IDs that support the specified protocol.
- Parameters:
protocol (
str) – Protocol name to search for in interfaces.- Return type:
list[UsbId]- Returns:
List of USB IDs supporting the specified protocol.
- is_protocol_supported(protocol)#
Check if any interface supports the given protocol.
The method verifies whether either the ROM or flashloader interface supports the specified communication protocol.
- Parameters:
protocol (
str) – Protocol name to check for support.- Return type:
bool- Returns:
True if either ROM or flashloader supports the protocol, False otherwise.
- classmethod load(config)#
Load database configuration from dictionary.
Creates a new instance by loading ROM and flashloader bootloader configurations from the provided configuration dictionary.
- Parameters:
config (
dict) – Configuration dictionary containing ‘rom’ and ‘flashloader’ keys.- Return type:
Self- Returns:
New instance loaded from the configuration.
- update(config)#
Update the object from configuration.
This method updates both ROM and flashloader configurations from the provided configuration dictionary.
- Parameters:
config (
dict) – Configuration dictionary containing ‘rom’ and/or ‘flashloader’ keys.- Return type:
None
- class spsdk.utils.database.MemBlock(name, desc)#
Bases:
objectMemory block representation from device memory map.
This class represents a single memory block within a device’s memory map, providing access to memory block properties such as base address, size, and external memory classification. It supports parsing of memory block names including core, block type, and instance identification.
- Variables:
BLOCK_NAMES – List of supported memory block type names.
CORES – List of supported processor core identifiers.
SECURITY – List of supported security domain identifiers.
Initialize a MemBlock instance.
- Parameters:
name (
str) – Name of the memory block.desc (
dict[str,Any]) – Dictionary containing the memory block description with configuration data.
- 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 from the parsed name.
Extracts and returns the block name component by parsing the instance name using the parse_name method.
- Returns:
The block name component extracted from the parsed name.
- property core: str | None#
Get core name if specified.
Extracts the core name from the parsed device name using the parse_name method.
- Returns:
Core name if present in the device name, None otherwise.
- classmethod create_name(block_name, core=None, instance=None, secure_access=None)#
Create full name of memory block.
The method constructs a memory block name by combining core name, block name, instance number, and secure access specification into a standardized format.
- Parameters:
block_name (
str) – Name of memory blockcore (
Optional[str]) – Optional core name, defaults to Noneinstance (
Optional[int]) – Optional instance number, defaults to Nonesecure_access (
Optional[bool]) – Optional specification if block has secure or non secure access, defaults to None
- Raises:
SPSDKError – Unknown core name provided
- Return type:
str- Returns:
Full block name with optional core prefix, instance suffix, and security suffix
- property external: bool#
Check if this is an external memory block.
The method checks the ‘external’ field in the description dictionary to determine if the memory block is configured as external memory.
- Returns:
True if external, False otherwise.
- property instance: int | None#
Get instance if specified.
- Returns:
Instance number if present in the name, None otherwise.
- classmethod parse_name(name)#
Parse name to base elements.
Parses a memory block name string into its constituent components including core name, memory name, instance index, and security access flag.
- Parameters:
name (
str) – Name of the memory block to parse.- Raises:
SPSDKError – Invalid memory block name format or unknown security flag.
- 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.
The method parses the name attribute to extract security access information and returns whether security access is enabled or not.
- Returns:
True if security access is enabled, False if disabled, None if not 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 manager.
This class manages memory block configurations for NXP MCU devices, providing functionality to load, organize, and query memory layout information. It handles memory block definitions including base addresses, sizes, and access properties.
Initialize device memory map configuration.
- Parameters:
mem_map (
dict[str,MemBlock]) – Dictionary mapping memory region names to MemBlock objects.
- find_memory_blocks(block_name=None, core=None, instance=None, secure_access=None, external=None, name_regex=None, base_address_range=None)#
Find memory blocks matching the specified criteria.
All criteria are optional and combined with logical AND. If a criterion is None, it’s not used for filtering.
- Parameters:
block_name (
Optional[str]) – Exact block name to match.core (
Optional[str]) – Core name to match.instance (
Optional[int]) – Instance number to match.secure_access (
Optional[bool]) – Security access flag to match.external (
Optional[bool]) – External memory flag to match.name_regex (
Optional[str]) – Regular expression pattern to match against the full block name.base_address_range (
Optional[tuple[int,int]]) – Tuple of (min_address, max_address) to match blocks within address range.
- Return type:
list[MemBlock]- Returns:
List of memory blocks matching all specified criteria.
- get_memory(block_name, core=None, instance=None, secure=None)#
Get the memory block by specified parameters.
The method searches for a memory block using the provided parameters. If the exact match is not found and secure parameter is None, it attempts to find the block with secure_access set to False as a fallback.
- Parameters:
block_name (
str) – Core block name to search for.core (
Optional[str]) – Optional core name, defaults to None.instance (
Optional[int]) – Optional instance number, defaults to None.secure (
Optional[bool]) – Optional selection of secure/non-secure memory access, defaults to None.
- Return type:
- Returns:
Memory block matching the specified parameters.
- Raises:
SPSDKError – Block has not been found with given parameters.
- get_table()#
Get string table with memory map description.
Creates a formatted table showing memory blocks with their index, name, base address, size, and external flag. The table uses double border style for better readability.
- Return type:
str- Returns:
Formatted string table containing memory map information.
- classmethod load(mem_map)#
Load the Memory map from configuration.
Creates a new instance by converting dictionary configuration into MemBlock objects.
- Parameters:
mem_map (
dict[str,dict[str,Any]]) – Dictionary with all blocks where keys are block names and values are block configurations.- Return type:
Self- Returns:
New instance with loaded memory blocks.
- class spsdk.utils.database.QuickDatabase#
Bases:
objectSPSDK Quick Database for lightweight device information access.
This class provides a lightweight database loaded at SPSDK startup to supply basic device information for CLI operations such as help texts and enumeration choices without requiring the full heavyweight database to be loaded.
Initialize the database with empty device and feature collections.
Sets up internal data structures for storing device information and feature data, along with an empty database hash for integrity checking.
- 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.
The method organizes devices into groups based on their purpose attribute from the device database. Each group contains devices with the same purpose, sorted alphabetically.
- Parameters:
devices (
list[str]) – List of device names to be grouped.- Return type:
dict[str,list[str]]- Returns:
Dictionary where the key is group name and value is list of devices.
- class spsdk.utils.database.Revisions(iterable=(), /)#
Bases:
list[Features]Device revision collection for SPSDK operations.
This class extends the built-in list to store and manage Features objects representing different device revisions, providing convenient access methods for retrieving revisions by name or getting the latest available revision.
- 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:
SPSDKErrorSPSDK exception for missing device in database operations.
This exception is raised when attempting to access or reference a device that is not found in the SPSDK device database, providing specific error context about the missing device.
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 device communication.
This class represents a USB device identifier consisting of Vendor ID (VID) and Product ID (PID) values. It provides functionality for creating, updating, validating, and comparing USB identifiers used in device communication and configuration management.
Initialize a USB ID instance.
- Parameters:
vid (
Optional[int]) – USB Vendor ID (optional).pid (
Optional[int]) – USB Product ID (optional).
- is_valid()#
Check if the USB ID is valid.
The method validates that both vendor ID and product ID are properly set and not None values.
- 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.
The method extracts vendor ID and product ID from the provided configuration dictionary and creates a new UsbId instance with these values.
- Parameters:
usb_config (
dict) – Dictionary containing ‘vid’ and/or ‘pid’ keys with USB identifiers.- Return type:
Self- Returns:
New UsbId instance with configured vendor and product IDs.
- update(usb_config)#
Update the USB ID from a configuration dictionary.
- Parameters:
usb_config (
dict) – Dictionary containing ‘vid’ and/or ‘pid’ keys with USB vendor and product IDs.- Return type:
None
- class spsdk.utils.database.UsbIdArray(iterable=(), /)#
Bases:
list[UsbId]Collection of USB identifiers for device communication.
This class extends the built-in list to store and manage multiple UsbId objects, providing convenient access methods for retrieving USB identifiers by index or validating all identifiers in the collection.
- all_valid()#
Check if all USB IDs in the collection are valid.
- Return type:
bool- Returns:
True if all UsbId instances are valid, False otherwise.
- classmethod load(usb_configs)#
Create a UsbIdArray instance from a list of configuration dictionaries.
- Parameters:
usb_configs (
list[dict]) – List of dictionaries containing ‘vid’ and/or ‘pid’ keys.- Return type:
Self- Returns:
New UsbIdArray instance with configured USB identifiers.
- update(usb_configs)#
Update the USB ID array from a list of configuration dictionaries.
This method merges new USB IDs with existing ones. Only USB IDs that are not already present in the array are added.
- Parameters:
usb_configs (
list[dict]) – List of dictionaries 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 for the requested feature.
- Parameters:
feature (
str) – Name of the feature to get schema for.- Return type:
dict[str,Any]- Returns:
Loaded dictionary containing the JSON Schema file content.
- 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.
- Raises:
SPSDKValueError – If SPSDK_CACHE_FOLDER is set but not a valid absolute path.
- Return type:
str- Returns:
The path to the SPSDK cache directory.