From 9f690c9c2057d9d9321e8b8e67fe1a1e5deeae1e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:12 +0100 Subject: [PATCH 01/57] feat(automation): compare a learned number in a condition (service) Adds the learned_value condition type to the rules schema and the Python engine. It compares a learned number with a threshold, given as a number or a learned reference, with hysteresis like balance_threshold. A missing or stale value falls back to the configured fallback. Co-Authored-By: Claude Sonnet 5.5 --- services/automation/automation_mqtt.py | 32 +++++++- .../automation/automation_rules.schema.json | 12 +-- services/automation/learned.py | 30 +++++++- services/automation/tests/test_learned.py | 77 +++++++++++++++++++ 4 files changed, 141 insertions(+), 10 deletions(-) diff --git a/services/automation/automation_mqtt.py b/services/automation/automation_mqtt.py index cbc32eb7..7fcb477b 100644 --- a/services/automation/automation_mqtt.py +++ b/services/automation/automation_mqtt.py @@ -30,8 +30,8 @@ import ha_template import regulator import sun -from learned import (LEARNABLE, LEARNED_KEY_RE, cond_learned_keys, field_kind, is_ref, learned_topic, - resolve_condition, state_value, validate_ref) +from learned import (LEARNABLE, LEARNED_KEY_RE, cond_learned_keys, evaluate_learned_value, field_kind, is_ref, + learned_number, learned_topic, resolve_condition, state_value, validate_ref) LOG = logging.getLogger("automation_mqtt") @@ -125,7 +125,7 @@ def validate_publish_topic(topic: str) -> Optional[str]: _TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$") _CONDITION_TYPES = {"balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", - "chain_finding", "chain_value", "learned_state"} + "chain_finding", "chain_value", "learned_state", "learned_value"} _CHAIN_ID_RE = re.compile(r"^[a-z0-9_]+$") _SUN_EVENTS = ("sunrise", "sunset") _SUN_OFFSET_MAX_MIN = 240 @@ -246,6 +246,22 @@ def _validate_condition(cond: dict, index: int, errors: list[str]) -> dict: if "max_age_s" in result and not _is_positive_number(result["max_age_s"]): errors.append(f"{prefix}: max_age_s must be a number above 0") result.setdefault("hold_seconds", 0) + elif ctype == "learned_value": + if not isinstance(result.get("learned"), str) or LEARNED_KEY_RE.fullmatch(result["learned"]) is None: + errors.append(f"{prefix}: learned must be a key like site/pv_reserve_w") + if result.get("comparison") not in ("above", "below"): + errors.append(f"{prefix}: comparison must be 'above' or 'below'") + if not _learned_field(result, "threshold", prefix, errors) \ + and not _number(result.get("threshold")): + errors.append(f"{prefix}: threshold must be a number") + if not _number(result.get("fallback")): + errors.append(f"{prefix}: fallback must be a number") + hysteresis = result.setdefault("hysteresis", 0) + if not _number(hysteresis) or hysteresis < 0: + errors.append(f"{prefix}: hysteresis must be a number from 0") + if "max_age_s" in result and not _is_positive_number(result["max_age_s"]): + errors.append(f"{prefix}: max_age_s must be a number above 0") + result.setdefault("hold_seconds", 0) elif ctype == "sun_window": for key in ("from", "to"): if result.get(key) not in _SUN_EVENTS: @@ -898,6 +914,9 @@ def evaluate_condition_raw(cond: dict, *, balance: Optional[dict], topic_values: value, _ = state_value(cond, topic_values, now_ts) return value == cond["equals"], "" + if ctype == "learned_value": + return evaluate_learned_value(cond, topic_values, now_ts), "" + if ctype in ("topic_value", "entity_value") and cond.get("comparison") == "stale": age = _topic_age(cond, topic_seen_at, started_at, now_ts) if age is None: @@ -985,6 +1004,10 @@ def condition_value(cond: dict, *, balance: Optional[dict], topic_values: dict, value, _ = state_value(cond, topic_values, now_ts) return value, cond["equals"] + if ctype == "learned_value": + value, _ = learned_number(cond, topic_values, now_ts) + return value, cond.get("threshold") + if ctype == "topic_value": payload = topic_values.get(cond["topic"]) numeric = cond["comparison"] in ("above", "below") @@ -1188,6 +1211,9 @@ def _evaluate_one(cond: dict, cond_rt: ConditionRuntime, *, balance, topic_value latched = _apply_hysteresis(cond, cond_rt, balance) if latched is not None: raw_met = latched + if cond["type"] == "learned_value" and cond.get("hysteresis", 0) > 0: + raw_met = evaluate_learned_value(cond, topic_values, now_ts, latched=cond_rt.latched) + cond_rt.latched = raw_met if not raw_met: cond_rt.since = None diff --git a/services/automation/automation_rules.schema.json b/services/automation/automation_rules.schema.json index 460d351e..83ea2726 100644 --- a/services/automation/automation_rules.schema.json +++ b/services/automation/automation_rules.schema.json @@ -89,7 +89,7 @@ "additionalProperties": true, "required": ["type"], "properties": { - "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state"] }, + "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state", "learned_value"] }, "field": {"type": "string"}, "comparison": { "type": "string", "enum": ["above", "below", "equals", "not_equals", "stale"] }, "threshold": {}, @@ -108,7 +108,7 @@ "from_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "to_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "month_days": {"type": "array", "items": {"type": "integer", "minimum": 1, "maximum": 31}, "description": "Day of the month 1 to 31. Empty means every day. The day on which the window starts counts, even across midnight."}, "max_age_s": {"type": "number", "exclusiveMinimum": 0, "description": "Only for comparison stale: seconds since the last message on topic after which the condition is met."}, "weekdays": { "type": "array", "items": { "type": "integer", "minimum": 0, "maximum": 6 }, "description": "0 = Monday … 6 = Sunday. Empty means every day. The day on which the window starts counts, even across midnight." } - }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"const": "balance_threshold"}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] + }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "learned_value"]}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state", "learned_value"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}, {"if": {"properties": {"type": {"const": "learned_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "comparison", "threshold", "fallback"], "properties": {"type": {"const": "learned_value"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "comparison": {"type": "string", "enum": ["above", "below"]}, "threshold": {}, "fallback": {"type": "number"}, "hysteresis": {"type": "number", "minimum": 0}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] } } } @@ -129,7 +129,7 @@ "additionalProperties": true, "required": ["type"], "properties": { - "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state"] }, + "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state", "learned_value"] }, "field": {"type": "string"}, "comparison": { "type": "string", "enum": ["above", "below", "equals", "not_equals", "stale"] }, "threshold": {}, @@ -148,7 +148,7 @@ "from_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "to_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "month_days": {"type": "array", "items": {"type": "integer", "minimum": 1, "maximum": 31}, "description": "Day of the month 1 to 31. Empty means every day. The day on which the window starts counts, even across midnight."}, "max_age_s": {"type": "number", "exclusiveMinimum": 0, "description": "Only for comparison stale: seconds since the last message on topic after which the condition is met."}, "weekdays": { "type": "array", "items": { "type": "integer", "minimum": 0, "maximum": 6 }, "description": "0 = Monday … 6 = Sunday. Empty means every day. The day on which the window starts counts, even across midnight." } - }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"const": "balance_threshold"}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] + }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "learned_value"]}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state", "learned_value"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}, {"if": {"properties": {"type": {"const": "learned_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "comparison", "threshold", "fallback"], "properties": {"type": {"const": "learned_value"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "comparison": {"type": "string", "enum": ["above", "below"]}, "threshold": {}, "fallback": {"type": "number"}, "hysteresis": {"type": "number", "minimum": 0}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] } } }, @@ -696,7 +696,7 @@ "additionalProperties": true, "required": ["type"], "properties": { - "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state"] }, + "type": { "type": "string", "enum": ["balance_threshold", "topic_value", "time_window", "entity_value", "sun_window", "chain_finding", "chain_value", "learned_state", "learned_value"] }, "field": {"type": "string"}, "comparison": { "type": "string", "enum": ["above", "below", "equals", "not_equals", "stale"] }, "threshold": {}, @@ -715,7 +715,7 @@ "from_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "to_offset_min": { "type": "integer", "minimum": -240, "maximum": 240, "default": 0 }, "month_days": {"type": "array", "items": {"type": "integer", "minimum": 1, "maximum": 31}, "description": "Day of the month 1 to 31. Empty means every day. The day on which the window starts counts, even across midnight."}, "max_age_s": {"type": "number", "exclusiveMinimum": 0, "description": "Only for comparison stale: seconds since the last message on topic after which the condition is met."}, "weekdays": { "type": "array", "items": { "type": "integer", "minimum": 0, "maximum": 6 }, "description": "0 = Monday … 6 = Sunday. Empty means every day. The day on which the window starts counts, even across midnight." } - }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"const": "balance_threshold"}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] + }, "allOf": [{"if": {"properties": {"type": {"const": "chain_finding"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "kind"], "properties": {"type": {"const": "chain_finding"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "kind": {"type": "string", "enum": ["any", "drift", "frozen", "contradiction", "sign", "unit"]}, "points": {"type": "array", "items": {"type": "string"}}, "min_age_s": {"type": "number", "minimum": 0, "maximum": 86400}, "once": {"type": "boolean"}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "chain_id", "field", "comparison", "value"], "properties": {"type": {"const": "chain_value"}, "chain_id": {"type": "string", "pattern": "^[a-z0-9_]+$"}, "field": {"type": "string", "enum": ["loss_w", "efficiency_pct", "standby_w"]}, "comparison": {"type": "string", "enum": ["above", "below"]}, "value": {"type": "number"}, "hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400}}}}, {"if": {"properties": {"type": {"const": "chain_value"}}, "required": ["type"]}, "else": {"properties": {"field": {"type": "string", "pattern": "^(grid_export|grid_import|pv|load_total|base|wallbox|heat_pump|battery_charge|battery_discharge|gap_applied|autarkie|eigenverbrauch|battery_soc|battery_capacity_kwh|battery_energy_kwh|custom:[a-z0-9_]+)$"}}}}, {"if": {"properties": {"threshold": {"type": "object"}}, "required": ["threshold"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "learned_value"]}, "threshold": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"threshold": {"type": "number"}}}}, {"if": {"properties": {"value": {"type": "object"}}, "required": ["value"]}, "then": {"required": ["comparison"], "properties": {"type": {"enum": ["topic_value", "entity_value"]}, "comparison": {"enum": ["above", "below"]}, "value": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"value": {"type": "number"}}}}, {"if": {"properties": {"start": {"type": "object"}}, "required": ["start"]}, "then": {"properties": {"type": {"const": "time_window"}, "start": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"start": {"type": "string"}}}}, {"if": {"properties": {"end": {"type": "object"}}, "required": ["end"]}, "then": {"properties": {"type": {"const": "time_window"}, "end": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "max": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "fallback": {"type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"}, "offset": {"type": "integer", "minimum": -720, "maximum": 720}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"end": {"type": "string"}}}}, {"if": {"properties": {"hold_seconds": {"type": "object"}}, "required": ["hold_seconds"]}, "then": {"properties": {"type": {"enum": ["balance_threshold", "topic_value", "entity_value", "time_window", "sun_window", "learned_state", "learned_value"]}, "hold_seconds": {"type": "object", "additionalProperties": false, "required": ["learned", "min", "max", "fallback"], "properties": {"learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "min": {"type": "number"}, "max": {"type": "number"}, "fallback": {"type": "number"}, "offset": {"type": "number"}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}}}}}, "else": {"properties": {"hold_seconds": {"type": "number", "minimum": 0, "maximum": 86400, "default": 0}}}}, {"if": {"properties": {"type": {"const": "learned_state"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "equals", "fallback"], "properties": {"type": {"const": "learned_state"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "equals": {"type": "string", "minLength": 1}, "fallback": {"type": "string", "minLength": 1}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}, {"if": {"properties": {"type": {"const": "learned_value"}}, "required": ["type"]}, "then": {"additionalProperties": false, "required": ["type", "learned", "comparison", "threshold", "fallback"], "properties": {"type": {"const": "learned_value"}, "learned": {"type": "string", "pattern": "^(device/[^/#+\\s]{1,96}|site)/[a-z0-9_]{1,40}$"}, "comparison": {"type": "string", "enum": ["above", "below"]}, "threshold": {}, "fallback": {"type": "number"}, "hysteresis": {"type": "number", "minimum": 0}, "max_age_s": {"type": "number", "exclusiveMinimum": 0}, "hold_seconds": {}}}}] } }, "actions": { diff --git a/services/automation/learned.py b/services/automation/learned.py index d5225633..50769e31 100644 --- a/services/automation/learned.py +++ b/services/automation/learned.py @@ -28,6 +28,7 @@ "time_window": ("start", "end", "hold_seconds"), "sun_window": ("hold_seconds",), "learned_state": ("hold_seconds",), + "learned_value": ("threshold", "hold_seconds"), } _TIME_FIELDS = ("start", "end") @@ -212,9 +213,36 @@ def state_value(cond: dict, topic_values: dict, now_ts: float) -> tuple[str, str return value, "learned" +def learned_number(cond: dict, store: dict, now_ts: float) -> tuple[float, str]: + """Zahl einer `learned_value`-Bedingung als (Wert, Herkunft). Fehlt oder altert + der Lernwert, gilt `fallback`. Anders als bei Bezugsangaben wird nicht geklemmt.""" + payload = store.get(learned_topic(cond["learned"])) + value = _fresh_value(payload, "number", now_ts, cond.get("max_age_s", DEFAULT_MAX_AGE_S)) + if value is None: + return cond["fallback"], "fallback" + return value, "learned" + + +def evaluate_learned_value(cond: dict, store: dict, now_ts: float, latched: bool = False) -> bool: + """Vergleicht den Lernwert mit der Schwelle. `store` bildet Topics auf den + Payload-Text ab, wie topic_values in der Engine. Eine Schwelle als Bezugsangabe + wird hier aufgeloest. Mit hysteresis > 0 zaehlt `latched`, der Zustand der letzten + Auswertung: wahr bleibt wahr, bis der Wert um die Hysterese zurueckfaellt (wie + balance_threshold).""" + value, _ = learned_number(cond, store, now_ts) + threshold = cond["threshold"] + if is_ref(threshold): + threshold, _ = resolve_ref(threshold, "number", store.get(learned_topic(threshold["learned"])), now_ts) + hysteresis = cond.get("hysteresis", 0) + held = latched and hysteresis > 0 + if cond["comparison"] == "above": + return value >= threshold - hysteresis if held else value > threshold + return value <= threshold + hysteresis if held else value < threshold + + def cond_learned_keys(cond: dict) -> set[str]: keys: set[str] = set() - if cond.get("type") == "learned_state" and isinstance(cond.get("learned"), str): + if cond.get("type") in ("learned_state", "learned_value") and isinstance(cond.get("learned"), str): keys.add(cond["learned"]) for field in LEARNABLE.get(cond.get("type"), ()): ref = cond.get(field) diff --git a/services/automation/tests/test_learned.py b/services/automation/tests/test_learned.py index 52e2c514..2a9b41ce 100644 --- a/services/automation/tests/test_learned.py +++ b/services/automation/tests/test_learned.py @@ -158,3 +158,80 @@ def test_hold_seconds_may_be_learned_on_time_window_and_sun_window(): assert learned.cond_learned_keys({"type": "time_window", "hold_seconds": hold}) == {"site/hold_s"} assert learned.cond_learned_keys({"type": "sun_window", "hold_seconds": hold}) == {"site/hold_s"} assert learned.cond_learned_keys({"type": "chain_finding", "hold_seconds": hold}) == set() + + +NOW = 1_800_000_000.0 + + +def _store(key, value, age_s=0): + return {learned.learned_topic(key): json.dumps({"value": value, "n": 1, "at": NOW - age_s})} + + +def _lv(**extra): + cond = {"type": "learned_value", "learned": "site/pv_reserve_w", "comparison": "above", + "threshold": 1500, "fallback": 0, "max_age_s": 1800, "hold_seconds": 0} + cond.update(extra) + return cond + + +def test_learned_value_above_threshold_is_met(): + assert learned.evaluate_learned_value(_lv(), _store("site/pv_reserve_w", 1600), NOW) is True + + +def test_learned_value_missing_uses_fallback_zero_and_is_not_met(): + assert learned.evaluate_learned_value(_lv(), {}, NOW) is False + + +def test_learned_value_older_than_max_age_uses_fallback(): + store = _store("site/pv_reserve_w", 1600, age_s=2000) + assert learned.evaluate_learned_value(_lv(), store, NOW) is False + assert learned.learned_number(_lv(), store, NOW) == (0, "fallback") + + +def test_learned_value_fallback_above_threshold_counts_as_met(): + assert learned.evaluate_learned_value(_lv(fallback=2000), {}, NOW) is True + + +def test_learned_value_hysteresis_keeps_met_until_value_drops_below_band(): + cond = _lv(hysteresis=100) + met = learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 1600), NOW) + assert met is True + still = learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 1450), NOW, latched=met) + assert still is True + dropped = learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 1390), NOW, latched=still) + assert dropped is False + + +def test_learned_value_without_hysteresis_ignores_latched_state(): + cond = _lv(hysteresis=0) + assert learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 1450), NOW, latched=True) is False + + +def test_learned_value_below_comparison_with_hysteresis(): + cond = _lv(comparison="below", threshold=500, hysteresis=50) + assert learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 540), NOW, latched=True) is True + assert learned.evaluate_learned_value(cond, _store("site/pv_reserve_w", 560), NOW, latched=True) is False + + +def test_learned_value_threshold_as_reference_resolves_on_cycle_wh(): + ref = {"learned": "device/wallbox_1/cycle_wh", "min": 500, "max": 3000, "fallback": 1000} + cond = _lv(threshold=ref) + store = _store("device/wallbox_1/cycle_wh", 1200) + assert learned.evaluate_learned_value(cond, {**store, **_store("site/pv_reserve_w", 1250)}, NOW) is True + assert learned.evaluate_learned_value(cond, {**store, **_store("site/pv_reserve_w", 1100)}, NOW) is False + assert "device/wallbox_1/cycle_wh" in learned.cond_learned_keys(cond) + assert "site/pv_reserve_w" in learned.cond_learned_keys(cond) + + +def test_learned_value_invalid_key_is_a_validation_error(): + import automation_mqtt + errors = [] + automation_mqtt._validate_condition(_lv(learned="site/../pv"), 0, errors) + assert any("learned must be a key" in e for e in errors) + + +def test_learned_value_validation_accepts_the_documented_form(): + import automation_mqtt + errors = [] + automation_mqtt._validate_condition(_lv(hysteresis=100), 0, errors) + assert errors == [] From da541e8cc7175f13b68f63086f0ebed95c726a87 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:21:19 +0100 Subject: [PATCH 02/57] feat(autolearn): parse the learned_value condition The compared learned key, its fallback and max_age_s are read under learned, a threshold reference is read like the other learned fields. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/rules.go | 29 +++++++++++++ dashboard/internal/autolearn/rules_test.go | 49 ++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index 53226929..448ce30e 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -33,6 +33,7 @@ type Rule struct { // balance_threshold, Value from value of a topic_value or entity_value, // HoldSeconds from hold_seconds. A field that holds a learned value is not a // number: it stays 0 or nil here and is listed in Learned under its field name. +// The value a learned_value condition compares is listed under learned. // Raw keeps the original JSON of the condition. type Condition struct { Type string @@ -143,6 +144,14 @@ type wireCondition struct { HoldSeconds json.RawMessage `json:"hold_seconds"` } +// wireLearnedValue holds the top level learned key of a learned_value +// condition, the value it compares, with its fallback and max age. +type wireLearnedValue struct { + Learned string `json:"learned"` + Fallback any `json:"fallback"` + MaxAgeS float64 `json:"max_age_s"` +} + // wireLearnedRef mirrors the JSON of a learned reference. type wireLearnedRef struct { Learned string `json:"learned"` @@ -267,6 +276,11 @@ func parseCondition(rawCond json.RawMessage) (Condition, error) { if _, err := learnedRef(wc.End, "end", learned); err != nil { return Condition{}, err } + if wc.Type == "learned_value" { + if err := learnedValueRef(rawCond, learned); err != nil { + return Condition{}, err + } + } condition := Condition{ Type: wc.Type, Field: wc.Field, Comparison: wc.Comparison, Topic: wc.Topic, EntityID: wc.EntityID, Hysteresis: wc.Hysteresis, Value: value, HoldSeconds: holdSeconds, @@ -298,6 +312,21 @@ func number(raw json.RawMessage, name string, learned map[string]LearnedRef) (*f return &n, nil } +// learnedValueRef records the key a learned_value condition compares under +// learned, with its top level fallback and max_age_s. Without a key nothing is +// recorded. +func learnedValueRef(rawCond json.RawMessage, learned map[string]LearnedRef) error { + var wv wireLearnedValue + if err := json.Unmarshal(rawCond, &wv); err != nil { + return err + } + if wv.Learned == "" { + return nil + } + learned["learned"] = LearnedRef{Key: wv.Learned, Fallback: wv.Fallback, MaxAgeS: wv.MaxAgeS} + return nil +} + // learnedRef records raw under name when it is a learned reference and reports // whether it was one. // An object is a reference only with a non empty text under learned, as the diff --git a/dashboard/internal/autolearn/rules_test.go b/dashboard/internal/autolearn/rules_test.go index 12d2b4c4..1895e43e 100644 --- a/dashboard/internal/autolearn/rules_test.go +++ b/dashboard/internal/autolearn/rules_test.go @@ -416,3 +416,52 @@ func TestParseDocReadsRegulatorSpec(t *testing.T) { t.Errorf("scenario without regulator = %+v, want nil", doc.Scenarios[2].Regulator) } } + +// A learned_value condition keeps the key it compares under learned, with its +// top level fallback and max_age_s. A threshold may be a reference of its own. +func TestParseLearnedValueRules(t *testing.T) { + doc, err := ParseDoc([]byte(`{"rules":[{"id":"r","name":"R","enabled":true,"conditions":[` + + `{"type":"learned_value","learned":"site/pv_reserve_w","comparison":"above","threshold":1500,` + + `"fallback":0,"hysteresis":100,"max_age_s":120,"hold_seconds":30},` + + `{"type":"learned_value","learned":"site/pv_reserve_w","comparison":"below",` + + `"threshold":{"learned":"device/wallbox_1/cycle_wh","min":500,"max":3000,"fallback":1500,"offset":10},` + + `"fallback":0}` + + `],"actions":[]}]}`)) + if err != nil { + t.Fatalf("ParseDoc: %v", err) + } + conds := doc.Rules[0].Conditions + if len(conds) != 2 { + t.Fatalf("conditions = %d, want 2", len(conds)) + } + + plain := conds[0] + if plain.Type != "learned_value" || plain.Comparison != "above" || plain.Threshold != 1500 || plain.Hysteresis != 100 { + t.Errorf("plain condition = %+v", plain) + } + if plain.HoldSeconds == nil || *plain.HoldSeconds != 30 { + t.Errorf("HoldSeconds = %v, want 30", plain.HoldSeconds) + } + ref := plain.Learned["learned"] + if ref.Key != "site/pv_reserve_w" || ref.Fallback != float64(0) || ref.MaxAgeS != 120 { + t.Errorf("compared value reference = %+v", ref) + } + if _, ok := plain.Learned["threshold"]; ok { + t.Errorf("plain threshold is a reference, want a number") + } + if !strings.Contains(string(plain.Raw), `"max_age_s":120`) { + t.Errorf("Raw = %s, want the original condition JSON", plain.Raw) + } + + bound := conds[1] + if bound.Comparison != "below" || bound.Threshold != 0 { + t.Errorf("bound condition = %+v", bound) + } + thr := bound.Learned["threshold"] + if thr.Key != "device/wallbox_1/cycle_wh" || thr.Min != float64(500) || thr.Max != float64(3000) || thr.Fallback != float64(1500) || thr.Offset != 10 { + t.Errorf("threshold reference = %+v", thr) + } + if bound.Learned["learned"].Key != "site/pv_reserve_w" { + t.Errorf("compared value reference = %+v", bound.Learned["learned"]) + } +} From 672ca294956ad344b3322e0a18c0ce9e494d368b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:25:19 +0100 Subject: [PATCH 03/57] feat(automations): edit the learned_value condition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add learned_value as a condition type in the automations editor. The condition reads as "PV reserve above 1500 W" (German: "PV-Reserve über 1500 W") and gets a learned chip with its origin. The threshold offers learned values in the unit of the learned key, or of its reference. Catalogs in German and English gain the new labels. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 5 ++ dashboard/internal/webui/catalogs/en.json | 5 ++ .../webui/static/js/automation-learned.js | 14 +++- .../webui/static/js/automations-view.js | 21 +++++- .../webui/static/js/automations.page.js | 17 ++++- dashboard/test/automation-learned.test.mjs | 67 ++++++++++++++++++- dashboard/test/automations.page.test.mjs | 8 +-- 7 files changed, 125 insertions(+), 12 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 51622798..a0e80164 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -369,6 +369,7 @@ "automations.condition_type.entity.label": "Gerätewert", "automations.condition_type.entity.short": "Temperatur, Zustand", "automations.condition_type.learned_state.short": "Haus", + "automations.condition_type.learned_value.short": "Lernwert", "automations.condition_type.sun.hint": "Gilt zwischen Sonnenaufgang und Sonnenuntergang oder umgekehrt, jeweils mit Versatz in Minuten. Braucht den Standort in den Einstellungen.", "automations.condition_type.sun.label": "Sonnenzeit", "automations.condition_type.sun.short": "Auf- und Untergang", @@ -664,6 +665,8 @@ "automations.learned.state.now": "Jetzt {state}. Gelernt aus {n} Tagen, aktualisiert vor {age}.", "automations.learned.state.quiet": "Haus ist ruhig", "automations.learned.state.stale": "Der letzte Wert ist älter als {age}. Es gilt: {state}.", + "automations.learned.value.condition": "Lernwert", + "automations.learned.value.help": "Ein gelernter Zahlwert, etwa die PV-Reserve, gegen eine feste Schwelle oder eine andere Bezugsangabe. Ohne frischen Wert gilt die Ersatzwahl.", "automations.learned.year.line": "Der Wert lag im {high_month} bei {high} und im {low_month} bei {low}", "automations.limit.rules": "Höchstens {max} Regeln", "automations.limit.scenarios": "Höchstens {max} Szenarien", @@ -874,6 +877,8 @@ "automations.summary.chain_value": "{field} {comparison} {value} {unit}", "automations.summary.entity_value": "{comparison} {expected}", "automations.summary.entity_value_unit": "{comparison} {expected} {unit}", + "automations.summary.learned_value": "{name} {comparison} {threshold} {unit}", + "automations.summary.learned_value_hysteresis": "{name} {comparison} {threshold} {unit}, Hysterese {hysteresis}", "automations.summary.topic_value": "{comparison} {expected}", "automations.sun_event.sunrise": "Sonnenaufgang", "automations.sun_event.sunset": "Sonnenuntergang", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 77225b18..a036ed41 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -369,6 +369,7 @@ "automations.condition_type.entity.label": "Device value", "automations.condition_type.entity.short": "Temperature, state", "automations.condition_type.learned_state.short": "House", + "automations.condition_type.learned_value.short": "Learned value", "automations.condition_type.sun.hint": "Applies between sunrise and sunset or the other way round, each with an offset in minutes. Needs the location in the settings.", "automations.condition_type.sun.label": "Sun time", "automations.condition_type.sun.short": "Sunrise and sunset", @@ -664,6 +665,8 @@ "automations.learned.state.now": "Now {state}. Learned from {n} days, updated {age} ago.", "automations.learned.state.quiet": "House is quiet", "automations.learned.state.stale": "The last value is older than {age}. This applies: {state}.", + "automations.learned.value.condition": "Learned value", + "automations.learned.value.help": "A learned number, such as the PV reserve, compared with a fixed threshold or another reference. Without a fresh value the fallback applies.", "automations.learned.year.line": "The value was {high} in {high_month} and {low} in {low_month}", "automations.limit.rules": "At most {max} rules", "automations.limit.scenarios": "At most {max} scenarios", @@ -874,6 +877,8 @@ "automations.summary.chain_value": "{field} {comparison} {value} {unit}", "automations.summary.entity_value": "{comparison} {expected}", "automations.summary.entity_value_unit": "{comparison} {expected} {unit}", + "automations.summary.learned_value": "{name} {comparison} {threshold} {unit}", + "automations.summary.learned_value_hysteresis": "{name} {comparison} {threshold} {unit}, hysteresis {hysteresis}", "automations.summary.topic_value": "{comparison} {expected}", "automations.sun_event.sunrise": "Sunrise", "automations.sun_event.sunset": "Sunset", diff --git a/dashboard/internal/webui/static/js/automation-learned.js b/dashboard/internal/webui/static/js/automation-learned.js index 12d45362..ba6010c5 100644 --- a/dashboard/internal/webui/static/js/automation-learned.js +++ b/dashboard/internal/webui/static/js/automation-learned.js @@ -21,7 +21,7 @@ pv_reserve_w: 'automations.learned.key.pv_reserve_w', surplus_left_wh: 'automations.learned.key.surplus_left_wh', }; - const FIELD_KIND = { start: 'time', end: 'time', hold_seconds: 'duration', threshold: 'number', value: 'number' }; + const FIELD_KIND = { start: 'time', end: 'time', hold_seconds: 'duration', threshold: 'number', value: 'number', learned: 'number' }; const LEARNABLE = { balance_threshold: ['threshold', 'hold_seconds'], topic_value: ['value', 'hold_seconds'], @@ -29,6 +29,8 @@ time_window: ['start', 'end', 'hold_seconds'], sun_window: ['hold_seconds'], learned_state: ['hold_seconds'], + // learned ist der gelernte Zahlwert selbst, threshold darf eine Bezugsangabe sein. + learned_value: ['learned', 'threshold', 'hold_seconds'], }; const norm = (m) => ((m % DAY) + DAY) % DAY; @@ -111,6 +113,14 @@ return fields.includes(field) ? FIELD_KIND[field] : null; } + // Einheit aus dem Namensende eines Lernwerts: _w ist W, _wh ist Wh, sonst keine. + function unitOfKey(key) { + const name = String(key || ''); + if (name.endsWith('_wh')) return 'Wh'; + if (name.endsWith('_w')) return 'W'; + return ''; + } + // Vorbelegung der Bezugsangabe aus dem festen Wert. Ohne gueltigen Wert keine Vorbelegung. function prefill(kind, value) { if (kind === 'time') { @@ -326,5 +336,5 @@ return coords.length >= YEAR_MIN_WEEKS ? coords.join(' ') : null; } - window.AutomationLearned = { isRef, kindOf, resolve, prefill, choices, keyLabel, validate, origin, valueSuffix, scale, yearLine, yearPlot }; + window.AutomationLearned = { isRef, kindOf, resolve, prefill, choices, keyLabel, unitOfKey, validate, origin, valueSuffix, scale, yearLine, yearPlot }; })(); diff --git a/dashboard/internal/webui/static/js/automations-view.js b/dashboard/internal/webui/static/js/automations-view.js index 7e07c6dc..b4ac209d 100644 --- a/dashboard/internal/webui/static/js/automations-view.js +++ b/dashboard/internal/webui/static/js/automations-view.js @@ -81,7 +81,7 @@ return event.reason ? [{ kind: 'reason', title: '', text: event.reason }] : []; } - // i18n-keys: automations.condition_type.balance.hint, automations.condition_type.balance.label, automations.condition_type.entity.hint, automations.condition_type.entity.label, automations.condition_type.sun.hint, automations.condition_type.sun.label, automations.condition_type.time.hint, automations.condition_type.time.label, automations.condition_type.learned_state.short, automations.learned.state.condition, automations.learned.state.help + // i18n-keys: automations.condition_type.balance.hint, automations.condition_type.balance.label, automations.condition_type.entity.hint, automations.condition_type.entity.label, automations.condition_type.sun.hint, automations.condition_type.sun.label, automations.condition_type.time.hint, automations.condition_type.time.label, automations.condition_type.learned_state.short, automations.condition_type.learned_value.short, automations.learned.state.condition, automations.learned.state.help, automations.learned.value.condition, automations.learned.value.help // Was der Bearbeiten-Modus als Bedingung anbieten darf. "balance" heisst // bewusst Energiewert und nicht PV-Ueberschuss: der Typ balance_threshold // deckt jedes Bilanzfeld ab - Netzbezug, Autarkiegrad, Batterie-Fuellstand -, @@ -102,6 +102,9 @@ // kommen aus den Lernwert-Texten, die Kurzform hat eigene Texte. { key: 'learned_state', icon: 'ico-learning', label: 'automations.learned.state.condition', hint: 'automations.learned.state.help', short: 'automations.condition_type.learned_state.short' }, + // Gelernter Zahlwert gegen eine feste Schwelle oder eine Bezugsangabe, etwa die PV-Reserve. + { key: 'learned_value', icon: 'ico-learning', label: 'automations.learned.value.condition', + hint: 'automations.learned.value.help', short: 'automations.condition_type.learned_value.short' }, ]; // i18n-keys: automations.chain.signal.finding, automations.chain.signal.loss_w, automations.chain.signal.efficiency_pct, automations.chain.signal.standby_w, automations.chain.kind.any, automations.chain.once, automations.chain.min_age, automations.chain.missing, automations.summary.chain_finding, automations.summary.chain_value, diagnostics.rule.chain_drift.title, diagnostics.rule.chain_frozen.title, diagnostics.rule.chain_contradiction.title, diagnostics.rule.chain_sign.title, diagnostics.rule.chain_unit.title @@ -345,7 +348,8 @@ function learnedValue(condition, field, learned) { const AL = window.AutomationLearned; const cond = condition || {}; - const ref = cond.type === 'learned_state' && field === 'learned' + // learned_state und learned_value tragen den Lernwert flach am Typ. + const ref = (cond.type === 'learned_state' || cond.type === 'learned_value') && field === 'learned' ? { learned: cond.learned, fallback: cond.fallback, max_age_s: cond.max_age_s } : cond[field]; if (!AL || !AL.isRef(ref)) return null; @@ -478,6 +482,19 @@ return { icon: 'ico-sun', title: t('automations.sun_window'), unit: '', summary: `${from} – ${to}${weekdaySuffix(condition)}` }; } + if (type === 'learned_value') { + // Einheit: die der Schwelle, wenn sie eine Bezugsangabe ist, sonst die des Lernwerts. + const AL = window.AutomationLearned; + const thresholdKey = AL && AL.isRef(condition.threshold) ? condition.threshold.learned : condition.learned; + const unit = AL ? AL.unitOfKey(thresholdKey) : ''; + const name = AL ? AL.keyLabel(condition.learned, learned && learned.devices, t) : String(condition.learned || ''); + const comparison = t(COMPARISON_WORDS[condition.comparison] || condition.comparison); + const threshold = shownValue(condition, 'threshold', learned); + const summaryKey = condition.hysteresis ? 'automations.summary.learned_value_hysteresis' : 'automations.summary.learned_value'; + // i18n-keys: automations.summary.learned_value, automations.summary.learned_value_hysteresis + const summary = t(summaryKey, { name, comparison, threshold, unit, hysteresis: condition.hysteresis }).trim(); + return { icon: 'ico-learning', title: t('automations.learned.value.condition'), unit, summary }; + } if (type === 'learned_state') { const state = condition.equals === 'active' ? 'automations.learned.state.active' : 'automations.learned.state.quiet'; return { icon: 'ico-learning', title: t('automations.learned.state.condition'), unit: '', summary: t(state) }; diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index d7a88bf6..96673add 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -2348,6 +2348,12 @@ hold_seconds: Math.max(LEARNED_STATE_HOLD_S, this.minPublishInterval()) }); }, + // Gelernter Zahlwert: PV-Reserve ueber 1500 W, mit Hysterese und Ersatzwert. Der Ausgangswert entspricht dem Beispiel im Plan. + addLearnedValueCondition(rule) { + rule.conditions.push({ type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold: 1500, + hysteresis: 100, fallback: 0, max_age_s: 1800, hold_seconds: 0 }); + }, + // Eintrag des Endpunkts zu einem Lernwert-Schluessel, sonst null. learnedEntry(key) { return this.learnedList().find((value) => value && value.key === key) || null; @@ -2388,6 +2394,12 @@ // Einheit der Lernwerte fuer ein Zahlfeld: Schwellen in W, sonst die Einheit der Entitaet. learnUnitOf(condition, field) { if (this.learnKind(condition, field) !== 'number') return undefined; + // Der gelernte Zahlwert selbst nimmt jede Einheit, die Schwelle die des Lernwerts oder ihrer Bezugsangabe. + if (field === 'learned') return undefined; + if (condition.type === 'learned_value') { + const ref = isRefValue(condition.threshold) ? condition.threshold.learned : condition.learned; + return window.AutomationLearned.unitOfKey(ref) || undefined; + } if (field === 'threshold') return 'W'; const entity = this.entityForCondition(condition); return (entity && entity.unit_of_measurement) || undefined; @@ -2535,7 +2547,9 @@ const kind = AL.kindOf(condition.type, field); if (kind && AL.isRef(condition[field])) codes.push(...AL.validate(condition[field], kind)); } - if (condition.type === 'learned_state') codes.push(...AL.validate({ learned: condition.learned }, 'state')); + if (condition.type === 'learned_state' || condition.type === 'learned_value') { + codes.push(...AL.validate({ learned: condition.learned }, 'state')); + } const keys = { 'learned.min_max': 'automations.learned.error.min_max', 'learned.fallback_range': 'automations.learned.error.fallback_range', @@ -2716,6 +2730,7 @@ if (key === 'time') result = this.addTimeWindowCondition(rule); if (key === 'sun') result = this.addSunWindowCondition(rule); if (key === 'learned_state') result = this.addLearnedStateCondition(rule); + if (key === 'learned_value') result = this.addLearnedValueCondition(rule); if (key === 'chain') result = this.addChainCondition(rule); this.loadEditLive(rule); return result; diff --git a/dashboard/test/automation-learned.test.mjs b/dashboard/test/automation-learned.test.mjs index b24b8660..1e14522b 100644 --- a/dashboard/test/automation-learned.test.mjs +++ b/dashboard/test/automation-learned.test.mjs @@ -16,20 +16,33 @@ const vectors = JSON.parse(fs.readFileSync( const viewSource = fs.readFileSync(path.join(jsDir, 'automations-view.js'), 'utf8'); +const deCatalog = JSON.parse(fs.readFileSync(path.join(here, '..', 'internal', 'webui', 'catalogs', 'de.json'), 'utf8')); +// Die Oberflaeche uebersetzt mit dem deutschen Katalog, so stehen die Saetze der Karte im Test wie im Editor. +function translate(key, params) { + let text = Object.prototype.hasOwnProperty.call(deCatalog, key) ? deCatalog[key] : key; + for (const [name, value] of Object.entries(params || {})) text = text.split(`{${name}}`).join(String(value)); + return text; +} + function load() { const dom = new JSDOM('', { runScripts: 'outside-only' }); const context = dom.getInternalVMContext(); // Monatsnamen des Jahresverlaufs kommen aus der Sprache der Oberflaeche. - dom.window.I18n = { locale: 'de-DE', formatDate: (value, options) => new Date(value).toLocaleDateString('de-DE', options) }; + dom.window.I18n = { + locale: 'de-DE', + formatDate: (value, options) => new Date(value).toLocaleDateString('de-DE', options), + t: translate, + }; vm.runInContext(source, context); // origin formats the age with the view's formatSeconds, so the view loads into the same window. vm.runInContext(viewSource, context); - return dom.window.AutomationLearned; + return dom.window; } // Results come from the vm realm, so they are copied into this realm before strict comparison. const plain = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v))); -const raw = load(); +const win = load(); +const raw = win.AutomationLearned; const L = Object.fromEntries(Object.entries(raw).map(([name, fn]) => [name, (...args) => plain(fn(...args))])); const t = (key, params) => (params ? key + ' ' + JSON.stringify(params) : key); @@ -278,3 +291,51 @@ test('origin adds the other programs of a cycle energy value', () => { assert.equal(L.origin('learned', { ...entry, programs: undefined }, 1000 + 3600, t).endsWith('}'), true); assert.equal(L.origin('fallback', null, 0, t), 'automations.learned.origin.fallback'); }); + +test('kindOf maps the learned_value fields to their kind', () => { + assert.equal(L.kindOf('learned_value', 'learned'), 'number'); + assert.equal(L.kindOf('learned_value', 'threshold'), 'number'); + assert.equal(L.kindOf('learned_value', 'hold_seconds'), 'duration'); + assert.equal(L.kindOf('learned_value', 'fallback'), null); + assert.equal(L.kindOf('learned_value', 'comparison'), null); +}); + +test('unitOfKey reads the unit from the key suffix', () => { + assert.equal(L.unitOfKey('site/pv_reserve_w'), 'W'); + assert.equal(L.unitOfKey('device/wb/cycle_wh'), 'Wh'); + assert.equal(L.unitOfKey('site/house_state'), ''); +}); + +test('a learned_value threshold offers only values in the unit of the learned key', () => { + const values = [ + { key: 'site/pv_reserve_w', kind: 'number', unit: 'W' }, + { key: 'device/wb/cycle_wh', kind: 'number', unit: 'Wh' }, + ]; + const kind = L.kindOf('learned_value', 'threshold'); + assert.deepEqual(L.choices(values, kind, L.unitOfKey('site/pv_reserve_w')).map((v) => v.key), ['site/pv_reserve_w']); + assert.deepEqual(L.choices(values, L.kindOf('learned_value', 'learned')).map((v) => v.key), + ['site/pv_reserve_w', 'device/wb/cycle_wh']); +}); + +test('a learned_value condition reads as PV-Reserve über 1500 W', () => { + const condition = { type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold: 1500, + hysteresis: 0, fallback: 0, max_age_s: 1800, hold_seconds: 0 }; + const card = win.__automationsView.describeCondition(condition, null, [], [], null); + assert.equal(card.icon, 'ico-learning'); + assert.equal(card.title, 'Lernwert'); + assert.equal(card.summary, 'PV-Reserve über 1500 W'); +}); + +test('a learned_value condition with hysteresis names the hysteresis', () => { + const condition = { type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold: 1500, + hysteresis: 100, fallback: 0, max_age_s: 1800, hold_seconds: 0 }; + const card = win.__automationsView.describeCondition(condition, null, [], [], null); + assert.equal(card.summary, 'PV-Reserve über 1500 W, Hysterese 100'); +}); + +test('a learned_value threshold given as a reference shows the resolved value in its own chip', () => { + const condition = { type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', + threshold: { learned: 'device/wb/cycle_wh', min: 800, max: 1200, fallback: 1000 }, fallback: 0, max_age_s: 1800, hold_seconds: 0 }; + const card = win.__automationsView.describeCondition(condition, null, [], [], null); + assert.equal(card.summary, 'PV-Reserve über 1000 Wh'); +}); diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 258fe087..7c6a17b7 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -1234,12 +1234,12 @@ test('save frischt den Geraetekatalog auf, bevor es die Auto-Praefixe bildet', a // --- Typ-Kacheln und Hilfetexte ------------------------------------------- -test('CONDITION_TYPES liefert genau die fuenf anbietbaren Bedingungstypen', () => { +test('CONDITION_TYPES liefert genau die sechs anbietbaren Bedingungstypen', () => { const { component } = createAutomationsPanel(); const types = component.conditionTypes(); // Spread statt direktem .map()-Vergleich: das Array kommt aus dem vm-Sandbox- // Realm der Komponente, deepEqual vergleicht sonst auch das Array-Prototyp. - assert.deepEqual([...types.map((entry) => entry.key)], ['balance', 'entity', 'time', 'sun', 'learned_state']); + assert.deepEqual([...types.map((entry) => entry.key)], ['balance', 'entity', 'time', 'sun', 'learned_state', 'learned_value']); assert.equal(types[0].label, 'Energiewert'); for (const entry of types) { assert.ok(entry.icon.startsWith('ico-'), `${entry.key} hat kein Sprite-Icon`); @@ -3125,10 +3125,10 @@ const testChains = [{ test('the chain tile is hidden without chains and shows with one', () => { const { component } = createAutomationsPanel(); - assert.deepEqual([...component.conditionTypes().map((entry) => entry.key)], ['balance', 'entity', 'time', 'sun', 'learned_state']); + assert.deepEqual([...component.conditionTypes().map((entry) => entry.key)], ['balance', 'entity', 'time', 'sun', 'learned_state', 'learned_value']); component.chains = [...testChains]; const keys = [...component.conditionTypes().map((entry) => entry.key)]; - assert.deepEqual(keys, ['balance', 'entity', 'time', 'sun', 'chain', 'learned_state']); + assert.deepEqual(keys, ['balance', 'entity', 'time', 'sun', 'chain', 'learned_state', 'learned_value']); const tile = component.conditionTypes().find((entry) => entry.key === 'chain'); assert.equal(tile.icon, 'ico-chain'); assert.equal(tile.label, 'Messkette'); From ae0c8e13da3595b89f9bc8630761639c176df8d8 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:26:49 +0100 Subject: [PATCH 04/57] feat(automations): edit the learned_value fields in the rule card Add the editor block for learned_value: learned value picker, comparison, threshold (fixed or learned reference), hysteresis, fallback, max age and hold. The condition defaults to a half hour hold, like learned_state, so a rule with a publish action passes the hold check. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 1 + dashboard/internal/webui/catalogs/en.json | 1 + .../webui/static/js/automations.page.js | 15 +++++- .../webui/templates/automations-rows.html | 45 ++++++++++++++++ dashboard/test/automations.page.test.mjs | 53 +++++++++++++++++++ 5 files changed, 114 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index a0e80164..fe75659a 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -667,6 +667,7 @@ "automations.learned.state.stale": "Der letzte Wert ist älter als {age}. Es gilt: {state}.", "automations.learned.value.condition": "Lernwert", "automations.learned.value.help": "Ein gelernter Zahlwert, etwa die PV-Reserve, gegen eine feste Schwelle oder eine andere Bezugsangabe. Ohne frischen Wert gilt die Ersatzwahl.", + "automations.learned.value.max_age": "Wert gilt höchstens", "automations.learned.year.line": "Der Wert lag im {high_month} bei {high} und im {low_month} bei {low}", "automations.limit.rules": "Höchstens {max} Regeln", "automations.limit.scenarios": "Höchstens {max} Szenarien", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index a036ed41..56c61a8b 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -667,6 +667,7 @@ "automations.learned.state.stale": "The last value is older than {age}. This applies: {state}.", "automations.learned.value.condition": "Learned value", "automations.learned.value.help": "A learned number, such as the PV reserve, compared with a fixed threshold or another reference. Without a fresh value the fallback applies.", + "automations.learned.value.max_age": "Value counts for at most", "automations.learned.year.line": "The value was {high} in {high_month} and {low} in {low_month}", "automations.limit.rules": "At most {max} rules", "automations.limit.scenarios": "At most {max} scenarios", diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 96673add..8208f2d6 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -2351,7 +2351,20 @@ // Gelernter Zahlwert: PV-Reserve ueber 1500 W, mit Hysterese und Ersatzwert. Der Ausgangswert entspricht dem Beispiel im Plan. addLearnedValueCondition(rule) { rule.conditions.push({ type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold: 1500, - hysteresis: 100, fallback: 0, max_age_s: 1800, hold_seconds: 0 }); + hysteresis: 100, fallback: 0, max_age_s: 1800, + hold_seconds: Math.max(LEARNED_STATE_HOLD_S, this.minPublishInterval()) }); + }, + + // Lernwerte fuer das Feld learned eines gelernten Zahlwerts. Der gewaehlte Schluessel bleibt auch ohne Eintrag sichtbar. + learnedValueOptions(condition) { + const AL = window.AutomationLearned; + const options = this.learnedChoices(condition, 'learned') + .map((entry) => ({ key: entry.key, label: AL.keyLabel(entry.key, this.devices, t) })); + const key = condition.learned; + if (key && !options.some((option) => option.key === key)) { + options.push({ key, label: AL.keyLabel(key, this.devices, t) }); + } + return options; }, // Eintrag des Endpunkts zu einem Lernwert-Schluessel, sonst null. diff --git a/dashboard/internal/webui/templates/automations-rows.html b/dashboard/internal/webui/templates/automations-rows.html index 84a9da21..08bdbe84 100644 --- a/dashboard/internal/webui/templates/automations-rows.html +++ b/dashboard/internal/webui/templates/automations-rows.html @@ -160,6 +160,51 @@ + +