From 5248b058a0332e784e78432fdccfd586e3ca45d1 Mon Sep 17 00:00:00 2001 From: Jumpmaster2 Date: Thu, 3 Dec 2026 14:28:00 +0000 Subject: [PATCH 1/2] Visit: warm the floor continuously before the visit (1.0.0b26) - Warm-floor areas run continuously for 60 min before a planned visit (window max(60 min, dead time + preheat reserve)), also at night and without a heating day; spontaneous visits get the hour from activation. - Warmup stops above visit target + 1.0 K; pulses keep +visit_floor_max_over. - First 2 h of a visit: at least 30 min floor run per hour. - Visit activation and warmup progress persisted across restarts. - New status visit_warmup, texts, AI prompt, docs, tests. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + README.en.md | 6 +- README.md | 6 +- .../house_assistant/frontend/heating.js | 1 + .../house_assistant/frontend/labels.js | 24 +- .../house_assistant/heating/coordinator.py | 96 ++++++-- .../heating/logic/controller.py | 22 +- .../house_assistant/heating/logic/prompts.py | 14 +- .../house_assistant/heating/logic/visit.py | 46 ++++ .../house_assistant/heating/messages.py | 4 + .../house_assistant/manifest.json | 2 +- .../house_assistant/strings.json | 7 +- .../house_assistant/translations/de.json | 7 +- .../house_assistant/translations/en.json | 7 +- docs/heating.en.md | 8 + docs/heating.md | 8 + tests/core/test_visit.py | 220 +++++++++++++++++- tests/heating/logic/test_visit.py | 106 ++++++++- tests/logic/test_storage.py | 15 +- 19 files changed, 548 insertions(+), 58 deletions(-) create mode 100644 custom_components/house_assistant/heating/logic/visit.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 29c0b24..f5341cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 1.0.0b26 (2026-12-03) + +### Fixed + +- Warm-floor visit areas now heat continuously before a planned visit for at least 60 minutes (or dead time plus reserve if longer), including at night and without a heating day. Spontaneous visits get one hour from activation; activation and completion survive restarts, avoiding duplicate warmups. Warmup ends above visit target + 1 K and keeps all safety and minimum switching rules. +- Floor pulses run at least 30 minutes per hour during the first two visit hours, then use the configured duration (default 15). Night pauses and the configured pulse temperature cap still apply. Added the translated `visit_warmup` status and updated panel help, AI prompts and heating documentation. + ## 1.0.0b25 (2026-12-01) ### Fixed diff --git a/README.en.md b/README.en.md index cb44da9..c81fc32 100644 --- a/README.en.md +++ b/README.en.md @@ -114,9 +114,9 @@ Messages go to the notification services of the house, without any as a notifica So guests in the living area do not get cold feet, even when its underfloor heating hardly ever runs: * **Switch Visit** on the device "House Assistant" with **Visit start** and **Visit end** (`datetime`, both optional), the same rules as departure and return: on at the start, off at the end, then empty. **Binary sensor Visit active**, logbook entry at start and end. In the panel under *House > Vacation*. -* Per room in the heating **During a visit**: *keep the floor warm* (target + 0.5 K up to the maximum, and at least 15 min run time per hour, also on days without heating; no runs at night by the night time of the ventilation or while the room is more than 0.5 K above its visit target), *heat a little less* (target − 0.5 K, not below the minimum) or *unchanged*. Values in the heating settings under *Vacation and visit*. -* Ahead of a planned visit the floor is warmed earlier by the dead time and the preheat reserve, the other rooms lower only at the start. Windows, recovery after airing, frost protection and off come first; on vacation the visit has no effect. -* Status "Visit" or "Visit: warming floor", attributes `visit_active` and `visit_role` on the thermostat. The AI knows about the visit and does not counter it; visit days do not count as errors of the heating day rule. +* Per room in the heating **During a visit**: *keep the floor warm* (target + 0.5 K up to the maximum, and at least 30 min run time per hour for the first 2 h, then 15 min by default, also on days without heating; no runs at night by the night time of the ventilation or while the room is more than 0.5 K above its visit target), *heat a little less* (target − 0.5 K, not below the minimum) or *unchanged*. Values in the heating settings under *Vacation and visit*. +* Ahead of a planned visit the floor heats continuously from at least 60 min before the start, or dead time plus preheat reserve if longer, until the start. Without a completed warmup beforehand it runs for the first 60 min from activation. Warmup also runs at night and without a heating day; above visit target + 1.0 K it ends for this visit. Activation and warmup memory survive HA restarts. No new setting. Other rooms lower only at the start. Windows, recovery after airing, frost protection and off come first; on vacation the visit has no effect. +* Status "Visit", "Visit: floor warmup" or "Visit: warming floor", attributes `visit_active` and `visit_role` on the thermostat. The AI knows about the visit and does not counter it; visit days do not count as errors of the heating day rule. ## Dashboard cards diff --git a/README.md b/README.md index bbd7160..9f02c64 100644 --- a/README.md +++ b/README.md @@ -114,9 +114,9 @@ Meldungen gehen an die Benachrichtigungsdienste des Hauses, ohne sie als Benachr Damit Gäste im Wohnbereich keine kalten Füße haben, auch wenn dessen Fußbodenheizung sonst kaum läuft: * **Schalter Besuch** am Gerät „House Assistant“ mit **Besuch: von** und **Besuch: bis** (`datetime`, beide optional), dieselben Regeln wie Abreise und Rückkehr: zum Beginn an, zum Ende aus, danach leer. **Binärsensor Besuch aktiv**, Logbuch bei Beginn und Ende. Im Panel unter *Haus > Urlaub*. -* Je Raum in der Heizung **Bei Besuch**: *Fußboden warm halten* (Ziel + 0,5 K bis höchstens zum Maximum, dazu mindestens 15 min Laufzeit je Stunde, auch an Tagen ohne Heizbedarf; kein Takt nachts laut Nachtzeit der Lüftung oder wenn der Raum mehr als 0,5 K über dem Besuchsziel liegt), *etwas weniger heizen* (Ziel − 0,5 K, nicht unter das Minimum) oder *unverändert*. Werte in den Einstellungen der Heizung unter *Urlaub und Besuch*. -* Der Fußboden wird vor einem geplanten Besuch um Totzeit und Vorheiz-Reserve früher angewärmt, die anderen Räume senken erst zum Beginn ab. Fenster, Erholung nach dem Lüften, Frostschutz und Aus haben Vorrang; im Urlaub wirkt der Besuch nicht. -* Status „Besuch“ bzw. „Besuch: Fußboden warm“, Attribute `visit_active` und `visit_role` am Thermostat. Die KI kennt den Besuch und regelt nicht dagegen; Besuchstage zählen nicht als Fehler der Heiztag-Regel. +* Je Raum in der Heizung **Bei Besuch**: *Fußboden warm halten* (Ziel + 0,5 K bis höchstens zum Maximum, in den ersten 2 h mindestens 30 min Laufzeit je Stunde, danach standardmäßig 15 min, auch an Tagen ohne Heizbedarf; kein Takt nachts laut Nachtzeit der Lüftung oder wenn der Raum mehr als 0,5 K über dem Besuchsziel liegt), *etwas weniger heizen* (Ziel − 0,5 K, nicht unter das Minimum) oder *unverändert*. Werte in den Einstellungen der Heizung unter *Urlaub und Besuch*. +* Der Fußboden wird vor einem geplanten Besuch durchgehend angeheizt: Beginn minus mindestens 60 min oder Totzeit plus Vorheiz-Reserve, falls länger, bis zum Beginn. Ohne vorheriges vollständiges Anheizen läuft er die ersten 60 min ab Aktivierung. Das gilt auch nachts und ohne Heiztag; über Besuchsziel + 1,0 K wird das Anheizen für diesen Besuch beendet. Aktivierung und Anheizmerker bleiben bei einem HA-Neustart erhalten. Keine neue Einstellung. Die anderen Räume senken erst zum Beginn ab. Fenster, Erholung nach dem Lüften, Frostschutz und Aus haben Vorrang; im Urlaub wirkt der Besuch nicht. +* Status „Besuch“, „Besuch: Fußboden anheizen“ bzw. „Besuch: Fußboden warm“, Attribute `visit_active` und `visit_role` am Thermostat. Die KI kennt den Besuch und regelt nicht dagegen; Besuchstage zählen nicht als Fehler der Heiztag-Regel. ## Dashboard-Karten diff --git a/custom_components/house_assistant/frontend/heating.js b/custom_components/house_assistant/frontend/heating.js index 53e4ee8..3ad96c5 100644 --- a/custom_components/house_assistant/frontend/heating.js +++ b/custom_components/house_assistant/frontend/heating.js @@ -496,6 +496,7 @@ const STATUS_PILL = { heating: "warn", preheat: "warn", visit_floor: "warn", + visit_warmup: "warn", visit: "ok", emergency: "warn", window_open: "muted", diff --git a/custom_components/house_assistant/frontend/labels.js b/custom_components/house_assistant/frontend/labels.js index 50759a0..8a7c255 100644 --- a/custom_components/house_assistant/frontend/labels.js +++ b/custom_components/house_assistant/frontend/labels.js @@ -141,7 +141,7 @@ export const LABELS = { ], "visit_floor_minutes": [ "Besuch: Fußboden-Laufzeit je Stunde", - "So lange läuft der Kreis eines Raums mit „Fußboden warm halten“ mindestens je Stunde, damit der Boden nicht kalt ist. Nachts (Nachtzeit der Lüftung) pausiert das. 0 = nur das höhere Ziel." + "Nach dem festen Anheizen läuft der Kreis mindestens so lange je Stunde; in den ersten 2 Besuchsstunden mindestens 30 min. Takte pausieren nachts (Nachtzeit der Lüftung). 0 = danach nur das höhere Ziel. Das Anheizen läuft unabhängig davon auch nachts." ], "visit_floor_max_over": [ "Besuch: Fußboden aus ab", @@ -626,7 +626,7 @@ export const LABELS = { ], "visit_floor_minutes": [ "Besuch: Fußboden-Laufzeit je Stunde", - "So lange läuft der Kreis eines Raums mit „Fußboden warm halten“ mindestens je Stunde, damit der Boden nicht kalt ist. Nachts (Nachtzeit der Lüftung) pausiert das. 0 = nur das höhere Ziel." + "Nach dem festen Anheizen läuft der Kreis mindestens so lange je Stunde; in den ersten 2 Besuchsstunden mindestens 30 min. Takte pausieren nachts (Nachtzeit der Lüftung). 0 = danach nur das höhere Ziel. Das Anheizen läuft unabhängig davon auch nachts." ], "visit_floor_max_over": [ "Besuch: Fußboden aus ab", @@ -2619,7 +2619,8 @@ export const LABELS = { "emergency": "Notfallregel", "sensor_error": "Sensorfehler", "actuator_unavailable": "Aktor nicht erreichbar", - "no_circuit": "Kein Heizkreis" + "no_circuit": "Kein Heizkreis", + "visit_warmup": "Besuch: Fußboden anheizen" } } }, @@ -2764,7 +2765,7 @@ export const LABELS = { ], "visit_floor_minutes": [ "Visit: floor run time per hour", - "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target." + "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night." ], "visit_floor_max_over": [ "Visit: no floor runs above", @@ -3249,7 +3250,7 @@ export const LABELS = { ], "visit_floor_minutes": [ "Visit: floor run time per hour", - "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target." + "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night." ], "visit_floor_max_over": [ "Visit: no floor runs above", @@ -5242,7 +5243,8 @@ export const LABELS = { "emergency": "Emergency rule", "sensor_error": "Sensor error", "actuator_unavailable": "Actuator unavailable", - "no_circuit": "No heating circuit" + "no_circuit": "No heating circuit", + "visit_warmup": "Visit: floor warmup" } } } @@ -5734,7 +5736,7 @@ export const HEATING = { ], "visit_floor_minutes": [ "Besuch: Fußboden-Laufzeit je Stunde", - "So lange läuft der Kreis eines Raums mit „Fußboden warm halten“ mindestens je Stunde, damit der Boden nicht kalt ist. Nachts (Nachtzeit der Lüftung) pausiert das. 0 = nur das höhere Ziel." + "Nach dem festen Anheizen läuft der Kreis mindestens so lange je Stunde; in den ersten 2 Besuchsstunden mindestens 30 min. Takte pausieren nachts (Nachtzeit der Lüftung). 0 = danach nur das höhere Ziel. Das Anheizen läuft unabhängig davon auch nachts." ], "visit_floor_max_over": [ "Besuch: Fußboden aus ab", @@ -6164,7 +6166,8 @@ export const HEATING = { "emergency": "Notfallregel", "sensor_error": "Sensorfehler", "actuator_unavailable": "Aktor nicht erreichbar", - "no_circuit": "Kein Heizkreis" + "no_circuit": "Kein Heizkreis", + "visit_warmup": "Besuch: Fußboden anheizen" }, "ventilation": { "unknown": "Unbekannt", @@ -6303,7 +6306,7 @@ export const HEATING = { ], "visit_floor_minutes": [ "Visit: floor run time per hour", - "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target." + "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night." ], "visit_floor_max_over": [ "Visit: no floor runs above", @@ -6733,7 +6736,8 @@ export const HEATING = { "emergency": "Emergency rule", "sensor_error": "Sensor error", "actuator_unavailable": "Actuator unavailable", - "no_circuit": "No heating circuit" + "no_circuit": "No heating circuit", + "visit_warmup": "Visit: floor warmup" }, "ventilation": { "unknown": "Unknown", diff --git a/custom_components/house_assistant/heating/coordinator.py b/custom_components/house_assistant/heating/coordinator.py index bf70fb8..cf7c7e4 100644 --- a/custom_components/house_assistant/heating/coordinator.py +++ b/custom_components/house_assistant/heating/coordinator.py @@ -181,6 +181,9 @@ validate_nightly, ) from .logic.controller import ( + EPS, + VISIT_WARMUP_MAX_OVER, + VISIT_WARMUP_S, AreaRuntime, AreaSettings, AreaStatus, @@ -248,6 +251,7 @@ recommend, room_limits, ) +from .logic.visit import VisitState from .logic.windows import WINDOW_FIELDS, largest, open_area, own_windows, size_fields from .messages import label_of, text @@ -334,8 +338,9 @@ class Area: preheat_from: float | None = None # start of preheating for the return visit_role: str = VISIT_NONE visit: bool = False # the visit changes the target of this area now - visit_floor_from: float | None = None # start of the floor pulses for a planned visit - visit_pulses: bool = False # a floor pulse of the visit runs the circuit now + visit_floor_from: float | None = None # start of the continuous planned warmup + visit_warmup: bool = False + visit_pulses: bool = False # visit floor demand: pulse or continuous warmup decision: ControlDecision | None = None ventilation: VentilationResult | None = None status: str = AreaStatus.IDLE @@ -464,6 +469,7 @@ def __init__(self, module: HeatingModule) -> None: self._hourly_ts: float | None = None self.season_active = False self.vacation = False + self.visit_state = VisitState() self._visit_logged: set[str] = set() # areas whose floor is warmed ahead # the visit of the house (no effect on vacation): on, planned start, end self.visit = False @@ -682,6 +688,7 @@ async def _async_setup(self) -> None: **ai_schema, "vent": {**ai_schema, "history": [{"areas": {"*": {"*": optional(number)}}}]}, }, + "visit": dataclass_schema(VisitState), "sun": {"scale": optional(number)}, "meter": dataclass_schema(HeatMeter), "room_energy": room_energy_schema(), @@ -721,6 +728,7 @@ async def _async_setup(self) -> None: else: stored[key] = recovery.record(key, raw, schema) await recovery.finish() + self.visit_state = VisitState.from_dict(stored.get("visit")) self.day_state = stored.get("day", {}) self.ai_state = stored.get("ai", {}) self.budget = Budget.from_dict(self.ai_state.get("budget")) @@ -1412,6 +1420,7 @@ def _data_to_save(self) -> dict[str, Any]: } for area in self.areas.values() }, + "visit": self.visit_state.as_dict(), "day": self.day_state, "ai": self.ai_state, "sun": {"scale": self.sun_scale.value}, @@ -1459,6 +1468,7 @@ async def _async_update_data(self) -> int: visit_on, self.visit_start, self.visit_end = ( house.visit_times() if house is not None else (False, None, None) ) + self._update_visit(visit_on, ts) self.visit = visit_on and not self.vacation if self.visit and (current := self.current_day) is not None and not current.get("visit"): current["visit"] = True # the day does not count for learning the rule @@ -1856,16 +1866,29 @@ def _friendly(self, entity_id: str) -> str: state = self._state(entity_id) return str(state.attributes.get("friendly_name") or entity_id) if state else entity_id + def _update_visit(self, active: bool, ts: float) -> None: + """Persist activation and clear area memory only at the end or a new plan.""" + before = self.visit_state.as_dict() + if self.visit_state.update(active, self.visit_start, ts): + for area in self.areas.values(): + area.runtime.visit_warmup_started_at = None + area.runtime.visit_warmup_done = False + self._visit_logged.clear() + if before != self.visit_state.as_dict(): + self._save() + def _visit(self, area: Area, ts: float, learned: LearnedValues) -> tuple[float, float | None]: - """Does the visit change this area now? Sets ``area.visit``; returns the floor - pulse minutes per hour (0 at night) and how far above the target pulses stop. + """Select continuous warmup or hourly floor pulses, independently of heating day. - The floor of a warm-floor area is warmed ahead of a planned visit, by the dead - time and the preheat reserve: it should be warm when the guests arrive. + Warmup uses a wall-clock window: safety pauses do not extend it. A planned + warmup observed for a full hour avoids another hour when the visit starts. + A late/missed planned warmup gets the spontaneous hour from activation. + One tick of tolerance accounts for the minute-based control interval. """ role = str(area.cfg.get(CONF_VISIT_ROLE) or VISIT_NONE) area.visit_role = role area.visit = False + area.visit_warmup = False area.visit_floor_from = None if self.vacation or role == VISIT_NONE: return 0.0, None @@ -1874,20 +1897,40 @@ def _visit(self, area: Area, ts: float, learned: LearnedValues) -> tuple[float, return 0.0, None if role != VISIT_WARM_FLOOR: return 0.0, None + rt = area.runtime area.visit = self.visit start = self.visit_start + beginning = self.visit_state.beginning if not self.visit and start is not None and start > ts: - area.visit_floor_from = start - ( - learned.dead_time_s + float(self.opt(CONF_PREHEAT_RESERVE)) * 60 + area.visit_floor_from = start - max( + VISIT_WARMUP_S, + learned.dead_time_s + float(self.opt(CONF_PREHEAT_RESERVE)) * 60, ) area.visit = ts >= area.visit_floor_from - if area.visit and area.area_id not in self._visit_logged: - self._visit_logged.add(area.area_id) - self._log("visit_preheat", area) - if not self.visit and area.visit_floor_from is None: - self._visit_logged.discard(area.area_id) + area.visit_warmup = area.visit and not rt.visit_warmup_done + elif self.visit and beginning is not None and not rt.visit_warmup_done: + planned = rt.visit_warmup_started_at + if ( + planned is not None and planned <= beginning - VISIT_WARMUP_S + TICK_SECONDS + ) or ts >= beginning + VISIT_WARMUP_S: + rt.visit_warmup_done = True + self._save() + else: + area.visit_warmup = True if not area.visit: return 0.0, None + if area.visit_warmup and area.temp is not None: + target = self._visit_target(area, area.target) + if area.temp > target + VISIT_WARMUP_MAX_OVER + EPS: + # Abort for this visit, rather than restart as soon as it cools a little. + rt.visit_warmup_done = True + area.visit_warmup = False + self._save() + if area.visit_warmup: + if area.area_id not in self._visit_logged: + self._visit_logged.add(area.area_id) + self._log("visit_warmup" if self.visit else "visit_preheat", area) + return 0.0, None # no night pause or hourly pulse cap during warmup now = dt_util.as_local(dt_util.utc_from_timestamp(ts)).time() night_start = _night_time(self.opt(CONF_NIGHT_START), 20) night_end = _night_time(self.opt(CONF_NIGHT_END), 8) @@ -1896,8 +1939,10 @@ def _visit(self, area: Area, ts: float, learned: LearnedValues) -> tuple[float, if night_start > night_end else (night_start <= now < night_end) ) - minutes = 0.0 if night else float(self.opt(CONF_VISIT_FLOOR_MINUTES)) - return minutes, float(self.opt(CONF_VISIT_FLOOR_MAX_OVER)) + minutes = float(self.opt(CONF_VISIT_FLOOR_MINUTES)) + if self.visit and beginning is not None and ts < beginning + 2 * VISIT_WARMUP_S: + minutes = max(minutes, 30.0) + return (0.0 if night else minutes), float(self.opt(CONF_VISIT_FLOOR_MAX_OVER)) def _visit_payload(self) -> dict[str, Any] | None: """The visit for the AI, None without one.""" @@ -1980,6 +2025,7 @@ async def _control_area( vacation=self.vacation, preheat=area.preheat, visit=area.visit and area.visit_role == VISIT_WARM_FLOOR, + visit_warmup=area.visit_warmup, floor_minutes=floor_minutes, floor_cap=floor_cap, ), @@ -1990,7 +2036,25 @@ async def _control_area( ) area.decision = decision area.status = decision.status - area.visit_pulses = decision.status == AreaStatus.VISIT_FLOOR + area.visit_pulses = decision.status in (AreaStatus.VISIT_FLOOR, AreaStatus.VISIT_WARMUP) + if not self.visit and (area.visit_warmup or self.vacation): + warming = decision.status == AreaStatus.VISIT_WARMUP and ( + area.switch_on or (decision.may_switch and area.switch_available) + ) + if warming and rt.visit_warmup_started_at is None: + rt.visit_warmup_started_at = ts + self._save() + elif not warming and rt.visit_warmup_started_at is not None: + # A safety pause breaks the evidence of a complete planned warmup. + rt.visit_warmup_started_at = None + self._save() + if ( + area.visit_pulses + and (current := self.current_day) is not None + and not current.get("visit") + ): + current["visit"] = True + self._save() if not area.switch_available: area.status = AreaStatus.ACTUATOR_UNAVAILABLE self._handle_events(area, ts, window_open_since, temp_before) diff --git a/custom_components/house_assistant/heating/logic/controller.py b/custom_components/house_assistant/heating/logic/controller.py index 65495c5..2b67e90 100644 --- a/custom_components/house_assistant/heating/logic/controller.py +++ b/custom_components/house_assistant/heating/logic/controller.py @@ -18,6 +18,8 @@ FROST_HYSTERESIS = 0.5 # K above the frost limit before frost protection ends RECOVERED_MARGIN = 0.1 # K below the temperature before airing counts as recovered FORCE_ON_BELOW = 1.0 # K below target: heat regardless of predictions +VISIT_WARMUP_S = 3600.0 # fixed continuous floor warmup, never AI-adjusted +VISIT_WARMUP_MAX_OVER = 1.0 # K above the visit target FLOOR_PULSE_PERIOD_S = 3600.0 # the floor pulses of a visit: run time per hour EPS = 1e-6 # tolerance for comparing sensor values in 0.1 K steps (21.0 - 0.1 > 20.9) @@ -37,6 +39,7 @@ class AreaStatus(StrEnum): PREHEAT = "preheat" VISIT = "visit" VISIT_FLOOR = "visit_floor" + VISIT_WARMUP = "visit_warmup" EMERGENCY = "emergency" SENSOR_ERROR = "sensor_error" ACTUATOR_UNAVAILABLE = "actuator_unavailable" @@ -123,6 +126,8 @@ class AreaRuntime: emergency_active: bool = False frost_active: bool = False heating_since: float | None = None + visit_warmup_started_at: float | None = None # planned warmup observed by this area + visit_warmup_done: bool = False # also latched when the temperature cap aborts it # Overshoot carried over a switch-off: the floor keeps warming the room for a while. was_on: bool = False last_peak: float | None = None # expected peak on the last tick with the circuit on @@ -172,6 +177,7 @@ class ControlInput: preheat: bool = False # visit: the floor of this area is kept warm (raised target already in ``target``) visit: bool = False + visit_warmup: bool = False floor_minutes: float = 0.0 # pulse run time per hour now, 0 = no pulses (e.g. night) floor_cap: float | None = None # no pulses above this temperature @@ -476,7 +482,13 @@ def step( if recovering and not rt.short_recovery: return ControlDecision(False, AreaStatus.RECOVERY, may_switch) - if not data.heating_day: + warmup = ( + data.visit + and data.visit_warmup + and not data.vacation + and data.temp <= data.target + VISIT_WARMUP_MAX_OVER + EPS + ) + if not data.heating_day and not warmup: _update_emergency(data, params, settings, learned, rt) if not rt.emergency_active: return ControlDecision(False, AreaStatus.NO_HEATING_DAY, may_switch) @@ -486,8 +498,8 @@ def step( want, predicted, peak = thermostat( data, params, control_learned, rt.carry_peak, settings.force_on_below ) - pulse = not want and floor_pulse(data) - want = want or pulse + pulse = not want and not warmup and not data.vacation and floor_pulse(data) + want = want or warmup or pulse if data.switch_on: # Carry only the own circuit's residual heat; external sources are read # afresh each tick and must not survive their switch-off in carry_peak. @@ -495,7 +507,9 @@ def step( if hold and want and not data.switch_on: status = AreaStatus.WINDOW_OPEN if data.window_open else AreaStatus.RECOVERY return ControlDecision(False, status, may_switch, predicted, peak) - if not data.heating_day: + if warmup: + status = AreaStatus.VISIT_WARMUP + elif not data.heating_day: status = AreaStatus.EMERGENCY elif data.preheat: status = AreaStatus.PREHEAT diff --git a/custom_components/house_assistant/heating/logic/prompts.py b/custom_components/house_assistant/heating/logic/prompts.py index ddf2d53..551199b 100644 --- a/custom_components/house_assistant/heating/logic/prompts.py +++ b/custom_components/house_assistant/heating/logic/prompts.py @@ -94,7 +94,11 @@ class PromptSpec: "visit", "visit in the data: guests are expected or present. While a visit runs the user " "wants the floor of some areas warm and the others a little cooler; such a day " - "is no error of the rule.", + "is no error of the rule. Warm-floor areas run continuously for at least one hour before " + "a planned visit (at least dead time plus reserve ahead), or from activation if " + "unplanned, even at night. Warmup stops above visit target + 1 K. The first " + "two visit hours use at least 30 min floor runs per hour, then the configured " + "duration (default 15); only these pulses pause at night.", ), ), tail=( @@ -215,7 +219,13 @@ class PromptSpec: PromptBlock( "visit", "visit in the data: while it is active, areas with visit_role warm_floor get a " - "raised target and fixed floor runs each hour, areas with visit_role reduce a " + "raised target, continuous warmup before a planned visit (at least 60 min, or " + "dead time plus reserve if longer), otherwise the first 60 min from activation. " + "Warmup also runs at night and stops above target + 1 K; it survives restarts " + "and is not repeated after a completed planned warmup. Hourly floor runs are " + "at least 30 min for the first two visit hours, then the configured duration " + "(default 15); pulses pause at night and above their configured cap. " + "Areas with visit_role reduce get a " "lowered target. The user wants this: do not counter it with targets or " "parameters, and do not count its extra run time or heat above target as a " "mistake.", diff --git a/custom_components/house_assistant/heating/logic/visit.py b/custom_components/house_assistant/heating/logic/visit.py new file mode 100644 index 0000000..bba4c43 --- /dev/null +++ b/custom_components/house_assistant/heating/logic/visit.py @@ -0,0 +1,46 @@ +"""Persisted visit identity, independent of vacation and per-area floor control.""" + +from dataclasses import asdict, dataclass +from typing import Any + +from ...core.store_validation import checked_fields, dataclass_schema + + +@dataclass +class VisitState: + """Keep the start after the house clears its planned start at activation.""" + + active: bool = False + activated_at: float | None = None + planned_start: float | None = None + + def as_dict(self) -> dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: dict[str, Any] | None) -> "VisitState": + return cls(**checked_fields(data, dataclass_schema(cls))) + + def update(self, active: bool, start: float | None, now: float) -> bool: + """Return whether area warmup memory belongs to an ended/replaced visit.""" + reset = False + if not active: + reset = self.active or self.planned_start != start + self.activated_at = None + self.planned_start = start + elif self.activated_at is None: + # Old stores / HA down at activation: prefer a known scheduled beginning. + planned = start if start is not None else self.planned_start + self.activated_at = planned if planned is not None and planned <= now else now + self.active = active + return reset + + @property + def beginning(self) -> float | None: + if ( + self.planned_start is not None + and self.activated_at is not None + and self.planned_start <= self.activated_at + ): + return self.planned_start + return self.activated_at diff --git a/custom_components/house_assistant/heating/messages.py b/custom_components/house_assistant/heating/messages.py index abd8e41..846859d 100644 --- a/custom_components/house_assistant/heating/messages.py +++ b/custom_components/house_assistant/heating/messages.py @@ -32,6 +32,10 @@ "en": "Window closed: recovery until {until} at the latest.", }, "recovery_end": {"de": "Erholung beendet.", "en": "Recovery finished."}, + "visit_warmup": { + "de": "Fußboden wird nach Besuchsbeginn eine Stunde angeheizt.", + "en": "Warming the floor for one hour after the visit starts.", + }, "visit_preheat": { "de": "Fußboden wird für den Besuch vorgewärmt.", "en": "Warming the floor ahead of the visit.", diff --git a/custom_components/house_assistant/manifest.json b/custom_components/house_assistant/manifest.json index 11c6966..7facc29 100644 --- a/custom_components/house_assistant/manifest.json +++ b/custom_components/house_assistant/manifest.json @@ -21,5 +21,5 @@ "loggers": ["anthropic"], "requirements": ["anthropic>=0.125.0"], "single_config_entry": true, - "version": "1.0.0b25" + "version": "1.0.0b26" } diff --git a/custom_components/house_assistant/strings.json b/custom_components/house_assistant/strings.json index 2415193..5113b4d 100644 --- a/custom_components/house_assistant/strings.json +++ b/custom_components/house_assistant/strings.json @@ -89,7 +89,7 @@ "preheat_reserve": "Additional time added to the calculated preheating time.", "visit_target_raise": "Rooms set to keep the floor warm get this much more during a visit, at most up to the room maximum.", "visit_others_lower": "Rooms set to heat a little less are lowered by this much during a visit, not below the room minimum. The heat of the living area spreads through open doors.", - "visit_floor_minutes": "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target.", + "visit_floor_minutes": "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night.", "visit_floor_max_over": "No floor runs while the room is this much above its visit target." } }, @@ -491,7 +491,7 @@ "preheat_reserve": "Additional time added to the calculated preheating time (e.g. 30 min).", "visit_target_raise": "Rooms set to keep the floor warm get this much more during a visit, at most up to the room maximum.", "visit_others_lower": "Rooms set to heat a little less are lowered by this much during a visit, not below the room minimum. The heat of the living area spreads through open doors.", - "visit_floor_minutes": "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target.", + "visit_floor_minutes": "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night.", "visit_floor_max_over": "No floor runs while the room is this much above its visit target." } }, @@ -2163,7 +2163,8 @@ "emergency": "Emergency rule", "sensor_error": "Sensor error", "actuator_unavailable": "Actuator unavailable", - "no_circuit": "No heating circuit" + "no_circuit": "No heating circuit", + "visit_warmup": "Visit: floor warmup" } } }, diff --git a/custom_components/house_assistant/translations/de.json b/custom_components/house_assistant/translations/de.json index 4cd4080..5d0cfd6 100644 --- a/custom_components/house_assistant/translations/de.json +++ b/custom_components/house_assistant/translations/de.json @@ -89,7 +89,7 @@ "preheat_reserve": "Zusätzliche Zeit zur berechneten Vorheizzeit.", "visit_target_raise": "Räume mit „Fußboden warm halten“ bekommen bei Besuch dieses Ziel zusätzlich, höchstens bis zum Maximum des Raums.", "visit_others_lower": "Räume mit „etwas weniger heizen“ werden bei Besuch um diesen Wert abgesenkt, nicht unter das Minimum des Raums. Die Wärme aus dem Wohnbereich zieht über offene Türen nach.", - "visit_floor_minutes": "So lange läuft der Kreis eines Raums mit „Fußboden warm halten“ mindestens je Stunde, damit der Boden nicht kalt ist. Nachts (Nachtzeit der Lüftung) pausiert das. 0 = nur das höhere Ziel.", + "visit_floor_minutes": "Nach dem festen Anheizen läuft der Kreis mindestens so lange je Stunde; in den ersten 2 Besuchsstunden mindestens 30 min. Takte pausieren nachts (Nachtzeit der Lüftung). 0 = danach nur das höhere Ziel. Das Anheizen läuft unabhängig davon auch nachts.", "visit_floor_max_over": "Liegt der Raum so weit über dem Besuchsziel, läuft kein Fußboden-Takt." } }, @@ -491,7 +491,7 @@ "preheat_reserve": "Zusätzliche Zeit zur berechneten Vorheizzeit (z. B. 30 min).", "visit_target_raise": "Räume mit „Fußboden warm halten“ bekommen bei Besuch dieses Ziel zusätzlich, höchstens bis zum Maximum des Raums.", "visit_others_lower": "Räume mit „etwas weniger heizen“ werden bei Besuch um diesen Wert abgesenkt, nicht unter das Minimum des Raums. Die Wärme aus dem Wohnbereich zieht über offene Türen nach.", - "visit_floor_minutes": "So lange läuft der Kreis eines Raums mit „Fußboden warm halten“ mindestens je Stunde, damit der Boden nicht kalt ist. Nachts (Nachtzeit der Lüftung) pausiert das. 0 = nur das höhere Ziel.", + "visit_floor_minutes": "Nach dem festen Anheizen läuft der Kreis mindestens so lange je Stunde; in den ersten 2 Besuchsstunden mindestens 30 min. Takte pausieren nachts (Nachtzeit der Lüftung). 0 = danach nur das höhere Ziel. Das Anheizen läuft unabhängig davon auch nachts.", "visit_floor_max_over": "Liegt der Raum so weit über dem Besuchsziel, läuft kein Fußboden-Takt." } }, @@ -2163,7 +2163,8 @@ "emergency": "Notfallregel", "sensor_error": "Sensorfehler", "actuator_unavailable": "Aktor nicht erreichbar", - "no_circuit": "Kein Heizkreis" + "no_circuit": "Kein Heizkreis", + "visit_warmup": "Besuch: Fußboden anheizen" } } }, diff --git a/custom_components/house_assistant/translations/en.json b/custom_components/house_assistant/translations/en.json index 2415193..5113b4d 100644 --- a/custom_components/house_assistant/translations/en.json +++ b/custom_components/house_assistant/translations/en.json @@ -89,7 +89,7 @@ "preheat_reserve": "Additional time added to the calculated preheating time.", "visit_target_raise": "Rooms set to keep the floor warm get this much more during a visit, at most up to the room maximum.", "visit_others_lower": "Rooms set to heat a little less are lowered by this much during a visit, not below the room minimum. The heat of the living area spreads through open doors.", - "visit_floor_minutes": "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target.", + "visit_floor_minutes": "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night.", "visit_floor_max_over": "No floor runs while the room is this much above its visit target." } }, @@ -491,7 +491,7 @@ "preheat_reserve": "Additional time added to the calculated preheating time (e.g. 30 min).", "visit_target_raise": "Rooms set to keep the floor warm get this much more during a visit, at most up to the room maximum.", "visit_others_lower": "Rooms set to heat a little less are lowered by this much during a visit, not below the room minimum. The heat of the living area spreads through open doors.", - "visit_floor_minutes": "A room set to keep the floor warm runs at least this long per hour, so the floor is not cold. Paused at night (night time of the ventilation). 0 = only the raised target.", + "visit_floor_minutes": "After the fixed warmup the circuit runs at least this long per hour; at least 30 min during the first 2 visit hours. Pulses pause at night (ventilation night time). 0 = only the raised target afterwards. Warmup runs independently, including at night.", "visit_floor_max_over": "No floor runs while the room is this much above its visit target." } }, @@ -2163,7 +2163,8 @@ "emergency": "Emergency rule", "sensor_error": "Sensor error", "actuator_unavailable": "Actuator unavailable", - "no_circuit": "No heating circuit" + "no_circuit": "No heating circuit", + "visit_warmup": "Visit: floor warmup" } } }, diff --git a/docs/heating.en.md b/docs/heating.en.md index 990f8b4..34fdcc5 100644 --- a/docs/heating.en.md +++ b/docs/heating.en.md @@ -29,6 +29,14 @@ Rooms and windows come from the **house** (panel *House Assistant > House*): a r * **Heating period:** outside of it (e.g. 01.04. to 30.09.) all circuits stay off and there are no AI requests. * **Vacation:** during the vacation of the house (switch *Vacation* with departure and return, or an external source such as a calendar; see [README](../README.en.md#vacation)) the vacation temperature applies to every room. With the learned heating rate it preheats in time so the normal target is reached at the return; the own return of the switch comes before a return entity. A return in the past is ignored and the vacation temperature applies. The ventilation advice rests on vacation (option *Ventilation advice rests*, on by default). +## Visit: floor warmup + +`warm_floor` heats continuously before a planned visit in `[start − max(60 min, dead time + preheat reserve), start]`, including at night and without a heating day. Without a completed warmup beforehand it runs for the first 60 min from activation. Above visit target + 1.0 K, warmup ends for this visit; status `visit_warmup` ("Visit: floor warmup"). Subsequent pulses use at least 30 min/h during the first 2 h from the planned beginning or activation, then `visit_floor_minutes` (default 15). Only pulses pause at night and above `visit_floor_max_over` (default +0.5 K). + +Sensor errors, frost protection, off, heating season, windows/recovery and vacation keep priority; minimum on/off times still apply. Safety pauses do not extend the windows. A planned warmup that started late gets the spontaneous hour at activation. Exceeding the temperature cap prevents another warmup during this visit. Warmup counts as visit run time and marks the heating day as a visit day. + +Persistence: `.storage/house_assistant..heating`, central `visit` with `active`, `activated_at`, `planned_start`, and per area `areas..runtime.visit_warmup_started_at` and `visit_warmup_done`. If activation is unknown for an active visit, use the known planned beginning, otherwise now. Visit end, replacing or cancelling a plan clears the area markers. No new setting; the AI must not counter these comfort runs. + ## Heating day decision (nightly run) Once a night (time configurable) it is decided whether to heat at all today. diff --git a/docs/heating.md b/docs/heating.md index 62208aa..b6ebdbb 100644 --- a/docs/heating.md +++ b/docs/heating.md @@ -29,6 +29,14 @@ Räume und Fenster kommen aus dem **Haus** (Panel *House Assistant > Haus*): Ein * **Heizperiode:** Außerhalb (z. B. 01.04. bis 30.09.) bleiben alle Kreise aus, es gibt keine KI-Abfragen. * **Urlaub:** Im Urlaub des Hauses (Schalter *Urlaub* mit Abreise und Rückkehr, oder eine externe Quelle wie ein Kalender; siehe [README](../README.md#urlaub)) gilt die Urlaubstemperatur für alle Räume. Anhand der gelernten Aufheizrate wird so rechtzeitig vorgeheizt, dass zur Rückkehr der normale Sollwert erreicht ist; die eigene Rückkehr des Schalters hat Vorrang vor einer Rückkehr-Entität. Liegt die Rückkehr in der Vergangenheit, wird sie ignoriert und die Urlaubstemperatur gilt. Die Lüftungsempfehlung ruht im Urlaub (Option *Lüftungsempfehlung ruht*, Standard an). +## Besuch: Fußboden anheizen + +`warm_floor` heizt vor einem geplanten Besuch durchgehend im Fenster `[Beginn − max(60 min, Totzeit + Vorheiz-Reserve), Beginn]`, auch nachts und ohne Heiztag. Ohne vollständiges vorheriges Anheizen läuft der Kreis die ersten 60 min ab Aktivierung. Über Besuchsziel + 1,0 K wird das Anheizen für diesen Besuch beendet; Status `visit_warmup` („Besuch: Fußboden anheizen“). Danach gelten die normalen Takte: in den ersten 2 h ab geplantem Beginn bzw. Aktivierung mindestens 30 min/h, anschließend `visit_floor_minutes` (Standard 15). Nur die Takte pausieren nachts und über `visit_floor_max_over` (Standard +0,5 K). + +Sensorfehler, Frostschutz, Aus, Heizperiode, Fenster/Erholung und Urlaub behalten Vorrang; Mindestlauf und Mindestpause gelten weiter. Sicherheitsunterbrechungen verlängern die Zeitfenster nicht. Ein erst verspätet begonnenes geplantes Anheizen erhält bei Besuchsbeginn die spontane Stunde. Bei Überschreiten der Temperaturgrenze wird für diesen Besuch kein neuer Anheizlauf gestartet. Anheizen zählt als Besuchslaufzeit und markiert den Heiztag als Besuchstag. + +Persistenz: `.storage/house_assistant..heating`, zentral `visit` mit `active`, `activated_at`, `planned_start`, je Bereich unter `areas..runtime` die Felder `visit_warmup_started_at` und `visit_warmup_done`. Fehlt bei aktivem Besuch die Aktivierung, gilt der bekannte geplante Beginn, sonst jetzt. Besuchsende, Planwechsel oder Planlöschung setzen die Bereichsmerker zurück. Keine neue Einstellung; die KI soll diese Komfortläufe nicht gegenregeln. + ## Heiztag-Entscheidung (Nachtlauf) Einmal pro Nacht (Uhrzeit einstellbar) wird entschieden, ob heute überhaupt geheizt wird. diff --git a/tests/core/test_visit.py b/tests/core/test_visit.py index 1af8056..adee650 100644 --- a/tests/core/test_visit.py +++ b/tests/core/test_visit.py @@ -159,11 +159,14 @@ async def test_floor_pulses_by_day_not_at_night(hass: HomeAssistant, freezer) -> await _switch(hass, SWITCH, True) coordinator = _coordinator(entry) living = coordinator.areas["living"] - # the circuit was switched off just now: the next pulse after 45 minutes await coordinator.async_refresh() - assert living.status == AreaStatus.VISIT + assert living.status == AreaStatus.VISIT_WARMUP + freezer.tick(timedelta(minutes=60)) + await coordinator.async_refresh() + assert living.runtime.visit_warmup_done + # During the second visit hour: 30 min on, 30 min off. hass.states.async_set("input_boolean.living_circuit", "off", force_update=True) - freezer.tick(timedelta(minutes=46)) + freezer.tick(timedelta(minutes=31)) hass.states.async_set("sensor.living_temperature", "21.8", {"unit_of_measurement": "°C"}) await coordinator._tick_area(living, dt_util.utcnow().timestamp(), 1, False, None) # a pulse also on a day without heating @@ -200,7 +203,7 @@ async def test_start_end_and_warming_ahead(hass: HomeAssistant, freezer) -> None living, kids = coordinator.areas["living"], coordinator.areas["kids"] assert not living.visit # dead time and preheat reserve (30 + 30 min by default) ahead of the start - lead = living.learned_values.dead_time_s + HEATING_DEFAULTS["preheat_reserve"] * 60 + lead = max(3600, living.learned_values.dead_time_s + HEATING_DEFAULTS["preheat_reserve"] * 60) assert living.visit_floor_from == pytest.approx(start.timestamp() - lead) freezer.move_to(start - timedelta(seconds=lead - 60)) @@ -270,3 +273,212 @@ async def test_panel(hass: HomeAssistant, hass_ws_client) -> None: assert msg["success"], msg assert msg["result"]["visit"]["on"] is False assert msg["result"]["visit"]["end"] is None + + +async def test_spontaneous_warmup_persists_and_ends_on_time(hass: HomeAssistant, freezer) -> None: + freezer.move_to(DAY) + entry = _entry() + await _setup(hass, entry, temp=21.8) + await _switch(hass, SWITCH, True) + c = _coordinator(entry) + await c.async_refresh() + activation = c.visit_state.activated_at + assert activation == dt_util.utcnow().timestamp() + assert c.areas["living"].status == AreaStatus.VISIT_WARMUP + assert c.areas["living"].visit_pulses + assert c.current_day["visit"] + + freezer.tick(timedelta(minutes=20)) + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + c = _coordinator(entry) + await c.async_refresh() + assert c.visit_state.activated_at == activation + assert c.areas["living"].status == AreaStatus.VISIT_WARMUP + assert c.areas["living"].decision.want_on + + freezer.tick(timedelta(minutes=40)) + await c.async_refresh() + assert c.areas["living"].runtime.visit_warmup_done + assert c.areas["living"].status != AreaStatus.VISIT_WARMUP + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + c = _coordinator(entry) + assert c.visit_state.activated_at == activation + assert c.areas["living"].runtime.visit_warmup_done + assert c.areas["living"].status != AreaStatus.VISIT_WARMUP + + await _switch(hass, SWITCH, False) + await c.async_refresh() + assert c.visit_state.activated_at is None + assert not c.areas["living"].runtime.visit_warmup_done + await _switch(hass, SWITCH, True) + await c.async_refresh() + assert c.areas["living"].status == AreaStatus.VISIT_WARMUP + assert c.visit_state.activated_at > activation + + +@pytest.mark.parametrize("dead_time,reserve,lead", [(60, 0, 3600), (5400, 30, 7200)]) +async def test_planned_warmup_window_continuous_at_night( + hass: HomeAssistant, freezer, dead_time, reserve, lead +) -> None: + from custom_components.house_assistant.heating.logic.controller import LearnedValues + + freezer.move_to(NIGHT) + entry = _entry() + await _setup(hass, entry, temp=21.8) + c = _coordinator(entry) + room = c.areas["living"] + start = dt_util.utcnow().timestamp() + 3 * 3600 + c.visit_start = start + c.opts["preheat_reserve"] = reserve + c._update_visit(False, start - lead - 1) + learned = LearnedValues(dead_time_s=dead_time) + c._visit(room, start - lead - 1, learned) + assert room.visit_floor_from == start - lead + assert not room.visit + for offset in (0, 15 * 60, 30 * 60, lead - 1): + c._visit(room, start - lead + offset, learned) + assert room.visit + assert room.visit_warmup # no 15 min pulse cutoff, even at night + # Safety cap ends this visit's warmup, including across restart serialization. + room.temp = 22.5 # target 21.5 + 1.0: still allowed + c._visit(room, start - 60, learned) + assert room.visit_warmup + room.temp = 22.6 + c._visit(room, start - 60, learned) + assert not room.visit_warmup + assert room.runtime.visit_warmup_done + from custom_components.house_assistant.heating.logic.controller import AreaRuntime + + room.runtime = AreaRuntime.from_dict(room.runtime.as_dict()) + room.temp = 21.8 + c._visit(room, start - 30, learned) + assert not room.visit_warmup + + +@pytest.mark.parametrize("first_tick_s", [0, 30]) +async def test_completed_planned_warmup_not_repeated_after_restart( + hass: HomeAssistant, freezer, first_tick_s +) -> None: + freezer.move_to(DAY) + entry = _entry() + await _setup(hass, entry, temp=21.8) + c = _coordinator(entry) + start = dt_util.utcnow() + timedelta(hours=2) + await hass.services.async_call( + "datetime", "set_value", {"entity_id": START, "datetime": start}, blocking=True + ) + await hass.async_block_till_done(wait_background_tasks=True) + freezer.move_to(start - timedelta(hours=1) + timedelta(seconds=first_tick_s)) + # Permit the initial switch-on; the existing switch guard is tested separately. + room = c.areas["living"] + await c.async_refresh() + assert room.status == AreaStatus.VISIT_WARMUP + assert room.runtime.visit_warmup_started_at == dt_util.utcnow().timestamp() + for minute in range(1, 60): + freezer.move_to(start - timedelta(hours=1) + timedelta(minutes=minute, seconds=first_tick_s)) + await c.async_refresh() + assert room.status == AreaStatus.VISIT_WARMUP + assert room.decision.want_on + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + c = _coordinator(entry) + assert c.areas["living"].runtime.visit_warmup_started_at == start.timestamp() - 3600 + first_tick_s + await _advance(hass, freezer, timedelta(seconds=60 - first_tick_s)) + await c.async_refresh() + assert c.visit + assert c.visit_start is None # house clears the plan at activation + assert c.visit_state.beginning == start.timestamp() + assert c.areas["living"].runtime.visit_warmup_done + assert c.areas["living"].status != AreaStatus.VISIT_WARMUP + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + c = _coordinator(entry) + assert c.areas["living"].runtime.visit_warmup_done + assert c.areas["living"].status != AreaStatus.VISIT_WARMUP + + +async def test_floor_first_two_hours_and_night(hass: HomeAssistant, freezer) -> None: + freezer.move_to(DAY) + entry = _entry() + await _setup(hass, entry, temp=21.8) + await _switch(hass, SWITCH, True) + c = _coordinator(entry) + await c.async_refresh() + room = c.areas["living"] + start = c.visit_state.beginning + room.runtime.visit_warmup_done = True + for minutes, expected in ((0, 30), (60, 30), (119, 30), (120, 15), (180, 15)): + pulse, cap = c._visit(room, start + minutes * 60, room.learned_values) + assert pulse == expected + assert cap == 0.5 + c.opts["visit_floor_minutes"] = 45 + assert c._visit(room, start + 3600, room.learned_values)[0] == 45 + c.opts["visit_floor_minutes"] = 0 + assert c._visit(room, start + 3600, room.learned_values)[0] == 30 + assert c._visit(room, start + 7200, room.learned_values)[0] == 0 + freezer.move_to(NIGHT) + assert c._visit(room, dt_util.utcnow().timestamp(), room.learned_values)[0] == 0 + + +async def test_spontaneous_warmup_at_night_and_vacation_priority( + hass: HomeAssistant, freezer +) -> None: + freezer.move_to(NIGHT) + entry = _entry() + await _setup(hass, entry, temp=21.8) + await _switch(hass, SWITCH, True) + c = _coordinator(entry) + await c.async_refresh() + room = c.areas["living"] + assert room.status == AreaStatus.VISIT_WARMUP + assert room.decision.want_on + await _switch(hass, VACATION, True) + await c.async_refresh() + assert not room.visit_warmup + assert not room.decision.want_on + await c._tick_area(room, dt_util.utcnow().timestamp(), 1, True, None) + assert room.status == AreaStatus.VACATION + + +async def test_late_planned_warmup_gets_hour_from_activation(hass: HomeAssistant, freezer) -> None: + freezer.move_to(DAY) + entry = _entry() + await _setup(hass, entry, temp=21.8) + c = _coordinator(entry) + room = c.areas["living"] + start = dt_util.utcnow().timestamp() + 3600 + c.visit_start = start + c._update_visit(False, start - 1800) + c._visit(room, start - 1800, room.learned_values) + assert room.visit_warmup + room.runtime.visit_warmup_started_at = start - 1800 + c.visit_start = None + c._update_visit(True, start) + c.visit = True + c._visit(room, start, room.learned_values) + assert room.visit_warmup + c._visit(room, start + 3599, room.learned_values) + assert room.visit_warmup + c._visit(room, start + 3600, room.learned_values) + assert not room.visit_warmup + assert room.runtime.visit_warmup_done + + +async def test_vacation_interrupts_evidence_of_planned_warmup(hass: HomeAssistant, freezer) -> None: + freezer.move_to(DAY) + entry = _entry() + await _setup(hass, entry, temp=21.8) + c = _coordinator(entry) + room = c.areas["living"] + now = dt_util.utcnow().timestamp() + c.visit_start = now + 3600 + c._update_visit(False, now) + room.runtime.visit_warmup_started_at = now + c.vacation = True + await c._control_area(room, now + 600, 1, True, None) + assert not room.visit_warmup + assert not room.decision.want_on + assert room.runtime.visit_warmup_started_at is None + assert not room.runtime.visit_warmup_done diff --git a/tests/heating/logic/test_visit.py b/tests/heating/logic/test_visit.py index 1be9f05..9006706 100644 --- a/tests/heating/logic/test_visit.py +++ b/tests/heating/logic/test_visit.py @@ -1,5 +1,7 @@ """Floor pulses of a visit in the per area controller.""" +import pytest + from custom_components.house_assistant.heating.logic.controller import ( AreaRuntime, AreaSettings, @@ -75,18 +77,21 @@ def test_thermostat_demand_wins_over_the_pulse_status() -> None: assert decision.status == AreaStatus.HEATING -def test_pulses_over_hours_give_fifteen_minutes_per_hour() -> None: - """Simulate the switch following the decision: 15 min on, 45 min off.""" +@pytest.mark.parametrize("floor_minutes,expected", [(15, 45), (30, 90)]) +def test_pulses_over_hours(floor_minutes: float, expected: int) -> None: + """Simulate the real switch following hourly visit pulse decisions.""" rt = AreaRuntime() switch_on, changed, on_minutes = False, NOW - 7200, 0 for minute in range(180): now = NOW + minute * 60 - data = _input(now=now, switch_on=switch_on, last_switch_change=changed) + data = _input( + now=now, switch_on=switch_on, last_switch_change=changed, floor_minutes=floor_minutes + ) decision = step(data, PARAMS, SETTINGS, LEARNED, rt) if decision.may_switch and decision.want_on != switch_on: switch_on, changed = decision.want_on, now on_minutes += switch_on - assert on_minutes == 45 + assert on_minutes == expected def test_pulse_never_overrides_protection() -> None: @@ -138,3 +143,96 @@ def test_visit_days_are_no_rule_errors() -> None: assert hd.rule_errors(history, 7) == 1 # stored and loaded again assert hd.DayRecord.from_dict(history[1].as_dict()).visit + + +def test_visit_warmup_is_continuous_and_respects_temperature_limit() -> None: + # Unlike a pulse, a warmup does not stop after 15 min or at the +0.5 K pulse cap. + for minute in range(60): + data = _input( + now=NOW + minute * 60, + visit_warmup=True, + floor_minutes=0, + temp=23.0, + switch_on=True, + last_switch_change=NOW, + heating_day=False, + ) + decision = step(data, PARAMS, SETTINGS, LEARNED, AreaRuntime()) + assert decision.want_on + assert decision.status == AreaStatus.VISIT_WARMUP + decision = step( + _input(visit_warmup=True, temp=23.1), PARAMS, SETTINGS, LEARNED, AreaRuntime() + ) + assert not decision.want_on + assert decision.status != AreaStatus.VISIT_WARMUP + + +def test_visit_warmup_preserves_minimum_switch_times() -> None: + for on in (False, True): + decision = step( + _input(visit_warmup=True, switch_on=on, last_switch_change=NOW - 60), + PARAMS, SETTINGS, LEARNED, AreaRuntime(), + ) + assert decision.want_on + assert not decision.may_switch + + +def test_visit_warmup_preserves_safety_priority() -> None: + cases = ( + ({"temp": None}, AreaStatus.SENSOR_ERROR, False), + ({"temp": 5.0, "hvac_on": False}, AreaStatus.FROST_PROTECTION, True), + ({"hvac_on": False}, AreaStatus.OFF, False), + ({"season_active": False}, AreaStatus.OUT_OF_SEASON, False), + ({"window_open": True}, AreaStatus.WINDOW_OPEN, False), + ({"vacation": True}, AreaStatus.VACATION, False), + ) + for changes, status, want_on in cases: + decision = step( + _input(visit_warmup=True, **changes), PARAMS, SETTINGS, LEARNED, AreaRuntime() + ) + assert decision.status == status + assert decision.want_on == want_on + rt = AreaRuntime(recovery_until=NOW + 1000, temp_before_open=24.0) + decision = step(_input(visit_warmup=True), PARAMS, SETTINGS, LEARNED, rt) + assert decision.status == AreaStatus.RECOVERY + assert not decision.want_on + + +def test_visit_state_activation_plan_and_restart() -> None: + from custom_components.house_assistant.heating.logic.visit import VisitState + + state = VisitState() + assert state.update(False, NOW + 7200, NOW) + assert not state.update(True, None, NOW + 7200) + assert state.beginning == NOW + 7200 + restored = VisitState(**state.as_dict()) + assert not restored.update(True, None, NOW + 8100) + assert restored.activated_at == NOW + 7200 + assert restored.update(False, None, NOW + 9000) + assert restored.beginning is None + assert not restored.update(True, None, NOW + 9100) + assert restored.beginning == NOW + 9100 + + +def test_visit_state_unknown_activation_fallback() -> None: + from custom_components.house_assistant.heating.logic.visit import VisitState + + state = VisitState() + state.update(True, NOW - 600, NOW) + assert state.beginning == NOW - 600 + unknown = VisitState() + unknown.update(True, None, NOW) + assert unknown.beginning == NOW + + +def test_visit_state_missing_activation_after_restart_and_plan_changes() -> None: + from custom_components.house_assistant.heating.logic.visit import VisitState + + state = VisitState.from_dict({"active": True, "planned_start": NOW - 600}) + assert not state.update(True, None, NOW) + assert state.activated_at == NOW - 600 + assert state.update(False, NOW + 7200, NOW + 100) + assert state.update(False, NOW + 8000, NOW + 200) # replaced plan + assert state.update(False, None, NOW + 300) # cancelled plan + assert state.activated_at is None + assert state.planned_start is None diff --git a/tests/logic/test_storage.py b/tests/logic/test_storage.py index a879a84..96cabcf 100644 --- a/tests/logic/test_storage.py +++ b/tests/logic/test_storage.py @@ -19,13 +19,17 @@ ThermalModel, ) from custom_components.house_assistant.heating.logic.room_energy import RoomEnergyModel +from custom_components.house_assistant.heating.logic.visit import VisitState from custom_components.house_assistant.meter.meter import MeterState, meter_state_schema from custom_components.house_assistant.runtime import HouseRuntime, Module @pytest.mark.parametrize( "cls", - [Budget, ControlParams, AreaRuntime, HeatMeter, HumidityProfile, ThermalModel, RecoveryModel], + [ + Budget, ControlParams, AreaRuntime, VisitState, HeatMeter, + HumidityProfile, ThermalModel, RecoveryModel, + ], ) def test_valid_dataclass_roundtrip(cls): value = cls() @@ -440,7 +444,12 @@ class Restored(Exception): hvac_on=True, params=ControlParams(puffer=0.812345), learner=AreaLearner.create(2100, 2300), - runtime=AreaRuntime(carry_peak=22.5, carry_since=1793275200.5), + runtime=AreaRuntime( + carry_peak=22.5, + carry_since=1793275200.5, + visit_warmup_started_at=1793275200.0, + visit_warmup_done=i == 0, + ), day=DayAreaStats(), check={}, start={}, @@ -458,6 +467,7 @@ class Restored(Exception): ) obj = SimpleNamespace( areas=areas, + visit_state=VisitState(active=True, activated_at=1793275300.0, planned_start=1793275200.0), day_state={}, ai_state={}, budget=Budget(), @@ -490,6 +500,7 @@ def build(area_id, title, cfg, stored, index): ): with pytest.raises(Restored): await HeatingCoordinator._async_setup(obj) + assert obj.visit_state.as_dict() == original["visit"] for i in range(5): assert captured[f"room{i}"] == original["areas"][f"room{i}"] if corrupt: From 3d1ba900e4927508a86b15ee56c4543bf3209256 Mon Sep 17 00:00:00 2001 From: Jumpmaster2 Date: Thu, 3 Dec 2026 14:32:24 +0000 Subject: [PATCH 2/2] Format tests (ruff format) Co-Authored-By: Claude Opus 5.5 --- tests/core/test_visit.py | 8 ++++++-- tests/heating/logic/test_visit.py | 9 +++++---- tests/logic/test_storage.py | 10 ++++++++-- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/tests/core/test_visit.py b/tests/core/test_visit.py index adee650..38cf0c2 100644 --- a/tests/core/test_visit.py +++ b/tests/core/test_visit.py @@ -377,14 +377,18 @@ async def test_completed_planned_warmup_not_repeated_after_restart( assert room.status == AreaStatus.VISIT_WARMUP assert room.runtime.visit_warmup_started_at == dt_util.utcnow().timestamp() for minute in range(1, 60): - freezer.move_to(start - timedelta(hours=1) + timedelta(minutes=minute, seconds=first_tick_s)) + freezer.move_to( + start - timedelta(hours=1) + timedelta(minutes=minute, seconds=first_tick_s) + ) await c.async_refresh() assert room.status == AreaStatus.VISIT_WARMUP assert room.decision.want_on assert await hass.config_entries.async_reload(entry.entry_id) await hass.async_block_till_done(wait_background_tasks=True) c = _coordinator(entry) - assert c.areas["living"].runtime.visit_warmup_started_at == start.timestamp() - 3600 + first_tick_s + assert ( + c.areas["living"].runtime.visit_warmup_started_at == start.timestamp() - 3600 + first_tick_s + ) await _advance(hass, freezer, timedelta(seconds=60 - first_tick_s)) await c.async_refresh() assert c.visit diff --git a/tests/heating/logic/test_visit.py b/tests/heating/logic/test_visit.py index 9006706..5bd3289 100644 --- a/tests/heating/logic/test_visit.py +++ b/tests/heating/logic/test_visit.py @@ -160,9 +160,7 @@ def test_visit_warmup_is_continuous_and_respects_temperature_limit() -> None: decision = step(data, PARAMS, SETTINGS, LEARNED, AreaRuntime()) assert decision.want_on assert decision.status == AreaStatus.VISIT_WARMUP - decision = step( - _input(visit_warmup=True, temp=23.1), PARAMS, SETTINGS, LEARNED, AreaRuntime() - ) + decision = step(_input(visit_warmup=True, temp=23.1), PARAMS, SETTINGS, LEARNED, AreaRuntime()) assert not decision.want_on assert decision.status != AreaStatus.VISIT_WARMUP @@ -171,7 +169,10 @@ def test_visit_warmup_preserves_minimum_switch_times() -> None: for on in (False, True): decision = step( _input(visit_warmup=True, switch_on=on, last_switch_change=NOW - 60), - PARAMS, SETTINGS, LEARNED, AreaRuntime(), + PARAMS, + SETTINGS, + LEARNED, + AreaRuntime(), ) assert decision.want_on assert not decision.may_switch diff --git a/tests/logic/test_storage.py b/tests/logic/test_storage.py index 96cabcf..a3eedc5 100644 --- a/tests/logic/test_storage.py +++ b/tests/logic/test_storage.py @@ -27,8 +27,14 @@ @pytest.mark.parametrize( "cls", [ - Budget, ControlParams, AreaRuntime, VisitState, HeatMeter, - HumidityProfile, ThermalModel, RecoveryModel, + Budget, + ControlParams, + AreaRuntime, + VisitState, + HeatMeter, + HumidityProfile, + ThermalModel, + RecoveryModel, ], ) def test_valid_dataclass_roundtrip(cls):