-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
633 lines (554 loc) · 25.4 KB
/
__init__.py
File metadata and controls
633 lines (554 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
"""Heating Simulator integration for Home Assistant."""
from __future__ import annotations
import logging
from datetime import timedelta
from typing import Any
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.event import (
async_track_state_change_event,
async_track_time_interval,
)
from homeassistant.helpers import device_registry as dr
from .const import (
DOMAIN,
# shared
CONF_MODEL_TYPE,
CONF_CONTROL_MODE,
CONF_INITIAL_TEMP,
CONF_EXTERNAL_TEMP,
CONF_EXTERNAL_TEMP_FIXED,
CONF_UPDATE_INTERVAL,
# simple
CONF_HEATER_POWER,
CONF_HEAT_LOSS_COEFF,
CONF_THERMAL_MASS,
CONF_THERMAL_INERTIA,
# R2C2
CONF_C_AIR,
CONF_C_FABRIC,
CONF_R_FABRIC,
CONF_R_EXT,
CONF_R_INF,
CONF_HEATER_POWER_R2C2,
CONF_SOLAR_ENTITY,
CONF_SOLAR_FIXED,
CONF_WINDOW_AREA,
CONF_WINDOW_TRANSMITTANCE,
# radiator
CONF_FLOW_TEMP,
CONF_FLOW_TEMP_ENTITY,
CONF_C_RAD,
CONF_K_RAD,
CONF_RAD_EXPONENT,
CONF_FLOW_RATE_MAX,
CONF_HEAT_LOSS_COEFF_RAD,
CONF_C_ROOM_RAD,
CONF_PIPE_DELAY,
CONF_VALVE_CHARACTERISTIC,
# model types
MODEL_SIMPLE,
MODEL_R2C2,
MODEL_RADIATOR,
MODEL_R2C2_RADIATOR,
CONTROL_MODE_LINEAR,
# defaults — simple
DEFAULT_HEATER_POWER,
DEFAULT_HEAT_LOSS_COEFF,
DEFAULT_THERMAL_MASS,
DEFAULT_THERMAL_INERTIA,
# defaults — R2C2
DEFAULT_C_AIR,
DEFAULT_C_FABRIC,
DEFAULT_R_FABRIC,
DEFAULT_R_EXT,
DEFAULT_R_INF,
DEFAULT_HEATER_POWER_R2C2,
DEFAULT_SOLAR_FIXED,
DEFAULT_WINDOW_AREA,
DEFAULT_WINDOW_TRANSMITTANCE,
# defaults — radiator
DEFAULT_FLOW_TEMP,
DEFAULT_C_RAD,
DEFAULT_K_RAD,
DEFAULT_RAD_EXPONENT,
DEFAULT_FLOW_RATE_MAX,
DEFAULT_HEAT_LOSS_COEFF_RAD,
DEFAULT_C_ROOM_RAD,
DEFAULT_PIPE_DELAY,
DEFAULT_VALVE_CHARACTERISTIC,
# defaults — shared
DEFAULT_INITIAL_TEMP,
DEFAULT_EXTERNAL_TEMP_FIXED,
DEFAULT_UPDATE_INTERVAL,
# reset action
ACTION_RESET,
ACTION_SET_WEATHER,
PRESET_COLD_START,
PRESET_OVERNIGHT,
PRESET_ROOM_TEMPERATURE,
RESET_PRESETS,
# F-11 external temp profile
CONF_EXT_TEMP_PROFILE_ENABLED, CONF_EXT_TEMP_BASE, CONF_EXT_TEMP_AMPLITUDE,
CONF_EXT_TEMP_MIN_HOUR, CONF_EXT_TEMP_MAX_HOUR,
DEFAULT_EXT_TEMP_PROFILE_ENABLED, DEFAULT_EXT_TEMP_BASE, DEFAULT_EXT_TEMP_AMPLITUDE,
DEFAULT_EXT_TEMP_MIN_HOUR, DEFAULT_EXT_TEMP_MAX_HOUR,
# F-05 occupancy
CONF_OCCUPANCY_ENABLED, CONF_OCCUPANCY_MAX_OCCUPANTS, CONF_OCCUPANCY_COOKING_POWER,
CONF_OCCUPANCY_COOKING_DURATION, CONF_OCCUPANCY_COOKING_EVENTS_PER_DAY, CONF_OCCUPANCY_SEED,
DEFAULT_OCCUPANCY_ENABLED, DEFAULT_OCCUPANCY_MAX_OCCUPANTS, DEFAULT_OCCUPANCY_COOKING_POWER,
DEFAULT_OCCUPANCY_COOKING_DURATION, DEFAULT_OCCUPANCY_COOKING_EVENTS_PER_DAY, DEFAULT_OCCUPANCY_SEED,
# F-06, F-14 weather
CONF_WIND_SPEED, CONF_WIND_COEFFICIENT, CONF_RAIN_INTENSITY, CONF_RAIN_MOISTURE_FACTOR,
DEFAULT_WIND_SPEED, DEFAULT_WIND_COEFFICIENT, DEFAULT_RAIN_INTENSITY, DEFAULT_RAIN_MOISTURE_FACTOR,
)
from .thermal_model import SimpleThermalModel, R2C2ThermalModel, WetRadiatorModel, R2C2RadiatorModel
from .disturbances import ExternalTempProfile, OccupancyProfile, WeatherProfile
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [Platform.SENSOR, Platform.NUMBER, Platform.SWITCH]
_SET_WEATHER_SERVICE_SCHEMA = vol.Schema(
{
vol.Optional("device_id"): vol.Any(str, [str]),
vol.Optional("entity_id"): vol.Any(str, [str]),
vol.Optional("area_id"): vol.Any(str, [str]),
vol.Optional("wind_speed_m_s"): vol.All(vol.Coerce(float), vol.Range(min=0, max=50)),
vol.Optional("rain_intensity_fraction"): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)),
}
)
_RESET_SERVICE_SCHEMA = vol.Schema(
{
vol.Optional("device_id"): vol.Any(str, [str]),
vol.Optional("entity_id"): vol.Any(str, [str]),
vol.Optional("area_id"): vol.Any(str, [str]),
vol.Optional("preset"): vol.In(
[PRESET_COLD_START, PRESET_OVERNIGHT, PRESET_ROOM_TEMPERATURE]
),
vol.Optional("t_room"): vol.Coerce(float),
vol.Optional("t_fabric"): vol.Coerce(float),
vol.Optional("t_rad"): vol.Coerce(float),
}
)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Heating Simulator from a config entry."""
hass.data.setdefault(DOMAIN, {})
config = {**entry.data, **entry.options}
simulator = HeatingSimulator(hass, entry, config)
hass.data[DOMAIN][entry.entry_id] = simulator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
await simulator.async_start()
entry.async_on_unload(entry.add_update_listener(_async_update_options))
async def _handle_reset(call) -> None:
"""Handle the reset_model service call."""
target_entry_ids: set[str] | None = None
target_devices = call.data.get("device_id")
if target_devices:
if isinstance(target_devices, str):
target_devices = [target_devices]
dev_reg = dr.async_get(hass)
target_entry_ids = set()
for device_id in target_devices:
device = dev_reg.async_get(device_id)
if device is None:
continue
for entry_id in device.config_entries:
if entry_id in hass.data[DOMAIN]:
target_entry_ids.add(entry_id)
for entry_id, sim in hass.data[DOMAIN].items():
if target_entry_ids is None or entry_id in target_entry_ids:
sim.reset_model(
t_room=call.data.get("t_room"),
t_fabric=call.data.get("t_fabric"),
t_rad=call.data.get("t_rad"),
preset=call.data.get("preset"),
)
if not hass.services.has_service(DOMAIN, ACTION_RESET):
hass.services.async_register(
DOMAIN,
ACTION_RESET,
_handle_reset,
schema=_RESET_SERVICE_SCHEMA,
)
async def _handle_set_weather(call) -> None:
"""Handle the set_weather service call."""
target_devices = call.data.get("device_id")
target_entry_ids: set[str] | None = None
if target_devices:
if isinstance(target_devices, str):
target_devices = [target_devices]
dev_reg = dr.async_get(hass)
target_entry_ids = set()
for device_id in target_devices:
device = dev_reg.async_get(device_id)
if device is None:
continue
for entry_id in device.config_entries:
if entry_id in hass.data[DOMAIN]:
target_entry_ids.add(entry_id)
for entry_id, sim in hass.data[DOMAIN].items():
if target_entry_ids is None or entry_id in target_entry_ids:
sim.set_weather(
wind_speed_m_s=call.data.get("wind_speed_m_s"),
rain_intensity_fraction=call.data.get("rain_intensity_fraction"),
)
if not hass.services.has_service(DOMAIN, ACTION_SET_WEATHER):
hass.services.async_register(
DOMAIN,
ACTION_SET_WEATHER,
_handle_set_weather,
schema=_SET_WEATHER_SERVICE_SCHEMA,
)
return True
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate config entries to the current schema version (2).
All parameters added across versions are optional with zero/False defaults,
so no data transformation is ever required between any two versions.
This handler stamps entries stored at any version ≤ 2 up to version 2,
eliminating the "migration handler not found" errors on startup.
If the stored version is somehow higher than what the code supports,
we refuse the migration and log an error rather than silently corrupting
the entry.
"""
_LOGGER.debug(
"Migrating %s entry %s from version %s to version 2",
DOMAIN,
entry.entry_id,
entry.version,
)
if entry.version > 2:
_LOGGER.error(
"Cannot migrate %s entry %s: stored version %s is newer than "
"the integration supports (2). Upgrade the integration.",
DOMAIN,
entry.entry_id,
entry.version,
)
return False
# version 1 → 2 and version 2 → 2: no data transformation needed
hass.config_entries.async_update_entry(entry, version=2)
_LOGGER.info(
"Migrated %s entry %s to version 2 (no data changes needed)",
DOMAIN,
entry.entry_id,
)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
simulator: HeatingSimulator = hass.data[DOMAIN].pop(entry.entry_id)
simulator.async_stop()
# Remove the service only when the last instance is unloaded
if not hass.data[DOMAIN]:
hass.services.async_remove(DOMAIN, ACTION_RESET)
hass.services.async_remove(DOMAIN, ACTION_SET_WEATHER)
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
async def _async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
await hass.config_entries.async_reload(entry.entry_id)
# ---------------------------------------------------------------------------
# Coordinator
# ---------------------------------------------------------------------------
class HeatingSimulator:
"""
Coordinates the active thermal model and exposes its state to HA entities.
Responsibilities:
- Instantiate the correct ThermalModel subclass from config.
- Tick the model on a fixed interval.
- Track external temperature, solar irradiance, and flow temperature entities.
- Provide a unified set_power_fraction / set_pwm_switch API for entities.
- Notify listeners (push, not poll) on every tick and on input changes.
"""
def __init__(
self,
hass: HomeAssistant,
entry: ConfigEntry,
config: dict[str, Any],
) -> None:
self.hass = hass
self.entry = entry
self.config = config
self.model_type: str = config.get(CONF_MODEL_TYPE, MODEL_SIMPLE)
self.control_mode: str = config.get(CONF_CONTROL_MODE, CONTROL_MODE_LINEAR)
self.update_interval: int = int(config.get(CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL))
initial_temp = float(config.get(CONF_INITIAL_TEMP, DEFAULT_INITIAL_TEMP))
initial_ext = float(config.get(CONF_EXTERNAL_TEMP_FIXED, DEFAULT_EXTERNAL_TEMP_FIXED))
self.model = self._build_model(config, initial_temp, initial_ext)
self._pwm_on: bool = False
self._listeners: list = []
self._unsub_interval = None
self._unsub_ext_temp = None
self._unsub_solar = None
self._unsub_flow_temp = None
# Simulated time counter (seconds since midnight of day 0).
# Seeded from the real wall-clock so that simulated day aligns with the
# actual calendar day.
import datetime as _dt
_now = _dt.datetime.now()
_midnight = _now.replace(hour=0, minute=0, second=0, microsecond=0)
self._sim_time_s: float = (_now - _midnight).total_seconds()
# Disturbance profiles — rebuilt from config on each reload.
cfg = config
self._ext_temp_profile = self._build_ext_temp_profile(cfg)
self._occupancy_profile = self._build_occupancy_profile(cfg)
self._weather_profile = self._build_weather_profile(cfg)
# ------------------------------------------------------------------
# Model factory
# ------------------------------------------------------------------
def _build_model(self, cfg: dict, initial_temp: float, initial_ext: float):
if self.model_type == MODEL_R2C2_RADIATOR:
return R2C2RadiatorModel(
flow_temperature=float(cfg.get(CONF_FLOW_TEMP, DEFAULT_FLOW_TEMP)),
c_radiator=float(cfg.get(CONF_C_RAD, DEFAULT_C_RAD)),
k_radiator=float(cfg.get(CONF_K_RAD, DEFAULT_K_RAD)),
radiator_exponent=float(cfg.get(CONF_RAD_EXPONENT, DEFAULT_RAD_EXPONENT)),
flow_rate_max=float(cfg.get(CONF_FLOW_RATE_MAX, DEFAULT_FLOW_RATE_MAX)),
pipe_delay=float(cfg.get(CONF_PIPE_DELAY, DEFAULT_PIPE_DELAY)),
valve_characteristic=cfg.get(CONF_VALVE_CHARACTERISTIC, DEFAULT_VALVE_CHARACTERISTIC),
c_air=float(cfg.get(CONF_C_AIR, DEFAULT_C_AIR)),
c_fabric=float(cfg.get(CONF_C_FABRIC, DEFAULT_C_FABRIC)),
r_fabric=float(cfg.get(CONF_R_FABRIC, DEFAULT_R_FABRIC)),
r_ext=float(cfg.get(CONF_R_EXT, DEFAULT_R_EXT)),
r_inf=float(cfg.get(CONF_R_INF, DEFAULT_R_INF)),
window_area=float(cfg.get(CONF_WINDOW_AREA, DEFAULT_WINDOW_AREA)),
window_transmittance=float(cfg.get(CONF_WINDOW_TRANSMITTANCE, DEFAULT_WINDOW_TRANSMITTANCE)),
initial_temp=initial_temp,
initial_external_temp=initial_ext,
initial_solar=float(cfg.get(CONF_SOLAR_FIXED, DEFAULT_SOLAR_FIXED)),
)
elif self.model_type == MODEL_RADIATOR:
return WetRadiatorModel(
flow_temperature=float(cfg.get(CONF_FLOW_TEMP, DEFAULT_FLOW_TEMP)),
c_radiator=float(cfg.get(CONF_C_RAD, DEFAULT_C_RAD)),
k_radiator=float(cfg.get(CONF_K_RAD, DEFAULT_K_RAD)),
radiator_exponent=float(cfg.get(CONF_RAD_EXPONENT, DEFAULT_RAD_EXPONENT)),
flow_rate_max=float(cfg.get(CONF_FLOW_RATE_MAX, DEFAULT_FLOW_RATE_MAX)),
heat_loss_coeff=float(cfg.get(CONF_HEAT_LOSS_COEFF_RAD, DEFAULT_HEAT_LOSS_COEFF_RAD)),
c_room=float(cfg.get(CONF_C_ROOM_RAD, DEFAULT_C_ROOM_RAD)),
pipe_delay=float(cfg.get(CONF_PIPE_DELAY, DEFAULT_PIPE_DELAY)),
valve_characteristic=cfg.get(CONF_VALVE_CHARACTERISTIC, DEFAULT_VALVE_CHARACTERISTIC),
initial_temp=initial_temp,
initial_external_temp=initial_ext,
)
elif self.model_type == MODEL_R2C2:
return R2C2ThermalModel(
heater_power_watts=float(cfg.get(CONF_HEATER_POWER_R2C2, DEFAULT_HEATER_POWER_R2C2)),
c_air=float(cfg.get(CONF_C_AIR, DEFAULT_C_AIR)),
c_fabric=float(cfg.get(CONF_C_FABRIC, DEFAULT_C_FABRIC)),
r_fabric=float(cfg.get(CONF_R_FABRIC, DEFAULT_R_FABRIC)),
r_ext=float(cfg.get(CONF_R_EXT, DEFAULT_R_EXT)),
r_inf=float(cfg.get(CONF_R_INF, DEFAULT_R_INF)),
window_area=float(cfg.get(CONF_WINDOW_AREA, DEFAULT_WINDOW_AREA)),
window_transmittance=float(cfg.get(CONF_WINDOW_TRANSMITTANCE, DEFAULT_WINDOW_TRANSMITTANCE)),
initial_temp=initial_temp,
initial_external_temp=initial_ext,
initial_solar=float(cfg.get(CONF_SOLAR_FIXED, DEFAULT_SOLAR_FIXED)),
)
else: # MODEL_SIMPLE
return SimpleThermalModel(
heater_power_watts=float(cfg.get(CONF_HEATER_POWER, DEFAULT_HEATER_POWER)),
heat_loss_coeff=float(cfg.get(CONF_HEAT_LOSS_COEFF, DEFAULT_HEAT_LOSS_COEFF)),
thermal_mass=float(cfg.get(CONF_THERMAL_MASS, DEFAULT_THERMAL_MASS)),
thermal_inertia_tau=float(cfg.get(CONF_THERMAL_INERTIA, DEFAULT_THERMAL_INERTIA)),
initial_temp=initial_temp,
initial_external_temp=initial_ext,
)
# ------------------------------------------------------------------
# Disturbance profile factories
# ------------------------------------------------------------------
def _build_ext_temp_profile(self, cfg: dict) -> ExternalTempProfile:
return ExternalTempProfile(
enabled=bool(cfg.get(CONF_EXT_TEMP_PROFILE_ENABLED, DEFAULT_EXT_TEMP_PROFILE_ENABLED)),
base_temp=float(cfg.get(CONF_EXT_TEMP_BASE, DEFAULT_EXT_TEMP_BASE)),
temp_amplitude=float(cfg.get(CONF_EXT_TEMP_AMPLITUDE, DEFAULT_EXT_TEMP_AMPLITUDE)),
min_hour=float(cfg.get(CONF_EXT_TEMP_MIN_HOUR, DEFAULT_EXT_TEMP_MIN_HOUR)),
max_hour=float(cfg.get(CONF_EXT_TEMP_MAX_HOUR, DEFAULT_EXT_TEMP_MAX_HOUR)),
)
def _build_occupancy_profile(self, cfg: dict) -> OccupancyProfile:
return OccupancyProfile(
enabled=bool(cfg.get(CONF_OCCUPANCY_ENABLED, DEFAULT_OCCUPANCY_ENABLED)),
max_occupants=int(cfg.get(CONF_OCCUPANCY_MAX_OCCUPANTS, DEFAULT_OCCUPANCY_MAX_OCCUPANTS)),
cooking_power_watts=float(cfg.get(CONF_OCCUPANCY_COOKING_POWER, DEFAULT_OCCUPANCY_COOKING_POWER)),
cooking_duration_s=float(cfg.get(CONF_OCCUPANCY_COOKING_DURATION, DEFAULT_OCCUPANCY_COOKING_DURATION)),
cooking_events_per_day=float(cfg.get(CONF_OCCUPANCY_COOKING_EVENTS_PER_DAY, DEFAULT_OCCUPANCY_COOKING_EVENTS_PER_DAY)),
seed=int(cfg.get(CONF_OCCUPANCY_SEED, DEFAULT_OCCUPANCY_SEED)),
)
def _build_weather_profile(self, cfg: dict) -> WeatherProfile:
return WeatherProfile(
wind_speed_m_s=float(cfg.get(CONF_WIND_SPEED, DEFAULT_WIND_SPEED)),
wind_coefficient=float(cfg.get(CONF_WIND_COEFFICIENT, DEFAULT_WIND_COEFFICIENT)),
rain_intensity_fraction=float(cfg.get(CONF_RAIN_INTENSITY, DEFAULT_RAIN_INTENSITY)),
rain_moisture_factor=float(cfg.get(CONF_RAIN_MOISTURE_FACTOR, DEFAULT_RAIN_MOISTURE_FACTOR)),
)
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
async def async_start(self) -> None:
"""Start the simulation loop and subscribe to input entities."""
self._unsub_interval = async_track_time_interval(
self.hass,
self._async_tick,
timedelta(seconds=self.update_interval),
)
self._subscribe_ext_temp()
self._subscribe_solar()
self._subscribe_flow_temp()
def restore_temperatures(
self,
t_room: float | None,
t_fabric: float | None = None,
t_rad: float | None = None,
) -> None:
"""Inject previously-persisted temperatures into the model after HA restarts."""
if t_room is not None:
self.model.restore_room_temp(t_room)
if t_fabric is not None and hasattr(self.model, "restore_fabric_temp"):
self.model.restore_fabric_temp(t_fabric)
if t_rad is not None and hasattr(self.model, "restore_radiator_temp"):
self.model.restore_radiator_temp(t_rad)
def reset_model(
self,
t_room: float | None = None,
t_fabric: float | None = None,
t_rad: float | None = None,
preset: str | None = None,
) -> None:
"""Reset the simulation to a known state."""
if preset is not None and preset in RESET_PRESETS:
p = RESET_PRESETS[preset]
t_room = p["t_room"] if t_room is None else t_room
t_fabric = p["t_fabric"] if t_fabric is None else t_fabric
if t_room is None:
t_room = self.model.external_temperature
if t_room is not None:
self.model.restore_room_temp(float(t_room))
if t_fabric is not None and hasattr(self.model, "restore_fabric_temp"):
self.model.restore_fabric_temp(float(t_fabric))
elif t_room is not None and hasattr(self.model, "restore_fabric_temp"):
self.model.restore_fabric_temp(float(t_room))
if t_rad is not None and hasattr(self.model, "restore_radiator_temp"):
self.model.restore_radiator_temp(float(t_rad))
elif t_room is not None and hasattr(self.model, "restore_radiator_temp"):
self.model.restore_radiator_temp(float(t_room))
self._notify_listeners()
def async_stop(self) -> None:
"""Stop the simulation loop and unsubscribe from input entities."""
if self._unsub_interval:
self._unsub_interval()
if self._unsub_ext_temp:
self._unsub_ext_temp()
if self._unsub_solar:
self._unsub_solar()
if self._unsub_flow_temp:
self._unsub_flow_temp()
def _subscribe_ext_temp(self) -> None:
entity_id = self.config.get(CONF_EXTERNAL_TEMP, "")
if entity_id:
self._unsub_ext_temp = async_track_state_change_event(
self.hass, [entity_id], self._async_ext_temp_changed
)
def _subscribe_solar(self) -> None:
entity_id = self.config.get(CONF_SOLAR_ENTITY, "")
if entity_id and hasattr(self.model, "set_solar_irradiance"):
self._unsub_solar = async_track_state_change_event(
self.hass, [entity_id], self._async_solar_changed
)
def _subscribe_flow_temp(self) -> None:
entity_id = self.config.get(CONF_FLOW_TEMP_ENTITY, "")
if entity_id and hasattr(self.model, "set_flow_temperature"):
self._unsub_flow_temp = async_track_state_change_event(
self.hass, [entity_id], self._async_flow_temp_changed
)
# ------------------------------------------------------------------
# Tick
# ------------------------------------------------------------------
async def _async_tick(self, now) -> None:
dt = float(self.update_interval)
# F-11: external temperature profile
if self._ext_temp_profile.enabled:
t_ext = self._ext_temp_profile.temperature_at(self._sim_time_s)
self.model.set_external_temperature(t_ext)
# F-05: Occupancy / internal gain
self.model.internal_gain_watts = self._occupancy_profile.gain_at(self._sim_time_s)
# F-06, F-14: Wind and rain effects on heat loss
self.model.weather_k_multiplier = self._weather_profile.multiplier
self._sim_time_s += dt
self.model.step(dt)
self._notify_listeners()
# ------------------------------------------------------------------
# Entity state callbacks
# ------------------------------------------------------------------
@callback
def _async_ext_temp_changed(self, event) -> None:
new_state = event.data.get("new_state")
if new_state and new_state.state not in ("unknown", "unavailable"):
try:
self.model.set_external_temperature(float(new_state.state))
except ValueError:
pass
@callback
def _async_solar_changed(self, event) -> None:
new_state = event.data.get("new_state")
if new_state and new_state.state not in ("unknown", "unavailable"):
try:
self.model.set_solar_irradiance(float(new_state.state))
except (ValueError, AttributeError):
pass
@callback
def _async_flow_temp_changed(self, event) -> None:
new_state = event.data.get("new_state")
if new_state and new_state.state not in ("unknown", "unavailable"):
try:
self.model.set_flow_temperature(float(new_state.state))
except (ValueError, AttributeError):
pass
# ------------------------------------------------------------------
# Weather control (live update without reload)
# ------------------------------------------------------------------
def set_weather(
self,
wind_speed_m_s: float | None = None,
rain_intensity_fraction: float | None = None,
) -> None:
"""Update weather disturbance inputs live."""
if wind_speed_m_s is not None:
self._weather_profile.wind_speed_m_s = max(0.0, float(wind_speed_m_s))
if rain_intensity_fraction is not None:
self._weather_profile.rain_intensity_fraction = max(0.0, min(1.0, float(rain_intensity_fraction)))
self._notify_listeners()
@property
def wind_speed(self) -> float:
return self._weather_profile.wind_speed_m_s
@property
def rain_intensity(self) -> float:
return self._weather_profile.rain_intensity_fraction
# ------------------------------------------------------------------
# Power control (unified API for entities)
# ------------------------------------------------------------------
def set_linear_power(self, percent: float) -> None:
fraction = max(0.0, min(1.0, percent / 100.0))
self.model.set_power_fraction(fraction)
self._pwm_on = fraction > 0.0
self._notify_listeners()
def set_pwm_switch(self, on: bool) -> None:
self._pwm_on = on
self.model.set_power_fraction(1.0 if on else 0.0)
self._notify_listeners()
@property
def pwm_on(self) -> bool:
return self._pwm_on or self.model.power_setpoint > 0.0
@property
def power_percent(self) -> float:
return self.model.power_setpoint * 100.0
# ------------------------------------------------------------------
# Listeners
# ------------------------------------------------------------------
def register_listener(self, cb) -> callback:
self._listeners.append(cb)
@callback
def unsubscribe():
if cb in self._listeners:
self._listeners.remove(cb)
return unsubscribe
@callback
def _notify_listeners(self) -> None:
for cb in self._listeners:
cb()