Utils Module API
Module containing various functions/modules used throughout the SPSDK.
Utils easy enum
EasyEnum allows numerical value, string tag and description to an enum element.
- class spsdk.utils.easy_enum.Enum
Bases:
objectEnum Type Class.
- classmethod desc(default='')
Description of the specified value.
- Parameters:
key (
Union[str,int]) – either value or name (name is case INSENSITIVE)default (
str) – value in case key does not exist
- Return type:
str- Returns:
description of the value; empty string if description was not specified
- Raises:
SPSDKTypeError – Key is nor string or int
- classmethod from_int()
Converts integer value into enumeration.
Note: the method does two things: - checks whether given integer value is defined within the enumeration - formally converts value into enumeration (for type hints), even the returned value is same as input :type value:
int:param value: integer value to be converted :rtype:Enum:return: corresponding enumeration :raises SPSDKError: If specified value does not match any enumeration value
- classmethod get(default=None)
Converts enumeration value to name OR name to enumeration value.
- Parameters:
key (
Union[str,int]) – either value or name (name is case INSENSITIVE)default (
Union[str,int,None]) – value in case key does not exist
- Return type:
str- Returns:
name for value; value for name
- classmethod name(default=None)
Returns name of selected enumeration tag.
- Parameters:
key (
int) – enumeration tagdefault (
Optional[str]) – value to return of tag not found; if not defined, KeyError exception will be raised
- Return type:
str- Returns:
name of the corresponding enumeration tag
- Raises:
SPSDKKeyError – if tag not supported and default value not provided
- classmethod tags()
Return sequence of all enumerations tags.
- Return type:
Sequence[int]
Utils crypto
Module for cryptographic utilities.
General utils
Miscellaneous functions used throughout the SPSDK.
- class spsdk.utils.misc.BinaryPattern(pattern)
Bases:
objectBinary pattern class.
- Supported patterns:
rand: Random Pattern
zeros: Filled with zeros
ones: Filled with all ones
inc: Filled with repeated numbers incremented by one 0-0xff
any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.
Constructor of pattern class.
- Parameters:
pattern (
str) – Supported patterns: - rand: Random Pattern - zeros: Filled with zeros - ones: Filled with all ones - inc: Filled with repeated numbers incremented by one 0-0xff - any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.- Raises:
SPSDKValueError – Unsupported pattern detected.
- SPECIAL_PATTERNS = ['rand', 'zeros', 'ones', 'inc']
- get_block(size)
Get block filled with pattern.
- Parameters:
size (
int) – Size of block to return.- Return type:
bytes- Returns:
Filled up block with specified pattern.
- property pattern: str
Get the pattern.
- Returns:
Pattern in string representation.
- class spsdk.utils.misc.SingletonMeta
Bases:
typeSingleton metaclass.
- class spsdk.utils.misc.Timeout(timeout, units='s')
Bases:
objectSimple timeout handle class.
Simple timeout class constructor.
- Parameters:
timeout (
int) – Timeout value.units (
str) – Timeout units (MUST be from the UNITS list)
- Raises:
SPSDKValueError – Invalid input value.
- UNITS = {'ms': 1000, 's': 1000000, 'us': 1}
- get_consumed_time()
Returns consumed time since start of timeout operation.
- Return type:
int- Returns:
Consumed time in units as the class was constructed
- get_consumed_time_ms()
Returns consumed time since start of timeouted operation in milliseconds.
- Return type:
int- Returns:
Consumed time in milliseconds
- get_rest_time(raise_exc=False)
Returns rest time to timeout overflow.
- Parameters:
raise_exc (
bool) – If set, the function raise SPSDKTimeoutError in case of overflow.- Return type:
int- Returns:
Rest time in units as the class was constructed
- Raises:
SPSDKTimeoutError – In case of overflow
- get_rest_time_ms(raise_exc=False)
Returns rest time to timeout overflow.
- Parameters:
raise_exc (
bool) – If set, the function raise SPSDKTimeoutError in case of overflow.- Return type:
int- Returns:
Rest time in milliseconds
- Raises:
SPSDKTimeoutError – In case of overflow
- overflow(raise_exc=False)
Check the the timer has been overflowed.
- Parameters:
raise_exc (
bool) – If set, the function raise SPSDKTimeoutError in case of overflow.- Return type:
bool- Returns:
True if timeout overflowed, False otherwise.
- Raises:
SPSDKTimeoutError – In case of overflow
- spsdk.utils.misc.align(number, alignment=4)
Align number (size or address) size to specified alignment, typically 4, 8 or 16 bytes boundary.
- Parameters:
number (
int) – input to be alignedalignment (
int) – the boundary to align; typical value is power of 2
- Return type:
int- Returns:
aligned number; result is always >= size (e.g. aligned up)
- Raises:
SPSDKError – When there is wrong alignment
- spsdk.utils.misc.align_block(data, alignment=4, padding=None)
Align binary data block length to specified boundary by adding padding bytes to the end.
- Parameters:
data (
Union[bytes,bytearray]) – to be alignedalignment (
int) – boundary alignment (typically 2, 4, 16, 64 or 256 boundary)padding (
Union[int,str,BinaryPattern,None]) – byte to be added or BinaryPattern
- Return type:
bytes- Returns:
aligned block
- Raises:
SPSDKError – When there is wrong alignment
- spsdk.utils.misc.align_block_fill_random(data, alignment=4)
Same as align_block, just parameter padding is fixed to -1 to fill with random data.
- Return type:
bytes
- spsdk.utils.misc.change_endianness(bin_data)
Convert binary format used in files to binary used in register object.
- Parameters:
bin_data (
bytes) – input binary array.- Return type:
bytes- Returns:
Converted array (practically little to big endianness).
- Raises:
SPSDKError – Invalid value on input.
- spsdk.utils.misc.check_range(x, start=0, end=4294967295)
Check if the number is in range.
- Parameters:
x (
int) – Number to check.start (
int) – Lower border of range, default is 0.end (
int) – Upper border of range, default is unsigned 32-bit range.
- Return type:
bool- Returns:
True if fits, False otherwise.
- spsdk.utils.misc.extend_block(data, length, padding=0)
Add padding to the binary data block to extend the length to specified value.
- Parameters:
data (
bytes) – block to be extendedlength (
int) – requested block length; the value must be >= current block lengthpadding (
int) – 8-bit value value to be used as a padding
- Return type:
bytes- Returns:
block extended with padding
- Raises:
SPSDKError – When the length is incorrect
- spsdk.utils.misc.find_file(file_path, use_cwd=True, search_paths=None, raise_exc=True)
Return a full path to the file.
search_paths takes precedence over CWD if used (default)
- Parameters:
file_path (
str) – File name, part of file path or full pathuse_cwd (
bool) – Try current working directory to find the file, defaults to Truesearch_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to Noneraise_exc (
bool) – Raise exception if file is not found, defaults to True
- Return type:
str- Returns:
Full path to the file
- Raises:
SPSDKError – File not found
- spsdk.utils.misc.find_first(iterable, predicate)
Find first element from the list, that matches the condition.
- Parameters:
iterable (
Iterable[TypeVar(T)]) – list of elementspredicate (
Callable[[TypeVar(T)],bool]) – function for selection of the element
- Return type:
Optional[TypeVar(T)]- Returns:
found element; None if not found
- spsdk.utils.misc.format_value(value, size, delimiter='_', use_prefix=True)
Convert the ‘value’ into either BIN or HEX string, depending on ‘size’.
if ‘size’ is divisible by 8, function returns HEX, BIN otherwise digits in result string are grouped by 4 using ‘delimiter’ (underscore)
- Return type:
str
- spsdk.utils.misc.get_abs_path(file_path, base_dir=None)
Return a full path to the file.
param base_dir: Base directory to create absolute path, if not specified the system CWD is used. return: Absolute file path.
- Return type:
str
- spsdk.utils.misc.get_bytes_cnt_of_int(value, align_to_2n=True, byte_cnt=None)
Returns count of bytes needed to store handled integer.
- Parameters:
value (
int) – Input integer value.align_to_2n (
bool) – The result will be aligned to standard sizes 1,2,4,8,12,16,20.byte_cnt (
Optional[int]) – The result count of bytes.
- Raises:
SPSDKValueError – The integer input value doesn’t fit into byte_cnt.
- Return type:
int- Returns:
Number of bytes needed to store integer.
- spsdk.utils.misc.get_hash(text)
Returns hash of given text.
- Return type:
str
- spsdk.utils.misc.get_key_by_val(value, dictionary)
Return key by its value.
- Parameters:
value (
str) – Value to find.dictionary (
Dict[str,List[str]]) – Dictionary to find in.
- Raises:
SPSDKValueError – Value is not present in dictionary.
- Return type:
str- Returns:
Key name
- spsdk.utils.misc.load_binary(path, search_paths=None)
Loads binary file into bytes.
- Parameters:
path (
str) – Path to the file.search_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Return type:
bytes- Returns:
content of the binary file as bytes
- spsdk.utils.misc.load_configuration(path, search_paths=None)
Load configuration from yml/json file.
- Parameters:
path (
str) – Path to configuration filesearch_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – When unsupported file is provided
- Return type:
Dict- Returns:
Content of configuration as dictionary
- spsdk.utils.misc.load_file(path, mode='r', search_paths=None)
Loads a file into bytes.
- Parameters:
path (
str) – Path to the file.mode (
str) – mode for reading the file ‘r’/’rb’search_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Return type:
Union[str,bytes]- Returns:
content of the binary file as bytes or str (based on mode)
- spsdk.utils.misc.load_text(path, search_paths=None)
Loads text file into string.
- Parameters:
path (
str) – Path to the file.search_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Return type:
str- Returns:
content of the text file as string
- spsdk.utils.misc.numberify_version(version, separator='.', valid_numbers=3)
Turn version string into a number.
Each group is weighted by a multiple of 1000
1.2.3 -> 1 * 1_000_000 + 2 * 1_000 + 3 * 1 = 1_002_003 21.100.9 -> 21 * 1_000_000 + 100 * 1_000 + 9 * 1 = 21_100_009
- Parameters:
version (
str) – Version string numbers separated by separatorseparator (
str) – Separator used in the version string, defaults to “.”valid_numbers (
int) – Amount of numbers to sanitize to consider, defaults to 3
- Return type:
int- Returns:
Number representing the version
- spsdk.utils.misc.reverse_bits_in_bytes(arr)
The function reverse bits order in input bytes.
- Parameters:
arr (
bytes) – Input array.- Return type:
bytes- Returns:
New array with reversed bits in bytes.
- Raises:
SPSDKError – Raises when invalid value is in input.
- spsdk.utils.misc.reverse_bytes_in_longs(arr)
The function reverse byte order in longs from input bytes.
- Parameters:
arr (
bytes) – Input array.- Return type:
bytes- Returns:
New array with reversed bytes.
- Raises:
SPSDKError – Raises when invalid value is in input.
- spsdk.utils.misc.sanitize_version(version, separator='.', valid_numbers=3)
Sanitize version string.
Append ‘.0’ in case version string has fewer parts than valid_numbers Remove right-most version parts after valid_numbers amount of parts
1.2 -> 1.2.0 1.2.3.4 -> 1.2.3
- Parameters:
version (
str) – Original version stringseparator (
str) – Separator used in the version string, defaults to “.”valid_numbers (
int) – Amount of numbers to sanitize, defaults to 3
- Return type:
str- Returns:
Sanitized version string
- spsdk.utils.misc.size_fmt(num, use_kibibyte=True)
Size format.
- Return type:
str
- spsdk.utils.misc.split_data(data, size)
Split data into chunks of size.
- Parameters:
data (bytearray) – array of bytes to be split
size (int) – size of splitted array
- Return Generator[bytes]:
splitted array
- Return type:
Generator[bytes,None,None]
- spsdk.utils.misc.swap16(x)
Swap bytes in half word (16bit).
- Parameters:
x (
int) – Original number- Return type:
int- Returns:
Number with swapped bytes
- Raises:
SPSDKError – When incorrect number to be swapped is provided
- spsdk.utils.misc.swap32(x)
Swap 32 bit integer.
- Parameters:
x (
int) – integer to be swapped- Return type:
int- Returns:
swapped value
- Raises:
SPSDKError – When incorrect number to be swapped is provided
- spsdk.utils.misc.use_working_directory(path)
Execute the block in given directory.
Cd into specific directory. Execute the block. Change the directory back into the original one.
- Parameters:
path (
str) – the path, where the current directory will be changed to- Return type:
Iterator[None]
- spsdk.utils.misc.value_to_bool(value)
Function decode bool value from various formats.
- Parameters:
value (
Union[bool,int,str]) – Input value.- Return type:
bool- Returns:
Boolean value.
- Raises:
SPSDKError – Unsupported input type.
- spsdk.utils.misc.value_to_bytes(value, align_to_2n=True, byte_cnt=None, endianness='big')
Function loads value from lot of formats.
- Parameters:
value (
Union[bytes,bytearray,int,str]) – Input value.align_to_2n (
bool) – When is set, the function aligns length of return array to 1,2,4,8,12 etc.byte_cnt (
Optional[int]) – The result count of bytes.endianness (
str) – The result bytes endianness [‘big’, ‘little’].
- Return type:
bytes- Returns:
Value in bytes.
- spsdk.utils.misc.value_to_int(value, default=None)
Function loads value from lot of formats to integer.
- Parameters:
value (
Union[bytes,bytearray,int,str]) – Input value.default (
Optional[int]) – Default Value in case of invalid input.
- Return type:
int- Returns:
Value in Integer.
- Raises:
SPSDKError – Unsupported input type.
- spsdk.utils.misc.write_file(data, path, mode='w', encoding=None)
Writes data into a file.
- Parameters:
data (
Union[str,bytes]) – data to writepath (
str) – Path to the file.mode (
str) – writing mode, ‘w’ for text, ‘wb’ for binary data, defaults to ‘w’encoding (
Optional[str]) – Encoding of written file (‘ascii’, ‘utf-8’).
- Return type:
int- Returns:
number of written elements
Image utils
Module to keep additional utilities for binary images.
- class spsdk.utils.images.BinaryImage(name, size=0, offset=0, description=None, binary=None, pattern=None, alignment=1, parent=None)
Bases:
objectBinary Image class.
Binary Image class constructor.
- Parameters:
name (
str) – Name of Image.size (
int) – Image size.offset (
int) – Image offset in parent image, defaults to 0description (
Optional[str]) – Text description of image, defaults to Nonebinary (
Optional[bytes]) – Optional binary content.pattern (
Optional[BinaryPattern]) – Optional binary pattern.alignment (
int) – Optional alignment of result imageparent (
Optional[BinaryImage]) – Handle to parent object, defaults to None
- MINIMAL_DRAW_WIDTH = 30
- property absolute_address: int
Image absolute address relative to base parent.
- Returns:
Absolute address relative to base parent
- add_image(image)
Add new sub image information.
- Parameters:
image (
BinaryImage) – Image object.- Return type:
None
- aligned_length(alignment=4)
Returns aligned length for erasing purposes.
- Parameters:
alignment (
int) – The alignment value, defaults to 4.- Return type:
int- Returns:
Ceil alignment length.
- aligned_start(alignment=4)
Returns aligned start address.
- Parameters:
alignment (
int) – The alignment value, defaults to 4.- Return type:
int- Returns:
Floor alignment address.
- draw(include_sub_images=True, width=0, color='', no_color=False)
Draw the image into the ASCII graphics.
- Parameters:
include_sub_images (
bool) – Include also sub images into, defaults to Truewidth (
int) – Fixed width of table, 0 means autosize.color (
str) – Color of this block, None means automatic color.no_color (
bool) – Disable adding colors into output.
- Raises:
SPSDKValueError – In case of invalid width.
- Return type:
str- Returns:
ASCII art representation of image.
- export()
Export represented binary image.
- Return type:
bytes- Returns:
Byte array of binary image.
- static generate_config_template()
Generate configuration template.
- Return type:
str- Returns:
Template to create binary merge..
- get_min_draw_width(include_sub_images=True)
Get minimal width of table for draw function.
- Parameters:
include_sub_images (
bool) – Include also sub images into, defaults to True- Return type:
int- Returns:
Minimal width in characters.
- static get_validation_schemas()
Get validation schemas list to check a supported configuration.
- Return type:
List[Dict[str,Any]]- Returns:
Validation schemas.
- property image_name: str
Image name including all parents.
- Returns:
Full Image name
- join_images()
Join all sub images into main binary block.
- Return type:
None
- static load_binary_image(path, name=None, size=0, offset=0, description=None, pattern=None, search_paths=None, alignment=1, load_bin=True)
Load binary data file.
Supported formats are ELF, HEX, SREC and plain binary
- Parameters:
path (
str) – Path to the file.name (
Optional[str]) – Name of Image, defaults to file name.size (
int) – Image size, defaults to 0.offset (
int) – Image offset in parent image, defaults to 0description (
Optional[str]) – Text description of image, defaults to Nonepattern (
Optional[BinaryPattern]) – Optional binary pattern.search_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to Nonealignment (
int) – Optional alignment of result imageload_bin (
bool) – Load as binary in case of every other format load fails
- Raises:
SPSDKError – The binary file cannot be loaded.
- Return type:
- Returns:
Binary data represented in BinaryImage class.
- static load_from_config(config, search_paths=None)
Converts the configuration option into an Binary Image object.
- Parameters:
config (
Dict[str,Any]) – Description of binary image.search_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
Initialized Binary Image.
- save_binary_image(path, file_format='BIN')
Save binary data file.
- Parameters:
path (
str) – Path to the file.file_format (
str) – Format of saved file (‘BIN’, ‘HEX’, ‘S19’), defaults to ‘BIN’.
- Raises:
SPSDKValueError – The file format is invalid.
- Return type:
None
- property size: int
Size property.
- update_offsets()
Update offsets from the sub images into main offset value begin offsets.
- Return type:
None
- validate()
Validate if the images doesn’t overlaps each other.
- Return type:
None
- class spsdk.utils.images.ColorPicker
Bases:
objectSimple class to get each time when ask different color from list.
Constructor of ColorPicker.
- COLORS = ['\x1b[90m', '\x1b[34m', '\x1b[32m', '\x1b[36m', '\x1b[33m', '\x1b[35m', '\x1b[37m', '\x1b[94m', '\x1b[96m', '\x1b[92m', '\x1b[95m', '\x1b[97m', '\x1b[93m']
- get_color(unwanted_color=None)
Get new color from list.
- Parameters:
unwanted_color (
Optional[str]) – Color that should be omitted.- Return type:
str- Returns:
Color
Interfaces utils
Device Interfaces.
Serial Proxy
SerialProxy serves as patch replacement for serial.Serial class.
- class spsdk.utils.serial_proxy.SerialProxy(port, timeout, baudrate, write_timeout=None)
Bases:
objectSerialProxy is used to simulate communication with serial device.
It can be used as mock.patch for serial.Serial class. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))
Basic initialization for serial.Serial class.
__init__ signature must accommodate instantiation of serial.Serial
- Parameters:
port (
str) – Serial port nametimeout (
int) – timeout (does nothing)write_timeout (
Optional[int]) – does nothingbaudrate (
int) – Serial port speed (does nothing)
- close()
Simulates closing a serial port.
- Return type:
None
- flush()
Simulates flushing input buffer.
- Return type:
None
-
ignore_ack:
bool= False
- classmethod init_proxy(data, ignore_ack=False)
Initialized response dictionary of write and read bytes.
- Parameters:
data (
Dict[bytes,bytes]) – Dictionary of write and read bytesignore_ack (
bool) – Don’t modify internal buffer upon receiving a ACK packet
- Return type:
Type[SerialProxy]- Returns:
SerialProxy class with configured data
- open()
Simulates opening a serial port.
- Return type:
None
- read(length)
Read portion of pre-configured data.
- Parameters:
length (
int) – Amount of data to read from buffer- Return type:
bytes- Returns:
Data read
- reset_input_buffer()
Simulates resetting input buffer.
- Return type:
None
- reset_output_buffer()
Simulates resetting output buffer.
- Return type:
None
-
responses:
Dict[bytes,bytes] = {}
- write(data)
Simulates a write, currently just pick up response from responses.
- Parameters:
data (
bytes) – Bytes to write, key in responses- Return type:
None
- class spsdk.utils.serial_proxy.SimpleReadSerialProxy(port, timeout, baudrate, write_timeout=None)
Bases:
SerialProxySimpleReadSerialProxy is used to simulate communication with serial device.
It simplifies reading method. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))
Basic initialization for serial.Serial class.
__init__ signature must accommodate instantiation of serial.Serial
- Parameters:
port (
str) – Serial port nametimeout (
int) – timeout (does nothing)write_timeout (
Optional[int]) – does nothingbaudrate (
int) – Serial port speed (does nothing)
- FULL_BUFFER = b''
- classmethod init_data_proxy(data)
Initialized response dictionary of write and read bytes.
- Parameters:
data (
bytes) – Dictionary of write and read bytes- Return type:
Type[SimpleReadSerialProxy]- Returns:
SerialProxy class with configured data
- write(data)
Simulates a write method, but it does nothing.
- Parameters:
data (
bytes) – Bytes to write, key in responses- Return type:
None
USB Filter
Module defining a USB filtering class.
- class spsdk.utils.usbfilter.NXPUSBDeviceFilter(usb_id=None, nxp_device_names=None)
Bases:
USBDeviceFilterNXP Device Filtering class.
Extension of the generic USB device filter class to support filtering based on NXP devices. Modifies the way, how single number is handled. By default, if single value is provided, it’s content is expected to be VID. However, legacy tooling were expecting PID, so from this perspective if a single number is provided, we expect that VID is out of range NXP_VIDS.
Initialize the USB Device Filtering.
- Parameters:
usb_id (
Optional[str]) – usb_id stringnxp_device_names (
Optional[Dict[str,Tuple[int,int]]]) – Dictionary holding NXP device vid/pid {“device_name”: [vid(int), pid(int)]}
- NXP_VIDS = [8137, 5538, 1137, 3368]
- compare(usb_device_object)
Compares the internal usb_id with provided usb_device_object.
Extends the comparison by USB names - dictionary of device name and corresponding VID/PID.
- Parameters:
usb_device_object (
Any) – lpcusbsio USB HID device object- Return type:
bool- Returns:
True on match, False otherwise
- class spsdk.utils.usbfilter.USBDeviceFilter(usb_id=None, search_by_pid=False)
Bases:
objectGeneric USB Device Filtering class.
Create a filtering instance. This instance holds the USB ID you are interested in during USB HID device search and allows you to compare, whether provided USB HID object is the one you are interested in. The allowed format of usb_id string is following:
vid or pid - vendor ID or product ID. String holding hex or dec number. Hex number must be preceded by 0x or 0X. Number of characters after 0x is 1 - 4. Mixed upper & lower case letters is allowed. e.g. “0xaB12”, “0XAB12”, “0x1”, “0x0001”. The decimal number is restricted only to have 1 - 5 digits, e.g. “65535” It’s allowed to set the USB filter ID to decimal number “99999”, however, as the USB VID number is four-byte hex number (max value is 65535), this will lead to zero results. Leading zeros are not allowed e.g. 0001. This will result as invalid match.
The user may provide a single number as usb_id. In such a case the number may represent either VID or PID. By default, the filter expects this number to be a VID. In rare cases the user may want to filter based on PID. Initialize the search_by_pid parameter to True in such cases.
vid/pid - string of vendor ID & product ID separated by ‘:’ or ‘,’ Same rules apply to the number format as in VID case, except, that the string consists of two numbers separated by ‘:’ or ‘,’. It’s not allowed to mix hex and dec numbers, e.g. “0xab12:12345” is not allowed. Valid vid/pid strings: “0x12aB:0xabc”, “1,99999”
Windows specific: instance ID - String in following format “HIDVID_<HEX>&PID_<HEX><instance_id>”, see instance ID in device manager under Windows OS.
Linux specific: USB device path - HID API returns path in following form: ‘0003:0002:00’
The first number represents the Bus, the second Device and the third interface. The Bus:Device number is unique so interface is not necessary and Bus:Device should be sufficient.
The Bus:Device can be observed using ‘lsusb’ command. The interface can be observed using ‘lsusb -t’. lsusb returns the Bus and Device as a 3-digit number. It has been agreed, that the expected input is: <Bus in dec>#<Device in dec>, e.g. 3#11
Mac specific: USB device path - HID API returns path in roughly following form: ‘IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/XHC1@14/XHC1@14000000/HS01@14100000/SE Blank RT Family @14100000/IOUSBHostInterface@0/AppleUserUSBHostHIDDevice’
This path can be found using the ‘ioreg’ utility or using ‘IO Hardware Registry Explorer’ tool. However, using the system report from ‘About This MAC -> System Report -> USB’ a partial path can also be gathered. Using the name of USB device from the ‘USB Device Tree’ and appending the ‘Location ID’ should work. The name can be ‘SE Blank RT Family’ and the ‘Location ID’ is in form <hex> / <dec>, e.g. ‘0x14200000 / 18’. So the ‘usb_id’ name should be ‘SE Blank RT Family @14200000’ and the filter should be able to filter out such device.
Initialize the USB Device Filtering.
- Parameters:
usb_id (
Optional[str]) – usb_id stringsearch_by_pid (
bool) – if true, expects usb_id to be a PID number, VID otherwise.
- compare(usb_device_object)
Compares the internal usb_id with provided usb_device_object.
The provided USB ID during initialization may be VID or PID, VID/PID pair, or a path. See private methods for details.
- Parameters:
usb_device_object (
Dict[str,Any]) – Libusbsio/HID_API device object (dictionary)- Return type:
bool- Returns:
True on match, False otherwise
- static convert_usb_path(hid_api_usb_path)
Converts the Libusbsio/HID_API path into string, which can be observed from OS.
DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided. Additionally, this method relies on the fact that the provided path comes from the Libusbsio/HID_API. This method will most probably fail or provide improper results in case path from different USB API is provided.
- Parameters:
hid_api_usb_path (
bytes) – USB device path from Libusbsio/HID_API- Return type:
str- Returns:
Libusbsio/HID_API path converted for given platform
Registers descriptions with support for XML files
Module to handle registers descriptions with support for XML files.
- class spsdk.utils.registers.ConfigProcessor(description='')
Bases:
objectBase class for processing configuration data.
Initialize the processor.
- NAME = 'NOP'
- classmethod from_str(config_string)
Create config processor instance from configuration string.
- Return type:
- classmethod from_xml(element)
Create config processor from XML data entry.
- Return type:
Optional[ConfigProcessor]
- classmethod get_description(config_string)
Return extra description for config processor.
- Return type:
str
- classmethod get_method_name(config_string)
Return config processor method name.
- Return type:
str
- classmethod get_params(config_string)
Return config processor method parameters.
- Return type:
Dict[str,int]
- post_process(value)
Post-process value going to config file.
- Return type:
int
- pre_process(value)
Pre-process value coming from config file.
- Return type:
int
- width_update(value)
Update bit-width of value going to config file.
- Return type:
int
- class spsdk.utils.registers.Registers(device_name, base_endianness='big')
Bases:
objectSPSDK Class for registers handling.
Initialization of Registers class.
- add_register(reg)
Adds register into register list.
- Parameters:
reg (
RegsRegister) – Register to add to the class.- Raises:
SPSDKError – Invalid type has been provided.
SPSDKRegsError – Cannot add register with same name
- Return type:
None
- create_yml_config(exclude_regs=None, exclude_fields=None, ignored_fields=None, diff=False, indent=0)
The function creates the configuration YML file.
- Parameters:
exclude_regs (
Optional[List[str]]) – List of excluded registersexclude_fields (
Optional[Dict[str,Dict[str,str]]]) – Dictionary with lists of excluded bitfields per registerignored_fields (
Optional[List[str]]) – List of ignored names in fields.diff (
bool) – Get only configuration with difference value to reset state.indent (
int) – Indent in space to generate YML.
- Return type:
Any- Returns:
YAML commented map of registers value.
- create_yml_config_white_list(white_list=None, diff=False, indent=0)
The function creates the configuration YML file.
- Parameters:
white_list (
Optional[Dict[str,Any]]) – Dictionary with lists of registers and its bitfieldsdiff (
bool) – Get only configuration with difference value to reset state.indent (
int) – Indent in space to generate YML.
- Return type:
Any- Returns:
YAML commented map of registers value.
- export(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)
Export Registers into binary.
- Parameters:
size (
int) – Result size of Image, 0 means automatic minimal size.pattern (
BinaryPattern) – Pattern of gaps, defaults to “zeros”
- Return type:
bytes
- find_reg(name, include_group_regs=False)
Returns the instance of the register by its name.
- Parameters:
name (
str) – The name of the register.include_group_regs (
bool) – The algorithm will check also group registers.
- Return type:
- Returns:
Instance of the register.
- Raises:
SPSDKRegsErrorRegisterNotFound – The register doesn’t exist.
- generate_html(heading1, heading2, regs_exclude=None, fields_exclude=None)
Generate describing HTML file with registers.
- Parameters:
heading1 (
str) – The main title in HTML.heading2 (
str) – The sub-title in HTML.regs_exclude (
Optional[List[str]]) – The exclude registers list.fields_exclude (
Optional[List[str]]) – The exclude bitfield list.
- Return type:
str- Returns:
The content of HTML file.
- get_reg_names(exclude=None, include_group_regs=False)
Returns list of the register names.
- Parameters:
exclude (
Optional[List[str]]) – Exclude list of register names if needed.include_group_regs (
bool) – The algorithm will check also group registers.
- Return type:
List[str]- Returns:
List of register names.
- get_registers(exclude=None, include_group_regs=False)
Returns list of the registers.
Method allows exclude some register by their names. :type exclude:
Optional[List[str]] :param exclude: Exclude list of register names if needed. :type include_group_regs:bool:param include_group_regs: The algorithm will check also group registers. :rtype:List[RegsRegister] :return: List of register names.
- get_validation_schema()
Get the JSON SCHEMA for registers.
- Return type:
Dict- Returns:
JSON SCHEMA.
- image_info(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)
Export Registers into binary information.
- Parameters:
size (
int) – Result size of Image, 0 means automatic minimal size.pattern (
BinaryPattern) – Pattern of gaps, defaults to “zeros”
- Return type:
- load_registers_from_xml(xml, filter_reg=None, grouped_regs=None)
Function loads the registers from the given XML.
- Parameters:
xml (
str) – Input XML data in string format.filter_reg (
Optional[List[str]]) – List of register names that should be filtered out.grouped_regs (
Optional[List[dict]]) – List of register prefixes names to be grouped into one.
- Raises:
SPSDKRegsError – XML parse problem occurs.
- Return type:
None
- load_yml_config(yml_data, exclude_regs=None, exclude_fields=None)
The function loads the configuration from YML file.
- Parameters:
yml_data (
Any) – The YAML commented data with register values.exclude_regs (
Optional[List[str]]) – List of excluded registersexclude_fields (
Optional[Dict[str,Dict[str,str]]]) – Dictionary with lists of excluded bitfields
- Return type:
None
- parse(binary)
Parse the binary data values into loaded registers.
- Parameters:
binary (
bytes) – Binary data to parse.- Return type:
None
- remove_register(reg)
Remove register from register list by its instance reference.
- Reg:
Instance of register that should be removed.
- Raises:
SPSDKError – Invalid type has been provided.
- Return type:
None
- remove_register_by_name(reg_names)
Removes register from register list by List of its names.
- Reg_names:
List of names of registers that should be removed.
- Return type:
None
- reset_values(exclude=None)
The method reset values in registers.
- Parameters:
exclude (
Optional[List[str]]) – The list of register names to be excluded.- Return type:
None
- run_hooks(exclude=None)
The method run hooks on all regular registers.
- Parameters:
exclude (
Optional[List[str]]) – The list of register names to be excluded.- Return type:
None
- write_xml(file_name)
Write loaded register structures into XML file.
- Parameters:
file_name (
str) – The name of XML file that should be created.- Return type:
None
- class spsdk.utils.registers.RegsBitField(parent, name, offset, width, description=None, reset_val='0', access='RW', hidden=False, config_processor=None)
Bases:
objectStorage for register bitfields.
Constructor of RegsBitField class. Used to store bitfield information.
- Parameters:
parent (
RegsRegister) – Parent register of bitfield.name (
str) – Name of bitfield.offset (
int) – Bit offset of bitfield.width (
int) – Bit width of bitfield.description (
Optional[str]) – Text description of bitfield.reset_val (
Any) – Reset value of bitfield.access (
str) – Access type of bitfield.hidden (
bool) – The bitfield will be hidden from standard searches.
- add_enum(enum)
Add bitfield enum.
- Parameters:
enum (
RegsEnum) – New enumeration value for bitfield.- Return type:
None
- add_et_subelement(parent)
Creates the register XML structure in ElementTree.
- Parameters:
parent (
Element) – The parent object of ElementTree.- Return type:
None
- classmethod from_xml_element(xml_element, parent)
Initialization register by XML ET element.
- Parameters:
xml_element (
Element) – Input XML subelement with register data.parent (
RegsRegister) – Reference to parent RegsRegister object.
- Return type:
- Returns:
The instance of this class.
- get_enum_constant(enum_name)
Returns constant representation of enum by its name.
- Return type:
int- Returns:
Constant of enum.
- Raises:
SPSDKRegsErrorEnumNotFound – The enum has not been found.
- get_enum_names()
Returns list of the enum strings.
- Return type:
List[str]- Returns:
List of enum names.
- get_enum_value()
Returns enum value of the bitfield.
- Return type:
Union[str,int]- Returns:
Current value of bitfield.
- get_enums()
Returns bitfield enums.
- Return type:
List[RegsEnum]- Returns:
List of bitfield enumeration values.
- get_hex_value()
Get the value of register in string hex format.
- Return type:
str- Returns:
Hexadecimal value of register.
- get_html_data_element()
Returns HTML element of bitfield.
- Return type:
Mapping[str,Union[str,dict,list]]- Returns:
HTML element.
- get_reset_value()
Returns integer reset value of the bitfield.
- Return type:
int- Returns:
Reset value of bitfield.
- get_value()
Returns integer value of the bitfield.
- Return type:
int- Returns:
Current value of bitfield.
- has_enums()
Returns if the bitfields has enums.
- Return type:
bool- Returns:
True is has enums, False otherwise.
- set_enum_value(new_val, raw=False)
Updates the value of the bitfield by its enum value.
- Parameters:
new_val (
str) – New enum value of bitfield.raw (
bool) – If set, no automatic modification of value is applied.
- Raises:
SPSDKRegsErrorEnumNotFound – Input value cannot be decoded.
- Return type:
None
- set_value(new_val, raw=False)
Updates the value of the bitfield.
- Parameters:
new_val (
Any) – New value of bitfield.raw (
bool) – If set, no automatic modification of value is applied.
- Raises:
SPSDKValueError – The input value is out of range.
- Return type:
None
- class spsdk.utils.registers.RegsEnum(name, value, description, max_width=0)
Bases:
objectStorage for register enumerations.
Constructor of RegsEnum class. Used to store enumeration information of bitfield.
- Parameters:
name (
str) – Name of enumeration.value (
Any) – Value of enumeration.description (
str) – Text description of enumeration.max_width (
int) – Maximal width of enum value used to format output
- Raises:
SPSDKRegsError – Invalid input value.
- add_et_subelement(parent)
Creates the register XML structure in ElementTree.
- Parameters:
parent (
Element) – The parent object of ElementTree.- Return type:
None
- classmethod from_xml_element(xml_element, maxwidth=0)
Initialization Enum by XML ET element.
- Parameters:
xml_element (
Element) – Input XML subelement with enumeration data.maxwidth (
int) – The maximal width of bitfield for this enum (used for formatting).
- Return type:
- Returns:
The instance of this class.
- Raises:
SPSDKRegsError – Error during enum XML parsing.
- get_value_int()
Method returns Integer value of enum.
- Return type:
int- Returns:
Integer value of Enum.
- get_value_str()
Method returns formatted value.
- Return type:
str- Returns:
Formatted string with enum value.
- class spsdk.utils.registers.RegsRegister(name, offset, width, description=None, reverse=False, access=None, config_as_hexstring=False, otp_index=None, reverse_subregs_order=False, base_endianness='big', alt_widths=None)
Bases:
objectInitialization register by input information.
Constructor of RegsRegister class. Used to store register information.
- Parameters:
name (
str) – Name of register.offset (
int) – Byte offset of register.width (
int) – Bit width of register.description (
Optional[str]) – Text description of register.reverse (
bool) – Multi byte register value could be printed in reverse order.access (
Optional[str]) – Access type of register.config_as_hexstring (
bool) – Config is stored as a hex string.otp_index (
Optional[int]) – Index of OTP fuse.reverse_subregs_order (
bool) – Reverse order of sub registers.base_endianness (
Literal['little','big']) – Base endianness for bytes import/export of value.alt_widths (
Optional[List[int]]) – List of alternative widths.
- add_bitfield(bitfield)
Add register bitfield.
- Parameters:
bitfield (
RegsBitField) – New bitfield value for register.- Return type:
None
- add_et_subelement(parent)
Creates the register XML structure in ElementTree.
- Parameters:
parent (
Element) – The parent object of ElementTree.- Return type:
None
- add_group_reg(reg)
Add group element for this register.
- Parameters:
reg (
RegsRegister) – Register member of this register group.- Raises:
SPSDKRegsErrorRegisterGroupMishmash – When any inconsistency is detected.
- Return type:
None
- add_setvalue_hook(hook, context=None)
Set the value hook for write operation.
- Parameters:
hook (
Callable) – Callable hook for set value operation.context (
Optional[Any]) – Context data for this hook.
- Return type:
None
- find_bitfield(name)
Returns the instance of the bitfield by its name.
- Parameters:
name (
str) – The name of the bitfield.- Return type:
- Returns:
Instance of the bitfield.
- Raises:
SPSDKRegsErrorBitfieldNotFound – The bitfield doesn’t exist.
- classmethod from_xml_element(xml_element)
Initialization register by XML ET element.
- Parameters:
xml_element (
Element) – Input XML subelement with register data.- Return type:
- Returns:
The instance of this class.
- get_bitfield_names(exclude=None)
Returns list of the bitfield names.
- Parameters:
exclude (
Optional[List[str]]) – Exclude list of bitfield names if needed.- Return type:
List[str]- Returns:
List of bitfield names.
- get_bitfields(exclude=None)
Returns register bitfields.
Method allows exclude some bitfields by their names. :type exclude:
Optional[List[str]] :param exclude: Exclude list of bitfield names if needed. :rtype:List[RegsBitField] :return: Returns List of register bitfields.
- get_bytes_value(raw=False)
Get the bytes value of register.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
bytes- Returns:
Register value in bytes.
- get_hex_value(raw=False)
Get the value of register in string hex format.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
str- Returns:
Hexadecimal value of register.
- get_html_data_element(exclude=None)
Returns HTML element of register.
- Return type:
Mapping[str,Union[str,dict,list]]- Returns:
HTML element.
- get_reset_value()
Returns reset value of the register.
- Return type:
int- Returns:
Reset value of register.
- get_value(raw=False)
Get the value of register.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
int
- has_group_registers()
Returns true if register is compounded from sub-registers.
- Return type:
bool- Returns:
True if register has sub-registers, False otherwise.
- reset_value(raw=False)
Reset the value of register.
- Parameters:
raw (
bool) – Do not use any modification hooks.- Return type:
None
- set_value(val, raw=False)
Set the new value of register.
- Parameters:
val (
Any) – The new value to set.raw (
bool) – Do not use any modification hooks.
- Raises:
SPSDKError – When invalid values is loaded into register
- Return type:
None
- class spsdk.utils.registers.ShiftRightConfigProcessor(count, description='')
Bases:
ConfigProcessorConfig processor performing the right-shift operation.
Initialize the right-shift config processor.
- Parameters:
count (
int) – Count of bit for shift operationdescription (
str) – Extra description for config processor, defaults to “”
- NAME = 'SHIFT_RIGHT'
- classmethod from_str(config_string)
Create config processor instance from configuration string.
- Return type:
- post_process(value)
Post-process value going to config file.
- Return type:
int
- pre_process(value)
Pre-process value coming from config file.
- Return type:
int
- width_update(value)
Update bit-width of value going to config file.
- Return type:
int
Register’s configuration
Module to handle registers configuration.
- class spsdk.utils.reg_config.RegConfig(path, index=None)
Bases:
DatabaseClass that helps manage the registers configuration.
Register Configuration class constructor.
- Parameters:
path (
str) – The path to configuration JSON file.index (
Optional[int]) – Values with {index} will be replaced with index value
- get_address(device, alt_read_address=False)
Get the area address in chip memory.
- Parameters:
device (
str) – The device name.alt_read_address (
bool) – The flag is used if an alternate read address applies.
- Return type:
int- Returns:
Base address of registers.
- get_antipole_regs(device=None)
Return the list of inverted registers.
- Parameters:
device (
Optional[str]) – The device name.- Return type:
Dict[str,str]- Returns:
The dictionary of antipole registers.
- get_computed_fields(device=None)
Return the list of computed fields (not used in config YML files).
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
Dict[str,Dict[str,str]]- Returns:
The dictionary of computed fields.
- get_computed_registers(device=None)
Return the dictionary of computed registers.
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
Dict[str,Any]- Returns:
The dictionary of computed registers.
- get_data_file(device, revision)
Return the full path to data file (xml).
- Parameters:
device (
str) – The device name.revision (
str) – The chip revision.
- Raises:
SPSDKValueError – When datafile is not defined in the database
- Return type:
str- Returns:
The path to data file.
- get_grouped_registers(device=None)
Return the list of grouped registers description.
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
List[dict]- Returns:
The list of grouped registers descriptions.
- get_ignored_fields(device=None)
Return the list of ignored fields.
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
List[str]- Returns:
The list of ignored fields.
- get_seal_count(device=None)
Return the seal count.
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
Optional[int]- Returns:
The seal count.
- Raises:
SPSDKError – When there is invalid seal count
- get_seal_start_address(device=None)
Return the seal start address.
- Parameters:
device (
Optional[str]) – The device name, if not specified, the general value is used.- Return type:
Optional[str]- Returns:
The seal start register name.
- Raises:
SPSDKError – When seal start address has invalid name
- get_value(key, device=None, default=None)
Return any parameter by key.
- Parameters:
key (
str) – The Key of the parameter to be returned.device (
Optional[str]) – The device name.default (
Optional[Any]) – The default Value in case that is not specified in config file.
- Return type:
Any- Returns:
The Value of parameter by handled Key.
USB Device Scanner
NXP USB Device Scanner API.
- spsdk.utils.nxpdevscan.search_libusbsio_devices()
Returns a list of all LIBUSBSIO devices.
- Retval:
list of UartDeviceDescription devices from devicedescription module
- Raises:
SPSDKError – In any case of LIBUSBSIO problems.
- Return type:
List[SIODeviceDescription]
- spsdk.utils.nxpdevscan.search_nxp_sdio_devices()
Searches all NXP SDIO devices based on their device path.
- Return type:
List[SDIODeviceDescription]- Returns:
list of SDIODeviceDescription corresponding to NXP devices
- spsdk.utils.nxpdevscan.search_nxp_uart_devices()
Returns a list of all NXP devices connected via UART.
- Retval:
list of UartDeviceDescription devices from devicedescription module
- Return type:
List[UartDeviceDescription]
- spsdk.utils.nxpdevscan.search_nxp_usb_devices(extend_vid_list=None)
Searches all NXP USB devices based on their Vendor ID.
- Extend_vid_list:
list of VIDs, to extend the default NXP VID list (int)
- Return type:
List[USBDeviceDescription]- Returns:
list of USBDeviceDescription corresponding to NXP devices
Device description
Module for NXP device description classes.
- class spsdk.utils.devicedescription.DeviceDescription
Bases:
ABCBase class for all logical devices.
The intent is to have a generic container for providing info about devices of any type. Thus the class is named as ‘logical’, because it doesn’t allow you to control the device in any way.
This is just a base class and as such shouldn’t be used. If you want to use it, create your own class inheriting from this class and redefining the methods listed in this class!
- class spsdk.utils.devicedescription.SDIODeviceDescription(vid, pid, path)
Bases:
DeviceDescriptionSimple container holding information about SDIO device.
This container should be used instead of any SDIO API related objects, as this container will be the same all the time compared to specific SDIO API implementations.
Constructor.
- Parameters:
vid (
int) – Vendor IDpid (
int) – Product ID
See
get_usb_device_name()function to getg the name from VID and PID. Seeconvert_usb_path()function to provide a proper path string.
- class spsdk.utils.devicedescription.SIODeviceDescription(info)
Bases:
DeviceDescriptionSimple container holding information about LIBUSBSIO device.
This container contains information about LIBUSBSIOdevice.
Constructor.
- Parameters:
info (
HIDAPI_DEVICE_INFO_T) – LIBUSBSIO device information class.
- class spsdk.utils.devicedescription.USBDeviceDescription(vid, pid, path, product_string, manufacturer_string, name, serial, original_path=None)
Bases:
DeviceDescriptionSimple container holding information about USB device.
This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific USB API implementations.
Constructor.
- Parameters:
vid (
int) – Vendor IDpid (
int) – Product IDproduct_string (
str) – Product stringmanufacturer_string (
str) – Manufacturer stringname (
str) – Name(s) of NXP devices as defined under spsdk.mboot.interfaces.usb or spsdk.sdp.interfaces.usbserial (
str) – The serial number of device.
See
get_usb_device_name()function to get the name from VID and PID. Seeconvert_usb_path()function to provide a proper path string.
- class spsdk.utils.devicedescription.UartDeviceDescription(name=None, dev_type=None)
Bases:
DeviceDescriptionSimple container holding information about UART device.
This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific UART API implementations.
Constructor.
The ‘dev_type’ can be in general any string identifying the device type.
- Parameters:
name (
Optional[str]) – COM port namedev_type (
Optional[str]) – ‘mboot device’ or ‘SDP device’
- spsdk.utils.devicedescription.get_usb_device_name(vid, pid, device_names=None)
Returns ‘name’ device identifier based on VID/PID, from dicts.
Searches provided dictionary for device name based on VID/PID. If the dict is None, the search happens on USB_DEVICES under mboot/interfaces/usb.py and sdphost/interfaces/usb.py
DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided.
- Parameters:
vid (
int) – Vendor ID we are interested inpid (
int) – Product ID we are interested indevice_names (
Optional[Dict[str,Tuple[int,int]]]) – dict where str is device name, first int vid, second int pid
- Return type:
List[str]- Returns:
list containing device names with corresponding VID/PID
Module for schema-based configuration validation
Module for schema-based configuration validation.
- class spsdk.utils.schema_validator.CommentedConfig(main_title, schemas, values=None, note=None, export_template=True)
Bases:
objectClass for generating commented config templates or custom configurations.
Constructor for Config templates.
- Parameters:
main_title (
str) – Main title of final template.schemas (
List[Dict[str,Any]]) – Main description of final template.values (
Optional[Dict[str,Any]]) –for configuration, this is dictionary of values to be saved
for schema, this is dictionary of override values (overriding default values)
note (
Optional[str]) – Additional Note after title test.export_template (
bool) – True to export schema template; False to export custom configuration
- MAX_LINE_LENGTH = 118
- static convert_cm_to_yaml(config)
Convert Commented Map for into final YAML string.
- Parameters:
config (
CommentedMap) – Configuration in CM format.- Raises:
SPSDKError – If configuration is empty
- Return type:
str- Returns:
YAML string with configuration to use to store in file.
- export()
Export configuration template into CommentedMap.
- Raises:
SPSDKError – Error
- Return type:
CommentedMap- Returns:
Configuration template in CM.
- export_to_yaml()
Export Configuration template directly into YAML string format.
- Return type:
str- Returns:
YAML string.
- static get_property_optional_required(key, block)
Function to determine if the config property is required or not.
- Parameters:
key (
str) – Name of config recordblock (
Dict[str,Any]) – Source data block
- Return type:
- Returns:
Final description.
- property max_line: int
Maximal line with current indent.
- class spsdk.utils.schema_validator.PropertyRequired
Bases:
EnumEnum describing if the property is required or optional.
- CONDITIONALLY_REQUIRED = 1
- OPTIONAL = 2
- REQUIRED = 0
- class spsdk.utils.schema_validator.SPSDKListStrategies(strategy_list)
Bases:
ListStrategiesExtended List Strategies.
- static strategy_set(_config, _path, base, nxt)
Use the set of both as a output.
- class spsdk.utils.schema_validator.SPSDKMerger(type_strategies, fallback_strategies, type_conflict_strategies)
Bases:
MergerModified Merger to add new list strategy ‘set’.
- PROVIDED_TYPE_STRATEGIES = {<class 'list'>: <class 'spsdk.utils.schema_validator.SPSDKListStrategies'>, <class 'dict'>: <class 'deepmerge.strategy.dict.DictStrategies'>, <class 'set'>: <class 'deepmerge.strategy.set.SetStrategies'>}
- class spsdk.utils.schema_validator.ValidationSchemas
Bases:
objectManager for validation schemas.
- static get_schema_file(sch_file)
Return load schema file. Use SingleTon behavior.
- Parameters:
sch_file (
str) – Path to schema config file.- Raises:
SPSDKError – Invalid schema config file.
- Return type:
Dict[str,Any]- Returns:
Loaded schema file.
- spsdk.utils.schema_validator.check_config(config, schemas, extra_formatters=None, search_paths=None)
Check the configuration by provided list of validation schemas.
- Parameters:
config (
Union[str,Dict[str,Any]]) – Configuration to checkschemas (
List[Dict[str,Any]]) – List of validation schemasextra_formatters (
Optional[Dict[str,Callable[[str],bool]]]) – Additional custom formatterssearch_paths (
Optional[List[str]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – Invalid validation schema or configuration
- Return type:
None
- spsdk.utils.schema_validator.cmap_update(cmap, updater)
Update CMap including comments.
- Parameters:
cmap (
CommentedMap) – Original CMap to be updated.updater (
CommentedMap) – CMap updater.
- Return type:
None
Utils Exceptions
Module provides exceptions for SPSDK utilities.
- exception spsdk.utils.exceptions.SPSDKRegsError(desc=None)
Bases:
SPSDKErrorGeneral Error group for utilities SPSDK registers module.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorBitfieldNotFound(desc=None)
Bases:
SPSDKRegsErrorBitfield has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorEnumNotFound(desc=None)
Bases:
SPSDKRegsErrorEnum has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterGroupMishmash(desc=None)
Bases:
SPSDKRegsErrorRegister Group inconsistency problem.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterNotFound(desc=None)
Bases:
SPSDKRegsErrorRegister has not been found.
Initialize the base SPSDK Exception.
- exception spsdk.utils.exceptions.SPSDKTimeoutError
Bases:
TimeoutError,SPSDKErrorSPSDK Timeout.
Database
Module to manage used databases in SPSDK.
- class spsdk.utils.database.Database(path, index=None)
Bases:
objectClass that helps manage used databases in SPSDK.
Register Configuration class constructor.
- Parameters:
path (
str) – The path to configuration JSON file.index (
Optional[int]) – Values with {index} will be replaced with index value
- get_device_value(key, device=None, revision='latest', default=None)
Return any parameter by key and replace the index if provided in DB.
- Parameters:
key (
str) – The Key of the parameter to be returned.device (
Optional[str]) – The device name.revision (
str) – The revision of the silicon.default (
Optional[Any]) – The default Value in case that is not specified in config file.
- Return type:
Any- Returns:
The Value of parameter by handled Key.
- classmethod get_devices(path)
Classmethod to get list of supported devices.
- Parameters:
path (
str) – Path to database file.- Return type:
- Returns:
List of all supported devices.
- replace_idx_value(value)
Replace index value if provided in the database.
- Parameters:
value (
str) – value to be replaced f-string containing index- Return type:
str- Returns:
value with replaced index
- class spsdk.utils.database.Device(name, device_alias=None, revisions=<factory>, attributes=<factory>)
Bases:
objectDevice dataclass represents a single device.
-
attributes:
dict
-
device_alias:
Optional[str] = None
- static load(name, device)
Loads the device from dictionary.
- Parameters:
name (
str) – The name of device.device (
dict) – Device data.
- Return type:
- Returns:
The Device object.
-
name:
str
-
attributes:
- class spsdk.utils.database.Devices(iterable=(), /)
Bases:
List[Device]List of devices.
- property device_names: List[str]
Get the list of all device names.
- get_by_name(name)
Return database device structure.
- Parameters:
name (
str) – String Key with device name.- Raises:
SPSDKValueError – In case the device with given name does not exist
- Return type:
- Returns:
Dictionary device configuration structure or None:
- static load(devices)
Loads the device from dictionary.
- Parameters:
devices (
dict) – Devices data.- Return type:
- Returns:
The Devices object.
- class spsdk.utils.database.Revision(name, is_latest, data_file=None, attributes=<factory>)
Bases:
objectRevision dataclass represents a single device revision.
-
attributes:
dict
-
data_file:
Optional[str] = None
-
is_latest:
bool
- static load(name, revision, is_latest=False)
Loads the revision from dictionary.
- Parameters:
name (
str) – The revision name.revision (
dict) – Revision data.is_latest (
bool) – Is latest device revision.
- Raises:
SPSDKTypeError – In case the revision is not a dictionary type
- Return type:
- Returns:
The Revision object.
-
name:
str
-
attributes:
- class spsdk.utils.database.Revisions(iterable=(), /)
Bases:
List[Revision]List of device revisions.
- 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.- Return type:
- Returns:
The Revision object.
- get_by_name(name)
Get the required revision.
- Parameters:
name (
str) – Required revision name- Raises:
SPSDKValueError – Incase of invalid device or revision value.
- Return type:
- Returns:
The Revision object.
- get_latest()
Get latest revision for device.
- Raises:
SPSDKValueError – Incase of there is no latest revision defined.
- Return type:
- Returns:
The Revision object.
- static load(revisions, latest=None)
Loads the revisions list from dictionary.
- Parameters:
revisions (
dict) – Revisions data.latest (
Optional[str]) – Name of latest revision.
- Raises:
SPSDKTypeError – In case the revisions parameter is not a dictionary type
- Return type:
- Returns:
The Revisions object.
- property revision_names: List[str]
Get list of revisions.
- Returns:
List of all supported device version.