flync.core¶
flync.core.annotations¶
external¶
External field annotations and output strategies.
- class NamingStrategy(*values)¶
Bases:
IntEnumThe strategy on how the external field file/folder will be named.
- class OutputStrategy(*values)¶
Bases:
IntFlagThe strategy on how an external field will be generated.
- class External(path: str | None = None, root: str | None = None, output_structure: OutputStrategy = <OutputStrategy.AUTO: 1>, naming_strategy: NamingStrategy = NamingStrategy.AUTO)¶
Bases:
objectIndicates this field is loaded from a separate location.
implied¶
Provides annotations for fields that are automatically derived rather than manually set.
- class ImpliedStrategy(*values)¶
Bases:
IntEnumThe strategy on how an implied field will be calculated.
- class Implied(strategy: ImpliedStrategy = ImpliedStrategy.AUTO)¶
Bases:
objectIndicates this field is implied instead of loaded/generated.
flync.core.base_models¶
base_models¶
Base Model that is used by FLYNC Model classes.
- class FLYNCBaseModel¶
Bases:
BaseModelBase Model that is used by FLYNC Model classes.
- model_config = {'extra': 'forbid', 'validate_assignment': True, 'validate_by_name': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_dump(**kwargs)¶
Override pydantics model_dump to dump with defaults.
flync.core.datatypes¶
- class Datatype¶
Bases:
FLYNCBaseModelBase class of every datatype.
Parameters¶
- namestr
Unique name of the datatype.
- descriptionstr, optional
Human-readable description of the datatype.
- typestr
Discriminator identifying the concrete datatype kind.
- endiannessLiteral[“BE”, “LE”], optional
Byte order used for encoding multibyte values. Defaults to big-endian (“BE”).
- member_namestr, optional
When this datatype is stored as a struct member, this field holds the member’s name within the struct (which may differ from the type’s own
name). None when the datatype is not a struct member or when member name equals the type name.
- class IPv4AddressEntry¶
Bases:
FLYNCBaseModelRepresents an IPv4 address entry for a network interface.
Parameters¶
- address
IPv4Address The IPv4 address. “0.0.0.0” means dynamic.
- ipv4netmask
IPv4Address The subnet mask in IPv4 format.
- address
- class IPv6AddressEntry¶
Bases:
FLYNCBaseModelRepresents an IPv6 address entry for a network interface.
Parameters¶
- address
IPv6Address The IPv6 address. “::” means dynamic.
- ipv6prefixint
The prefix length (0-128).
- address
- class MACAddressEntry¶
Bases:
FLYNCBaseModelRepresents an MAC address entry for a network interface.
Parameters¶
- addressMacAddress
Source MAC address to filter by. Format: “xx:xx:xx:xx:xx:xx”
- macmaskstr
The mask in MAC format. Format: “xx:xx:xx:xx:xx:xx”. Defaults to
"xx:xx:xx:xx:xx:xx".
- class MACAddressUnicast¶
Bases:
MACAddressEntryRepresents a Unicast MAC address entry for a network interface.
Parameters¶
- addressMacAddress
Multicast MAC address. Format:
"xx:xx:xx:xx:xx:xx".
- class MACAddressMulticast¶
Bases:
MACAddressEntryRepresents a Multicast MAC address entry for a network interface.
Parameters¶
- addressMacAddress
Multicast MAC address. Format:
"xx:xx:xx:xx:xx:xx".
- class BitRange¶
Bases:
DatatypeRepresents a range of bits in a signal or data array.
Parameters¶
- namestr
Unique name of the datatype.
- descriptionstr, optional
Human-readable description of the datatype.
- typestr
Datatype discriminator inherited from
Datatype.- endiannessLiteral[“BE”, “LE”], optional
Byte order used for encoding multibyte values. Defaults to big-endian (“BE”).
- startint
Starting bit position (inclusive).
- endint
Ending bit position (inclusive).
- class Bitmask¶
Bases:
FLYNCBaseModelBit pattern together with a mask selecting the bits that are significant.
A candidate value matches when
(candidate & mask) == data.Parameters¶
- dataint
Expected bit pattern, written as a quoted hexadecimal (
"0x0800") or binary ("0b0000 1000 0000 0000") literal. Whitespace inside the literal groups nibbles or bytes and is ignored. A plain integer is accepted as well and is widened to whole bytes. Both the bit width of the literal (leading zeros included) and its notation are kept and written back on dump, so the pattern survives a load/dump cycle unchanged. Must be greater or equal to 0.- maskint, optional
Bits that are significant, written like
dataand describing the same number of bits. Defaults to all bits ofdata; that default is not written back on dump. Must be greater or equal to 1.
- class ValueRange¶
Bases:
FLYNCBaseModelDefines an inclusive range of integer values.
This datatype is typically used to express valid numeric intervals for parameters, identifiers, or signal values.
Parameters¶
- from_valueint
Lower bound of the range (inclusive).
- to_valueint
Upper bound of the range (inclusive).
- class ValueTable¶
Bases:
FLYNCBaseModelRepresents a table of values with an associated description.
Parameters¶
- num_valueint
The numeric value associated with this table entry.
- descriptionstr
Human-readable description of the table entry.
- class Ethertype¶
Bases:
EnumEtherType values relevant for automotive and TSN Ethernet networks.
Each member maps a protocol to its IEEE-registered EtherType (the 16-bit field in the Ethernet header that identifies the upper-layer protocol).
Supported EtherTypes:
Name
Hex
Description
ARP
0x0806
Address Resolution Protocol
ASAM_CMP
0x99FE
ASAM Capture Module Protocol
AVTP
0x22F0
IEEE 1722 Audio Video Transport Protocol
EAPoL
0x888E
EAP over LAN including MACsec Key Agreement (MKA)
ETH_FLOWCTRL
0x8808
Ethernet flow control (PAUSE / IEEE 802.3x)
HSR
0x892F
High-availability Seamless Redundancy (IEC 62439-3)
IPv4
0x0800
Internet Protocol version 4
IPv6
0x86DD
Internet Protocol version 6
LLDP
0x88CC
Link Layer Discovery Protocol (IEEE 802.1AB)
MACsec
0x88E5
MAC Security (IEEE 802.1AE)
PRP
0x88FB
Parallel Redundancy Protocol supervision (IEC 62439-3)
PTP
0x88F7
Precision Time Protocol / gPTP (IEEE 1588 / 802.1AS)
QinQ
0x88A8
Outer VLAN tag (IEEE 802.1ad)
SRP
0x22EA
Stream Reservation Protocol (IEEE 802.1Qat)
VLAN
0x8100
Inner VLAN tag (IEEE 802.1Q)
WAKE_ON_LAN
0x0842
Wake-on-LAN magic packet (ECU wakeup)
Usage:
The Ethertype can be specified in three ways:
By enum member:
Ethertype.AVTPBy name string:
"AVTP"By hex value:
0x22F0or"0x22F0"
Example:
from flync.core.datatypes import Ethertype # All of these are equivalent: et1 = Ethertype.AVTP et2 = Ethertype(0x22F0) et3 = Ethertype["AVTP"] # When used in a model, serialization returns hex format: # {"ethertype": "0x22F0"}
Use in Pydantic models:
eth_type: Annotated[Ethertype, PlainSerializer(serialize_ethertype), BeforeValidator(validate_ethertype_input)]
flync.core.utils¶
base_utils¶
Base Utils that can be useful throughout the whole FLYNC Library and toolchain.
- read_yaml(path: str | PathLike | Path)¶
Read a YAML file.
- Args:
path (str | os.PathLike | Path): Path to the YAML file
- Raises:
err_fatal: If path is not for YAML file.
- Returns:
Any: Retrieved data from YAML.
- get_yaml_paths(base_path: str | PathLike) list¶
Collect absolute paths to yaml files from a base_path.
- Args:
base_path (str | os.PathLike): Base Path to FLYNC Config.
- Returns:
list: List of absolute file paths to yaml files.
- is_mac_address(input: str) Tuple[bool, str]¶
Helper to check if an input is a valid MAC address based on pydantic validator.
- Args:
input (str): input string that should be checked.
- Returns:
bool: Returns the result of check as a boolean as well as a message that could be used in logging or exception handling. If the result boolean is true, the provided input is a MAC address. If the boolean is false, it is not.
- is_mac_unicast(input: str) Tuple[bool, str]¶
Helper to check if a MAC address is unicast. Unicast if first byte’s least significant bit is 0.
- Args:
input (str): input string that should be checked.
- Returns:
Union[bool, str]: Returns the result of check as a boolean as well as a message that could be used in logging or exception handling. If the result boolean is true, the provided input is a unicast MAC address. If the boolean is false, it is not.
- is_mac_multicast(input: str) Tuple[bool, str]¶
Method to check if a MAC address is multicast. Multicast if first byte’s least significant bit is 1.
- Args:
input (str): input string that should be checked.
- Returns:
Union[bool, str]: Returns the result of check as a boolean as well as a message that could be used in logging or exception handling. If the result boolean is true, the provided input is a MAC multicast address. If the boolean is false, it is not.
- is_ip_address(input: IPv4Address | IPv6Address | str) Tuple[bool, str]¶
Helper to check if an input is a valid IP address.
- Args:
input (
IPv4Address|IPv6Address| str): input string that should be checked.- Returns:
bool: Returns the result of check as a boolean as well as a message that could be used in logging or exception handling. If the result boolean is true, the provided input is an IP address. If the boolean is false, it is not.
- is_ip_multicast(input: IPv4Address | IPv6Address | str) Tuple[bool, str]¶
Method to check if a string is an IP multicast address.
- Args:
input (
IPv4Address|IPv6Address): input string that should be checked.- Returns:
Union[bool, str]: Returns the result of check as a boolean as well as a message that could be used in logging or exception handling. If the result boolean is true, the provided input is an IP multicast address. If the boolean is false, it is not.
- get_duplicates_in_list(input: list) list¶
Find duplicates in a list.
- Args:
input (list): a list where duplicates are suspected.
- Returns:
list: returns a list of the duplicates that were found.
- check_obj_in_list(obj, list)¶
Helper function: To check if the object is in the list or not
- deep_iter(obj, stop_class)¶
Helper function: To deeply iterate through an object and its children. The iteration will stop if an object of type stop_class is reached.
- Args:
obj: The object to iterate through. stop_class: The class type at which the iteration should stop.
- Returns:
Generator: A generator that yields objects of the specified type.
- find_all(base, target_class: Type[T]) list[T]¶
Helper to get all fields of certain type in nested data.
- Args:
base: The base object to start searching from. target_class: The class to search for.
- Returns:
list: A list of all instances of the target class found within the base object.
exceptions¶
Defines custom pydantic errors and the FLYNC error-id scheme.
- class Severity(*values)¶
Bases:
StrEnumString enum that represents errors severity levels
- class Category(*values)¶
Bases:
IntEnumInteger enum to represent categories for errors
- module_code_for(dotted_module: str) str¶
Resolve a module code from the
KEYdeclared in the nearest enclosing package.Walks the package chain (
flync.model.flync_4_ecu.port->flync_4_ecu->ECU). Falls back toGENfor the top-level model and version migrators,CMNotherwise.
- compose_error_id(severity: Severity, module_code: str, category: Category | None, error_number: str | None) str¶
Assemble
FLYNC-<MODULE>-<SEVERITY>-<CATEGORY>-<NUMBER>; unset category/number render asUNC/000.
- warn(msg: str, *, category: Category | None = None, error_number: str | None = None, **ctx) None¶
Record a validation warning without raising a validation error.
The message is appended to the active warning list (set up by
validate_with_policy) and will be returned alongsideload_errorsso that it appears in the warnings table. If called outside avalidate_with_policycontext the call is silently ignored.Parameters¶
- msgstr
Human-readable warning message.
- categoryCategory, optional
Semantic category used to compose the error id.
- error_numberstr, optional
Globally unique zero-padded number identifying this call site.
- ctxdict
Context arguments that define key-value pairs to fill the placeholders in msg.
- warn_from_error(error: PydanticCustomError) None¶
Record a validation warning from an already-raised
PydanticCustomError, preserving its original error id and message instead of composing a new one at the catch site.Use this when downgrading a caught error to a warning (e.g. a best-effort
bind()call whose failures should not be fatal) so the warning still reports the id of the validator that actually raised it, rather than the id of the catch site.Parameters¶
- errorPydanticCustomError
The error caught from a factory call (
err_minor/err_major/err_fatal).
- err_minor(msg: str, *, category: Category | None = None, error_number: str | None = None, **ctx) PydanticCustomError¶
Factory that returns PydanticCustomError with type minor.
Parameters¶
- msgstr
Error message that may contain placeholders
- categoryCategory, optional
Semantic category used to compose the error id.
- error_numberstr, optional
Globally unique zero-padded number identifying this call site.
- ctxdict
Context arguments that define key-value pairs to fill the placeholders in msg
Returns¶
PydanticCustomError
- err_major(msg: str, *, category: Category | None = None, error_number: str | None = None, **ctx) PydanticCustomError¶
Factory that returns PydanticCustomError with type major.
Parameters¶
- msgstr
Error message that may contain placeholders
- categoryCategory, optional
Semantic category used to compose the error id.
- error_numberstr, optional
Globally unique zero-padded number identifying this call site.
- ctxdict
Context arguments that define key-value pairs to fill the placeholders in msg
Returns¶
PydanticCustomError
- err_fatal(msg: str, *, category: Category | None = None, error_number: str | None = None, **ctx) PydanticCustomError¶
Factory that returns PydanticCustomError with type fatal.
Parameters¶
- msgstr
Error message that may contain placeholders
- categoryCategory, optional
Semantic category used to compose the error id.
- error_numberstr, optional
Globally unique zero-padded number identifying this call site.
Returns¶
PydanticCustomError
exceptions_handling¶
Provides utilities for validating models and handling errors.
- is_semantic_validation_error(err: ErrorDetails) bool¶
Return
Trueiferris a user-raised semantic validation error.User code raises semantic errors via
err_major(),err_minor(), orerr_fatal(); theirtypeis exactly"major"/"minor"/"fatal"andctxcarries the formatter kwargs only. A native Pydantic mismatch rewrapped by_wrap_native_error()shares the"major"type but always setsctx["sub_errors"]— that key distinguishes structural mismatches from semantic failures.
- resolve_alias(model: type[BaseModel], field_name: str) str¶
Return the YAML key used for a Pydantic field, considering alias.
- get_name_by_alias(model: type[BaseModel], alias: str)¶
Return the Python field name that corresponds to the given alias.
Parameters¶
- modeltype[BaseModel]
The Pydantic model class to search.
- aliasstr
The alias to look up.
Returns¶
- str
The Python attribute name whose alias matches
alias.
Raises¶
- KeyError
If no field with the given alias is found.
- safe_yaml_position(node: Any, loc: tuple, model: type[BaseModel] | None = None) Tuple[int | None, int | None]¶
Given a ruamel.yaml node and a Pydantic loc tuple, return (line, column). Falls back gracefully if key/item is missing.
- locate_errors(errors: List[ErrorDetails], model: type[BaseModel] | None, yaml_node: Node | None) None¶
Stamp the YAML
line/colonto errors that do not carry a position yet, in place.Workspace documents are validated from plain (safe-loaded) data that has no source marks, so positions are resolved afterwards against the document’s composed ruamel.yaml node tree. Errors whose location cannot be found in
yaml_nodeare left unchanged.Parameters¶
- errorsList[ErrorDetails]
Errors recorded for the document.
- modeltype[BaseModel], optional
The model the document was validated against, used to resolve field aliases.
- yaml_noderuamel.yaml.nodes.Node, optional
The composed YAML tree of the document.
- errors_to_init_errors(errors: List[ErrorDetails], model: type[BaseModel] | None = None, yaml_data: object | None = None, yaml_path: str | None = None) List[InitErrorDetails]¶
Convert Pydantic validation errors into
InitErrorDetailsfor re-raising.Optionally enriches each error with YAML source location information when
modelandyaml_dataare provided, and with the file path whenyaml_pathis provided.Parameters¶
- errorsList[ErrorDetails]
The list of errors to convert.
- modeltype[BaseModel], optional
The Pydantic model class used to resolve field aliases for YAML position look-ups.
- yaml_dataobject, optional
The parsed ruamel.yaml AST of the document, used together with
modelto locate the error position within the file.- yaml_pathstr, optional
The workspace-relative file path to embed in each error’s context as
yaml_path.
Returns¶
- List[InitErrorDetails]
The converted errors, ready to be passed to
ValidationError.from_exception_data.
- delete_at_loc(data: Any, loc: Tuple)¶
Helper function to remove the key/item from original object by loc(path to an element within the object).
Parameters¶
- dataAny
Data to remove the item from. Will be mutated.
- locTuple
Path to the location of item to remove.
- get_unique_errors(errors: List[ErrorDetails]) List[ErrorDetails]¶
A function to get the list of unique errors.
Parameters¶
- errors: List[ErrorDetails]
The list of pydantic’s error details
Returns¶
List[ErrorDetails]
- validate_with_policy(model: Type[FLYNCBaseModel], data: Any, path) Tuple[FLYNCBaseModel | None, List[ErrorDetails]]¶
Helper function to perform model validation from the given data, collect errors with different severity and perform action based on severity.
For minor/major errors the offending field is removed from the working data via
delete_at_loc()and validation is retried, so that the model can still be constructed without the invalid field. The loop continues until either validation succeeds, a fatal error is encountered, or no further progress can be made (all error locations already removed).Parameters¶
- modelType[FLYNCBaseModel]
Flync model class.
- dataAny
Data to validate and instantiate the model with.
Returns¶
- Tuple[Optional[FLYNCBaseModel], List]
Tuple with optional model instance and list of errors.
Raises¶
ValidationError
- has_validators(model_type: type[FLYNCBaseModel]) bool¶
Check if a model class has @model_validator or @field_validator decorators.
- Args:
model_type (type[FLYNCBaseModel]): The model class to inspect.
- Returns:
bool: True if the model has any validators.
flync.core.validators¶
address¶
Validators for VLAN identifiers and unicast/multicast MAC and IP addresses.
- before_validate_mac_address(value: Any) Any¶
Pre-validation for MAC address fields with user-friendly error messages.
Catches common mistakes before pydantic_extra_types processes the value: - Integer input (e.g. YAML parses 001122334455 as an int) - None - String without separators (e.g. “aabbccddeeff”)
- validate_vlan_id(value)¶
Validate a VLAN identifier.
Noneis treated as untagged and returned unchanged. Values in the range 0-4094 are accepted as-is. The reserved value 4095 is accepted but emits a warning viawarn(). Anything outside 0-4095 raises a minor validation error.
- validate_mac_unicast(input: str) str¶
Custom Validator for Unicast MAC addresses.
- Args:
input (str): MAC address to validate.
- Raises:
err_minor: Input is not a Unicast address based on the expected format.
- Returns:
Any: Input is handed over.
- validate_mac_multicast(input: str) Any¶
Custom Validator for Multicast MAC addresses.
- Args:
input (str): MAC address to validate.
- Raises:
err_minor: Input is not a Multicast address based on the expected format.
- Returns:
Any: Input is handed over.
- validate_ip_multicast(input: IPv4Address | IPv6Address | str) Any¶
Custom Validator for Multicast IP addresses.
- Args:
input (
IPv4Address|IPv6Address): IP address to validate.- Raises:
err_minor: Input is not a Multicast address based on the expected format.
- Returns:
Any: Input is handed over.
- validate_any_multicast_address(input: IPv4Address | IPv6Address | str) Any¶
Custom Validator for Multicast MAC or IP addresses.
- Args:
input (
IPv4Address|IPv6Address| str): IP address or MAC Address to validate.- Raises:
err_minor: The address is not a multicast address.
- Returns:
Any: Input is handed over.
- validate_multicast_list_only_ip(input_list: list)¶
Custom Validator for a list of Multicast IP addresses.
- Args:
input_list (list): List of only Multicast IPs.
- Raises:
err_minor: Any of the addresses in the list is not an IP multicast address.
- validate_multicast_list(input_list: list)¶
Custom Validator for a list of Multicast MAC or IP addresses.
- Args:
input_list (list): List of Multicast IPs and MACs.
- Raises:
err_minor: Any of the addresses in the list is not a multicast address.
bit_ranges¶
Validators for bit-range placement inside PDUs and CAN/LIN frames, plus the value/from_value/to_value input-format check.
- collect_bit_ranges(items: Iterable[Any], get_range: Callable[[Any], Tuple[str, int, int] | None]) List[Tuple[str, int, int]]¶
Build a list of
(name, start_bit, end_bit_exclusive)ranges fromitems.get_range(item)is called for every entry and should return either a(name, start_bit, end_bit_exclusive)tuple orNonewhen the item is unplaced and should be skipped (e.g. aSignalInstancewith nobit_position).
- check_bit_ranges_within(context: str, ranges: Iterable[Tuple[str, int, int]], max_bits: int) None¶
Raise
err_minor()when any range extends pastmax_bits.contextis a human-readable label of the container (PDU or frame name) used in the error message.
- check_bit_ranges_no_overlap(context: str, ranges: List[Tuple[str, int, int]]) None¶
Raise
err_minor()when any two ranges inrangesintersect.Ranges are half-open
[start, end); two ranges overlap whenstart_a < end_b and start_b < end_a.contextis included in the error message to identify the enclosing PDU or frame.
- validate_value_input_format(data: dict) dict¶
Validating combinations of ‘value’, ‘from_value’ and ‘to_value’.
connection_compatibility¶
Validators for the compatibility of interface/connection settings between two components: MII, MACsec, gPTP, HTB, CBS/ingress streams and VLAN uniqueness.
- validate_ingress_streams_fields(streams, location: str)¶
Raise err_minor if any stream carries an ipv or ats value.
locationis a human-readable label such as"compute node"or"controller interface"used in the error message.
- validate_vlan_ids_unique(virtual_interfaces, name: str)¶
Raise err_major if any VLAN ID appears more than once.
- validate_cbs_idleslopes_fit_portspeed(traffic_classes: list, port_speed: int)¶
Custom Validator for a list of Traffic Classes to check conformity to MII/MDI speed.
- Args:
traffic_classes (list): List of element type TrafficClass.
port_speed (int): MII or MDI speed of the port.
- Raises:
err_major: The sum of idleslopes of all shapers on one port must be equal or lower than the port speed.
- Returns:
list: Return list of traffic classes as received.
- validate_optional_mii_config_compatibility(comp1, comp2, id)¶
Custom validator for optional MII configuration compatibility between two components.
- Args:
comp1 (object): First component that may contain a
mii_configattribute.comp2 (object): Second component that may contain a
mii_configattribute.id (Any): Identifier of the connection (used only in error messages).
- Raises:
err_major: One component has an MII config while the other does not.
err_major: Both components have an MII config but the mode values are identical. The modes must differ.
err_major: Both components have an MII config but the speed values are different.
err_major: Both components have an MII config but the type values are different.
- validate_compulsory_mii_config_compatibility(comp1, comp2, id)¶
Validator that enforces a mandatory MII configuration on both components and then checks optional compatibility.
- Args:
comp1 (object): First component. Must have
mii_config.comp2 (object): Second component. Must have
mii_config.id (Any): Identifier of the connection (used only in error messages).
- Raises:
err_major: Either component is missing a required MII configuration.
err_major: Propagated from
validate_optional_mii_config_compatibility()when the optional checks fail.
- validate_htb(comp, speed)¶
Validator that checks an HTB (Hierarchical Token Bucket) configuration against the physical link speed.
- Args:
comp (object): Component that owns an
htbattribute withchild_classes.speed (int): Link speed of the interface (same unit as the HTB rates).
- Raises:
err_major: The sum of the
ratevalues of all child classes exceeds the providedspeed.
- validate_macsec(comp1, comp2, id)¶
Validator for MACsec configuration compatibility between two components.
- Args:
comp1 (object): First component: May contain a
macsec_config.comp2 (object): Second component: May contain a
macsec_config.id (Any): Identifier of the connection (used only in error messages).
- Raises:
err_major: One component has a MACsec config while the other does not.
err_major: MKA (Key Agreement) enabled state differs between the two components.
err_major:
macsec_modediffers between the two components.
- validate_gptp(comp1, comp2, id)¶
Validator that checks gPTP (generic Precision Time Protocol) configuration compatibility between two components.
- Args:
comp1 (object): First component. May contain a
ptp_config.comp2 (object): Second component. May contain a
ptp_config.id (Any): Identifier of the connection (used only in error messages).
- Raises:
err_major: PTP configuration present on one side only.
err_major: Mismatch of the
cmlds_linkport_enabledflag between the two components.err_major: Propagated from
validate_gptp_domains()when domain level checks fail.
- validate_gptp_domains(comp1, comp2, ptp1, ptp2, id)¶
Helper that validates matching PTP domains and sync-config types between two components.
- Args:
comp1 (object): First component (source of
ptp1).comp2 (object): Second component (source of
ptp2).ptp1 (object):
ptp_configofcomp1.ptp2 (object):
ptp_configofcomp2.id (Any): Identifier of the connection (used only in error messages).
- Raises:
err_major: A domain present in
ptp1is missing inptp2.err_major: The
sync_config.typeof a matching domain is identical on both sides (they must differ for a valid configuration).
forwarder¶
Workspace-level validators for PDU forwarders and PDU sender/receiver socket deployments (forwarder-based or standalone).
- validate_forwarder_refs(model: FLYNCModel) None¶
Workspace pass: resolve every forwarder’s PDU / frame / extract refs and assert payload-fit on CAN egresses.
- validate_pdu_deployment_refs(model: FLYNCModel) None¶
Workspace pass: every pdu_sender / pdu_receiver
pdu_refmust name a PDU declared undercommunication.channels.Any PDU kind is a valid target (Standard, Multiplexed, or Container). The pass covers all deployments, whether they take part in a forwarder chain or are standalone senders/receivers.
- validate_forwarder_locality(model: FLYNCModel) None¶
Workspace pass: assert every egress is same-controller and the target carries the matching
pdu_sender/sender_frames.
- detect_forwarder_cycles(model: FLYNCModel) None¶
Workspace pass: three-color DFS over the forwarder graph; raises
err_majorwith the cycle path on a back-edge.
generic¶
Generic reusable validators for FLYNC models: sub-model and list removal
validators, plus helpers to turn None/singletons into lists and to check
uniqueness and element membership.
- validate_or_remove(label: str, field_type: Any, severity: str = 'minor')¶
Factory that returns a BeforeValidator for sub-model fields.
Use inside
Annotatedto pre-validate a field before Pydantic processes it. If the raw data fails validation all sub-errors are packed into a single error."minor"severity: the field is removed and the parent model still loads without it.The message says “Removing {label}…”.
"major"severity: the parent model will fail regardless (the field is required).The message reports the validation failure without implying graceful removal.
The parent object’s
namefield is included in the error message when available viainfo.data.Parameters¶
- labelstr
Human-readable field label used in the error message.
- field_typeAny
Pydantic-compatible type to validate the data against.
- severitystr, optional
Error severity —
"minor"(default) or"major".
Returns¶
- Callable
A two-argument validator
(data, info)ready for use withBeforeValidator.
- validate_list_items_and_remove(label: str, item_type: Any, severity: str = 'minor')¶
Validate each item in a list individually, removing only invalid entries.
Unlike
validate_or_remove(), which discards the entire list when any item fails, this validator keeps valid items and removes only those that fail validation. Per-item errors are forwarded to the_validation_warningschannel so they appear in the final error report even though the model continues building with the remaining valid items.Use inside
Annotatedas aBeforeValidator.Parameters¶
- labelstr
Human-readable field label used in error messages.
- item_typeAny
Pydantic-compatible type for each individual list item.
- severitystr, optional
Error severity for removed items —
"minor"(default) or"major".
Returns¶
- Callable
A two-argument validator
(data, info)ready for use withBeforeValidator.
- validate_list_items_unique(input_list: list, list_label: str | None = None) list¶
Custom Validator for a list of items where every item should be unique.
- Args:
input_list (list): List of items.
list_label(str): Add an optional label to the error message.
- Raises:
err_major: List contains duplicates.
- Returns:
list: Input is handed over.
- validate_elements_in(subset: Iterable[Any], superset: Iterable[Any], msg: str | None = None)¶
Custom Validator that checks if every element in subset appears at least once in superset. E.g. Validate if port_name is in switch_port_names.
- Args:
subset (Iterable[Any]): Subset where elements are expected to be in superset.
superset (Iterable[Any]): Reference set.
- Returns:
Iterable[Any]: Return subset as received.
- none_to_empty_list(v, info=None)¶
Make the field defined as optional [] if accidentally declared by the user as None.
- single_to_list(v)¶
Accept a single item where a list is expected and wrap it into a one-element list.
Used for fields that started out as a single sub-model and later grew into a list, so that YAML written in the old single-mapping form keeps loading.
Noneand existing list/tuple values are returned unchanged.
interface¶
Workspace-level validators for bus interface frame references (CAN / CAN FD and LIN).
Complements flync.core.validators.forwarder, which resolves forwarder references only.
The passes here cover the plain sender_frames / receiver_frames declarations of the bus
interfaces, plus the interface’s own bus_ref, so that a dangling id or a CAN interface pointing at
a LIN bus (or vice versa) is reported instead of silently ignored.
- validate_interface_frame_refs(model: FLYNCModel) None¶
Workspace pass: every CAN / LIN interface must name a declared bus of its own kind and resolve its frame refs.
The check is a plain lookup - is this frame id declared on this bus - performed against the catalog of the interface’s own bus kind. Both aspects are load-bearing:
Scoped by bus, because a CAN id is only unique within a bus: id
0x100onCAN1and onCAN2are two different frames, which is whyCANFrameRefcarries abus_refnext to theframe_ref. Asking only whether an id exists somewhere would accept an interface onCAN1declaring a frame that only exists onCAN2.Scoped by bus kind, because
bus_refis a plain string andframe_refa plain int - the type system stops aLINFrameReffrom landing in aCANInterface, but nothing stops a CAN interface from naming a LIN bus. Resolving a CAN interface againstcan_busesonly is what catches that, so no separate cross-kind rule is needed: the LIN bus name simply is not in the CAN catalog. A single catalog merged over both kinds would instead accept LIN ids on a CAN interface, and would be ambiguous anyway - bus names are unique per kind but not across kinds, so a workspace may hold a CAN bus and a LIN bus of the same name.A bus kind whose catalog is empty is skipped: FLYNC supports partial models (an ECU or controller may be modeled without the bus catalog it will later be wired into), and there is nothing to resolve against. Once a workspace declares buses of a kind, every interface of that kind must resolve.
state_management¶
Cross-model validation for state management groups.
Invoked from a model_validator on FLYNCModel.
The derived effective member set per group lives on each
StateManagementGroup
as _effective_members (PrivateAttr). The members are collected by
collect_effective_members().
ECU and controller-level memberships are pre-populated during
ECU.model_post_init(); bus-level memberships are added by that function.
- validate_state_management(model: FLYNCModel) None¶
Run all state management rules. Called from FLYNCModel.
traffic_classes¶
Validators for traffic classes in a controller interface or switch: unique priorities, PCPs and internal priority values (ipvs).
- check_prio_unique(traffic_classes)¶
Check if the traffic class prios are unique across various traffic classes in a controller interface or switch.
- check_pcps_different(traffic_classes)¶
Check if the PCPs are different across traffic classes.
- check_ipvs_unique(traffic_classes)¶
Check if ipvs across traffic classes are unique.
- validate_traffic_classes(traffic_classes)¶
Validate the traffic classes in a controller interface and switch to find out if a pcp, ipv or traffic class prio is reused or not.