plesty.lib.device.params ======================== .. py:module:: plesty.lib.device.params .. autoapi-nested-parse:: Configuration parameter system for Plesty device models. Attributes ---------- .. autoapisummary:: plesty.lib.device.params._PARSER_KINDS Classes ------- .. autoapisummary:: plesty.lib.device.params.AutoResponseParser plesty.lib.device.params.RegexResponseParser plesty.lib.device.params.DelimitedResponseParser plesty.lib.device.params.Command plesty.lib.device.params.ConfigParameter plesty.lib.device.params.ConfigGroup plesty.lib.device.params.ConfigSystem Functions --------- .. autoapisummary:: plesty.lib.device.params._as_text plesty.lib.device.params.register_parser_kind plesty.lib.device.params.parser_kinds plesty.lib.device.params.resolve_parser Module Contents --------------- .. py:class:: AutoResponseParser Bases: :py:obj:`plesty.lib.device.device_utils.ResponseParser` A response parser that autocasts raw responses to the expected data type. .. py:method:: __call__(response, param=None, separator=',', **kwargs) Attempt to autocast a value to the specified data type. Supported types include basic types (int, float, str, bool) and iterable types like List[int], Tuple[float], etc. For iterable types, if the input is a string, it will be split by the specified separator. :param response: The raw response value to be cast. :param param: The config parameter providing the target dtype. :param separator: Separator for splitting string inputs for iterable types. :param \*\*kwargs: Additional keyword arguments (unused). .. py:function:: _as_text(response: Any, encoding: str) -> str Return *response* as text so a pattern or a separator can be applied to it. :param response: The raw device reply. :param encoding: Codec used when the reply arrives as bytes, as it does over serial. .. py:class:: RegexResponseParser(pattern: str, group: int | str = 1, encoding: str = 'utf-8') Bases: :py:obj:`plesty.lib.device.device_utils.ResponseParser` A response parser that takes the value out of a reply carrying text around it. The captured text is handed to :class:`AutoResponseParser`, so the parameter's declared ``dtype`` still performs the conversion — the pattern only decides which characters are the value. :param pattern: Regular expression searched in the raw response. :param group: Capture group holding the value, by number or by name. Group ``0`` is the whole match. :param encoding: Codec used to decode a bytes response before matching. :raises ValueError: If the pattern is invalid or names a group it does not define. Both are raised here, at registration, rather than on the first query. Compile *pattern* and check *group* against it. .. py:attribute:: group :value: 1 .. py:attribute:: encoding :value: 'utf-8' .. py:attribute:: _auto .. py:method:: parse(response, param=None, **kwargs) -> Any Return the captured text of *response*, cast to the parameter dtype. .. py:class:: DelimitedResponseParser(index: int = 0, separator: str = ',', encoding: str = 'utf-8') Bases: :py:obj:`plesty.lib.device.device_utils.ResponseParser` A response parser that keeps one field of a delimited reply. :class:`AutoResponseParser` already splits a reply when the parameter's dtype is a list or a tuple. This parser covers the other case: the reply carries several fields and the parameter is a single one of them. :param index: Zero-based field to keep. Negative indices count from the end. :param separator: String the reply is split on. :param encoding: Codec used to decode a bytes response before splitting. :raises ValueError: If the index is not an integer or the separator is empty. Check the field selection before any reply arrives. .. py:attribute:: index :value: 0 .. py:attribute:: separator :value: ',' .. py:attribute:: encoding :value: 'utf-8' .. py:attribute:: _auto .. py:method:: parse(response, param=None, **kwargs) -> Any Return the selected field of *response*, cast to the parameter dtype. .. py:data:: _PARSER_KINDS :type: dict[str, Callable[Ellipsis, plesty.lib.device.device_utils.ResponseParser]] .. py:function:: register_parser_kind(name: str, factory: Callable[Ellipsis, plesty.lib.device.device_utils.ResponseParser]) -> None Make *factory* available to schemas as ``"parser": {"kind": name, ...}``. A device whose reply the built-in kinds cannot describe — a binary frame, a reply keyed by mnemonic — registers its own parser once, and every parameter then names it from the schema. The decoding rule stays next to ``command`` and ``unit`` instead of being re-solved per parameter in the solver. :param name: Kind name as written in a schema. :param factory: Callable returning a :class:`ResponseParser`. Schema keys other than ``kind`` are passed to it as keyword arguments. :raises ValueError: If *name* already names a different factory. .. py:function:: parser_kinds() -> list[str] Return the response parser kinds a schema can currently name. .. py:function:: resolve_parser(parser: Any) -> plesty.lib.device.device_utils.ResponseParser | None Turn a schema ``parser`` value into a :class:`ResponseParser` instance. Accepts what a schema can hold — a kind name, or a mapping of a ``kind`` and its configuration — as well as a ``ResponseParser`` instance passed from Python, which is returned unchanged. :param parser: ``None``, a kind name, a ``{"kind": ..., ...}`` mapping, or a ``ResponseParser`` instance. :returns: The parser instance, or ``None`` when no parser was configured. :raises ValueError: If the kind is unknown or its configuration is rejected. :raises TypeError: If the value is of a type a schema cannot resolve. .. py:class:: Command Represents a command that can be sent to the device. .. py:attribute:: name :type: str .. py:attribute:: command :type: str .. py:attribute:: required_params :type: List[str] | None :value: None .. py:attribute:: optional_params :type: List[str] | None :value: None .. py:attribute:: mode :type: str :value: 'write' .. py:attribute:: description :type: str | None :value: None .. py:class:: ConfigParameter Represents a single configuration parameter for a device. .. py:attribute:: name :type: str .. py:attribute:: default :type: Any :value: None .. py:attribute:: value :type: Any :value: None .. py:attribute:: dtype :type: type | Any :value: None .. py:attribute:: unit :type: str | None :value: None .. py:attribute:: read_only :type: bool :value: False .. py:attribute:: write_only :type: bool :value: False .. py:attribute:: min_value :type: float | int | None :value: None .. py:attribute:: max_value :type: float | int | None :value: None .. py:attribute:: options :type: list[Any] | None :value: None .. py:attribute:: command :type: str | Command | None :value: None .. py:attribute:: parser :type: plesty.lib.device.device_utils.ResponseParser | None :value: None .. py:attribute:: description :type: str | None :value: None .. py:class:: ConfigGroup Represents a group of configuration parameters for a device. .. py:attribute:: name :type: str .. py:attribute:: parameters :type: Dict[str, ConfigParameter] .. py:attribute:: command_prefix :type: str :value: '' .. py:attribute:: allowed_commands :type: List[Command] :value: [] .. py:attribute:: description :type: str | None :value: None .. py:class:: ConfigSystem(param_schema=None, solver=None) Manage configuration parameters, groups, and validation rules. Initialize with optional schema and command solver. .. py:attribute:: _config .. py:attribute:: auto_parser .. py:attribute:: _cmd_solver :value: None .. py:method:: _parse_command(command: Any) -> str | Command | None :staticmethod: Parse command field from schema. .. py:method:: _register_param_dict(params: dict[str, Any], group_name: str) -> None Register all parameters in a schema dictionary into the target group. .. py:method:: register_params_from_schema(schema: str | dict[str, Any]) -> list[str] Register parameters and groups from a schema path or dictionary. Supported schema shapes: 1) Flat parameters (registered to default group): .. code-block:: json { "param_a": { "type": "float", "default": 1.0 } } 2) Group map: .. code-block:: json { "group_a": { "description": "Example group", "command_prefix": "CFG", "allowed_commands": [ { "name": "set_mode", "command": "MODE", "mode": "write" } ], "parameters": { "param_a": { "type": "float", "default": 1.0 } } } } 3) Wrapped group map under "groups": .. code-block:: json { "groups": { "group_a": { "parameters": { "param_a": { "type": "float" } } } } } :returns: Registered parameter keys. :rtype: list[str] .. py:method:: register_config(key: str, group: str = 'default', default: Any = None, dtype: type | Any = None, unit: str | None = None, read_only: bool = False, write_only: bool = False, min_value: float | int | None = None, max_value: float | int | None = None, options: list[Any] | None = None, command: str | Command | None = None, parser: Any = None, description: str | None = None) -> ConfigParameter Register one configuration parameter after validating constraints. ``parser`` accepts what a schema can hold — a kind name such as ``"regex"``, or a ``{"kind": ..., ...}`` mapping — as well as a :class:`ResponseParser` instance; it is resolved to an instance here. Returns the registered ``ConfigParameter`` and raises if the key already exists in the group or the provided metadata is invalid. .. py:method:: _validate_config_param(param: ConfigParameter) -> None Check the validity of the parameter. .. py:method:: register_config_group(group_name: str, command_prefix: str = '', allowed_commands: List[Command] | None = None, parameters: Dict[str, ConfigParameter] | None = None, description: str | None = None) -> ConfigGroup Register a named group of related configuration parameters. Returns the registered ``ConfigGroup`` and raises if the group already exists or if any provided parameter metadata is invalid. .. py:method:: _check_register_min_max(min_value: float | int | None, max_value: float | int | None) -> None Check the validity of min and max values for a numeric parameter. .. py:method:: _check_type(param: ConfigParameter, value: Any) -> None Check if a value matches the expected data type for a parameter. .. py:method:: _check_in_range(param: ConfigParameter, value: float | int) -> None Check if a numeric value is within the allowed range for a parameter. .. py:method:: _check_in_options(param: ConfigParameter, value: Any) -> None Check if a categorical value is within the allowed options for a parameter. .. py:method:: _group_prefix(group: str) -> str Return the external prefix used in full keys. .. py:method:: _to_full_key(group: str, key: str) -> str Convert internal group/key to public full_key format. .. py:method:: _resolve_key(key: str, group: str = 'default') -> tuple[str, str] Resolve external key to (group_name, param_key). Grouped parameters must use full_key format ``group_prefix.param_key``. .. py:method:: get_config_list(group: str = 'default') -> list[str] Return registered configuration keys. For grouped schemas, keys are returned in full_key format ``group_prefix.param_key``. .. py:method:: get_group_list() -> list[str] Return a list of registered configuration group names. .. py:method:: get_group(group: str) -> ConfigGroup Retrieve a registered configuration group by name. .. py:method:: parameter_docs() -> dict[str, list[ConfigParameter]] Return the registered parameters grouped by configuration group. :returns: Mapping of group name to its :class:`ConfigParameter` objects, for documentation rendering. Empty groups are omitted. .. py:method:: get_config(key: str, group: str = 'default') -> ConfigParameter Retrieve a registered configuration parameter by key. .. py:method:: set_config_value(key: str, value: Any, group: str = 'default') -> None Set the value of a registered configuration parameter. .. py:method:: set_config_min_max(key: str, min_value: float | int | None, max_value: float | int | None, group: str = 'default') -> None Set the minimum and maximum allowed values for a numeric configuration parameter. .. py:method:: get_config_value(key: str, group: str = 'default') -> Any Get the current value of a registered configuration parameter. .. py:method:: check_write_config(key: str, value: Any, group: str = 'default') -> None Check if a value can be written to a configuration parameter. .. py:method:: check_query_config(key: str, group: str = 'default') -> None Check if a configuration parameter can be queried. .. py:method:: param_summary(constraints: bool = True, description: bool = False, style: str = 'short', include_title: bool = True, filename=None) -> str Return parameter summary in short, markdown, or Google-style format. :param constraints: Include range/options metadata where available. :param description: Include parameter descriptions. :param style: One of ``short``, ``md``, or ``google``. :param include_title: Whether to include a title header in the output. :param filename: Optional output file path. :returns: Rendered summary text.