work: исправил архитектуру управления температурой. Теперь отдельный контроллер отвечает за нагрев для всех режимов авто ручной или временный ручной. Раньше в каждом режиме была своя логика.
This commit is contained in:
+223
-208
@@ -33,7 +33,7 @@ from app.my_dataclasses import (
|
||||
from app.auto import (
|
||||
AutoController,
|
||||
Co2SpeedPolicy,
|
||||
load_auto_config,
|
||||
load_auto_config_components,
|
||||
)
|
||||
|
||||
from app.auto.temperature_policy import TemperaturePolicy
|
||||
@@ -138,42 +138,118 @@ async def lifespan(app: FastAPI):
|
||||
schedule_load_error = None
|
||||
|
||||
try:
|
||||
auto_config = load_auto_config(AUTO_CONFIG_FILE)
|
||||
auto_config = load_auto_config_components(AUTO_CONFIG_FILE)
|
||||
|
||||
elica_assist = ElicaAutoAssistState(auto_config.elica_assist)
|
||||
auto_interval = auto_config.check_interval
|
||||
|
||||
auto_policy = Co2SpeedPolicy(
|
||||
base_speed=(
|
||||
auto_config.co2.base_speed
|
||||
),
|
||||
thresholds=(
|
||||
auto_config.co2.thresholds
|
||||
),
|
||||
hysteresis=(
|
||||
auto_config.co2.hysteresis
|
||||
),
|
||||
)
|
||||
auto_errors = dict(auto_config.errors)
|
||||
|
||||
temperature_policy = TemperaturePolicy(auto_config.temperature)
|
||||
|
||||
auto_interval = (auto_config.check_interval)
|
||||
|
||||
auto_load_error = None
|
||||
|
||||
except Exception as exc:
|
||||
# --------------------------------------------------
|
||||
# CO2 policy
|
||||
# --------------------------------------------------
|
||||
auto_policy = None
|
||||
if auto_config.co2 is not None:
|
||||
|
||||
try:
|
||||
auto_policy = Co2SpeedPolicy(
|
||||
base_speed=(
|
||||
auto_config.co2.base_speed
|
||||
),
|
||||
thresholds=(
|
||||
auto_config.co2.thresholds
|
||||
),
|
||||
hysteresis=(
|
||||
auto_config.co2.hysteresis
|
||||
),
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
auto_errors["co2_policy"] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Temperature policy
|
||||
# --------------------------------------------------
|
||||
|
||||
temperature_policy = None
|
||||
|
||||
if (
|
||||
auto_config.temperature
|
||||
is not None
|
||||
):
|
||||
|
||||
try:
|
||||
temperature_policy = TemperaturePolicy(auto_config.temperature)
|
||||
|
||||
except Exception as exc:
|
||||
auto_errors[
|
||||
"temperature_policy"
|
||||
] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Elica Assist
|
||||
# --------------------------------------------------
|
||||
|
||||
elica_assist = None
|
||||
|
||||
if (
|
||||
auto_config.elica_assist
|
||||
is not None
|
||||
):
|
||||
|
||||
try:
|
||||
elica_assist = ElicaAutoAssistState(auto_config.elica_assist)
|
||||
|
||||
except Exception as exc:
|
||||
auto_errors[
|
||||
"elica_assist"
|
||||
] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Общая диагностика
|
||||
# --------------------------------------------------
|
||||
|
||||
if auto_errors:
|
||||
auto_load_error = "; ".join(
|
||||
(
|
||||
f"{name}: {error}"
|
||||
)
|
||||
for name, error
|
||||
in auto_errors.items()
|
||||
)
|
||||
|
||||
else:
|
||||
auto_load_error = None
|
||||
|
||||
except Exception as exc:
|
||||
|
||||
# Здесь остаются только ошибки,
|
||||
# из-за которых невозможно разобрать
|
||||
# auto.yaml вообще.
|
||||
|
||||
auto_policy = None
|
||||
temperature_policy = None
|
||||
elica_assist = None
|
||||
|
||||
# Безопасный встроенный интервал нужен,
|
||||
# потому что auto.yaml сейчас недоступен.
|
||||
auto_interval = 5.0
|
||||
|
||||
auto_load_error = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# AutoController создаётся даже если, например,
|
||||
# CO2 policy не загрузилась.
|
||||
#
|
||||
# policy=None даст fallback скорости,
|
||||
# но TemperaturePolicy при этом может работать.
|
||||
# --------------------------------------------------
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=schedule_service,
|
||||
qingping_service=qingping_service,
|
||||
@@ -341,53 +417,25 @@ def get_status() -> dict:
|
||||
|
||||
if (
|
||||
tion_status is not None
|
||||
and schedule_service is not None
|
||||
and schedule_service.paused
|
||||
and auto_controller is not None
|
||||
):
|
||||
temperature_config = (auto_controller.effective_temperature_config())
|
||||
|
||||
if (
|
||||
auto_controller.manual_heater_enabled
|
||||
temperature_config.heater_enabled
|
||||
is not None
|
||||
):
|
||||
tion_status["heater"] = (
|
||||
auto_controller
|
||||
.manual_heater_enabled
|
||||
temperature_config.heater_enabled
|
||||
)
|
||||
|
||||
if (
|
||||
auto_controller.manual_target_temperature
|
||||
temperature_config.target_temp
|
||||
is not None
|
||||
):
|
||||
tion_status["target_temp"] = (
|
||||
auto_controller
|
||||
.manual_target_temperature
|
||||
temperature_config.target_temp
|
||||
)
|
||||
elif tion_status is not None:
|
||||
schedule = schedule_service
|
||||
|
||||
if schedule is not None:
|
||||
# Ручной override имеет приоритет над AUTO.
|
||||
if (
|
||||
schedule.override_active
|
||||
and schedule.override_settings.target_temp
|
||||
is not None
|
||||
):
|
||||
tion_status["target_temp"] = (
|
||||
schedule.override_settings.target_temp
|
||||
)
|
||||
|
||||
else:
|
||||
resolution = schedule.resolve()
|
||||
|
||||
if (
|
||||
resolution.enabled
|
||||
and resolution.auto_active
|
||||
and resolution.auto_target_temp
|
||||
is not None
|
||||
):
|
||||
tion_status["target_temp"] = (
|
||||
resolution.auto_target_temp
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -457,27 +505,15 @@ def get_effective_speed() -> int:
|
||||
|
||||
def get_effective_temperature() -> int:
|
||||
|
||||
if (
|
||||
schedule_service is not None
|
||||
and schedule_service.paused
|
||||
and auto_controller is not None
|
||||
and auto_controller.manual_target_temperature is not None
|
||||
):
|
||||
return (
|
||||
if auto_controller is not None:
|
||||
|
||||
config = (
|
||||
auto_controller
|
||||
.manual_target_temperature
|
||||
.effective_temperature_config()
|
||||
)
|
||||
|
||||
if (
|
||||
schedule_service is not None
|
||||
and schedule_service.override_active
|
||||
and schedule_service.override_settings.target_temp is not None
|
||||
):
|
||||
return (
|
||||
schedule_service
|
||||
.override_settings
|
||||
.target_temp
|
||||
)
|
||||
if config.target_temp is not None:
|
||||
return config.target_temp
|
||||
|
||||
state = service.state
|
||||
|
||||
@@ -529,6 +565,60 @@ async def execute_command(operation, override: ScheduledSettings | None = None):
|
||||
|
||||
return get_status()
|
||||
|
||||
async def execute_temperature_command(
|
||||
operation,
|
||||
settings: ScheduledSettings,
|
||||
):
|
||||
|
||||
try:
|
||||
|
||||
if (
|
||||
auto_controller is not None
|
||||
and schedule_service is not None
|
||||
and schedule_service.running
|
||||
and schedule_service.config.enabled
|
||||
):
|
||||
|
||||
# ------------------------------------------
|
||||
# PAUSE = полноценный ручной режим.
|
||||
# ------------------------------------------
|
||||
|
||||
if schedule_service.paused:
|
||||
|
||||
if settings.heater is not None:
|
||||
auto_controller.set_manual_heater_enabled(settings.heater)
|
||||
|
||||
if settings.target_temp is not None:
|
||||
auto_controller.set_manual_target_temperature(settings.target_temp)
|
||||
|
||||
# ------------------------------------------
|
||||
# SET / AUTO = temporary override.
|
||||
# ------------------------------------------
|
||||
|
||||
else:
|
||||
await schedule_service.apply_override(settings)
|
||||
|
||||
# Не ждём следующего 5-секундного цикла.
|
||||
await auto_controller.reconcile_temperature()
|
||||
|
||||
else:
|
||||
# Fallback, если расписание/AutoController
|
||||
# вообще не работают.
|
||||
await service.execute(operation)
|
||||
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={
|
||||
"message": "Tion unavailable",
|
||||
"error": (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
),
|
||||
},
|
||||
) from exc
|
||||
|
||||
return get_status()
|
||||
|
||||
|
||||
def occurrence_to_dict(occurrence) -> dict | None:
|
||||
|
||||
@@ -676,7 +766,6 @@ def get_auto_status() -> dict:
|
||||
# ----------------------------------------------------------------------
|
||||
# Status
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/status")
|
||||
async def status():
|
||||
return get_status()
|
||||
@@ -685,7 +774,6 @@ async def status():
|
||||
# ----------------------------------------------------------------------
|
||||
# Elica / exhaust
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/elica/status")
|
||||
async def elica_status():
|
||||
return get_elica_status()
|
||||
@@ -734,7 +822,6 @@ async def set_external_fan(state: Literal["on", "off"]):
|
||||
# ----------------------------------------------------------------------
|
||||
# Power
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/power/{state}")
|
||||
async def set_power(state: Literal["on", "off"]):
|
||||
|
||||
@@ -754,7 +841,6 @@ async def set_power(state: Literal["on", "off"]):
|
||||
# ----------------------------------------------------------------------
|
||||
# Fan speed increase / decrease
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/speed/increase")
|
||||
async def increase_speed():
|
||||
|
||||
@@ -816,116 +902,57 @@ async def set_speed(
|
||||
# ----------------------------------------------------------------------
|
||||
# Heater
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/heater/{state}")
|
||||
async def set_heater(state: Literal["on", "off"]):
|
||||
async def set_heater(
|
||||
state: Literal["on", "off"],
|
||||
):
|
||||
|
||||
enabled = state == "on"
|
||||
|
||||
if enabled:
|
||||
operation = lambda tion: tion.heater_on()
|
||||
else:
|
||||
operation = lambda tion: tion.heater_off()
|
||||
operation = (
|
||||
(lambda tion: tion.heater_on())
|
||||
if enabled
|
||||
else
|
||||
(lambda tion: tion.heater_off())
|
||||
)
|
||||
|
||||
|
||||
await execute_command(operation, ScheduledSettings(heater=enabled))
|
||||
|
||||
if (
|
||||
schedule_service is not None
|
||||
and schedule_service.paused
|
||||
and auto_controller is not None
|
||||
):
|
||||
auto_controller.set_manual_heater_enabled(
|
||||
enabled
|
||||
)
|
||||
|
||||
return get_status()
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Target temperature increase / decrease
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/temperature/increase")
|
||||
async def increase_temperature():
|
||||
|
||||
current_temperature = get_effective_temperature()
|
||||
|
||||
new_temperature = min(current_temperature + 1, MAX_TARGET_TEMP)
|
||||
|
||||
if new_temperature == current_temperature:
|
||||
return get_status()
|
||||
|
||||
await execute_command(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(
|
||||
new_temperature
|
||||
),
|
||||
return await execute_temperature_command(
|
||||
operation,
|
||||
ScheduledSettings(
|
||||
target_temp=new_temperature,
|
||||
heater=enabled,
|
||||
),
|
||||
)
|
||||
|
||||
if (
|
||||
schedule_service is not None
|
||||
and schedule_service.paused
|
||||
and auto_controller is not None
|
||||
):
|
||||
auto_controller.set_manual_target_temperature(new_temperature)
|
||||
|
||||
return get_status()
|
||||
|
||||
|
||||
@app.post("/api/tion/temperature/{temperature}")
|
||||
async def set_temperature(
|
||||
temperature: int,
|
||||
):
|
||||
await execute_command(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(
|
||||
temperature
|
||||
),
|
||||
ScheduledSettings(
|
||||
target_temp=temperature,
|
||||
),
|
||||
)
|
||||
|
||||
if (
|
||||
schedule_service is not None
|
||||
and schedule_service.paused
|
||||
and auto_controller is not None
|
||||
):
|
||||
auto_controller.set_manual_target_temperature(
|
||||
temperature
|
||||
)
|
||||
|
||||
return get_status()
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Target temperature
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/temperature/{temperature}")
|
||||
|
||||
async def set_temperature(
|
||||
temperature: Annotated[
|
||||
int,
|
||||
Path(
|
||||
ge=MIN_TARGET_TEMP,
|
||||
le=MAX_TARGET_TEMP,
|
||||
),
|
||||
],):
|
||||
int,
|
||||
Path(
|
||||
ge=MIN_TARGET_TEMP,
|
||||
le=MAX_TARGET_TEMP,
|
||||
),
|
||||
],
|
||||
):
|
||||
|
||||
return await execute_command(
|
||||
return await execute_temperature_command(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(temperature),
|
||||
ScheduledSettings(target_temp=temperature),
|
||||
tion.set_target_temperature(
|
||||
temperature
|
||||
),
|
||||
|
||||
ScheduledSettings(
|
||||
target_temp=temperature,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Air mode
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/mode/{mode}")
|
||||
async def set_mode(
|
||||
mode: str,
|
||||
@@ -957,7 +984,6 @@ async def set_mode(
|
||||
# ----------------------------------------------------------------------
|
||||
# Sound
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/sound/{value}")
|
||||
async def set_sound(
|
||||
value: Literal["on", "off"],
|
||||
@@ -980,7 +1006,6 @@ async def set_sound(
|
||||
# ----------------------------------------------------------------------
|
||||
# Light
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/light/{value}")
|
||||
async def set_light(
|
||||
value: Literal["on", "off"],
|
||||
@@ -1002,7 +1027,6 @@ async def set_light(
|
||||
# ----------------------------------------------------------------------
|
||||
# Переход в auto
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/schedule/config")
|
||||
async def get_schedule_config():
|
||||
try:
|
||||
@@ -1092,6 +1116,9 @@ async def clear_schedule_override():
|
||||
|
||||
await schedule_service.clear_override()
|
||||
|
||||
if auto_controller is not None:
|
||||
await auto_controller.reconcile_temperature()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"schedule": get_schedule_status(),
|
||||
@@ -1110,56 +1137,42 @@ async def pause_schedule():
|
||||
detail="Schedule service unavailable",
|
||||
)
|
||||
|
||||
state = service.state
|
||||
# ВАЖНО:
|
||||
# получаем логические настройки ДО pause(),
|
||||
# потому что там ещё действует SET/AUTO/override.
|
||||
temperature_config = None
|
||||
|
||||
manual_target = None
|
||||
|
||||
if state is not None:
|
||||
manual_target = state.target_temp
|
||||
|
||||
resolution = schedule_service.resolve()
|
||||
|
||||
# Если выходим в manual прямо из AUTO,
|
||||
# физическая уставка Tion могла быть 30°C.
|
||||
# Пользователю нужна настоящая AUTO-цель.
|
||||
if (
|
||||
resolution.auto_active
|
||||
and resolution.auto_target_temp
|
||||
is not None
|
||||
):
|
||||
manual_target = (
|
||||
resolution.auto_target_temp
|
||||
)
|
||||
|
||||
# Temporary override имеет ещё больший
|
||||
# приоритет.
|
||||
if (
|
||||
schedule_service.override_active
|
||||
and schedule_service
|
||||
.override_settings
|
||||
.target_temp is not None
|
||||
):
|
||||
manual_target = (
|
||||
schedule_service
|
||||
.override_settings
|
||||
.target_temp
|
||||
)
|
||||
if auto_controller is not None:
|
||||
temperature_config = (
|
||||
auto_controller
|
||||
.effective_temperature_config()
|
||||
)
|
||||
|
||||
await schedule_service.pause()
|
||||
|
||||
if (
|
||||
auto_controller is not None
|
||||
and state is not None
|
||||
and temperature_config is not None
|
||||
):
|
||||
auto_controller.set_manual_heater_enabled(
|
||||
state.heater
|
||||
)
|
||||
|
||||
if manual_target is not None:
|
||||
auto_controller.set_manual_target_temperature(
|
||||
manual_target
|
||||
if (
|
||||
temperature_config.heater_enabled
|
||||
is not None
|
||||
):
|
||||
auto_controller.set_manual_heater_enabled(
|
||||
temperature_config.heater_enabled
|
||||
)
|
||||
|
||||
if (
|
||||
temperature_config.target_temp
|
||||
is not None
|
||||
):
|
||||
auto_controller.set_manual_target_temperature(
|
||||
temperature_config.target_temp
|
||||
)
|
||||
|
||||
await auto_controller.reconcile_temperature()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"schedule": get_schedule_status(),
|
||||
@@ -1182,6 +1195,8 @@ async def resume_schedule():
|
||||
if auto_controller is not None:
|
||||
auto_controller.clear_manual_heater_control()
|
||||
|
||||
await auto_controller.reconcile_temperature()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"schedule": get_schedule_status(),
|
||||
|
||||
Reference in New Issue
Block a user