Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a000fb6c44 | ||
|
|
be4c2c403c | ||
|
|
e636bc53ca | ||
|
|
fdb798a430 | ||
|
|
33cdb205b3 | ||
|
|
8069ab65f2 | ||
|
|
455d191ea1 | ||
|
|
0172b6bcf2 | ||
|
|
65cf547c6c | ||
|
|
741be479a6 | ||
|
|
958691a481 | ||
|
|
c22e8bc71d |
Generated
-1
@@ -3,7 +3,6 @@
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.14 (ClimatController)" jdkType="Python SDK" />
|
||||
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
[version]
|
||||
major = 1
|
||||
minor = 5
|
||||
patch = 9
|
||||
minor = 2
|
||||
patch = 1
|
||||
|
||||
[build]
|
||||
date = "2026-09-29"
|
||||
time = "23:38:58"
|
||||
date = "2026-09-20"
|
||||
time = "11:28:15"
|
||||
|
||||
+92
-405
@@ -9,17 +9,12 @@ from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pathlib import Path as FilePath
|
||||
from app.qingping.service import QingpingService
|
||||
from app.metrics import PrometheusMetricsService
|
||||
from app.elica import ElicaConfig, ElicaController, ElicaService
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.my_dataclasses import (
|
||||
TION_MAC,
|
||||
QINGPING_MAC,
|
||||
QINGPING_MQTT_HOST,
|
||||
QINGPING_MQTT_PORT,
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
MIN_FAN_SPEED,
|
||||
MAX_FAN_SPEED,
|
||||
MIN_TARGET_TEMP,
|
||||
@@ -33,7 +28,7 @@ from app.my_dataclasses import (
|
||||
from app.auto import (
|
||||
AutoController,
|
||||
Co2SpeedPolicy,
|
||||
load_auto_config_components,
|
||||
load_auto_config,
|
||||
)
|
||||
|
||||
from app.auto.temperature_policy import TemperaturePolicy
|
||||
@@ -91,22 +86,12 @@ qingping_service = QingpingService(
|
||||
mac=QINGPING_MAC,
|
||||
)
|
||||
|
||||
elica_service = ElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
elica_controller = ElicaController(elica_service)
|
||||
|
||||
schedule_service: ScheduleService | None = None
|
||||
schedule_load_error: str | None = None
|
||||
|
||||
auto_controller: AutoController | None = None
|
||||
auto_load_error: str | None = None
|
||||
|
||||
metrics_service: PrometheusMetricsService | None = None
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Application lifecycle
|
||||
# ----------------------------------------------------------------------
|
||||
@@ -117,11 +102,9 @@ async def lifespan(app: FastAPI):
|
||||
global schedule_load_error
|
||||
global auto_controller
|
||||
global auto_load_error
|
||||
global metrics_service
|
||||
|
||||
await service.start()
|
||||
await qingping_service.start()
|
||||
await elica_service.start()
|
||||
|
||||
try:
|
||||
try:
|
||||
@@ -138,19 +121,8 @@ async def lifespan(app: FastAPI):
|
||||
schedule_load_error = None
|
||||
|
||||
try:
|
||||
auto_config = load_auto_config_components(AUTO_CONFIG_FILE)
|
||||
auto_config = load_auto_config(AUTO_CONFIG_FILE)
|
||||
|
||||
auto_interval = auto_config.check_interval
|
||||
|
||||
auto_errors = dict(auto_config.errors)
|
||||
|
||||
# --------------------------------------------------
|
||||
# CO2 policy
|
||||
# --------------------------------------------------
|
||||
auto_policy = None
|
||||
if auto_config.co2 is not None:
|
||||
|
||||
try:
|
||||
auto_policy = Co2SpeedPolicy(
|
||||
base_speed=(
|
||||
auto_config.co2.base_speed
|
||||
@@ -163,101 +135,30 @@ async def lifespan(app: FastAPI):
|
||||
),
|
||||
)
|
||||
|
||||
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}"
|
||||
)
|
||||
auto_interval = (auto_config.check_interval)
|
||||
|
||||
# --------------------------------------------------
|
||||
# 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,
|
||||
tion_service=service,
|
||||
elica_controller=elica_controller,
|
||||
policy=auto_policy,
|
||||
temperature_policy=temperature_policy,
|
||||
elica_assist=elica_assist,
|
||||
interval=auto_interval,
|
||||
)
|
||||
|
||||
@@ -266,36 +167,12 @@ async def lifespan(app: FastAPI):
|
||||
except Exception as exc:
|
||||
schedule_service = None
|
||||
schedule_load_error = f"{type(exc).__name__}: {exc}"
|
||||
|
||||
try:
|
||||
metrics_service = PrometheusMetricsService(
|
||||
tion_service=service,
|
||||
qingping_service=qingping_service,
|
||||
schedule_service=schedule_service,
|
||||
auto_controller=auto_controller,
|
||||
output_path=(
|
||||
"/var/lib/prometheus/"
|
||||
"node-exporter/"
|
||||
"climatcontroller.prom"
|
||||
),
|
||||
interval=5.0,
|
||||
)
|
||||
await metrics_service.start()
|
||||
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Could not start Prometheus metrics service")
|
||||
metrics_service = None
|
||||
|
||||
yield
|
||||
|
||||
finally:
|
||||
if metrics_service is not None:
|
||||
await metrics_service.stop()
|
||||
|
||||
if schedule_service is not None:
|
||||
await schedule_service.stop()
|
||||
|
||||
await elica_service.stop()
|
||||
await qingping_service.stop()
|
||||
await service.stop()
|
||||
|
||||
@@ -321,59 +198,22 @@ app.mount(
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return RedirectResponse(url="/ui/tion")
|
||||
return RedirectResponse(url="/ui/panel")
|
||||
|
||||
|
||||
@app.get("/ui", include_in_schema=False)
|
||||
async def ui_root():
|
||||
return RedirectResponse(url="/ui/tion")
|
||||
|
||||
|
||||
# Canonical UI routes. Device-specific names make room for additional
|
||||
# controllers/widgets without overloading generic "panel"/"widget" names.
|
||||
@app.get("/ui/tion", include_in_schema=False)
|
||||
async def ui_tion():
|
||||
return FileResponse(WEB_ROOT / "tion.html", headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/ui/tion-widget", include_in_schema=False)
|
||||
async def ui_tion_widget():
|
||||
return FileResponse(WEB_ROOT / "tion-widget.html", headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/ui/elica", include_in_schema=False)
|
||||
async def ui_elica():
|
||||
return FileResponse(WEB_ROOT / "elica.html", headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/ui/elica-widget", include_in_schema=False)
|
||||
async def ui_elica_widget():
|
||||
return FileResponse(WEB_ROOT / "elica-widget.html", headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
# Backward-compatible aliases for existing bookmarks/Homarr embeds.
|
||||
@app.get("/ui/panel", include_in_schema=False)
|
||||
async def ui_panel_legacy(request: Request):
|
||||
suffix = f"?{request.url.query}" if request.url.query else ""
|
||||
return RedirectResponse(url=f"/ui/tion{suffix}")
|
||||
return RedirectResponse(url="/ui/panel")
|
||||
|
||||
|
||||
@app.get("/ui/widget", include_in_schema=False)
|
||||
async def ui_widget_legacy(request: Request):
|
||||
suffix = f"?{request.url.query}" if request.url.query else ""
|
||||
return RedirectResponse(url=f"/ui/tion-widget{suffix}")
|
||||
async def ui_widget():
|
||||
return FileResponse(WEB_ROOT / "widget.html")
|
||||
|
||||
|
||||
@app.get("/ui/exhaust", include_in_schema=False)
|
||||
async def ui_exhaust_legacy(request: Request):
|
||||
suffix = f"?{request.url.query}" if request.url.query else ""
|
||||
return RedirectResponse(url=f"/ui/elica{suffix}")
|
||||
|
||||
|
||||
@app.get("/ui/exhaust-widget", include_in_schema=False)
|
||||
async def ui_exhaust_widget_legacy(request: Request):
|
||||
suffix = f"?{request.url.query}" if request.url.query else ""
|
||||
return RedirectResponse(url=f"/ui/elica-widget{suffix}")
|
||||
@app.get("/ui/panel", include_in_schema=False)
|
||||
async def ui_panel():
|
||||
return FileResponse(WEB_ROOT / "panel.html")
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
@@ -403,42 +243,6 @@ def get_status() -> dict:
|
||||
|
||||
state = service.state
|
||||
|
||||
tion_status = (
|
||||
state.to_dict()
|
||||
if state is not None
|
||||
else None
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# В ручном режиме UI должен видеть желание
|
||||
# пользователя, а не техническое состояние
|
||||
# внешнего регулятора.
|
||||
# --------------------------------------------------
|
||||
|
||||
if (
|
||||
tion_status is not None
|
||||
and auto_controller is not None
|
||||
):
|
||||
temperature_config = (auto_controller.effective_temperature_config())
|
||||
|
||||
if (
|
||||
temperature_config.heater_enabled
|
||||
is not None
|
||||
):
|
||||
tion_status["heater"] = (
|
||||
temperature_config.heater_enabled
|
||||
)
|
||||
|
||||
if (
|
||||
temperature_config.target_temp
|
||||
is not None
|
||||
):
|
||||
tion_status["target_temp"] = (
|
||||
temperature_config.target_temp
|
||||
)
|
||||
|
||||
|
||||
|
||||
return {
|
||||
"online": service.online,
|
||||
"running": service.running,
|
||||
@@ -451,37 +255,18 @@ def get_status() -> dict:
|
||||
|
||||
"last_error": service.last_error,
|
||||
|
||||
"tion": tion_status,
|
||||
|
||||
"tion": (
|
||||
state.to_dict()
|
||||
if state is not None
|
||||
else None
|
||||
),
|
||||
"auto": get_auto_status(),
|
||||
|
||||
"qingping": qingping_service.status(),
|
||||
|
||||
"elica": get_elica_status(),
|
||||
|
||||
"schedule": get_schedule_status(),
|
||||
}
|
||||
|
||||
def get_elica_status() -> dict:
|
||||
"""Текущее состояние ESP32, вытяжки Elica и внешнего вентилятора."""
|
||||
return elica_service.status()
|
||||
|
||||
|
||||
async def execute_elica_command(operation):
|
||||
try:
|
||||
await operation()
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={
|
||||
"message": "Elica unavailable",
|
||||
"error": f"{type(exc).__name__}: {exc}",
|
||||
},
|
||||
) from exc
|
||||
|
||||
return get_elica_status()
|
||||
|
||||
|
||||
def get_effective_speed() -> int:
|
||||
|
||||
if (
|
||||
@@ -505,16 +290,17 @@ def get_effective_speed() -> int:
|
||||
|
||||
def get_effective_temperature() -> int:
|
||||
|
||||
if auto_controller is not None:
|
||||
|
||||
config = (
|
||||
auto_controller
|
||||
.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
|
||||
|
||||
if state is None:
|
||||
@@ -565,60 +351,6 @@ 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:
|
||||
|
||||
@@ -766,62 +498,16 @@ def get_auto_status() -> dict:
|
||||
# ----------------------------------------------------------------------
|
||||
# Status
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/status")
|
||||
async def status():
|
||||
return get_status()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Elica / exhaust
|
||||
# ----------------------------------------------------------------------
|
||||
@app.get("/api/elica/status")
|
||||
async def elica_status():
|
||||
return get_elica_status()
|
||||
|
||||
|
||||
@app.post("/api/elica/power/{state}")
|
||||
async def set_elica_power(state: Literal["on", "off"]):
|
||||
operation = (
|
||||
elica_controller.power_on
|
||||
if state == "on"
|
||||
else elica_controller.power_off
|
||||
)
|
||||
return await execute_elica_command(operation)
|
||||
|
||||
|
||||
@app.post("/api/elica/speed/{speed}")
|
||||
async def set_elica_speed(
|
||||
speed: Annotated[int, Path(ge=1, le=4)],
|
||||
):
|
||||
return await execute_elica_command(
|
||||
lambda: elica_controller.set_speed(speed)
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/elica/timer/{state}")
|
||||
async def set_elica_timer(state: Literal["on", "off"]):
|
||||
enabled = state == "on"
|
||||
return await execute_elica_command(
|
||||
lambda: elica_controller.set_timer(enabled)
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/elica/light/toggle")
|
||||
async def toggle_elica_light():
|
||||
return await execute_elica_command(elica_controller.toggle_light)
|
||||
|
||||
|
||||
@app.post("/api/elica/external-fan/{state}")
|
||||
async def set_external_fan(state: Literal["on", "off"]):
|
||||
enabled = state == "on"
|
||||
return await execute_elica_command(
|
||||
lambda: elica_controller.set_external_fan(enabled)
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Power
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/power/{state}")
|
||||
async def set_power(state: Literal["on", "off"]):
|
||||
|
||||
@@ -841,6 +527,7 @@ async def set_power(state: Literal["on", "off"]):
|
||||
# ----------------------------------------------------------------------
|
||||
# Fan speed increase / decrease
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/speed/increase")
|
||||
async def increase_speed():
|
||||
|
||||
@@ -902,32 +589,76 @@ 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"
|
||||
|
||||
operation = (
|
||||
(lambda tion: tion.heater_on())
|
||||
if enabled
|
||||
else
|
||||
(lambda tion: tion.heater_off())
|
||||
if enabled:
|
||||
operation = lambda tion: tion.heater_on()
|
||||
else:
|
||||
operation = lambda tion: tion.heater_off()
|
||||
|
||||
|
||||
return await execute_command(
|
||||
operation,
|
||||
ScheduledSettings(heater=enabled),
|
||||
)
|
||||
|
||||
return await execute_temperature_command(
|
||||
operation,
|
||||
# ----------------------------------------------------------------------
|
||||
# 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()
|
||||
|
||||
return await execute_command(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(
|
||||
new_temperature
|
||||
),
|
||||
|
||||
ScheduledSettings(
|
||||
heater=enabled,
|
||||
target_temp=new_temperature,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/tion/temperature/decrease")
|
||||
async def decrease_temperature():
|
||||
|
||||
current_temperature = get_effective_temperature()
|
||||
|
||||
new_temperature = max(current_temperature - 1, MIN_TARGET_TEMP)
|
||||
|
||||
if new_temperature == current_temperature:
|
||||
return get_status()
|
||||
|
||||
return await execute_command(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(
|
||||
new_temperature
|
||||
),
|
||||
|
||||
ScheduledSettings(
|
||||
target_temp=new_temperature,
|
||||
),
|
||||
)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Target temperature
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/temperature/{temperature}")
|
||||
|
||||
async def set_temperature(
|
||||
temperature: Annotated[
|
||||
int,
|
||||
@@ -935,24 +666,19 @@ async def set_temperature(
|
||||
ge=MIN_TARGET_TEMP,
|
||||
le=MAX_TARGET_TEMP,
|
||||
),
|
||||
],
|
||||
):
|
||||
],):
|
||||
|
||||
return await execute_temperature_command(
|
||||
return await execute_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,
|
||||
@@ -984,6 +710,7 @@ async def set_mode(
|
||||
# ----------------------------------------------------------------------
|
||||
# Sound
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/sound/{value}")
|
||||
async def set_sound(
|
||||
value: Literal["on", "off"],
|
||||
@@ -1006,6 +733,7 @@ async def set_sound(
|
||||
# ----------------------------------------------------------------------
|
||||
# Light
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/tion/light/{value}")
|
||||
async def set_light(
|
||||
value: Literal["on", "off"],
|
||||
@@ -1027,6 +755,7 @@ async def set_light(
|
||||
# ----------------------------------------------------------------------
|
||||
# Переход в auto
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@app.get("/api/schedule/config")
|
||||
async def get_schedule_config():
|
||||
try:
|
||||
@@ -1116,9 +845,6 @@ 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(),
|
||||
@@ -1137,42 +863,8 @@ async def pause_schedule():
|
||||
detail="Schedule service unavailable",
|
||||
)
|
||||
|
||||
# ВАЖНО:
|
||||
# получаем логические настройки ДО pause(),
|
||||
# потому что там ещё действует SET/AUTO/override.
|
||||
temperature_config = None
|
||||
|
||||
if auto_controller is not None:
|
||||
temperature_config = (
|
||||
auto_controller
|
||||
.effective_temperature_config()
|
||||
)
|
||||
|
||||
await schedule_service.pause()
|
||||
|
||||
if (
|
||||
auto_controller is not None
|
||||
and temperature_config is not None
|
||||
):
|
||||
|
||||
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(),
|
||||
@@ -1192,11 +884,6 @@ async def resume_schedule():
|
||||
|
||||
await schedule_service.resume()
|
||||
|
||||
if auto_controller is not None:
|
||||
auto_controller.clear_manual_heater_control()
|
||||
|
||||
await auto_controller.reconcile_temperature()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"schedule": get_schedule_status(),
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
from .config import (
|
||||
AutoConfig,
|
||||
AutoConfigComponents,
|
||||
Co2Config,
|
||||
load_auto_config,
|
||||
load_auto_config_components,
|
||||
)
|
||||
|
||||
from .co2_policy import (
|
||||
@@ -21,6 +19,4 @@ __all__ = [
|
||||
"load_auto_config",
|
||||
"Co2SpeedPolicy",
|
||||
"AutoController",
|
||||
"AutoConfigComponents",
|
||||
"load_auto_config_components",
|
||||
]
|
||||
+68
-275
@@ -30,21 +30,6 @@ class Co2Config:
|
||||
class TemperatureConfig:
|
||||
hysteresis: float
|
||||
|
||||
|
||||
@dataclass(
|
||||
frozen=True,
|
||||
slots=True,
|
||||
)
|
||||
class ElicaAssistConfig:
|
||||
enabled: bool
|
||||
|
||||
# (скорость Tion, скорость Elica)
|
||||
speed_map: tuple[
|
||||
tuple[int, int],
|
||||
...
|
||||
]
|
||||
|
||||
|
||||
@dataclass(
|
||||
frozen=True,
|
||||
slots=True,
|
||||
@@ -54,23 +39,8 @@ class AutoConfig:
|
||||
check_interval: float
|
||||
co2: Co2Config
|
||||
temperature: TemperatureConfig
|
||||
elica_assist: ElicaAssistConfig
|
||||
|
||||
|
||||
@dataclass(
|
||||
frozen=True,
|
||||
slots=True,
|
||||
)
|
||||
class AutoConfigComponents:
|
||||
version: int
|
||||
check_interval: float
|
||||
|
||||
co2: Co2Config | None
|
||||
temperature: TemperatureConfig | None
|
||||
elica_assist: ElicaAssistConfig | None
|
||||
|
||||
errors: dict[str, str]
|
||||
|
||||
def _require_dict(name: str, value: Any) -> dict:
|
||||
|
||||
if not isinstance(value, dict):
|
||||
@@ -276,150 +246,9 @@ def _parse_co2(value: Any) -> Co2Config:
|
||||
thresholds=thresholds,
|
||||
)
|
||||
|
||||
def _parse_temperature(value: Any) -> TemperatureConfig:
|
||||
|
||||
data = _require_dict(
|
||||
"temperature",
|
||||
value,
|
||||
)
|
||||
def load_auto_config(path: str | Path) -> AutoConfig:
|
||||
|
||||
unknown = (
|
||||
set(data)
|
||||
- {
|
||||
"hysteresis",
|
||||
}
|
||||
)
|
||||
|
||||
if unknown:
|
||||
raise ValueError(
|
||||
f"Unknown temperature config fields: "
|
||||
f"{sorted(unknown)}"
|
||||
)
|
||||
|
||||
hysteresis = data.get(
|
||||
"hysteresis"
|
||||
)
|
||||
|
||||
if (
|
||||
type(hysteresis)
|
||||
not in {
|
||||
int,
|
||||
float,
|
||||
}
|
||||
):
|
||||
raise ValueError(
|
||||
"temperature.hysteresis "
|
||||
"must be a number"
|
||||
)
|
||||
|
||||
hysteresis = float(hysteresis)
|
||||
|
||||
if hysteresis < 0:
|
||||
raise ValueError(
|
||||
"temperature.hysteresis "
|
||||
"must be >= 0"
|
||||
)
|
||||
|
||||
return TemperatureConfig(
|
||||
hysteresis=hysteresis,
|
||||
)
|
||||
|
||||
def _parse_elica_assist(value: Any) -> ElicaAssistConfig:
|
||||
|
||||
data = _require_dict(
|
||||
"elica_assist",
|
||||
value,
|
||||
)
|
||||
|
||||
unknown = (
|
||||
set(data)
|
||||
- {
|
||||
"enabled",
|
||||
"speed_map",
|
||||
}
|
||||
)
|
||||
|
||||
if unknown:
|
||||
raise ValueError(
|
||||
"Unknown elica_assist config fields: "
|
||||
f"{sorted(unknown)}"
|
||||
)
|
||||
|
||||
enabled = data.get("enabled")
|
||||
|
||||
if type(enabled) is not bool:
|
||||
raise ValueError(
|
||||
"elica_assist.enabled "
|
||||
"must be a boolean"
|
||||
)
|
||||
|
||||
speed_map_data = data.get(
|
||||
"speed_map"
|
||||
)
|
||||
|
||||
if not isinstance(
|
||||
speed_map_data,
|
||||
dict,
|
||||
):
|
||||
raise ValueError(
|
||||
"elica_assist.speed_map "
|
||||
"must be an object"
|
||||
)
|
||||
|
||||
speed_map = []
|
||||
|
||||
for tion_speed, elica_speed in (
|
||||
speed_map_data.items()
|
||||
):
|
||||
|
||||
if type(tion_speed) is not int:
|
||||
raise ValueError(
|
||||
"elica_assist.speed_map keys "
|
||||
"must be integers"
|
||||
)
|
||||
|
||||
if not (
|
||||
MIN_FAN_SPEED
|
||||
<= tion_speed
|
||||
<= MAX_FAN_SPEED
|
||||
):
|
||||
raise ValueError(
|
||||
"Tion speed in "
|
||||
"elica_assist.speed_map "
|
||||
f"must be between "
|
||||
f"{MIN_FAN_SPEED} and "
|
||||
f"{MAX_FAN_SPEED}"
|
||||
)
|
||||
|
||||
if type(elica_speed) is not int:
|
||||
raise ValueError(
|
||||
"Elica speed in "
|
||||
"elica_assist.speed_map "
|
||||
"must be an integer"
|
||||
)
|
||||
|
||||
if not 1 <= elica_speed <= 4:
|
||||
raise ValueError(
|
||||
"Elica speed in "
|
||||
"elica_assist.speed_map "
|
||||
"must be between 1 and 4"
|
||||
)
|
||||
|
||||
speed_map.append(
|
||||
(
|
||||
tion_speed,
|
||||
elica_speed,
|
||||
)
|
||||
)
|
||||
|
||||
speed_map.sort()
|
||||
|
||||
return ElicaAssistConfig(
|
||||
enabled=enabled,
|
||||
speed_map=tuple(speed_map),
|
||||
)
|
||||
|
||||
def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
|
||||
path = Path(path)
|
||||
|
||||
with path.open(
|
||||
@@ -438,7 +267,6 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
|
||||
"check_interval",
|
||||
"co2",
|
||||
"temperature",
|
||||
"elica_assist",
|
||||
}
|
||||
|
||||
if unknown:
|
||||
@@ -460,8 +288,10 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
|
||||
)
|
||||
|
||||
if (
|
||||
type(check_interval)
|
||||
not in {int,float,}
|
||||
type(check_interval) not in {
|
||||
int,
|
||||
float,
|
||||
}
|
||||
):
|
||||
raise ValueError(
|
||||
"check_interval must be a number"
|
||||
@@ -472,125 +302,88 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
|
||||
"check_interval must be > 0"
|
||||
)
|
||||
|
||||
return (data, version, float(check_interval))
|
||||
|
||||
|
||||
def load_auto_config(
|
||||
path: str | Path,
|
||||
) -> AutoConfig:
|
||||
|
||||
(
|
||||
data,
|
||||
version,
|
||||
check_interval,
|
||||
) = _load_auto_root(path)
|
||||
|
||||
# --------------------------------------------------
|
||||
# CO2
|
||||
# --------------------------------------------------
|
||||
|
||||
if "co2" not in data:
|
||||
raise ValueError("co2 config is required")
|
||||
co2 = _parse_co2(data["co2"])
|
||||
raise ValueError(
|
||||
"co2 config is required"
|
||||
)
|
||||
|
||||
co2 = _parse_co2(
|
||||
data["co2"]
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Temperature
|
||||
# --------------------------------------------------
|
||||
|
||||
if "temperature" not in data:
|
||||
raise ValueError("temperature config is required")
|
||||
raise ValueError(
|
||||
"temperature config is required"
|
||||
)
|
||||
|
||||
temperature = _parse_temperature(data["temperature"])
|
||||
temperature_data = _require_dict(
|
||||
"temperature",
|
||||
data["temperature"],
|
||||
)
|
||||
|
||||
unknown_temperature = (
|
||||
set(temperature_data)
|
||||
- {
|
||||
"hysteresis",
|
||||
}
|
||||
)
|
||||
|
||||
if unknown_temperature:
|
||||
raise ValueError(
|
||||
f"Unknown temperature config fields: "
|
||||
f"{sorted(unknown_temperature)}"
|
||||
)
|
||||
|
||||
temperature_hysteresis = (
|
||||
temperature_data.get(
|
||||
"hysteresis"
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
type(temperature_hysteresis)
|
||||
not in {
|
||||
int,
|
||||
float,
|
||||
}
|
||||
):
|
||||
raise ValueError(
|
||||
"temperature.hysteresis "
|
||||
"must be a number"
|
||||
)
|
||||
|
||||
temperature_hysteresis = float(
|
||||
temperature_hysteresis
|
||||
)
|
||||
|
||||
if temperature_hysteresis < 0:
|
||||
raise ValueError(
|
||||
"temperature.hysteresis "
|
||||
"must be >= 0"
|
||||
)
|
||||
|
||||
temperature = TemperatureConfig(
|
||||
hysteresis=temperature_hysteresis,
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Elica Auto Assist
|
||||
# Result
|
||||
# --------------------------------------------------
|
||||
|
||||
if "elica_assist" not in data:
|
||||
raise ValueError("elica_assist config is required")
|
||||
|
||||
elica_assist = _parse_elica_assist(data["elica_assist"])
|
||||
|
||||
return AutoConfig(
|
||||
version=version,
|
||||
check_interval=check_interval,
|
||||
check_interval=float(
|
||||
check_interval
|
||||
),
|
||||
co2=co2,
|
||||
temperature=temperature,
|
||||
elica_assist=elica_assist,
|
||||
)
|
||||
|
||||
def load_auto_config_components(path: str | Path) -> AutoConfigComponents:
|
||||
|
||||
( data,
|
||||
version,
|
||||
check_interval,
|
||||
) = _load_auto_root(path)
|
||||
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
# --------------------------------------------------
|
||||
# CO2
|
||||
# --------------------------------------------------
|
||||
|
||||
co2 = None
|
||||
|
||||
if "co2" not in data:
|
||||
errors["co2"] = "ValueError: co2 config is required"
|
||||
|
||||
else:
|
||||
try:
|
||||
co2 = _parse_co2(data["co2"])
|
||||
|
||||
except Exception as exc:
|
||||
errors["co2"] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Temperature
|
||||
# --------------------------------------------------
|
||||
|
||||
temperature = None
|
||||
|
||||
if "temperature" not in data:
|
||||
errors["temperature"] = "ValueError: temperature config is required"
|
||||
|
||||
else:
|
||||
try:
|
||||
temperature = _parse_temperature(data["temperature"])
|
||||
|
||||
except Exception as exc:
|
||||
errors["temperature"] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Elica Assist
|
||||
# --------------------------------------------------
|
||||
|
||||
elica_assist = None
|
||||
|
||||
if "elica_assist" not in data:
|
||||
errors["elica_assist"] = "ValueError: elica_assist config is required"
|
||||
|
||||
else:
|
||||
try:
|
||||
elica_assist = _parse_elica_assist(data["elica_assist"])
|
||||
|
||||
except Exception as exc:
|
||||
errors["elica_assist"] = (
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
|
||||
return AutoConfigComponents(
|
||||
version=version,
|
||||
check_interval=check_interval,
|
||||
|
||||
co2=co2,
|
||||
temperature=temperature,
|
||||
elica_assist=elica_assist,
|
||||
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+173
-658
File diff suppressed because it is too large
Load Diff
@@ -1,181 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
from .config import ElicaAssistConfig
|
||||
|
||||
|
||||
class ElicaAssistMode(str, Enum):
|
||||
IDLE = "idle"
|
||||
OWNED = "owned"
|
||||
SUPPRESSED = "suppressed"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ElicaAssistRuntime:
|
||||
mode: ElicaAssistMode = ElicaAssistMode.IDLE
|
||||
|
||||
reason: str | None = None
|
||||
|
||||
tion_speed: int | None = None
|
||||
target_speed: int | None = None
|
||||
|
||||
# Скорость, которую автоматика считает
|
||||
# установленной ею самой.
|
||||
expected_speed: int | None = None
|
||||
|
||||
|
||||
class ElicaAutoAssistState:
|
||||
def __init__(
|
||||
self,
|
||||
config: ElicaAssistConfig,
|
||||
):
|
||||
self._config = config
|
||||
self._speed_map = dict(
|
||||
config.speed_map
|
||||
)
|
||||
|
||||
self._runtime = ElicaAssistRuntime()
|
||||
|
||||
@property
|
||||
def mode(self) -> ElicaAssistMode:
|
||||
return self._runtime.mode
|
||||
|
||||
@property
|
||||
def target_speed(self) -> int | None:
|
||||
return self._runtime.target_speed
|
||||
|
||||
@property
|
||||
def expected_speed(self) -> int | None:
|
||||
return self._runtime.expected_speed
|
||||
|
||||
def set_tion_speed(self, tion_speed: int) -> int | None:
|
||||
"""
|
||||
Обновляет текущую AUTO-скорость Tion
|
||||
и вычисляет требуемую скорость Elica.
|
||||
|
||||
Никаких команд Elica здесь нет.
|
||||
"""
|
||||
|
||||
self._runtime.tion_speed = tion_speed
|
||||
|
||||
if not self._config.enabled:
|
||||
target = None
|
||||
else:
|
||||
target = self._speed_map.get(tion_speed)
|
||||
|
||||
self._runtime.target_speed = target
|
||||
|
||||
# Если потребность в Elica закончилась,
|
||||
# SUPPRESSED можно сбросить:
|
||||
# следующий подъём Tion будет уже
|
||||
# новым циклом.
|
||||
if (
|
||||
target is None
|
||||
and self._runtime.mode
|
||||
== ElicaAssistMode.SUPPRESSED
|
||||
):
|
||||
self._runtime.mode = (
|
||||
ElicaAssistMode.IDLE
|
||||
)
|
||||
self._runtime.reason = None
|
||||
self._runtime.expected_speed = None
|
||||
|
||||
return target
|
||||
|
||||
def mark_owned(self, speed: int) -> None:
|
||||
"""
|
||||
Будем вызывать позже только после того,
|
||||
как автоматика действительно успешно
|
||||
включила Elica.
|
||||
"""
|
||||
|
||||
self._runtime.mode = ElicaAssistMode.OWNED
|
||||
|
||||
self._runtime.reason = None
|
||||
self._runtime.expected_speed = speed
|
||||
|
||||
def suppress(self, reason: str) -> None:
|
||||
"""
|
||||
Elica принадлежит пользователю.
|
||||
До конца текущего AUTO-цикла
|
||||
автоматика её не трогает.
|
||||
"""
|
||||
|
||||
self._runtime.mode = ElicaAssistMode.SUPPRESSED
|
||||
|
||||
self._runtime.reason = reason
|
||||
self._runtime.expected_speed = None
|
||||
|
||||
def reset(self) -> None:
|
||||
self._runtime = ElicaAssistRuntime()
|
||||
|
||||
def status(self) -> dict:
|
||||
return {
|
||||
"mode": self._runtime.mode.value,
|
||||
"reason": self._runtime.reason,
|
||||
"tion_speed": self._runtime.tion_speed,
|
||||
"target_speed": self._runtime.target_speed,
|
||||
"expected_speed": self._runtime.expected_speed,
|
||||
}
|
||||
|
||||
def observe_elica(
|
||||
self,
|
||||
power: bool,
|
||||
speed: int,
|
||||
timer: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Передаёт state machine фактическое состояние Elica.
|
||||
|
||||
Пока никаких команд вытяжке не отправляет.
|
||||
"""
|
||||
|
||||
target = self._runtime.target_speed
|
||||
|
||||
# Сейчас Elica для AUTO вообще не требуется.
|
||||
if target is None:
|
||||
return
|
||||
|
||||
# --------------------------------------------------
|
||||
# IDLE
|
||||
#
|
||||
# Tion уже требует помощи Elica, но вытяжка
|
||||
# оказалась включена ещё до того, как автоматика
|
||||
# получила над ней управление.
|
||||
#
|
||||
# Значит считаем её пользовательской и не трогаем
|
||||
# до конца текущего цикла.
|
||||
# --------------------------------------------------
|
||||
|
||||
if self._runtime.mode == ElicaAssistMode.IDLE:
|
||||
if power:
|
||||
self.suppress(
|
||||
"elica_already_on"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
# --------------------------------------------------
|
||||
# OWNED
|
||||
#
|
||||
# Позже в это состояние будем переходить после
|
||||
# успешной автоматической команды.
|
||||
#
|
||||
# Если фактическое состояние перестало совпадать
|
||||
# с тем, которое установила автоматика,
|
||||
# считаем это ручным вмешательством.
|
||||
# --------------------------------------------------
|
||||
|
||||
if self._runtime.mode == ElicaAssistMode.OWNED:
|
||||
expected = (
|
||||
self._runtime.expected_speed
|
||||
)
|
||||
|
||||
if (
|
||||
not power
|
||||
or speed != expected
|
||||
or timer
|
||||
):
|
||||
self.suppress(
|
||||
"manual_intervention"
|
||||
)
|
||||
@@ -1,14 +0,0 @@
|
||||
from .config import ElicaConfig
|
||||
from .controller import ElicaController
|
||||
from .models import ElicaLogicalState, ElicaPanelState, ElicaState, ExternalFanState
|
||||
from .service import ElicaService
|
||||
|
||||
__all__ = [
|
||||
"ElicaConfig",
|
||||
"ElicaController",
|
||||
"ElicaLogicalState",
|
||||
"ElicaPanelState",
|
||||
"ElicaService",
|
||||
"ElicaState",
|
||||
"ExternalFanState",
|
||||
]
|
||||
@@ -1,88 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ElicaConfig:
|
||||
mqtt_host: str
|
||||
mqtt_port: int = 1883
|
||||
|
||||
# Корневой MQTT topic ESPHome-контроллера Elica
|
||||
topic: str = "elica"
|
||||
|
||||
# Длительность виртуального нажатия кнопки
|
||||
pulse_ms: int = 300
|
||||
|
||||
# Физические реле платы ESP32 Relay X8 Modbus.
|
||||
# OUT1-OUT4 используются для кнопок Elica.
|
||||
power_relay: int = 1
|
||||
speed_relay: int = 2
|
||||
light_relay: int = 3
|
||||
timer_relay: int = 4
|
||||
|
||||
# Внешний вытяжной вентилятор подключён к OUT5.
|
||||
# Нагрузка заведена через NC-контакт реле, поэтому логическое
|
||||
# состояние вентилятора инвертировано относительно катушки реле:
|
||||
# relay OFF -> NC замкнут -> fan ON; relay ON -> fan OFF.
|
||||
external_fan_relay: int = 5
|
||||
external_fan_normally_closed: bool = True
|
||||
|
||||
# Индикаторы Elica -> IN
|
||||
speed_1_input: int = 1
|
||||
speed_2_input: int = 2
|
||||
speed_3_input: int = 3
|
||||
speed_4_input: int = 4
|
||||
power_input: int = 5
|
||||
|
||||
# Определение мигания индикатора скорости.
|
||||
blink_max_off_s: float = 1.5
|
||||
blink_hold_s: float = 2.5
|
||||
|
||||
@property
|
||||
def status_topic(self) -> str:
|
||||
"""
|
||||
Доступность ESP32.
|
||||
|
||||
Payload:
|
||||
online
|
||||
offline
|
||||
"""
|
||||
return f"{self.topic}/status"
|
||||
|
||||
def relay_command_topic(self, relay: int) -> str:
|
||||
"""
|
||||
Команда конкретному реле.
|
||||
|
||||
Payload:
|
||||
ON
|
||||
OFF
|
||||
"""
|
||||
return f"{self.topic}/relay/{relay}/set"
|
||||
|
||||
def relay_state_topic(self, relay: int) -> str:
|
||||
"""
|
||||
Состояние конкретного реле.
|
||||
|
||||
Payload:
|
||||
ON
|
||||
OFF
|
||||
"""
|
||||
return f"{self.topic}/relay/{relay}/state"
|
||||
|
||||
def input_state_topic(self, input_number: int) -> str:
|
||||
"""
|
||||
Состояние физического входа IN1-IN8.
|
||||
|
||||
Payload:
|
||||
ON
|
||||
OFF
|
||||
"""
|
||||
return f"{self.topic}/input/{input_number}/state"
|
||||
|
||||
@property
|
||||
def relay_state_wildcard(self) -> str:
|
||||
return f"{self.topic}/relay/+/state"
|
||||
|
||||
@property
|
||||
def input_state_wildcard(self) -> str:
|
||||
return f"{self.topic}/input/+/state"
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
|
||||
from .models import ElicaLogicalState
|
||||
from .service import ElicaService
|
||||
|
||||
|
||||
class ElicaController:
|
||||
"""
|
||||
Высокоуровневый контроллер вытяжки Elica.
|
||||
|
||||
ElicaService отвечает за ESP32, MQTT, реле и входы.
|
||||
ElicaController работает уже с понятиями самой вытяжки:
|
||||
питание, скорость, таймер и свет.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
service: ElicaService,
|
||||
state_timeout: float = 3.0,
|
||||
poll_interval: float = 0.05,
|
||||
speed_inter_press_delay: float = 0.4,
|
||||
|
||||
):
|
||||
self._service = service
|
||||
self._state_timeout = state_timeout
|
||||
self._poll_interval = poll_interval
|
||||
self._speed_inter_press_delay = max(0.0, speed_inter_press_delay)
|
||||
self._last_speed_press_finished_at: float | None = None
|
||||
|
||||
# Не допускаем одновременное выполнение нескольких
|
||||
# последовательностей нажатий кнопок.
|
||||
self._lock = asyncio.Lock()
|
||||
self._external_fan_lock = asyncio.Lock()
|
||||
|
||||
@property
|
||||
def service(self) -> ElicaService:
|
||||
return self._service
|
||||
|
||||
@property
|
||||
def state(self) -> ElicaLogicalState:
|
||||
return self._service.logical_state
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
def _ensure_available(self) -> None:
|
||||
if not self._service.running:
|
||||
raise RuntimeError("Elica service is not running")
|
||||
|
||||
if not self._service.state.mqtt_connected:
|
||||
raise RuntimeError("Elica MQTT is not connected")
|
||||
|
||||
if not self._service.state.device_online:
|
||||
raise RuntimeError("ESP32 Elica controller is offline")
|
||||
|
||||
async def _wait_state(
|
||||
self,
|
||||
predicate: Callable[[ElicaLogicalState], bool],
|
||||
description: str,
|
||||
timeout: float | None = None,
|
||||
) -> ElicaLogicalState:
|
||||
"""Ждёт подтверждения требуемого состояния по обратной связи."""
|
||||
timeout = self._state_timeout if timeout is None else timeout
|
||||
deadline = asyncio.get_running_loop().time() + timeout
|
||||
|
||||
while True:
|
||||
self._ensure_available()
|
||||
self._ensure_feedback_ready()
|
||||
state = self.state
|
||||
|
||||
if predicate(state):
|
||||
return state
|
||||
|
||||
if asyncio.get_running_loop().time() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"Elica did not reach expected state: {description}; "
|
||||
f"current state: {state}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(self._poll_interval)
|
||||
|
||||
async def _power_on_locked(self) -> ElicaLogicalState:
|
||||
"""Включает вытяжку. Вызывается только под self._lock."""
|
||||
await self._ensure_ready()
|
||||
state = self.state
|
||||
|
||||
if state.power:
|
||||
return state
|
||||
|
||||
await self._service.press_power()
|
||||
|
||||
return await self._wait_state(
|
||||
lambda value: value.power,
|
||||
"power on",
|
||||
)
|
||||
|
||||
async def _power_off_locked(self) -> ElicaLogicalState:
|
||||
"""Выключает вытяжку. Вызывается только под self._lock."""
|
||||
await self._ensure_ready()
|
||||
state = self.state
|
||||
|
||||
if not state.power:
|
||||
return state
|
||||
|
||||
await self._service.press_power()
|
||||
|
||||
return await self._wait_state(
|
||||
lambda value: not value.power,
|
||||
"power off",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Power
|
||||
# ------------------------------------------------------------------
|
||||
async def power_on(self) -> ElicaLogicalState:
|
||||
async with self._lock:
|
||||
return await self._power_on_locked()
|
||||
|
||||
async def power_off(self) -> ElicaLogicalState:
|
||||
async with self._lock:
|
||||
return await self._power_off_locked()
|
||||
|
||||
|
||||
async def _press_speed_locked(self) -> None:
|
||||
"""
|
||||
Нажимает Speed с гарантированным минимальным
|
||||
интервалом после предыдущего нажатия.
|
||||
|
||||
Интервал соблюдается и между разными
|
||||
вызовами set_speed().
|
||||
"""
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
if (
|
||||
self._last_speed_press_finished_at is not None
|
||||
and self._speed_inter_press_delay > 0
|
||||
):
|
||||
elapsed = (
|
||||
loop.time()
|
||||
- self._last_speed_press_finished_at
|
||||
)
|
||||
|
||||
remaining = (
|
||||
self._speed_inter_press_delay
|
||||
- elapsed
|
||||
)
|
||||
|
||||
if remaining > 0:
|
||||
await asyncio.sleep(
|
||||
remaining
|
||||
)
|
||||
|
||||
await self._service.press_speed()
|
||||
|
||||
self._last_speed_press_finished_at = (
|
||||
loop.time()
|
||||
)
|
||||
# ------------------------------------------------------------------
|
||||
# Speed
|
||||
# ------------------------------------------------------------------
|
||||
async def set_speed(self, speed: int) -> ElicaLogicalState:
|
||||
"""Устанавливает скорость 1-4 последовательными нажатиями Speed.
|
||||
|
||||
У Elica одна кнопка скорости и фиксированный цикл:
|
||||
1 -> 2 -> 3 -> 4 -> 1
|
||||
|
||||
Поэтому сначала определяем текущую скорость по индикаторам,
|
||||
вычисляем точное число нажатий и после каждого нажатия ждём
|
||||
подтверждения следующей скорости.
|
||||
"""
|
||||
if not 1 <= speed <= 4:
|
||||
raise ValueError("Elica speed must be between 1 and 4")
|
||||
|
||||
async with self._lock:
|
||||
await self._ensure_ready()
|
||||
state = self.state
|
||||
|
||||
if not state.power:
|
||||
# У Elica кнопка Speed сама включает вытяжку. Первое
|
||||
# нажатие из состояния OFF запускает её на скорости 1.
|
||||
# Поэтому при выборе скорости Power здесь не нажимаем.
|
||||
await self._press_speed_locked()
|
||||
state = await self._wait_state(
|
||||
lambda value: value.power and value.speed == 1,
|
||||
"speed 1",
|
||||
)
|
||||
|
||||
# Если питание уже было включено, но индикатор скорости ещё
|
||||
# не успел синхронизироваться, ждём корректное значение 1-4.
|
||||
if not 1 <= state.speed <= 4:
|
||||
state = await self._wait_state(
|
||||
lambda value: value.power and 1 <= value.speed <= 4,
|
||||
"initial speed",
|
||||
)
|
||||
|
||||
current_speed = state.speed
|
||||
presses = (speed - current_speed) % 4
|
||||
|
||||
for _ in range(presses):
|
||||
expected_speed = current_speed % 4 + 1
|
||||
|
||||
await self._press_speed_locked()
|
||||
|
||||
state = await self._wait_state(
|
||||
lambda value, expected=expected_speed: (
|
||||
value.power and value.speed == expected
|
||||
),
|
||||
f"speed {expected_speed}",
|
||||
)
|
||||
|
||||
current_speed = expected_speed
|
||||
|
||||
|
||||
return state
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Timer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def set_timer(self, enabled: bool) -> ElicaLogicalState:
|
||||
"""
|
||||
Включает или выключает таймер.
|
||||
|
||||
Состояние подтверждается по миганию индикатора скорости.
|
||||
"""
|
||||
async with self._lock:
|
||||
await self._ensure_ready()
|
||||
state = self.state
|
||||
|
||||
if not enabled and not state.power:
|
||||
return state
|
||||
|
||||
if enabled and not state.power:
|
||||
state = await self._power_on_locked()
|
||||
|
||||
if state.timer == enabled:
|
||||
return state
|
||||
|
||||
await self._service.press_timer()
|
||||
|
||||
# При выключении таймера logical_state.timer остаётся True,
|
||||
# пока не истечёт blink_hold_s после последнего мигания.
|
||||
timeout = max(
|
||||
self._state_timeout,
|
||||
self._service.config.blink_hold_s + 1.5,
|
||||
)
|
||||
|
||||
return await self._wait_state(
|
||||
lambda value: value.timer == enabled,
|
||||
f"timer {'on' if enabled else 'off'}",
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def timer_on(self) -> ElicaLogicalState:
|
||||
return await self.set_timer(True)
|
||||
|
||||
async def timer_off(self) -> ElicaLogicalState:
|
||||
return await self.set_timer(False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Light
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def toggle_light(self) -> None:
|
||||
"""
|
||||
Переключает свет.
|
||||
|
||||
Обратной связи о состоянии света сейчас нет,
|
||||
поэтому light_on/light_off реализовать достоверно нельзя.
|
||||
"""
|
||||
async with self._lock:
|
||||
await self._ensure_ready()
|
||||
await self._service.press_light()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# External fan (OUT5 / NC contact)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def set_external_fan(self, enabled: bool) -> bool:
|
||||
"""
|
||||
Управляет внешним вентилятором через OUT5.
|
||||
|
||||
Вентилятор подключён к NC-контакту, поэтому для включения
|
||||
вентилятора катушка реле должна быть выключена, а для выключения
|
||||
— включена. Физическая инверсия скрыта внутри этого метода.
|
||||
"""
|
||||
async with self._external_fan_lock:
|
||||
self._ensure_available()
|
||||
|
||||
relay = self._service.config.external_fan_relay
|
||||
await self._service.wait_relay_feedback_ready(
|
||||
relay,
|
||||
timeout=self._state_timeout,
|
||||
)
|
||||
|
||||
relay_enabled = (
|
||||
not enabled
|
||||
if self._service.config.external_fan_normally_closed
|
||||
else enabled
|
||||
)
|
||||
|
||||
if self._service.relay_state(relay) != relay_enabled:
|
||||
self._service.set_relay(relay, relay_enabled)
|
||||
await self._service.wait_relay_state(
|
||||
relay,
|
||||
relay_enabled,
|
||||
timeout=self._state_timeout,
|
||||
)
|
||||
|
||||
state = self._service.external_fan_state
|
||||
if state.on is None:
|
||||
raise RuntimeError("External fan state is unavailable")
|
||||
|
||||
return state.on
|
||||
|
||||
async def external_fan_on(self) -> bool:
|
||||
return await self.set_external_fan(True)
|
||||
|
||||
async def external_fan_off(self) -> bool:
|
||||
return await self.set_external_fan(False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Синхронизация начального состояния
|
||||
# ------------------------------------------------------------------
|
||||
async def _ensure_ready(self) -> None:
|
||||
"""Проверяет доступность и ждёт исходной синхронизации feedback."""
|
||||
self._ensure_available()
|
||||
await self._service.wait_feedback_ready(timeout=self._state_timeout)
|
||||
self._ensure_available()
|
||||
|
||||
def _ensure_feedback_ready(self) -> None:
|
||||
if not self._service.feedback_ready:
|
||||
raise RuntimeError("Elica feedback is not synchronized")
|
||||
@@ -1,70 +0,0 @@
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ElicaState:
|
||||
mqtt_connected: bool = False
|
||||
device_online: bool = False
|
||||
|
||||
last_message_at: datetime | None = None
|
||||
|
||||
firmware: str | None = None
|
||||
uptime_seconds: int | None = None
|
||||
|
||||
wifi_rssi: int | None = None
|
||||
|
||||
# Фактические состояния OUT1-OUT8,
|
||||
# полученные от ESPHome через MQTT.
|
||||
relay_states: tuple[bool, ...] = (
|
||||
False, False, False, False,
|
||||
False, False, False, False,
|
||||
)
|
||||
# Состояния оптовходов IN1-IN8, полученные от ESPHome через MQTT.
|
||||
# True означает электрически активный вход платы. Для линий
|
||||
# индикаторов Elica это НЕ равно "LED включён": Elica активна LOW.
|
||||
input_states: tuple[bool, ...] = (
|
||||
False, False, False, False,
|
||||
False, False, False, False,
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
result = asdict(self)
|
||||
|
||||
if result["last_message_at"] is not None:
|
||||
result["last_message_at"] = (
|
||||
result["last_message_at"].isoformat()
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ElicaPanelState:
|
||||
speed_leds: tuple[bool, bool, bool, bool] = (
|
||||
False, False, False, False
|
||||
)
|
||||
power_led: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ElicaLogicalState:
|
||||
power: bool = False
|
||||
speed: int = 0
|
||||
timer: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExternalFanState:
|
||||
available: bool = False
|
||||
on: bool | None = None
|
||||
relay: int = 5
|
||||
relay_on: bool | None = None
|
||||
normally_closed: bool = True
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
@@ -1,733 +0,0 @@
|
||||
import time
|
||||
import asyncio
|
||||
import logging
|
||||
import paho.mqtt.client as mqtt
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
from .config import ElicaConfig
|
||||
from .models import ElicaState, ElicaPanelState, ElicaLogicalState, ExternalFanState
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class ElicaService:
|
||||
"""
|
||||
Низкоуровневый сервис связи с ESP32-контроллером Elica.
|
||||
|
||||
На данном этапе умеет:
|
||||
- подключаться к MQTT;
|
||||
- отслеживать online/offline ESP32;
|
||||
- получать состояния OUT1-OUT8;
|
||||
- включать и выключать любое реле.
|
||||
|
||||
Логика самой вытяжки здесь пока отсутствует.
|
||||
"""
|
||||
def __init__(self, config: ElicaConfig):
|
||||
|
||||
self._config = config
|
||||
|
||||
self._state = ElicaState()
|
||||
self._running = False
|
||||
self._client: mqtt.Client | None = None
|
||||
self._last_speed = 0
|
||||
self._speed_led_off_at: float | None = None
|
||||
self._last_blink_at: float | None = None
|
||||
self._received_input_mask = 0
|
||||
self._received_relay_mask = 0
|
||||
|
||||
|
||||
@property
|
||||
def config(self) -> ElicaConfig:
|
||||
return self._config
|
||||
|
||||
@property
|
||||
def state(self) -> ElicaState:
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def running(self) -> bool:
|
||||
return self._running
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
|
||||
client_id="climatcontroller-elica",
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def stop(self) -> None:
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
self._running = False
|
||||
|
||||
if self._client is not None:
|
||||
self._client.disconnect()
|
||||
self._client.loop_stop()
|
||||
self._client = None
|
||||
|
||||
self._state = replace(
|
||||
self._state,
|
||||
mqtt_connected=False,
|
||||
device_online=False,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# MQTT callbacks
|
||||
# ------------------------------------------------------------------
|
||||
def _on_connect(
|
||||
self,
|
||||
_client,
|
||||
_userdata,
|
||||
_flags,
|
||||
reason_code,
|
||||
_properties=None,
|
||||
) -> None:
|
||||
if reason_code != 0:
|
||||
logger.error("ESP32 elica MQTT connection failed: %s",reason_code)
|
||||
return
|
||||
|
||||
logger.info("ESP32 elica MQTT connected")
|
||||
|
||||
self._received_input_mask = 0
|
||||
self._received_relay_mask = 0
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Подписки сервиса
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
#Статус
|
||||
_client.subscribe(self._config.status_topic)
|
||||
|
||||
#широковещательная подписка статусов реле
|
||||
_client.subscribe(self._config.relay_state_wildcard)
|
||||
|
||||
# широковещательная подписка статусов входов
|
||||
_client.subscribe(self._config.input_state_wildcard)
|
||||
|
||||
self._state = replace(self._state, mqtt_connected=True)
|
||||
|
||||
|
||||
def _on_disconnect(
|
||||
self,
|
||||
_client,
|
||||
_userdata,
|
||||
_disconnect_flags,
|
||||
reason_code,
|
||||
_properties=None,
|
||||
) -> None:
|
||||
|
||||
if self._running:
|
||||
logger.warning("ESP32 Elica MQTT disconnected unexpectedly: %s",reason_code)
|
||||
else:
|
||||
logger.info("ESP32 Elica MQTT disconnected: %s",reason_code)
|
||||
|
||||
self._received_input_mask = 0
|
||||
self._received_relay_mask = 0
|
||||
|
||||
self._state = replace(
|
||||
self._state,
|
||||
mqtt_connected=False,
|
||||
device_online=False,
|
||||
)
|
||||
|
||||
|
||||
def _on_message(
|
||||
self,
|
||||
_client,
|
||||
_userdata,
|
||||
message,
|
||||
) -> None:
|
||||
|
||||
|
||||
|
||||
if message.topic == self._config.status_topic:
|
||||
self._handle_status(message)
|
||||
return
|
||||
|
||||
relay_prefix = f"{self._config.topic}/relay/"
|
||||
if message.topic.startswith(relay_prefix) and message.topic.endswith("/state"):
|
||||
self._handle_relay_state(message)
|
||||
return
|
||||
|
||||
input_prefix = f"{self._config.topic}/input/"
|
||||
if message.topic.startswith(input_prefix) and message.topic.endswith("/state"):
|
||||
self._handle_input_state(message)
|
||||
return
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Device status
|
||||
# ------------------------------------------------------------------
|
||||
def _handle_status(self, message) -> None:
|
||||
payload = message.payload.decode("utf-8").strip()
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
if payload.lower() == "online":
|
||||
device_online = True
|
||||
elif payload.lower() == "offline":
|
||||
device_online = False
|
||||
else:
|
||||
logger.warning("Unknown Exhaust LWT payload: %r",payload)
|
||||
return
|
||||
|
||||
self._state = replace(
|
||||
self._state,
|
||||
device_online=device_online,
|
||||
last_message_at=now,
|
||||
)
|
||||
# ------------------------------------------------------------------
|
||||
# Relay state
|
||||
# ------------------------------------------------------------------
|
||||
def _handle_relay_state(self, message) -> None:
|
||||
"""
|
||||
Обрабатывает сообщения:
|
||||
|
||||
elica/relay/1/state
|
||||
...
|
||||
elica/relay/8/state
|
||||
|
||||
Payload:
|
||||
ON
|
||||
OFF
|
||||
"""
|
||||
|
||||
prefix = f"{self._config.topic}/relay/"
|
||||
suffix = "/state"
|
||||
|
||||
relay_text = message.topic[
|
||||
len(prefix):-len(suffix)
|
||||
]
|
||||
|
||||
try:
|
||||
relay = int(relay_text)
|
||||
except ValueError:
|
||||
logger.warning("Invalid ESP32 Elica relay topic: %s",message.topic)
|
||||
return
|
||||
|
||||
if not 1 <= relay <= 8:
|
||||
logger.warning("ESP32 Elica relay number out of range: %s",relay)
|
||||
return
|
||||
|
||||
try:
|
||||
payload = message.payload.decode("utf-8").strip().upper()
|
||||
|
||||
except UnicodeDecodeError:
|
||||
logger.warning("Invalid ESP32 Elica relay payload")
|
||||
return
|
||||
|
||||
if payload == "ON":
|
||||
enabled = True
|
||||
|
||||
elif payload == "OFF":
|
||||
enabled = False
|
||||
|
||||
else:
|
||||
logger.warning("Unknown ESP32 Elica relay payload: %r",payload,)
|
||||
return
|
||||
|
||||
relay_states = list(self._state.relay_states)
|
||||
|
||||
relay_states[relay - 1] = enabled
|
||||
|
||||
self._state = replace(
|
||||
self._state,
|
||||
relay_states=tuple(relay_states),
|
||||
last_message_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self._received_relay_mask |= 1 << (relay - 1)
|
||||
# ------------------------------------------------------------------
|
||||
# Input state
|
||||
# ------------------------------------------------------------------
|
||||
def _handle_input_state(self, message) -> None:
|
||||
"""
|
||||
Обрабатывает elica/input/1/state ... elica/input/8/state.
|
||||
Payload: ON / OFF.
|
||||
"""
|
||||
prefix = f"{self._config.topic}/input/"
|
||||
suffix = "/state"
|
||||
input_text = message.topic[len(prefix):-len(suffix)]
|
||||
|
||||
try:
|
||||
input_number = int(input_text)
|
||||
except ValueError:
|
||||
logger.warning("Invalid ESP32 Elica input topic: %s", message.topic)
|
||||
return
|
||||
|
||||
if not 1 <= input_number <= 8:
|
||||
logger.warning("ESP32 Elica input number out of range: %s", input_number)
|
||||
return
|
||||
|
||||
try:
|
||||
payload = message.payload.decode("utf-8").strip().upper()
|
||||
except UnicodeDecodeError:
|
||||
logger.warning("Invalid ESP32 Elica input payload")
|
||||
return
|
||||
|
||||
if payload == "ON":
|
||||
enabled = True
|
||||
elif payload == "OFF":
|
||||
enabled = False
|
||||
else:
|
||||
logger.warning("Unknown ESP32 Elica input payload: %r", payload)
|
||||
return
|
||||
|
||||
input_states = list(self._state.input_states)
|
||||
input_states[input_number - 1] = enabled
|
||||
|
||||
self._state = replace(
|
||||
self._state,
|
||||
input_states=tuple(input_states),
|
||||
last_message_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self._received_input_mask |= 1 << (input_number - 1)
|
||||
|
||||
self._update_panel_tracker()
|
||||
|
||||
def input_state(self, input_number: int) -> bool:
|
||||
"""Возвращает последнее известное состояние IN1-IN8."""
|
||||
if not 1 <= input_number <= 8:
|
||||
raise ValueError("Input number must be between 1 and 8")
|
||||
|
||||
return self._state.input_states[input_number - 1]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Elica state tracking
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _update_panel_tracker(self) -> None:
|
||||
"""Отслеживает скорость и мигание индикатора таймера."""
|
||||
# Пока не получили все пять входов панели, не пытаемся
|
||||
# интерпретировать их начальные значения. После инверсии Elica
|
||||
# значение False по умолчанию выглядело бы как включённый LED.
|
||||
if not self.feedback_ready:
|
||||
return
|
||||
|
||||
panel = self.panel_state
|
||||
now = time.monotonic()
|
||||
|
||||
if not panel.power_led:
|
||||
self._last_speed = 0
|
||||
self._speed_led_off_at = None
|
||||
self._last_blink_at = None
|
||||
return
|
||||
|
||||
active_speeds = [
|
||||
index + 1
|
||||
for index, enabled in enumerate(panel.speed_leds)
|
||||
if enabled
|
||||
]
|
||||
|
||||
if active_speeds:
|
||||
speed = active_speeds[0]
|
||||
|
||||
if speed != self._last_speed:
|
||||
self._last_speed = speed
|
||||
self._speed_led_off_at = None
|
||||
self._last_blink_at = None
|
||||
return
|
||||
|
||||
if self._speed_led_off_at is not None:
|
||||
off_time = now - self._speed_led_off_at
|
||||
|
||||
if off_time <= self._config.blink_max_off_s:
|
||||
self._last_blink_at = now
|
||||
|
||||
self._speed_led_off_at = None
|
||||
|
||||
return
|
||||
|
||||
if self._last_speed > 0 and self._speed_led_off_at is None:
|
||||
self._speed_led_off_at = now
|
||||
|
||||
@property
|
||||
def logical_state(self) -> ElicaLogicalState:
|
||||
"""Возвращает интерпретированное состояние вытяжки Elica."""
|
||||
if not self.feedback_ready:
|
||||
return ElicaLogicalState()
|
||||
|
||||
panel = self.panel_state
|
||||
now = time.monotonic()
|
||||
|
||||
if not panel.power_led:
|
||||
return ElicaLogicalState()
|
||||
|
||||
active_speeds = [
|
||||
index + 1
|
||||
for index, enabled in enumerate(panel.speed_leds)
|
||||
if enabled
|
||||
]
|
||||
|
||||
if active_speeds:
|
||||
speed = active_speeds[0]
|
||||
|
||||
elif (
|
||||
self._last_speed > 0
|
||||
and self._speed_led_off_at is not None
|
||||
and now - self._speed_led_off_at <= self._config.blink_max_off_s
|
||||
):
|
||||
speed = self._last_speed
|
||||
|
||||
else:
|
||||
speed = 0
|
||||
|
||||
timer = (
|
||||
speed > 0
|
||||
and self._last_blink_at is not None
|
||||
and now - self._last_blink_at <= self._config.blink_hold_s
|
||||
)
|
||||
|
||||
return ElicaLogicalState(
|
||||
power=True,
|
||||
speed=speed,
|
||||
timer=timer,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# MQTT publish
|
||||
# ------------------------------------------------------------------
|
||||
def _publish(
|
||||
self,
|
||||
topic: str,
|
||||
payload: str,
|
||||
) -> None:
|
||||
|
||||
if not self._running:
|
||||
raise RuntimeError("Elica service is not running")
|
||||
|
||||
if self._client is None or not self._state.mqtt_connected:
|
||||
raise RuntimeError("ESP32 Elica MQTT is not connected")
|
||||
|
||||
result = self._client.publish(
|
||||
topic,
|
||||
payload,
|
||||
retain=False,
|
||||
)
|
||||
|
||||
if result.rc != mqtt.MQTT_ERR_SUCCESS:
|
||||
raise RuntimeError(f"MQTT publish failed: {result.rc}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Relay control
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def set_relay(
|
||||
self,
|
||||
relay: int,
|
||||
enabled: bool,
|
||||
) -> None:
|
||||
"""
|
||||
Устанавливает состояние физического реле OUT1-OUT8.
|
||||
Это низкоуровневая функция.
|
||||
Например:
|
||||
set_relay(1, True)
|
||||
отправит:
|
||||
elica/relay/1/set -> ON
|
||||
"""
|
||||
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError("Relay number must be between 1 and 8")
|
||||
|
||||
topic = self._config.relay_command_topic(relay)
|
||||
payload = "ON" if enabled else "OFF"
|
||||
self._publish(topic, payload)
|
||||
|
||||
|
||||
def relay_state(
|
||||
self,
|
||||
relay: int,
|
||||
) -> bool:
|
||||
"""
|
||||
Возвращает последнее известное состояние реле.
|
||||
"""
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError("Relay number must be between 1 and 8")
|
||||
|
||||
return self._state.relay_states[relay - 1]
|
||||
|
||||
def relay_feedback_ready(self, relay: int) -> bool:
|
||||
"""True, если после подключения уже получено состояние реле."""
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError("Relay number must be between 1 and 8")
|
||||
|
||||
return bool(self._received_relay_mask & (1 << (relay - 1)))
|
||||
|
||||
@property
|
||||
def external_fan_state(self) -> ExternalFanState:
|
||||
"""Логическое состояние внешнего вентилятора на OUT5."""
|
||||
relay = self._config.external_fan_relay
|
||||
ready = self.relay_feedback_ready(relay)
|
||||
|
||||
if not ready:
|
||||
return ExternalFanState(
|
||||
available=False,
|
||||
on=None,
|
||||
relay=relay,
|
||||
relay_on=None,
|
||||
normally_closed=self._config.external_fan_normally_closed,
|
||||
)
|
||||
|
||||
relay_on = self.relay_state(relay)
|
||||
fan_on = (
|
||||
not relay_on
|
||||
if self._config.external_fan_normally_closed
|
||||
else relay_on
|
||||
)
|
||||
|
||||
return ExternalFanState(
|
||||
available=True,
|
||||
on=fan_on,
|
||||
relay=relay,
|
||||
relay_on=relay_on,
|
||||
normally_closed=self._config.external_fan_normally_closed,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public status
|
||||
# ------------------------------------------------------------------
|
||||
def status(self) -> dict:
|
||||
return {
|
||||
"running": self._running,
|
||||
"topic": self._config.topic,
|
||||
"pulse_ms": self._config.pulse_ms,
|
||||
"panel": self.panel_state.to_dict(),
|
||||
"elica": self.logical_state.to_dict(),
|
||||
"external_fan": self.external_fan_state.to_dict(),
|
||||
"feedback_ready": self.feedback_ready,
|
||||
"missing_feedback_inputs": self.missing_feedback_inputs,
|
||||
**self._state.to_dict(),
|
||||
}
|
||||
|
||||
async def pulse_relay(self, relay: int, pulse_ms: int | None = None) -> None:
|
||||
"""
|
||||
Кратковременно включает реле и затем выключает его.
|
||||
|
||||
Перед первой командой обязательно ждём
|
||||
синхронизации MQTT-feedback этого реле.
|
||||
"""
|
||||
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError(
|
||||
"Relay number must be between 1 and 8"
|
||||
)
|
||||
|
||||
duration_ms = (
|
||||
pulse_ms
|
||||
if pulse_ms is not None
|
||||
else self._config.pulse_ms
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ВАЖНО:
|
||||
# после MQTT connect состояния входов панели
|
||||
# и состояний реле приходят независимо.
|
||||
#
|
||||
# Нельзя начинать импульс, пока мы не получили
|
||||
# хотя бы первое достоверное состояние именно
|
||||
# этого OUT.
|
||||
# --------------------------------------------------
|
||||
|
||||
await self.wait_relay_feedback_ready(relay)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Перед новым импульсом реле обязано быть OFF.
|
||||
#
|
||||
# Это дополнительно восстанавливает состояние,
|
||||
# если предыдущая операция была аварийно
|
||||
# прервана на включённом реле.
|
||||
# --------------------------------------------------
|
||||
|
||||
if self.relay_state(relay):
|
||||
self.set_relay(relay,False)
|
||||
|
||||
await self.wait_relay_state(relay,False)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Нажатие
|
||||
# --------------------------------------------------
|
||||
|
||||
self.set_relay(relay,True)
|
||||
|
||||
try:
|
||||
await self.wait_relay_state(relay,True)
|
||||
await asyncio.sleep(duration_ms / 1000)
|
||||
|
||||
finally:
|
||||
# Relay обязательно пытаемся отпустить,
|
||||
# даже если подтверждение ON не пришло.
|
||||
try:
|
||||
self.set_relay(relay,False)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to release Elica relay %s",relay)
|
||||
|
||||
# И ждём подтверждённого отпускания.
|
||||
await self.wait_relay_state(relay,False)
|
||||
|
||||
|
||||
|
||||
|
||||
async def wait_relay_feedback_ready(
|
||||
self,
|
||||
relay: int,
|
||||
timeout: float = 3.0,
|
||||
poll_interval: float = 0.02,
|
||||
) -> None:
|
||||
"""Ждёт первого MQTT-состояния указанного реле после connect."""
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError("Relay number must be between 1 and 8")
|
||||
|
||||
deadline = asyncio.get_running_loop().time() + timeout
|
||||
|
||||
while not self.relay_feedback_ready(relay):
|
||||
if not self._running:
|
||||
raise RuntimeError("Elica service is not running")
|
||||
if not self._state.mqtt_connected:
|
||||
raise RuntimeError("Elica MQTT is not connected")
|
||||
if not self._state.device_online:
|
||||
raise RuntimeError("ESP32 Elica controller is offline")
|
||||
if asyncio.get_running_loop().time() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"Relay {relay} feedback synchronization timeout"
|
||||
)
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
|
||||
async def wait_relay_state(
|
||||
self,
|
||||
relay: int,
|
||||
expected: bool,
|
||||
timeout: float = 2.0,
|
||||
) -> None:
|
||||
"""
|
||||
Ждёт подтверждения состояния реле через MQTT.
|
||||
"""
|
||||
if not 1 <= relay <= 8:
|
||||
raise ValueError("Relay number must be between 1 and 8")
|
||||
|
||||
deadline = asyncio.get_running_loop().time() + timeout
|
||||
|
||||
while self.relay_state(relay) != expected:
|
||||
if asyncio.get_running_loop().time() >= deadline:
|
||||
state = self.relay_state(relay)
|
||||
raise TimeoutError(
|
||||
f"Relay {relay} did not reach state {expected}; current state: {state}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.02)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Elica buttons
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def press_power(self) -> None:
|
||||
"""Эмулирует нажатие кнопки Power."""
|
||||
await self.pulse_relay(self._config.power_relay)
|
||||
|
||||
async def press_speed(self) -> None:
|
||||
"""Эмулирует нажатие кнопки Speed."""
|
||||
await self.pulse_relay(self._config.speed_relay)
|
||||
|
||||
async def press_light(self) -> None:
|
||||
"""Эмулирует нажатие кнопки Light."""
|
||||
await self.pulse_relay(self._config.light_relay)
|
||||
|
||||
async def press_timer(self) -> None:
|
||||
"""Эмулирует нажатие кнопки Timer."""
|
||||
await self.pulse_relay(self._config.timer_relay)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Elica panel feedback
|
||||
# ------------------------------------------------------------------
|
||||
@property
|
||||
def panel_state(self) -> ElicaPanelState:
|
||||
"""Возвращает фактическое состояние светодиодов панели Elica.
|
||||
|
||||
Входы обратной связи имеют обратную полярность относительно LED:
|
||||
высокий уровень на IN означает, что соответствующий индикатор
|
||||
Elica погашен, низкий уровень — что индикатор горит.
|
||||
|
||||
MQTT-состояние входа поэтому инвертируем именно здесь, на границе
|
||||
между электрическим состоянием IN и логическим состоянием панели.
|
||||
"""
|
||||
return ElicaPanelState(
|
||||
speed_leds=(
|
||||
not self.input_state(self._config.speed_1_input),
|
||||
not self.input_state(self._config.speed_2_input),
|
||||
not self.input_state(self._config.speed_3_input),
|
||||
not self.input_state(self._config.speed_4_input),
|
||||
),
|
||||
power_led=not self.input_state(self._config.power_input),
|
||||
)
|
||||
|
||||
@property
|
||||
def feedback_ready(self) -> bool:
|
||||
"""True, когда получены состояния всех входов, необходимых для Elica."""
|
||||
return not self.missing_feedback_inputs
|
||||
|
||||
|
||||
@property
|
||||
def missing_feedback_inputs(self) -> tuple[int, ...]:
|
||||
"""Возвращает номера входов Elica, состояние которых ещё не получено."""
|
||||
required = (
|
||||
self._config.speed_1_input,
|
||||
self._config.speed_2_input,
|
||||
self._config.speed_3_input,
|
||||
self._config.speed_4_input,
|
||||
self._config.power_input,
|
||||
)
|
||||
|
||||
return tuple(
|
||||
input_number
|
||||
for input_number in required
|
||||
if not self._received_input_mask & (1 << (input_number - 1))
|
||||
)
|
||||
|
||||
async def wait_feedback_ready(
|
||||
self,
|
||||
timeout: float = 3.0,
|
||||
poll_interval: float = 0.05,
|
||||
) -> None:
|
||||
"""Ждёт получения исходного состояния всех входов панели Elica."""
|
||||
deadline = asyncio.get_running_loop().time() + timeout
|
||||
|
||||
while not self.feedback_ready:
|
||||
if not self._running:
|
||||
raise RuntimeError("Elica service is not running")
|
||||
|
||||
if not self._state.mqtt_connected:
|
||||
raise RuntimeError("Elica MQTT is not connected")
|
||||
|
||||
if not self._state.device_online:
|
||||
raise RuntimeError("ESP32 Elica controller is offline")
|
||||
|
||||
if asyncio.get_running_loop().time() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"Elica feedback synchronization timeout; "
|
||||
f"missing inputs: {self.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
@@ -1 +0,0 @@
|
||||
from .service import PrometheusMetricsService
|
||||
@@ -1,309 +0,0 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PrometheusMetricsService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tion_service,
|
||||
qingping_service,
|
||||
schedule_service=None,
|
||||
auto_controller=None,
|
||||
output_path: str | Path = (
|
||||
"/var/lib/prometheus/node-exporter/"
|
||||
"climatcontroller.prom"
|
||||
),
|
||||
interval: float = 5.0,
|
||||
):
|
||||
self._tion = tion_service
|
||||
self._qingping = qingping_service
|
||||
self._schedule = schedule_service
|
||||
self._auto = auto_controller
|
||||
|
||||
self._output_path = Path(output_path)
|
||||
self._interval = interval
|
||||
|
||||
self._running = False
|
||||
self._task = None
|
||||
self._last_error: str | None = None
|
||||
|
||||
@property
|
||||
def running(self) -> bool:
|
||||
return self._running
|
||||
|
||||
@property
|
||||
def last_error(self) -> str | None:
|
||||
return self._last_error
|
||||
|
||||
async def start(self) -> None:
|
||||
|
||||
if self._running:
|
||||
return
|
||||
|
||||
self._running = True
|
||||
|
||||
await self._write_metrics()
|
||||
|
||||
self._task = asyncio.create_task(
|
||||
self._loop()
|
||||
)
|
||||
|
||||
async def stop(self) -> None:
|
||||
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
self._running = False
|
||||
|
||||
if self._task is not None:
|
||||
self._task.cancel()
|
||||
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
self._task = None
|
||||
|
||||
async def _loop(self) -> None:
|
||||
|
||||
while self._running:
|
||||
|
||||
await asyncio.sleep(
|
||||
self._interval
|
||||
)
|
||||
|
||||
try:
|
||||
await self._write_metrics()
|
||||
|
||||
except Exception as exc:
|
||||
self._last_error = f"{type(exc).__name__}: {exc}"
|
||||
logger.exception("Prometheus metrics update failed")
|
||||
|
||||
async def _write_metrics(self) -> None:
|
||||
|
||||
lines: list[str] = []
|
||||
|
||||
# --------------------------------------------------
|
||||
# Время последнего успешного обновления файла.
|
||||
# Позволяет определить протухшие метрики.
|
||||
# --------------------------------------------------
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_metrics_timestamp_seconds",
|
||||
time.time(),
|
||||
"Unix timestamp of the last "
|
||||
"ClimatController metrics update",
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Tion
|
||||
# --------------------------------------------------
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_online",
|
||||
self._tion.online,
|
||||
"Tion connection state",
|
||||
)
|
||||
|
||||
tion_state = self._tion.state
|
||||
|
||||
if tion_state is not None:
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_power",
|
||||
tion_state.power,
|
||||
"Tion power state",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_heater",
|
||||
tion_state.heater,
|
||||
"Tion heater enabled state",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_heating",
|
||||
tion_state.heating,
|
||||
"Tion active heating state",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_fan_speed",
|
||||
tion_state.fan_speed,
|
||||
"Tion fan speed",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_in_temperature_celsius",
|
||||
tion_state.in_temp,
|
||||
"Tion inlet temperature",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_out_temperature_celsius",
|
||||
tion_state.out_temp,
|
||||
"Tion outside temperature",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_tion_target_temperature_celsius",
|
||||
tion_state.target_temp,
|
||||
"Tion target temperature",
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Qingping
|
||||
# --------------------------------------------------
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_online",
|
||||
self._qingping.online,
|
||||
"Qingping online state",
|
||||
)
|
||||
|
||||
qingping_state = self._qingping.state
|
||||
|
||||
if qingping_state is not None:
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_mqtt_connected",
|
||||
qingping_state.mqtt_connected,
|
||||
"Qingping MQTT connection state",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_temperature_celsius",
|
||||
qingping_state.temperature,
|
||||
"Qingping temperature",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_humidity_percent",
|
||||
qingping_state.humidity,
|
||||
"Qingping relative humidity",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_co2_ppm",
|
||||
qingping_state.co2,
|
||||
"Qingping CO2 concentration",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_pm25_ug_m3",
|
||||
qingping_state.pm25,
|
||||
"Qingping PM2.5 concentration",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_pm10_ug_m3",
|
||||
qingping_state.pm10,
|
||||
"Qingping PM10 concentration",
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_qingping_battery_percent",
|
||||
qingping_state.battery,
|
||||
"Qingping battery level",
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Schedule / AUTO
|
||||
# --------------------------------------------------
|
||||
|
||||
if self._schedule is not None:
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_schedule_paused",
|
||||
self._schedule.paused,
|
||||
"Schedule manual pause state",
|
||||
)
|
||||
|
||||
try:
|
||||
resolution = (
|
||||
self._schedule.resolve()
|
||||
)
|
||||
|
||||
self._add_gauge(
|
||||
lines,
|
||||
"climat_auto_active",
|
||||
resolution.auto_active,
|
||||
"AUTO schedule state",
|
||||
)
|
||||
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Schedule metrics resolve failed"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Atomic write
|
||||
# --------------------------------------------------
|
||||
|
||||
self._output_path.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True,
|
||||
)
|
||||
|
||||
temp_path = (
|
||||
self._output_path.with_suffix(
|
||||
self._output_path.suffix
|
||||
+ ".tmp"
|
||||
)
|
||||
)
|
||||
|
||||
temp_path.write_text(
|
||||
"\n".join(lines) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
temp_path.replace(
|
||||
self._output_path
|
||||
)
|
||||
|
||||
self._last_error = None
|
||||
|
||||
@staticmethod
|
||||
def _add_gauge(
|
||||
lines: list[str],
|
||||
name: str,
|
||||
value,
|
||||
help_text: str,
|
||||
) -> None:
|
||||
|
||||
if value is None:
|
||||
return
|
||||
|
||||
if isinstance(value, bool):
|
||||
value = 1 if value else 0
|
||||
|
||||
lines.append(f"# HELP {name} {help_text}")
|
||||
|
||||
lines.append(f"# TYPE {name} gauge")
|
||||
|
||||
lines.append(f"{name} {value}")
|
||||
@@ -10,13 +10,9 @@ from typing import Any, Mapping
|
||||
TION_MAC = "d1:74:9b:eb:ee:a6"
|
||||
|
||||
QINGPING_MAC = "CCB5D131BA93"
|
||||
QINGPING_MQTT_HOST = "192.168.7.100"
|
||||
QINGPING_MQTT_HOST = "192.168.7.3"
|
||||
QINGPING_MQTT_PORT = 1883
|
||||
|
||||
# ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS.
|
||||
ELICA_MQTT_HOST = "192.168.7.100"
|
||||
ELICA_MQTT_PORT = 1883
|
||||
|
||||
|
||||
MIN_FAN_SPEED = 1
|
||||
MAX_FAN_SPEED = 6
|
||||
|
||||
+2
-90
@@ -1,7 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import shutil
|
||||
import sys
|
||||
from typing import Any
|
||||
from bleak import BleakScanner
|
||||
from tion_btle import TionS4
|
||||
@@ -10,7 +7,6 @@ from .models import TionState
|
||||
|
||||
from app.my_dataclasses import *
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TionController:
|
||||
"""
|
||||
@@ -92,18 +88,7 @@ class TionController:
|
||||
# от предыдущего соединения.
|
||||
await self._reset_device()
|
||||
|
||||
# Сначала обычный поиск.
|
||||
ble_device = await BleakScanner.find_device_by_address(
|
||||
self._mac,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
if ble_device is None:
|
||||
# Возможно, предыдущий процесс умер через SIGKILL,
|
||||
# а ОС всё ещё удерживает старое BLE-соединение.
|
||||
await self._recover_stale_system_connection()
|
||||
|
||||
# После recovery пробуем найти Tion ещё раз.
|
||||
# Получаем свежий BLEDevice.
|
||||
ble_device = await BleakScanner.find_device_by_address(
|
||||
self._mac,
|
||||
timeout=5.0,
|
||||
@@ -165,18 +150,8 @@ class TionController:
|
||||
"""
|
||||
|
||||
async def power_on(self) -> TionState:
|
||||
# Tion 4S reliably wakes up when the power command also carries
|
||||
# a valid fan speed. The device keeps the last speed even while
|
||||
# powered off, so preserve it instead of forcing a new value.
|
||||
speed = (
|
||||
self._state.fan_speed
|
||||
if self._state is not None
|
||||
else MIN_FAN_SPEED
|
||||
)
|
||||
|
||||
return await self._set({
|
||||
"state": "on",
|
||||
"fan_speed": speed,
|
||||
"state": "on"
|
||||
})
|
||||
|
||||
async def power_off(self) -> TionState:
|
||||
@@ -298,66 +273,3 @@ class TionController:
|
||||
|
||||
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
|
||||
await self.disconnect()
|
||||
|
||||
async def _recover_stale_system_connection(self) -> None:
|
||||
"""
|
||||
Попытаться освободить зависшее BLE-соединение,
|
||||
оставшееся после аварийного завершения предыдущего процесса.
|
||||
|
||||
На Linux BlueZ может продолжать показывать Connected=yes,
|
||||
хотя процесс-владелец уже умер. В таком состоянии Tion может
|
||||
не advertising'иться, поэтому BleakScanner его не находит.
|
||||
|
||||
На других ОС ничего не делаем: основной код остаётся
|
||||
платформенно-независимым.
|
||||
"""
|
||||
|
||||
if not sys.platform.startswith("linux"):
|
||||
return
|
||||
|
||||
bluetoothctl = shutil.which("bluetoothctl")
|
||||
if bluetoothctl is None:
|
||||
logger.warning(
|
||||
"Tion stale-connection recovery skipped: "
|
||||
"bluetoothctl not found"
|
||||
)
|
||||
return
|
||||
|
||||
logger.warning(
|
||||
"Tion %s not found by scan; "
|
||||
"trying to clear stale BlueZ connection",
|
||||
self._mac,
|
||||
)
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
bluetoothctl,
|
||||
"disconnect",
|
||||
self._mac,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
process.communicate(),
|
||||
timeout=5.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
process.kill()
|
||||
await process.communicate()
|
||||
|
||||
logger.warning(
|
||||
"Timed out while clearing stale Tion BLE connection"
|
||||
)
|
||||
return
|
||||
|
||||
logger.warning(
|
||||
"Tion BlueZ recovery finished: rc=%s stdout=%s stderr=%s",
|
||||
process.returncode,
|
||||
stdout.decode(errors="replace").strip(),
|
||||
stderr.decode(errors="replace").strip(),
|
||||
)
|
||||
|
||||
# Даём BlueZ и самому Tion время освободить старое соединение
|
||||
# и снова начать advertising.
|
||||
await asyncio.sleep(1.0)
|
||||
@@ -24,12 +24,3 @@ co2:
|
||||
|
||||
temperature:
|
||||
hysteresis: 0.5
|
||||
|
||||
|
||||
elica_assist:
|
||||
enabled: true
|
||||
|
||||
speed_map:
|
||||
4: 1
|
||||
5: 2
|
||||
6: 3
|
||||
@@ -36,6 +36,7 @@ templates:
|
||||
|
||||
|
||||
weekend:
|
||||
|
||||
- time: "10:00"
|
||||
action:
|
||||
power: on
|
||||
@@ -61,12 +62,16 @@ templates:
|
||||
speed: 1
|
||||
|
||||
|
||||
|
||||
|
||||
days:
|
||||
|
||||
mon: workday
|
||||
tue: workday
|
||||
wed: workday
|
||||
thu: workday
|
||||
fri: workday
|
||||
|
||||
sat: weekend
|
||||
sun: weekend
|
||||
|
||||
@@ -1,348 +0,0 @@
|
||||
esphome:
|
||||
name: elica-relay
|
||||
friendly_name: Elica Relay Controller
|
||||
on_boot:
|
||||
# First disable 74HC595 outputs so relays cannot chatter during boot.
|
||||
- priority: 900
|
||||
then:
|
||||
- lambda: |-
|
||||
pinMode(13, OUTPUT);
|
||||
digitalWrite(13, HIGH);
|
||||
|
||||
# Initialise shared bus, force all relays OFF, then enable outputs.
|
||||
- priority: 600
|
||||
then:
|
||||
- delay: 500ms
|
||||
- lambda: |-
|
||||
pinMode(25, OUTPUT); // shared LATCH
|
||||
pinMode(26, OUTPUT); // shared CLOCK
|
||||
pinMode(33, OUTPUT); // data to 74HC595
|
||||
pinMode(27, INPUT); // data from 74HC165
|
||||
|
||||
digitalWrite(25, LOW);
|
||||
shiftOut(33, 26, MSBFIRST, 0xFF); // active-low relays: all OFF
|
||||
digitalWrite(25, HIGH);
|
||||
|
||||
id(relay_state) = 0x00;
|
||||
digitalWrite(13, LOW); // enable 74HC595 outputs
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: arduino
|
||||
|
||||
logger:
|
||||
|
||||
wifi:
|
||||
ssid: !secret wifi_ssid
|
||||
password: !secret wifi_password
|
||||
|
||||
ap:
|
||||
ssid: "Elica-Relay-Fallback"
|
||||
password: !secret fallback_password
|
||||
|
||||
captive_portal:
|
||||
|
||||
# We use MQTT as the main connection to the controller.
|
||||
# Home Assistant / native ESPHome API is deliberately not enabled.
|
||||
mqtt:
|
||||
broker: !secret mqtt_broker
|
||||
username: !secret mqtt_username
|
||||
password: !secret mqtt_password
|
||||
discovery: false
|
||||
|
||||
birth_message:
|
||||
topic: elica/status
|
||||
payload: online
|
||||
retain: true
|
||||
|
||||
will_message:
|
||||
topic: elica/status
|
||||
payload: offline
|
||||
retain: true
|
||||
|
||||
ota:
|
||||
- platform: esphome
|
||||
password: !secret ota_password
|
||||
|
||||
# Handy while commissioning the board.
|
||||
web_server:
|
||||
port: 80
|
||||
|
||||
globals:
|
||||
- id: relay_state
|
||||
type: uint8_t
|
||||
restore_value: no
|
||||
initial_value: '0x00'
|
||||
|
||||
- id: input_state
|
||||
type: uint8_t
|
||||
restore_value: no
|
||||
initial_value: '0xFF'
|
||||
|
||||
# Tracks the real Elica Power LED so OUT5 can be used as a hard
|
||||
# interlock for the external fan. The LED line is active LOW.
|
||||
- id: elica_power_initialized
|
||||
type: bool
|
||||
restore_value: no
|
||||
initial_value: 'false'
|
||||
|
||||
- id: elica_power_was_on
|
||||
type: bool
|
||||
restore_value: no
|
||||
initial_value: 'false'
|
||||
|
||||
script:
|
||||
- id: write_relays
|
||||
mode: restart
|
||||
then:
|
||||
- lambda: |-
|
||||
// Relay drivers are active LOW.
|
||||
digitalWrite(25, LOW);
|
||||
shiftOut(33, 26, MSBFIRST, ~id(relay_state));
|
||||
digitalWrite(25, HIGH);
|
||||
|
||||
# 74HC595 and 74HC165 share CLOCK/LATCH on this board.
|
||||
# Read inputs, then immediately restore the relay register.
|
||||
interval:
|
||||
- interval: 100ms
|
||||
then:
|
||||
- lambda: |-
|
||||
// Parallel-load current input state into 74HC165.
|
||||
digitalWrite(25, LOW);
|
||||
delayMicroseconds(10);
|
||||
digitalWrite(25, HIGH);
|
||||
|
||||
uint8_t v = 0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
v <<= 1;
|
||||
if (digitalRead(27)) v |= 1;
|
||||
|
||||
digitalWrite(26, HIGH);
|
||||
delayMicroseconds(2);
|
||||
digitalWrite(26, LOW);
|
||||
delayMicroseconds(2);
|
||||
}
|
||||
|
||||
id(input_state) = v;
|
||||
|
||||
// Elica Power LED is connected to IN5 (74HC165 mask 0x40).
|
||||
// IMPORTANT: on this board the 74HC165 raw state is inverted
|
||||
// relative to the MQTT binary_sensor state. Empirically:
|
||||
// raw bit 1 -> Elica Power LED ON, raw bit 0 -> LED OFF.
|
||||
const bool elica_power_on = (v & 0x40) != 0;
|
||||
bool relay5_changed = false;
|
||||
|
||||
if (!id(elica_power_initialized)) {
|
||||
id(elica_power_initialized) = true;
|
||||
|
||||
// If ESP32 boots while Elica is already running, enforce
|
||||
// the interlock immediately. If Elica is OFF, boot defaults
|
||||
// already leave Relay 5 OFF -> NC closed -> fan ON.
|
||||
if (elica_power_on && !(id(relay_state) & 0x10)) {
|
||||
id(relay_state) |= 0x10;
|
||||
relay5_changed = true;
|
||||
}
|
||||
} else if (elica_power_on) {
|
||||
// Hard interlock: while Elica is ON, Relay 5 must stay ON.
|
||||
// Relay 5 ON opens the NC contact and stops the external fan.
|
||||
if (!(id(relay_state) & 0x10)) {
|
||||
id(relay_state) |= 0x10;
|
||||
relay5_changed = true;
|
||||
}
|
||||
} else if (id(elica_power_was_on)) {
|
||||
// Elica has just switched OFF: automatically restore the
|
||||
// external fan. Relay 5 OFF closes NC and starts the fan.
|
||||
if (id(relay_state) & 0x10) {
|
||||
id(relay_state) &= ~0x10;
|
||||
relay5_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
id(elica_power_was_on) = elica_power_on;
|
||||
|
||||
// Shared bus changed while reading 74HC165:
|
||||
// restore the requested relay state in 74HC595.
|
||||
digitalWrite(25, LOW);
|
||||
shiftOut(33, 26, MSBFIRST, ~id(relay_state));
|
||||
digitalWrite(25, HIGH);
|
||||
|
||||
// Keep MQTT/web-server state in sync when the interlock itself
|
||||
// changes Relay 5 rather than an external command doing it.
|
||||
if (relay5_changed) {
|
||||
id(relay5).publish_state((id(relay_state) & 0x10) != 0);
|
||||
}
|
||||
|
||||
switch:
|
||||
- platform: template
|
||||
name: "Relay 1"
|
||||
id: relay1
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x01) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x01;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x01;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/1/set"
|
||||
state_topic: "elica/relay/1/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 2"
|
||||
id: relay2
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x02) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x02;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x02;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/2/set"
|
||||
state_topic: "elica/relay/2/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 3"
|
||||
id: relay3
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x04) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x04;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x04;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/3/set"
|
||||
state_topic: "elica/relay/3/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 4"
|
||||
id: relay4
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x08) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x08;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x08;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/4/set"
|
||||
state_topic: "elica/relay/4/state"
|
||||
|
||||
# OUT5 управляет внешним вентилятором через NC-контакт.
|
||||
# relay5=OFF -> NC замкнут -> внешний вентилятор ВКЛ.
|
||||
# relay5=ON -> NC разомкнут -> внешний вентилятор ВЫКЛ.
|
||||
#
|
||||
# HARD INTERLOCK по фактическому Power LED Elica (IN5):
|
||||
# Elica ON -> Relay 5 принудительно ON -> внешний вентилятор OFF.
|
||||
# Elica OFF -> при переходе автоматически Relay 5 OFF -> вентилятор ON.
|
||||
# Пока Elica включена, MQTT-команда Relay 5 OFF игнорируется, чтобы
|
||||
# внешний вентилятор нельзя было случайно включить одновременно с Elica.
|
||||
- platform: template
|
||||
name: "Relay 5"
|
||||
id: relay5
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x10) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x10;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: |-
|
||||
// Use the same raw IN5 polarity as the interlock above:
|
||||
// raw bit 1 means the Elica Power LED is ON.
|
||||
const bool elica_power_on = (id(input_state) & 0x40) != 0;
|
||||
if (elica_power_on) {
|
||||
id(relay_state) |= 0x10;
|
||||
} else {
|
||||
id(relay_state) &= ~0x10;
|
||||
}
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/5/set"
|
||||
state_topic: "elica/relay/5/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 6"
|
||||
id: relay6
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x20) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x20;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x20;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/6/set"
|
||||
state_topic: "elica/relay/6/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 7"
|
||||
id: relay7
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x40) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x40;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x40;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/7/set"
|
||||
state_topic: "elica/relay/7/state"
|
||||
|
||||
- platform: template
|
||||
name: "Relay 8"
|
||||
id: relay8
|
||||
restore_mode: ALWAYS_OFF
|
||||
lambda: return (id(relay_state) & 0x80) != 0;
|
||||
turn_on_action:
|
||||
- lambda: id(relay_state) |= 0x80;
|
||||
- script.execute: write_relays
|
||||
turn_off_action:
|
||||
- lambda: id(relay_state) &= ~0x80;
|
||||
- script.execute: write_relays
|
||||
command_topic: "elica/relay/8/set"
|
||||
state_topic: "elica/relay/8/state"
|
||||
|
||||
binary_sensor:
|
||||
- platform: template
|
||||
name: "Input 1"
|
||||
lambda: return !(id(input_state) & 0x10);
|
||||
state_topic: "elica/input/1/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 2"
|
||||
lambda: return !(id(input_state) & 0x08);
|
||||
state_topic: "elica/input/2/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 3"
|
||||
lambda: return !(id(input_state) & 0x20);
|
||||
state_topic: "elica/input/3/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 4"
|
||||
lambda: return !(id(input_state) & 0x04);
|
||||
state_topic: "elica/input/4/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 5"
|
||||
lambda: return !(id(input_state) & 0x40);
|
||||
state_topic: "elica/input/5/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 6"
|
||||
lambda: return !(id(input_state) & 0x02);
|
||||
state_topic: "elica/input/6/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 7"
|
||||
lambda: return !(id(input_state) & 0x80);
|
||||
state_topic: "elica/input/7/state"
|
||||
|
||||
- platform: template
|
||||
name: "Input 8"
|
||||
lambda: return !(id(input_state) & 0x01);
|
||||
state_topic: "elica/input/8/state"
|
||||
|
||||
- platform: status
|
||||
name: "Controller Status"
|
||||
@@ -1,28 +0,0 @@
|
||||
ELICA ESP32 RELAY X8 - INITIAL COMMISSIONING
|
||||
|
||||
Files:
|
||||
elica-relay.yaml Main ESPHome configuration
|
||||
secrets.yaml.template Copy/rename this to secrets.yaml and enter your values
|
||||
|
||||
Target hardware:
|
||||
LCTech ESP32 Relay Board X8 Modbus / 303e32dc812
|
||||
ESP32-WROOM-32E
|
||||
74HC595 relay outputs + 74HC165 optocoupled inputs on shared bus
|
||||
|
||||
First commissioning:
|
||||
1. Install ESPHome Device Builder.
|
||||
2. Put elica-relay.yaml and secrets.yaml in its config folder/project.
|
||||
3. Connect the board by USB-C.
|
||||
4. Compile and install via USB.
|
||||
5. After boot, supply the board from a suitable 9-24 V DC power supply for relay/input tests.
|
||||
6. Test all relays before connecting anything to Elica.
|
||||
|
||||
MQTT topics:
|
||||
elica/status
|
||||
elica/relay/1/set ... elica/relay/8/set
|
||||
elica/relay/1/state ... elica/relay/8/state
|
||||
elica/input/1/state ... elica/input/8/state
|
||||
|
||||
Relay commands use ON / OFF.
|
||||
All relays are forced OFF during boot.
|
||||
Inputs do not control relays.
|
||||
@@ -1,15 +0,0 @@
|
||||
# Fill these values before compiling.
|
||||
|
||||
wifi_ssid: "YOUR_WIFI_SSID"
|
||||
wifi_password: "YOUR_WIFI_PASSWORD"
|
||||
|
||||
# IP address or DNS name of the existing Mosquitto broker.
|
||||
mqtt_broker: "192.168.1.10"
|
||||
mqtt_username: "YOUR_MQTT_USERNAME"
|
||||
mqtt_password: "YOUR_MQTT_PASSWORD"
|
||||
|
||||
# Used only if normal Wi-Fi cannot be reached.
|
||||
fallback_password: "ChangeMe123!"
|
||||
|
||||
# Password for future wireless firmware updates.
|
||||
ota_password: "ChangeThisOTAPassword"
|
||||
@@ -1,425 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.controller import AutoController
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-auto-elica-already-on-test-"
|
||||
f"{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready.\n"
|
||||
f"mqtt_connected="
|
||||
f"{state.mqtt_connected}\n"
|
||||
f"device_online="
|
||||
f"{state.device_online}\n"
|
||||
f"feedback_ready="
|
||||
f"{service.feedback_ready}\n"
|
||||
f"missing_feedback_inputs="
|
||||
f"{service.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
elica_controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
initial = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": initial.power,
|
||||
"speed": initial.speed,
|
||||
"timer": initial.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Для этого теста Elica должна быть заранее
|
||||
# включена пользователем.
|
||||
# --------------------------------------------------
|
||||
|
||||
if not initial.power:
|
||||
raise RuntimeError(
|
||||
"Before starting this test, "
|
||||
"manually turn Elica ON "
|
||||
"at any speed."
|
||||
)
|
||||
|
||||
initial_power = initial.power
|
||||
initial_speed = initial.speed
|
||||
initial_timer = initial.timer
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=object(),
|
||||
qingping_service=object(),
|
||||
tion_service=object(),
|
||||
elica_controller=elica_controller,
|
||||
policy=None,
|
||||
temperature_policy=None,
|
||||
elica_assist=assist,
|
||||
interval=1.0,
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Пользовательская Elica уже включена.
|
||||
#
|
||||
# Tion AUTO поднимается до 4.
|
||||
#
|
||||
# AutoController должен:
|
||||
#
|
||||
# увидеть Elica ON
|
||||
# -> SUPPRESSED
|
||||
# -> reason = elica_already_on
|
||||
# -> ничего не переключать
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 1:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion AUTO speed 4 while "
|
||||
"Elica is already user-controlled."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
after_speed_4 = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after Tion speed 4:",
|
||||
{
|
||||
"power": after_speed_4.power,
|
||||
"speed": after_speed_4.speed,
|
||||
"timer": after_speed_4.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "suppressed":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter SUPPRESSED"
|
||||
)
|
||||
|
||||
if (
|
||||
assist.status()["reason"]
|
||||
!= "elica_already_on"
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Expected reason elica_already_on"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Elica обязана остаться полностью неизменной.
|
||||
# --------------------------------------------------
|
||||
|
||||
if (
|
||||
after_speed_4.power != initial_power
|
||||
or after_speed_4.speed != initial_speed
|
||||
or after_speed_4.timer != initial_timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController modified "
|
||||
"already-running user Elica"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"SUPPRESSION PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Пока Tion остаётся в диапазоне,
|
||||
# например поднимается 4 -> 5.
|
||||
#
|
||||
# Elica всё равно трогать нельзя.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 2:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion AUTO speed changes 4 -> 5."
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica must remain untouched."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
5
|
||||
)
|
||||
|
||||
after_speed_5 = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after Tion speed 5:",
|
||||
{
|
||||
"power": after_speed_5.power,
|
||||
"speed": after_speed_5.speed,
|
||||
"timer": after_speed_5.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "suppressed":
|
||||
raise RuntimeError(
|
||||
"Assist left SUPPRESSED "
|
||||
"during the same cycle"
|
||||
)
|
||||
|
||||
if (
|
||||
after_speed_5.power != initial_power
|
||||
or after_speed_5.speed != initial_speed
|
||||
or after_speed_5.timer != initial_timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController modified Elica "
|
||||
"while SUPPRESSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"SUPPRESSED HOLD PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 3
|
||||
#
|
||||
# Tion падает до 3.
|
||||
#
|
||||
# Текущий повышенный AUTO-цикл закончен.
|
||||
#
|
||||
# Elica должна остаться пользовательской,
|
||||
# но Assist может вернуться в IDLE.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print("STEP 3:")
|
||||
|
||||
print("Tion AUTO speed drops to 3.")
|
||||
|
||||
print(
|
||||
"Elica must remain ON and unchanged."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
3
|
||||
)
|
||||
|
||||
final_elica = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Final Elica:",
|
||||
{
|
||||
"power": final_elica.power,
|
||||
"speed": final_elica.speed,
|
||||
"timer": final_elica.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Final Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if (
|
||||
final_elica.power != initial_power
|
||||
or final_elica.speed != initial_speed
|
||||
or final_elica.timer != initial_timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController changed user Elica "
|
||||
"when the Tion cycle ended"
|
||||
)
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Assist did not return to IDLE "
|
||||
"after Tion dropped below threshold"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"CYCLE END PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print("Verified sequence:")
|
||||
|
||||
print(
|
||||
"User Elica already ON"
|
||||
" -> Tion 4"
|
||||
" -> SUPPRESSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 5"
|
||||
" -> Elica untouched"
|
||||
" -> still SUPPRESSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 3"
|
||||
" -> Elica untouched"
|
||||
" -> IDLE"
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print("Stopping Elica service...")
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,355 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.controller import AutoController
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
"""
|
||||
Используем отдельный MQTT client_id,
|
||||
чтобы тест не конфликтовал с обычным
|
||||
ClimatController.
|
||||
"""
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-auto-elica-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready.\n"
|
||||
f"mqtt_connected="
|
||||
f"{state.mqtt_connected}\n"
|
||||
f"device_online="
|
||||
f"{state.device_online}\n"
|
||||
f"feedback_ready="
|
||||
f"{service.feedback_ready}\n"
|
||||
f"missing_feedback_inputs="
|
||||
f"{service.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# --------------------------------------------------
|
||||
# Реальный ElicaService + ElicaController.
|
||||
# --------------------------------------------------
|
||||
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
elica_controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
initial = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": initial.power,
|
||||
"speed": initial.speed,
|
||||
"timer": initial.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Для чистого теста начинаем с выключенной Elica.
|
||||
if initial.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test. "
|
||||
"Turn it off manually and run again."
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Создаём настоящий Elica Auto Assist.
|
||||
# --------------------------------------------------
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Создаём настоящий AutoController.
|
||||
#
|
||||
# Schedule / Qingping / Tion здесь не нужны,
|
||||
# потому что мы НЕ запускаем его основной цикл,
|
||||
# а вызываем только _update_elica_assist().
|
||||
# --------------------------------------------------
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=object(),
|
||||
qingping_service=object(),
|
||||
tion_service=object(),
|
||||
elica_controller=elica_controller,
|
||||
policy=None,
|
||||
temperature_policy=None,
|
||||
elica_assist=assist,
|
||||
interval=1.0,
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Имитируем:
|
||||
#
|
||||
# Tion AUTO выбрал скорость 4.
|
||||
#
|
||||
# Именно реальный метод AutoController должен:
|
||||
#
|
||||
# target = 1
|
||||
# Elica OFF -> speed 1
|
||||
# mode -> OWNED
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"Calling AutoController "
|
||||
"_update_elica_assist(4)..."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
acquired = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after Tion speed 4:",
|
||||
{
|
||||
"power": acquired.power,
|
||||
"speed": acquired.speed,
|
||||
"timer": acquired.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if not acquired.power:
|
||||
raise RuntimeError(
|
||||
"AutoController did not turn Elica on"
|
||||
)
|
||||
|
||||
if acquired.speed != 1:
|
||||
raise RuntimeError(
|
||||
f"Expected Elica speed 1, "
|
||||
f"got {acquired.speed}"
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
if assist.expected_speed != 1:
|
||||
raise RuntimeError(
|
||||
"expected_speed is not 1"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"ACQUIRE PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Имитируем:
|
||||
#
|
||||
# Tion AUTO упал до скорости 3.
|
||||
#
|
||||
# Теперь реальный AutoController должен:
|
||||
#
|
||||
# target = None
|
||||
# проверить OWNED
|
||||
# выключить Elica
|
||||
# reset -> IDLE
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"Calling AutoController "
|
||||
"_update_elica_assist(3)..."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
3
|
||||
)
|
||||
|
||||
released = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after Tion speed 3:",
|
||||
{
|
||||
"power": released.power,
|
||||
"speed": released.speed,
|
||||
"timer": released.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if released.power:
|
||||
raise RuntimeError(
|
||||
"AutoController did not turn Elica off"
|
||||
)
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not return to IDLE"
|
||||
)
|
||||
|
||||
if assist.expected_speed is not None:
|
||||
raise RuntimeError(
|
||||
"expected_speed was not cleared"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"RELEASE PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Real AutoController successfully performed:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 4 -> Elica speed 1 -> OWNED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 3 -> Elica OFF -> IDLE"
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,422 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.controller import AutoController
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
MANUAL_CHANGE_TIMEOUT = 60.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-auto-exit-manual-test-"
|
||||
f"{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def wait_for_manual_change(
|
||||
service: ElicaService,
|
||||
*,
|
||||
power: bool,
|
||||
speed: int,
|
||||
timer: bool,
|
||||
):
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ MANUAL_CHANGE_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
ready = (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
)
|
||||
|
||||
if ready:
|
||||
logical = service.logical_state
|
||||
|
||||
if (
|
||||
logical.power != power
|
||||
or logical.speed != speed
|
||||
or logical.timer != timer
|
||||
):
|
||||
return logical
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"No manual Elica change detected "
|
||||
f"within {MANUAL_CHANGE_TIMEOUT} seconds"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
elica_controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
initial = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": initial.power,
|
||||
"speed": initial.speed,
|
||||
"timer": initial.timer,
|
||||
},
|
||||
)
|
||||
|
||||
if initial.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=object(),
|
||||
qingping_service=object(),
|
||||
tion_service=object(),
|
||||
elica_controller=elica_controller,
|
||||
policy=None,
|
||||
temperature_policy=None,
|
||||
elica_assist=assist,
|
||||
interval=1.0,
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# STEP 1
|
||||
#
|
||||
# AUTO активен:
|
||||
# Tion 4 -> Elica 1 -> OWNED
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print("STEP 1:")
|
||||
print(
|
||||
"Tion AUTO speed 4 "
|
||||
"-> Auto Assist acquires Elica"
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
owned = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica:",
|
||||
{
|
||||
"power": owned.power,
|
||||
"speed": owned.speed,
|
||||
"timer": owned.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if (
|
||||
not owned.power
|
||||
or owned.speed != 1
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not acquire "
|
||||
"Elica at speed 1"
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"ACQUIRE PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# STEP 2
|
||||
#
|
||||
# Пользователь вручную меняет Elica.
|
||||
# Например 1 -> 2.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print("STEP 2:")
|
||||
print(
|
||||
"Now MANUALLY change Elica."
|
||||
)
|
||||
|
||||
print(
|
||||
"For example change speed 1 -> 2."
|
||||
)
|
||||
|
||||
print(
|
||||
"The test is waiting..."
|
||||
)
|
||||
|
||||
changed = await wait_for_manual_change(
|
||||
service,
|
||||
power=owned.power,
|
||||
speed=owned.speed,
|
||||
timer=owned.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Manual Elica state:",
|
||||
{
|
||||
"power": changed.power,
|
||||
"speed": changed.speed,
|
||||
"timer": changed.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# STEP 3
|
||||
#
|
||||
# ВАЖНО:
|
||||
# AutoController ещё не успел сделать обычный
|
||||
# проход _update_elica_assist().
|
||||
#
|
||||
# Сразу имитируем выход из AUTO.
|
||||
#
|
||||
# _release_elica_assist() сам обязан заметить,
|
||||
# что actual != expected, и НЕ выключить Elica.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print("STEP 3:")
|
||||
print(
|
||||
"Simulating immediate exit from AUTO..."
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica must NOT be switched off."
|
||||
)
|
||||
|
||||
await auto_controller._release_elica_assist()
|
||||
|
||||
final_elica = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Final Elica:",
|
||||
{
|
||||
"power": final_elica.power,
|
||||
"speed": final_elica.speed,
|
||||
"timer": final_elica.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Final Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Elica должна остаться точно такой,
|
||||
# какой её сделал пользователь.
|
||||
# --------------------------------------------------
|
||||
|
||||
if (
|
||||
final_elica.power != changed.power
|
||||
or final_elica.speed != changed.speed
|
||||
or final_elica.timer != changed.timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController modified user's Elica "
|
||||
"during AUTO exit"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Сессия Auto Assist должна закончиться.
|
||||
# --------------------------------------------------
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Assist did not return to IDLE "
|
||||
"after AUTO exit"
|
||||
)
|
||||
|
||||
if assist.expected_speed is not None:
|
||||
raise RuntimeError(
|
||||
"expected_speed was not cleared"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"MANUAL TAKEOVER ON AUTO EXIT PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Verified sequence:"
|
||||
)
|
||||
|
||||
print(
|
||||
"AUTO -> Tion 4 "
|
||||
"-> Elica 1 "
|
||||
"-> OWNED"
|
||||
)
|
||||
|
||||
print(
|
||||
"User changes Elica"
|
||||
)
|
||||
|
||||
print(
|
||||
"AUTO exit "
|
||||
"-> Elica untouched "
|
||||
"-> IDLE"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Turn Elica off manually "
|
||||
"after the test."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,555 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.controller import AutoController
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
MANUAL_CHANGE_TIMEOUT = 60.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
"""
|
||||
Отдельный MQTT client_id для live-теста.
|
||||
"""
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-auto-elica-manual-test-"
|
||||
f"{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready.\n"
|
||||
f"mqtt_connected="
|
||||
f"{state.mqtt_connected}\n"
|
||||
f"device_online="
|
||||
f"{state.device_online}\n"
|
||||
f"feedback_ready="
|
||||
f"{service.feedback_ready}\n"
|
||||
f"missing_feedback_inputs="
|
||||
f"{service.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def wait_for_manual_change(
|
||||
service: ElicaService,
|
||||
*,
|
||||
power: bool,
|
||||
speed: int,
|
||||
timer: bool,
|
||||
):
|
||||
"""
|
||||
Ждём реального изменения Elica пользователем.
|
||||
|
||||
Потеря MQTT/feedback изменением
|
||||
не считается.
|
||||
"""
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ MANUAL_CHANGE_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
ready = (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
)
|
||||
|
||||
if ready:
|
||||
logical = service.logical_state
|
||||
|
||||
if (
|
||||
logical.power != power
|
||||
or logical.speed != speed
|
||||
or logical.timer != timer
|
||||
):
|
||||
return logical
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"No manual Elica change detected "
|
||||
f"within {MANUAL_CHANGE_TIMEOUT} seconds"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
elica_controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
initial = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": initial.power,
|
||||
"speed": initial.speed,
|
||||
"timer": initial.timer,
|
||||
},
|
||||
)
|
||||
|
||||
if initial.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test. "
|
||||
"Turn it off manually and run again."
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Создаём настоящий Auto Assist.
|
||||
# --------------------------------------------------
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Настоящий AutoController.
|
||||
#
|
||||
# Основной цикл мы не запускаем.
|
||||
# Вызываем только _update_elica_assist().
|
||||
# --------------------------------------------------
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=object(),
|
||||
qingping_service=object(),
|
||||
tion_service=object(),
|
||||
elica_controller=elica_controller,
|
||||
policy=None,
|
||||
temperature_policy=None,
|
||||
elica_assist=assist,
|
||||
interval=1.0,
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Tion 4
|
||||
# -> AutoController включает Elica 1
|
||||
# -> OWNED
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 1:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion AUTO speed 4 "
|
||||
"-> Auto Assist should acquire Elica"
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
owned = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica:",
|
||||
{
|
||||
"power": owned.power,
|
||||
"speed": owned.speed,
|
||||
"timer": owned.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if (
|
||||
not owned.power
|
||||
or owned.speed != 1
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController did not acquire "
|
||||
"Elica at speed 1"
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"ACQUIRE PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Теперь пользователь физически меняет Elica.
|
||||
#
|
||||
# Например:
|
||||
#
|
||||
# speed 1 -> 2
|
||||
#
|
||||
# AutoController пока ничего не делает.
|
||||
# Просто ждём реальный MQTT feedback.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 2:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Now MANUALLY change Elica."
|
||||
)
|
||||
|
||||
print(
|
||||
"For example change speed 1 -> 2."
|
||||
)
|
||||
|
||||
print(
|
||||
"The test is waiting..."
|
||||
)
|
||||
|
||||
changed = await wait_for_manual_change(
|
||||
service,
|
||||
power=owned.power,
|
||||
speed=owned.speed,
|
||||
timer=owned.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Manual Elica state:",
|
||||
{
|
||||
"power": changed.power,
|
||||
"speed": changed.speed,
|
||||
"timer": changed.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 3
|
||||
#
|
||||
# Tion всё ещё 4.
|
||||
#
|
||||
# Следующий проход AutoController должен увидеть:
|
||||
#
|
||||
# expected_speed = 1
|
||||
# actual speed = 2
|
||||
#
|
||||
# -> manual_intervention
|
||||
# -> SUPPRESSED
|
||||
#
|
||||
# И НИКАКИХ команд Elica.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 3:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion is still speed 4."
|
||||
)
|
||||
|
||||
print(
|
||||
"AutoController should detect "
|
||||
"manual intervention..."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
after_takeover = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after detection:",
|
||||
{
|
||||
"power": after_takeover.power,
|
||||
"speed": after_takeover.speed,
|
||||
"timer": after_takeover.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "suppressed":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter SUPPRESSED"
|
||||
)
|
||||
|
||||
if (
|
||||
assist.status()["reason"]
|
||||
!= "manual_intervention"
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Expected reason manual_intervention"
|
||||
)
|
||||
|
||||
# Elica должна остаться ровно такой,
|
||||
# какой её сделал пользователь.
|
||||
if (
|
||||
after_takeover.power
|
||||
!= changed.power
|
||||
or after_takeover.speed
|
||||
!= changed.speed
|
||||
or after_takeover.timer
|
||||
!= changed.timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController changed Elica "
|
||||
"after manual intervention"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"MANUAL TAKEOVER PASSED"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 4
|
||||
#
|
||||
# Теперь Tion падает ниже порога:
|
||||
#
|
||||
# 4 -> 3
|
||||
#
|
||||
# Текущий автоматический цикл заканчивается.
|
||||
#
|
||||
# Но Elica уже пользовательская,
|
||||
# поэтому выключать её ЗАПРЕЩЕНО.
|
||||
#
|
||||
# SUPPRESSED -> IDLE
|
||||
# Elica остаётся включена.
|
||||
# ==================================================
|
||||
|
||||
print()
|
||||
print(
|
||||
"STEP 4:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion AUTO speed drops to 3."
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica must NOT be switched off."
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
3
|
||||
)
|
||||
|
||||
final_elica = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Final Elica:",
|
||||
{
|
||||
"power": final_elica.power,
|
||||
"speed": final_elica.speed,
|
||||
"timer": final_elica.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Final Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Проверяем, что пользовательское состояние
|
||||
# вообще не изменилось.
|
||||
# --------------------------------------------------
|
||||
|
||||
if (
|
||||
final_elica.power
|
||||
!= changed.power
|
||||
or final_elica.speed
|
||||
!= changed.speed
|
||||
or final_elica.timer
|
||||
!= changed.timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"AutoController modified user's "
|
||||
"Elica when Tion dropped to speed 3"
|
||||
)
|
||||
|
||||
# Новый цикл должен быть готов начаться
|
||||
# в будущем.
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Assist did not return to IDLE "
|
||||
"after the automatic cycle ended"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"RELEASE AFTER TAKEOVER PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Verified sequence:"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 4"
|
||||
" -> Auto Elica 1"
|
||||
" -> OWNED"
|
||||
)
|
||||
|
||||
print(
|
||||
"User changes Elica"
|
||||
" -> SUPPRESSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Tion 3"
|
||||
" -> Elica untouched"
|
||||
" -> IDLE"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Turn Elica off manually "
|
||||
"after the test."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,314 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.controller import AutoController
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-auto-exit-test-"
|
||||
f"{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
elica_controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
initial = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": initial.power,
|
||||
"speed": initial.speed,
|
||||
"timer": initial.timer,
|
||||
},
|
||||
)
|
||||
|
||||
if initial.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
auto_controller = AutoController(
|
||||
schedule_service=object(),
|
||||
qingping_service=object(),
|
||||
tion_service=object(),
|
||||
elica_controller=elica_controller,
|
||||
policy=None,
|
||||
temperature_policy=None,
|
||||
elica_assist=assist,
|
||||
interval=1.0,
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Имитируем рабочий AUTO:
|
||||
# Tion speed 4 -> Elica speed 1 -> OWNED
|
||||
# --------------------------------------------------
|
||||
|
||||
print()
|
||||
print("STEP 1:")
|
||||
print(
|
||||
"Tion AUTO speed 4 "
|
||||
"-> Auto Assist acquires Elica"
|
||||
)
|
||||
|
||||
await auto_controller._update_elica_assist(
|
||||
4
|
||||
)
|
||||
|
||||
owned = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica:",
|
||||
{
|
||||
"power": owned.power,
|
||||
"speed": owned.speed,
|
||||
"timer": owned.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if (
|
||||
not owned.power
|
||||
or owned.speed != 1
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not acquire "
|
||||
"Elica at speed 1"
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"ACQUIRE PASSED"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Теперь имитируем не Tion speed 3,
|
||||
# а полный ВЫХОД ИЗ AUTO.
|
||||
#
|
||||
# Именно _release_elica_assist()
|
||||
# должен выключить принадлежащую нам Elica.
|
||||
# --------------------------------------------------
|
||||
|
||||
print()
|
||||
print("STEP 2:")
|
||||
print(
|
||||
"Simulating exit from Tion AUTO..."
|
||||
)
|
||||
|
||||
await auto_controller._release_elica_assist()
|
||||
|
||||
released = elica_controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica after AUTO exit:",
|
||||
{
|
||||
"power": released.power,
|
||||
"speed": released.speed,
|
||||
"timer": released.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist after AUTO exit:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ПРОВЕРКИ
|
||||
# --------------------------------------------------
|
||||
|
||||
if released.power:
|
||||
raise RuntimeError(
|
||||
"Elica remained ON after AUTO exit"
|
||||
)
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Assist did not return to IDLE"
|
||||
)
|
||||
|
||||
if assist.expected_speed is not None:
|
||||
raise RuntimeError(
|
||||
"expected_speed was not cleared"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"AUTO EXIT RELEASE PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Verified sequence:"
|
||||
)
|
||||
|
||||
print(
|
||||
"AUTO active"
|
||||
" -> Tion 4"
|
||||
" -> Elica 1"
|
||||
" -> OWNED"
|
||||
)
|
||||
|
||||
print(
|
||||
"AUTO exit"
|
||||
" -> Elica OFF"
|
||||
" -> IDLE"
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,341 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
# По нашей текущей таблице:
|
||||
# Tion 4 -> Elica 1
|
||||
TION_SPEED = 4
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
"""
|
||||
Отдельный MQTT client_id для live-теста,
|
||||
чтобы не конфликтовать с запущенным
|
||||
ClimatController.
|
||||
"""
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-acquire-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
"""
|
||||
Ждём подключения к MQTT, ESP32
|
||||
и полной обратной связи панели Elica.
|
||||
"""
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready.\n"
|
||||
f"mqtt_connected="
|
||||
f"{state.mqtt_connected}\n"
|
||||
f"device_online="
|
||||
f"{state.device_online}\n"
|
||||
f"feedback_ready="
|
||||
f"{service.feedback_ready}\n"
|
||||
f"missing_feedback_inputs="
|
||||
f"{service.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Перед началом теста Elica обязана быть OFF.
|
||||
# --------------------------------------------------
|
||||
|
||||
state = controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": state.power,
|
||||
"speed": state.speed,
|
||||
"timer": state.timer,
|
||||
},
|
||||
)
|
||||
|
||||
if state.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test. "
|
||||
"Turn it off manually and run the test again."
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Создаём Auto Assist.
|
||||
# --------------------------------------------------
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Имитируем решение AUTO Tion.
|
||||
# --------------------------------------------------
|
||||
|
||||
target_speed = (
|
||||
assist.set_tion_speed(
|
||||
TION_SPEED
|
||||
)
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
TION_SPEED,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target_speed,
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist before observe:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Проверяем исходное состояние Elica.
|
||||
#
|
||||
# Она OFF, поэтому ассистент должен
|
||||
# остаться IDLE и разрешить захват.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=state.power,
|
||||
speed=state.speed,
|
||||
timer=state.timer,
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist after observe:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not remain IDLE "
|
||||
"with Elica switched off"
|
||||
)
|
||||
|
||||
if target_speed is None:
|
||||
raise RuntimeError(
|
||||
"No Elica target speed "
|
||||
"for current Tion speed"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"AUTO ASSIST IS NOW GOING TO "
|
||||
f"SET ELICA SPEED {target_speed}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ПЕРВАЯ РЕАЛЬНАЯ КОМАНДА.
|
||||
#
|
||||
# Из OFF вызов set_speed(1) нажмёт Speed
|
||||
# и дождётся подтверждения:
|
||||
#
|
||||
# power=True
|
||||
# speed=1
|
||||
# --------------------------------------------------
|
||||
|
||||
result = await controller.set_speed(
|
||||
target_speed
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Confirmed Elica:",
|
||||
{
|
||||
"power": result.power,
|
||||
"speed": result.speed,
|
||||
"timer": result.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Только после подтверждённой команды
|
||||
# объявляем Elica принадлежащей автоматике.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.mark_owned(
|
||||
result.speed
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist after mark_owned:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Передаём подтверждённое фактическое
|
||||
# состояние ещё раз.
|
||||
#
|
||||
# Оно совпадает с expected_speed,
|
||||
# поэтому OWNED должен сохраниться.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=result.power,
|
||||
speed=result.speed,
|
||||
timer=result.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Assist after confirmed feedback:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Auto Assist did not enter OWNED state"
|
||||
)
|
||||
|
||||
if result.speed != target_speed:
|
||||
raise RuntimeError(
|
||||
"Elica reached unexpected speed"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica was acquired by Auto Assist "
|
||||
f"at speed {result.speed}."
|
||||
)
|
||||
|
||||
print(
|
||||
"Turn Elica off manually after the test."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,368 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
# Имитируем ситуацию:
|
||||
# AUTO-контроллер Tion выбрал скорость 4.
|
||||
TION_SPEED = 4
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
ELICA_CHANGE_TIMEOUT = 60.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
"""
|
||||
Тестовая версия ElicaService.
|
||||
|
||||
Отличие только одно:
|
||||
используется отдельный MQTT client_id,
|
||||
чтобы не конфликтовать с запущенным
|
||||
ClimatController.
|
||||
"""
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
"""
|
||||
Ждём полноценного подключения Elica:
|
||||
MQTT + ESP32 online + обратная связь.
|
||||
"""
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready.\n"
|
||||
f"mqtt_connected="
|
||||
f"{state.mqtt_connected}\n"
|
||||
f"device_online="
|
||||
f"{state.device_online}\n"
|
||||
f"feedback_ready="
|
||||
f"{service.feedback_ready}\n"
|
||||
f"missing_feedback_inputs="
|
||||
f"{service.missing_feedback_inputs}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def wait_for_elica_change(
|
||||
service: ElicaService,
|
||||
*,
|
||||
power: bool,
|
||||
speed: int,
|
||||
timer: bool,
|
||||
):
|
||||
"""
|
||||
Ждём реального ручного изменения Elica.
|
||||
|
||||
ВАЖНО:
|
||||
потеря MQTT, offline ESP32 или потеря
|
||||
feedback НЕ считаются ручным изменением.
|
||||
"""
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_CHANGE_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
# ----------------------------------------------
|
||||
# Если связь временно потеряна,
|
||||
# состояние logical_state использовать нельзя.
|
||||
#
|
||||
# Иначе OFF/0 после disconnect можно ошибочно
|
||||
# принять за ручное выключение Elica.
|
||||
# ----------------------------------------------
|
||||
|
||||
ready = (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
)
|
||||
|
||||
if ready:
|
||||
logical = service.logical_state
|
||||
|
||||
changed = (
|
||||
logical.power != power
|
||||
or logical.speed != speed
|
||||
or logical.timer != timer
|
||||
)
|
||||
|
||||
if changed:
|
||||
return logical
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"No real Elica change detected "
|
||||
f"within "
|
||||
f"{ELICA_CHANGE_TIMEOUT} seconds"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# --------------------------------------------------
|
||||
# Запускаем только тестовый ElicaService.
|
||||
#
|
||||
# Tion, Qingping, FastAPI и Schedule
|
||||
# здесь не участвуют.
|
||||
# --------------------------------------------------
|
||||
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Ждём реальную ESP32 Elica.
|
||||
# --------------------------------------------------
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Читаем текущее состояние.
|
||||
# --------------------------------------------------
|
||||
|
||||
elica = service.logical_state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Real Elica:",
|
||||
{
|
||||
"power": elica.power,
|
||||
"speed": elica.speed,
|
||||
"timer": elica.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Загружаем Auto Assist.
|
||||
# --------------------------------------------------
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Имитируем:
|
||||
#
|
||||
# Tion AUTO выбрал скорость 4.
|
||||
#
|
||||
# По текущей таблице:
|
||||
# Tion 4 -> Elica 1.
|
||||
# --------------------------------------------------
|
||||
|
||||
target = assist.set_tion_speed(
|
||||
TION_SPEED
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
TION_SPEED,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Before observe:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Передаём исходное реальное состояние Elica.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=elica.power,
|
||||
speed=elica.speed,
|
||||
timer=elica.timer,
|
||||
)
|
||||
|
||||
print(
|
||||
"After observe:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Запоминаем именно подтверждённое состояние.
|
||||
# --------------------------------------------------
|
||||
|
||||
initial_power = elica.power
|
||||
initial_speed = elica.speed
|
||||
initial_timer = elica.timer
|
||||
|
||||
print()
|
||||
print(
|
||||
"Now change Elica manually."
|
||||
)
|
||||
|
||||
print(
|
||||
"Change speed, turn it on/off "
|
||||
"or enable Timer."
|
||||
)
|
||||
|
||||
print(
|
||||
"The test is waiting for "
|
||||
"REAL MQTT feedback..."
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Здесь тест ждёт физического изменения Elica.
|
||||
# Disconnect теперь изменение не имитирует.
|
||||
# --------------------------------------------------
|
||||
|
||||
changed = await wait_for_elica_change(
|
||||
service,
|
||||
power=initial_power,
|
||||
speed=initial_speed,
|
||||
timer=initial_timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica changed:",
|
||||
{
|
||||
"power": changed.power,
|
||||
"speed": changed.speed,
|
||||
"timer": changed.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Передаём ручное изменение Auto Assist.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=changed.power,
|
||||
speed=changed.speed,
|
||||
timer=changed.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"After manual change:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,335 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
ELICA_CHANGE_TIMEOUT = 60.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-owned-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def wait_for_elica_change(
|
||||
service: ElicaService,
|
||||
*,
|
||||
power: bool,
|
||||
speed: int,
|
||||
timer: bool,
|
||||
):
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_CHANGE_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
ready = (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
)
|
||||
|
||||
if ready:
|
||||
logical = service.logical_state
|
||||
|
||||
if (
|
||||
logical.power != power
|
||||
or logical.speed != speed
|
||||
or logical.timer != timer
|
||||
):
|
||||
return logical
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"No real Elica change detected "
|
||||
f"within {ELICA_CHANGE_TIMEOUT} seconds"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
elica = service.logical_state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Current Elica:",
|
||||
{
|
||||
"power": elica.power,
|
||||
"speed": elica.speed,
|
||||
"timer": elica.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Для этого теста Elica должна быть
|
||||
# уже включена на скорости 1, 2 или 3.
|
||||
if (
|
||||
not elica.power
|
||||
or elica.speed not in (1, 2, 3)
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Before starting this test, "
|
||||
"manually turn Elica on "
|
||||
"at speed 1, 2 or 3"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# Находим скорость Tion, которой
|
||||
# соответствует текущая скорость Elica.
|
||||
tion_speed = None
|
||||
|
||||
for (
|
||||
candidate_tion_speed,
|
||||
candidate_elica_speed,
|
||||
) in config.elica_assist.speed_map:
|
||||
if (
|
||||
candidate_elica_speed
|
||||
== elica.speed
|
||||
):
|
||||
tion_speed = (
|
||||
candidate_tion_speed
|
||||
)
|
||||
break
|
||||
|
||||
if tion_speed is None:
|
||||
raise RuntimeError(
|
||||
"Current Elica speed is not "
|
||||
"present in elica_assist.speed_map"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Имитируем:
|
||||
#
|
||||
# Tion AUTO потребовал такую скорость Elica,
|
||||
# и автоматика якобы успешно её установила.
|
||||
# --------------------------------------------------
|
||||
|
||||
target = assist.set_tion_speed(
|
||||
tion_speed
|
||||
)
|
||||
|
||||
assist.mark_owned(
|
||||
elica.speed
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
tion_speed,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target,
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist after mark_owned:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Передаём совпадающую обратную связь.
|
||||
#
|
||||
# OWNED должен сохраниться.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=elica.power,
|
||||
speed=elica.speed,
|
||||
timer=elica.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"After matching feedback:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
initial_power = elica.power
|
||||
initial_speed = elica.speed
|
||||
initial_timer = elica.timer
|
||||
|
||||
print()
|
||||
print(
|
||||
"Now change Elica manually."
|
||||
)
|
||||
|
||||
print(
|
||||
"For example, change its speed."
|
||||
)
|
||||
|
||||
print(
|
||||
"The test is waiting for "
|
||||
"REAL MQTT feedback..."
|
||||
)
|
||||
|
||||
changed = await wait_for_elica_change(
|
||||
service,
|
||||
power=initial_power,
|
||||
speed=initial_speed,
|
||||
timer=initial_timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica changed:",
|
||||
{
|
||||
"power": changed.power,
|
||||
"speed": changed.speed,
|
||||
"timer": changed.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Теперь Auto Assist должен увидеть,
|
||||
# что фактическое состояние больше
|
||||
# не совпадает с expected_speed.
|
||||
# --------------------------------------------------
|
||||
|
||||
assist.observe_elica(
|
||||
power=changed.power,
|
||||
speed=changed.speed,
|
||||
timer=changed.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"After manual intervention:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,375 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-release-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
state = controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": state.power,
|
||||
"speed": state.speed,
|
||||
"timer": state.timer,
|
||||
},
|
||||
)
|
||||
|
||||
if state.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Tion AUTO = 4
|
||||
# Elica target = 1
|
||||
# Получаем OWNED.
|
||||
# --------------------------------------------------
|
||||
|
||||
target = assist.set_tion_speed(
|
||||
4
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
4,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target,
|
||||
)
|
||||
|
||||
if target != 1:
|
||||
raise RuntimeError(
|
||||
f"Expected target 1, got {target}"
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=state.power,
|
||||
speed=state.speed,
|
||||
timer=state.timer,
|
||||
)
|
||||
|
||||
result = await controller.set_speed(
|
||||
target
|
||||
)
|
||||
|
||||
assist.mark_owned(
|
||||
result.speed
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=result.power,
|
||||
speed=result.speed,
|
||||
timer=result.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica acquired:",
|
||||
{
|
||||
"power": result.power,
|
||||
"speed": result.speed,
|
||||
"timer": result.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Tion AUTO падает до 3.
|
||||
#
|
||||
# target_speed должен стать None.
|
||||
# --------------------------------------------------
|
||||
|
||||
target = assist.set_tion_speed(
|
||||
3
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
3,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target,
|
||||
)
|
||||
|
||||
if target is not None:
|
||||
raise RuntimeError(
|
||||
"Expected no Elica target "
|
||||
"at Tion speed 3"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Перед выключением обязательно ещё раз
|
||||
# проверяем фактическое состояние.
|
||||
#
|
||||
# Если оно уже не совпадает с expected_speed,
|
||||
# значит пользователь вмешался.
|
||||
# --------------------------------------------------
|
||||
|
||||
current = controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica before release:",
|
||||
{
|
||||
"power": current.power,
|
||||
"speed": current.speed,
|
||||
"timer": current.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist before release:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=current.power,
|
||||
speed=current.speed,
|
||||
timer=current.timer,
|
||||
)
|
||||
|
||||
# После проверки мы всё ещё должны
|
||||
# владеть Elica.
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Auto Assist lost ownership "
|
||||
"before release. "
|
||||
"Elica will NOT be switched off."
|
||||
)
|
||||
|
||||
expected = assist.expected_speed
|
||||
|
||||
if (
|
||||
not current.power
|
||||
or current.speed != expected
|
||||
or current.timer
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Actual Elica state does not match "
|
||||
"the state owned by Auto Assist"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ПЕРВОЕ АВТОМАТИЧЕСКОЕ ВЫКЛЮЧЕНИЕ.
|
||||
# --------------------------------------------------
|
||||
|
||||
print()
|
||||
print(
|
||||
"AUTO ASSIST IS NOW GOING TO "
|
||||
"TURN ELICA OFF"
|
||||
)
|
||||
|
||||
result_off = await controller.power_off()
|
||||
|
||||
print()
|
||||
print(
|
||||
"Confirmed Elica:",
|
||||
{
|
||||
"power": result_off.power,
|
||||
"speed": result_off.speed,
|
||||
"timer": result_off.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# После успешного выключения
|
||||
# текущий автоматический цикл завершён.
|
||||
assist.reset()
|
||||
|
||||
print(
|
||||
"Assist after release:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# ПРОВЕРКИ
|
||||
# --------------------------------------------------
|
||||
|
||||
if result_off.power:
|
||||
raise RuntimeError(
|
||||
"Elica did not switch off"
|
||||
)
|
||||
|
||||
if assist.mode.value != "idle":
|
||||
raise RuntimeError(
|
||||
"Assist did not return to IDLE"
|
||||
)
|
||||
|
||||
if assist.expected_speed is not None:
|
||||
raise RuntimeError(
|
||||
"expected_speed was not cleared"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Auto Assist acquired Elica, "
|
||||
"then released and switched it off "
|
||||
"when Tion dropped to speed 3."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,316 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-speed-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
state = controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": state.power,
|
||||
"speed": state.speed,
|
||||
"timer": state.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Для этого теста Elica должна быть выключена.
|
||||
if state.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Этап 1:
|
||||
# Tion AUTO = 4 -> Elica должна стать 1
|
||||
# --------------------------------------------------
|
||||
|
||||
target_1 = assist.set_tion_speed(4)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
4,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target_1,
|
||||
)
|
||||
|
||||
if target_1 != 1:
|
||||
raise RuntimeError(
|
||||
f"Expected Elica target 1, got {target_1}"
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=state.power,
|
||||
speed=state.speed,
|
||||
timer=state.timer,
|
||||
)
|
||||
|
||||
result_1 = await controller.set_speed(
|
||||
target_1
|
||||
)
|
||||
|
||||
assist.mark_owned(
|
||||
result_1.speed
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=result_1.power,
|
||||
speed=result_1.speed,
|
||||
timer=result_1.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"After first acquire:",
|
||||
{
|
||||
"power": result_1.power,
|
||||
"speed": result_1.speed,
|
||||
"timer": result_1.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist did not enter OWNED"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Этап 2:
|
||||
# Tion AUTO меняется 4 -> 5
|
||||
# Значит Elica 1 -> 2
|
||||
# --------------------------------------------------
|
||||
|
||||
target_2 = assist.set_tion_speed(5)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
5,
|
||||
)
|
||||
|
||||
print(
|
||||
"New Elica target:",
|
||||
target_2,
|
||||
)
|
||||
|
||||
if target_2 != 2:
|
||||
raise RuntimeError(
|
||||
f"Expected Elica target 2, got {target_2}"
|
||||
)
|
||||
|
||||
# --------------------------------------------------
|
||||
# Пока владельцем остаётся автоматика,
|
||||
# поэтому ей разрешено изменить скорость.
|
||||
# --------------------------------------------------
|
||||
|
||||
result_2 = await controller.set_speed(
|
||||
target_2
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Confirmed Elica after speed change:",
|
||||
{
|
||||
"power": result_2.power,
|
||||
"speed": result_2.speed,
|
||||
"timer": result_2.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Обновляем expected_speed только после
|
||||
# подтверждённой команды.
|
||||
assist.mark_owned(
|
||||
result_2.speed
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=result_2.power,
|
||||
speed=result_2.speed,
|
||||
timer=result_2.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Assist after speed change:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Assist lost OWNED after "
|
||||
"automatic speed change"
|
||||
)
|
||||
|
||||
if result_2.speed != 2:
|
||||
raise RuntimeError(
|
||||
"Elica did not reach speed 2"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Auto Assist changed Elica "
|
||||
"from speed 1 to speed 2 "
|
||||
"and kept OWNED."
|
||||
)
|
||||
|
||||
print(
|
||||
"Turn Elica off manually after the test."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,448 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from app.auto.config import load_auto_config
|
||||
from app.auto.elica_assist import ElicaAutoAssistState
|
||||
|
||||
from app.elica import (
|
||||
ElicaConfig,
|
||||
ElicaController,
|
||||
ElicaService,
|
||||
)
|
||||
|
||||
from app.my_dataclasses import (
|
||||
ELICA_MQTT_HOST,
|
||||
ELICA_MQTT_PORT,
|
||||
)
|
||||
|
||||
|
||||
AUTO_CONFIG = "config/auto.yaml"
|
||||
|
||||
ELICA_READY_TIMEOUT = 15.0
|
||||
|
||||
|
||||
class TestElicaService(ElicaService):
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
|
||||
client_id = (
|
||||
f"climatcontroller-elica-down-test-{os.getpid()}"
|
||||
)
|
||||
|
||||
print(
|
||||
"Test MQTT client_id:",
|
||||
client_id,
|
||||
)
|
||||
|
||||
client = mqtt.Client(
|
||||
callback_api_version=(
|
||||
mqtt.CallbackAPIVersion.VERSION2
|
||||
),
|
||||
client_id=client_id,
|
||||
)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_message = self._on_message
|
||||
|
||||
client.reconnect_delay_set(
|
||||
min_delay=1,
|
||||
max_delay=30,
|
||||
)
|
||||
|
||||
self._client = client
|
||||
self._running = True
|
||||
|
||||
client.connect_async(
|
||||
self._config.mqtt_host,
|
||||
self._config.mqtt_port,
|
||||
keepalive=60,
|
||||
)
|
||||
|
||||
client.loop_start()
|
||||
|
||||
|
||||
async def wait_for_elica(
|
||||
service: ElicaService,
|
||||
) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
deadline = (
|
||||
loop.time()
|
||||
+ ELICA_READY_TIMEOUT
|
||||
)
|
||||
|
||||
while True:
|
||||
state = service.state
|
||||
|
||||
if (
|
||||
state.mqtt_connected
|
||||
and state.device_online
|
||||
and service.feedback_ready
|
||||
):
|
||||
return
|
||||
|
||||
if loop.time() >= deadline:
|
||||
raise RuntimeError(
|
||||
"Elica did not become ready"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
async def set_speed_with_trace(
|
||||
controller: ElicaController,
|
||||
service: ElicaService,
|
||||
target_speed: int,
|
||||
):
|
||||
"""
|
||||
Выполняет обычный controller.set_speed(),
|
||||
параллельно записывая фактические скорости Elica.
|
||||
|
||||
Это позволяет увидеть реальный цикл:
|
||||
2 -> 3 -> 4 -> 1
|
||||
"""
|
||||
|
||||
path: list[int] = []
|
||||
|
||||
initial = service.logical_state
|
||||
|
||||
if (
|
||||
initial.power
|
||||
and 1 <= initial.speed <= 4
|
||||
):
|
||||
path.append(initial.speed)
|
||||
|
||||
task = asyncio.create_task(
|
||||
controller.set_speed(
|
||||
target_speed
|
||||
)
|
||||
)
|
||||
|
||||
while not task.done():
|
||||
state = service.logical_state
|
||||
|
||||
if (
|
||||
state.power
|
||||
and 1 <= state.speed <= 4
|
||||
):
|
||||
if (
|
||||
not path
|
||||
or path[-1] != state.speed
|
||||
):
|
||||
path.append(
|
||||
state.speed
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.02)
|
||||
|
||||
result = await task
|
||||
|
||||
# На всякий случай фиксируем конечное
|
||||
# подтверждённое состояние.
|
||||
if (
|
||||
result.power
|
||||
and 1 <= result.speed <= 4
|
||||
and (
|
||||
not path
|
||||
or path[-1] != result.speed
|
||||
)
|
||||
):
|
||||
path.append(
|
||||
result.speed
|
||||
)
|
||||
|
||||
return result, path
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
service = TestElicaService(
|
||||
ElicaConfig(
|
||||
mqtt_host=ELICA_MQTT_HOST,
|
||||
mqtt_port=ELICA_MQTT_PORT,
|
||||
)
|
||||
)
|
||||
|
||||
controller = ElicaController(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Starting Elica service..."
|
||||
)
|
||||
|
||||
await service.start()
|
||||
|
||||
try:
|
||||
print(
|
||||
f"Connecting to MQTT "
|
||||
f"{ELICA_MQTT_HOST}:"
|
||||
f"{ELICA_MQTT_PORT}..."
|
||||
)
|
||||
|
||||
await wait_for_elica(
|
||||
service
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica connected and "
|
||||
"feedback ready"
|
||||
)
|
||||
|
||||
state = controller.state
|
||||
|
||||
print()
|
||||
print(
|
||||
"Initial Elica:",
|
||||
{
|
||||
"power": state.power,
|
||||
"speed": state.speed,
|
||||
"timer": state.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Для чистоты начинаем с OFF.
|
||||
if state.power:
|
||||
raise RuntimeError(
|
||||
"Elica must be OFF before this test"
|
||||
)
|
||||
|
||||
config = load_auto_config(
|
||||
AUTO_CONFIG
|
||||
)
|
||||
|
||||
assist = ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 1
|
||||
#
|
||||
# Tion AUTO = 5
|
||||
# Elica target = 2
|
||||
#
|
||||
# Получаем OWNED на скорости 2.
|
||||
# ==================================================
|
||||
|
||||
target_2 = assist.set_tion_speed(
|
||||
5
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
5,
|
||||
)
|
||||
|
||||
print(
|
||||
"Elica target:",
|
||||
target_2,
|
||||
)
|
||||
|
||||
if target_2 != 2:
|
||||
raise RuntimeError(
|
||||
f"Expected Elica target 2, "
|
||||
f"got {target_2}"
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=state.power,
|
||||
speed=state.speed,
|
||||
timer=state.timer,
|
||||
)
|
||||
|
||||
result_2 = await controller.set_speed(
|
||||
target_2
|
||||
)
|
||||
|
||||
assist.mark_owned(
|
||||
result_2.speed
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=result_2.power,
|
||||
speed=result_2.speed,
|
||||
timer=result_2.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Elica acquired:",
|
||||
{
|
||||
"power": result_2.power,
|
||||
"speed": result_2.speed,
|
||||
"timer": result_2.timer,
|
||||
},
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if (
|
||||
assist.mode.value != "owned"
|
||||
or result_2.speed != 2
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Failed to acquire Elica "
|
||||
"at speed 2"
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ЭТАП 2
|
||||
#
|
||||
# Tion AUTO падает:
|
||||
#
|
||||
# 5 -> 4
|
||||
#
|
||||
# Новая цель Elica:
|
||||
#
|
||||
# 2 -> 1
|
||||
#
|
||||
# Но физически Elica должна пройти:
|
||||
#
|
||||
# 2 -> 3 -> 4 -> 1
|
||||
# ==================================================
|
||||
|
||||
target_1 = assist.set_tion_speed(
|
||||
4
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Tion AUTO speed:",
|
||||
4,
|
||||
)
|
||||
|
||||
print(
|
||||
"New Elica target:",
|
||||
target_1,
|
||||
)
|
||||
|
||||
print(
|
||||
"Assist before speed change:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
if target_1 != 1:
|
||||
raise RuntimeError(
|
||||
f"Expected Elica target 1, "
|
||||
f"got {target_1}"
|
||||
)
|
||||
|
||||
# ВАЖНО:
|
||||
#
|
||||
# Здесь НЕ вызываем observe_elica()
|
||||
# во время промежуточных скоростей.
|
||||
#
|
||||
# 3 и 4 являются частью нашей
|
||||
# собственной команды set_speed(1),
|
||||
# а не действиями пользователя.
|
||||
|
||||
result_1, speed_path = (
|
||||
await set_speed_with_trace(
|
||||
controller,
|
||||
service,
|
||||
target_1,
|
||||
)
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Observed speed path:",
|
||||
speed_path,
|
||||
)
|
||||
|
||||
print(
|
||||
"Confirmed Elica:",
|
||||
{
|
||||
"power": result_1.power,
|
||||
"speed": result_1.speed,
|
||||
"timer": result_1.timer,
|
||||
},
|
||||
)
|
||||
|
||||
# Только ПОСЛЕ завершения всей нашей
|
||||
# последовательности обновляем владение.
|
||||
assist.mark_owned(
|
||||
result_1.speed
|
||||
)
|
||||
|
||||
assist.observe_elica(
|
||||
power=result_1.power,
|
||||
speed=result_1.speed,
|
||||
timer=result_1.timer,
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Assist after speed change:",
|
||||
assist.status(),
|
||||
)
|
||||
|
||||
# ==================================================
|
||||
# ПРОВЕРКИ
|
||||
# ==================================================
|
||||
|
||||
if speed_path != [2, 3, 4, 1]:
|
||||
raise RuntimeError(
|
||||
"Unexpected Elica speed path: "
|
||||
f"{speed_path}; "
|
||||
"expected [2, 3, 4, 1]"
|
||||
)
|
||||
|
||||
if result_1.speed != 1:
|
||||
raise RuntimeError(
|
||||
"Elica did not reach speed 1"
|
||||
)
|
||||
|
||||
if assist.mode.value != "owned":
|
||||
raise RuntimeError(
|
||||
"Auto Assist lost OWNED "
|
||||
"during automatic speed change"
|
||||
)
|
||||
|
||||
if assist.expected_speed != 1:
|
||||
raise RuntimeError(
|
||||
"Auto Assist expected_speed "
|
||||
"was not updated to 1"
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"TEST PASSED"
|
||||
)
|
||||
|
||||
print(
|
||||
"Automatic Elica transition:"
|
||||
)
|
||||
|
||||
print(
|
||||
"2 -> 3 -> 4 -> 1"
|
||||
)
|
||||
|
||||
print(
|
||||
"Auto Assist kept OWNED."
|
||||
)
|
||||
|
||||
print()
|
||||
print(
|
||||
"Turn Elica off manually "
|
||||
"after the test."
|
||||
)
|
||||
|
||||
finally:
|
||||
print()
|
||||
print(
|
||||
"Stopping Elica service..."
|
||||
)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,112 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from app.elica.config import ElicaConfig
|
||||
from app.elica.service import ElicaService
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
config = ElicaConfig(
|
||||
mqtt_host="192.168.7.100", # IP Mosquitto
|
||||
mqtt_port=1883,
|
||||
)
|
||||
|
||||
service = ElicaService(config)
|
||||
|
||||
print("Starting ElicaService...")
|
||||
await service.start( )
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
try:
|
||||
# Даём MQTT время подключиться и получить retained elica/status.
|
||||
await asyncio.sleep(2)
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
service.status(),
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
assert service.state.mqtt_connected
|
||||
assert service.state.device_online
|
||||
|
||||
print("\nMQTT: OK")
|
||||
print("ESP32: ONLINE")
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# Проверяем все 8 реле по очереди
|
||||
# --------------------------------------------------------------
|
||||
|
||||
for relay in range(1, 9):
|
||||
# print(f"\nTesting Relay {relay}...")
|
||||
#
|
||||
# # ON
|
||||
# service.set_relay(relay,True,)
|
||||
#
|
||||
# await asyncio.sleep(0.5)
|
||||
#
|
||||
# state = service.relay_state(relay)
|
||||
#
|
||||
# print(f"Relay {relay} after ON: {state}")
|
||||
#
|
||||
# assert state is True, (f"Relay {relay} did not report ON")
|
||||
#
|
||||
# # OFF
|
||||
# service.set_relay(relay,False)
|
||||
#
|
||||
# await asyncio.sleep(0.5)
|
||||
#
|
||||
# state = service.relay_state(relay)
|
||||
#
|
||||
# print(f"Relay {relay} after OFF: {state}")
|
||||
#
|
||||
# assert state is False, (f"Relay {relay} did not report OFF")
|
||||
|
||||
print(f"Pulse Relay {relay}")
|
||||
await service.pulse_relay(relay)
|
||||
await asyncio.sleep(0.5)
|
||||
print(f"Relay {relay} state:", service.relay_state(relay))
|
||||
assert service.relay_state(relay) is False
|
||||
|
||||
print("\nAll 8 relays passed MQTT test.")
|
||||
print("\nFinal state:")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
service.status(),
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
# print("\nInitial inputs:")
|
||||
# print(service.state.input_states)
|
||||
#
|
||||
# print("\nToggle ESP32 inputs now...")
|
||||
# for _ in range(15):
|
||||
# await asyncio.sleep(1)
|
||||
# print(service.state.input_states)
|
||||
|
||||
finally:
|
||||
# На всякий случай гарантированно выключаем все реле.
|
||||
if service.state.mqtt_connected:
|
||||
|
||||
for relay in range(1, 9):
|
||||
service.set_relay(
|
||||
relay,
|
||||
False,
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
await service.stop()
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -561,9 +561,15 @@ class ScheduleService:
|
||||
if resolution.auto_active:
|
||||
# В режиме AUTO скорость принадлежит
|
||||
# AutoController.
|
||||
#
|
||||
# Остальные параметры расписания
|
||||
# (power, heater, temperature, mode...)
|
||||
# должны продолжать работать.
|
||||
settings = replace(
|
||||
settings,
|
||||
speed=None,
|
||||
heater=None,
|
||||
target_temp=None,
|
||||
)
|
||||
|
||||
await self._apply_settings(settings)
|
||||
@@ -592,6 +598,24 @@ class ScheduleService:
|
||||
tion.set_air_mode(settings.mode)
|
||||
)
|
||||
|
||||
if settings.target_temp is not None:
|
||||
await self._tion.execute(
|
||||
lambda tion:
|
||||
tion.set_target_temperature(
|
||||
settings.target_temp
|
||||
)
|
||||
)
|
||||
|
||||
if settings.heater is not None:
|
||||
if settings.heater:
|
||||
await self._tion.execute(
|
||||
lambda tion: tion.heater_on()
|
||||
)
|
||||
else:
|
||||
await self._tion.execute(
|
||||
lambda tion: tion.heater_off()
|
||||
)
|
||||
|
||||
if settings.speed is not None:
|
||||
await self._tion.execute(
|
||||
lambda tion:
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from app.auto.config import (
|
||||
load_auto_config_components,
|
||||
)
|
||||
|
||||
from app.auto.temperature_policy import (
|
||||
TemperaturePolicy,
|
||||
)
|
||||
|
||||
from app.auto.elica_assist import (
|
||||
ElicaAutoAssistState,
|
||||
)
|
||||
|
||||
|
||||
BROKEN_CO2_CONFIG = """
|
||||
version: 1
|
||||
|
||||
check_interval: 5.0
|
||||
|
||||
co2:
|
||||
base_speed: 2
|
||||
hysteresis: 100
|
||||
|
||||
thresholds:
|
||||
- ppm: 700
|
||||
speed: 2
|
||||
|
||||
- ppm: 1000
|
||||
speed: 3
|
||||
|
||||
temperature:
|
||||
hysteresis: 0.5
|
||||
|
||||
elica_assist:
|
||||
enabled: false
|
||||
|
||||
speed_map:
|
||||
4: 1
|
||||
5: 2
|
||||
6: 3
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
with TemporaryDirectory() as directory:
|
||||
|
||||
path = (
|
||||
Path(directory)
|
||||
/ "auto.yaml"
|
||||
)
|
||||
|
||||
path.write_text(
|
||||
BROKEN_CO2_CONFIG,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
config = (
|
||||
load_auto_config_components(
|
||||
path
|
||||
)
|
||||
)
|
||||
|
||||
# ----------------------------------------------
|
||||
# CO2 должен быть отключён.
|
||||
# ----------------------------------------------
|
||||
|
||||
assert config.co2 is None
|
||||
|
||||
assert "co2" in config.errors
|
||||
|
||||
assert (
|
||||
"First threshold speed must be "
|
||||
"greater than base_speed"
|
||||
in config.errors["co2"]
|
||||
)
|
||||
|
||||
# ----------------------------------------------
|
||||
# Temperature должна остаться рабочей.
|
||||
# ----------------------------------------------
|
||||
|
||||
assert config.temperature is not None
|
||||
|
||||
assert (
|
||||
config.temperature.hysteresis
|
||||
== 0.5
|
||||
)
|
||||
|
||||
temperature_policy = (
|
||||
TemperaturePolicy(
|
||||
config.temperature
|
||||
)
|
||||
)
|
||||
|
||||
assert (
|
||||
temperature_policy.heater_required(
|
||||
temperature=20,
|
||||
target_temp=24,
|
||||
heater_on=False,
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
# ----------------------------------------------
|
||||
# Elica Assist тоже не должна пострадать.
|
||||
# ----------------------------------------------
|
||||
|
||||
assert (
|
||||
config.elica_assist
|
||||
is not None
|
||||
)
|
||||
|
||||
elica_assist = (
|
||||
ElicaAutoAssistState(
|
||||
config.elica_assist
|
||||
)
|
||||
)
|
||||
|
||||
assert elica_assist is not None
|
||||
|
||||
# Ошибка должна быть только в CO2.
|
||||
assert set(config.errors) == {
|
||||
"co2",
|
||||
}
|
||||
|
||||
print(
|
||||
"AUTO CONFIG ISOLATION TEST PASSED"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,304 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.auto.config import (
|
||||
TemperatureConfig,
|
||||
)
|
||||
from app.auto.controller import (
|
||||
AutoController,
|
||||
)
|
||||
from app.auto.temperature_policy import (
|
||||
TemperaturePolicy,
|
||||
)
|
||||
|
||||
|
||||
class FakeQingpingService:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.online = True
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
temperature=19.4,
|
||||
)
|
||||
|
||||
|
||||
class FakeTionController:
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def heater_on(self):
|
||||
self.calls.append(
|
||||
("heater_on", None)
|
||||
)
|
||||
|
||||
async def heater_off(self):
|
||||
self.calls.append(
|
||||
("heater_off", None)
|
||||
)
|
||||
|
||||
|
||||
class FakeTionService:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.online = True
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
in_temp=18,
|
||||
)
|
||||
|
||||
self.controller = (
|
||||
FakeTionController()
|
||||
)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
operation,
|
||||
):
|
||||
return await operation(
|
||||
self.controller
|
||||
)
|
||||
|
||||
|
||||
def make_resolution(
|
||||
target_temp=20.0,
|
||||
):
|
||||
|
||||
return SimpleNamespace(
|
||||
scheduled_settings=(
|
||||
SimpleNamespace(
|
||||
target_temp=target_temp,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def make_controller():
|
||||
|
||||
qingping = (
|
||||
FakeQingpingService()
|
||||
)
|
||||
|
||||
tion = FakeTionService()
|
||||
|
||||
policy = TemperaturePolicy(
|
||||
TemperatureConfig(
|
||||
hysteresis=0.5,
|
||||
)
|
||||
)
|
||||
|
||||
controller = AutoController(
|
||||
schedule_service=None,
|
||||
qingping_service=qingping,
|
||||
tion_service=tion,
|
||||
temperature_policy=policy,
|
||||
)
|
||||
|
||||
return (
|
||||
controller,
|
||||
qingping,
|
||||
tion,
|
||||
)
|
||||
|
||||
|
||||
async def test_qingping_heating():
|
||||
|
||||
controller, qingping, tion = (
|
||||
make_controller()
|
||||
)
|
||||
|
||||
resolution = make_resolution()
|
||||
|
||||
# 19.4 < 19.5
|
||||
# Heater должен включиться.
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == [
|
||||
("heater_on", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is True
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature
|
||||
== 19.4
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature_source
|
||||
== "qingping"
|
||||
)
|
||||
|
||||
tion.controller.calls.clear()
|
||||
|
||||
# ----------------------------------------------
|
||||
# 19.8
|
||||
#
|
||||
# Heater уже ON.
|
||||
# До 20 градусов ещё не дошли.
|
||||
# Продолжаем греть.
|
||||
#
|
||||
# Новую команду отправлять не нужно.
|
||||
# ----------------------------------------------
|
||||
|
||||
qingping.state.temperature = 19.8
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == []
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is True
|
||||
)
|
||||
|
||||
# ----------------------------------------------
|
||||
# 20.0
|
||||
#
|
||||
# Цель достигнута.
|
||||
# ----------------------------------------------
|
||||
|
||||
qingping.state.temperature = 20.0
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == [
|
||||
("heater_off", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
async def test_tion_temperature_fallback():
|
||||
|
||||
controller, qingping, tion = (
|
||||
make_controller()
|
||||
)
|
||||
|
||||
resolution = make_resolution()
|
||||
|
||||
# Qingping отключился.
|
||||
qingping.online = False
|
||||
|
||||
# Используем Tion.
|
||||
tion.state.in_temp = 19
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == [
|
||||
("heater_on", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._temperature
|
||||
== 19
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature_source
|
||||
== "tion"
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is True
|
||||
)
|
||||
|
||||
|
||||
async def test_no_temperature():
|
||||
|
||||
controller, qingping, tion = (
|
||||
make_controller()
|
||||
)
|
||||
|
||||
resolution = make_resolution()
|
||||
|
||||
qingping.online = False
|
||||
tion.online = False
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == [
|
||||
("heater_off", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._temperature
|
||||
is None
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature_source
|
||||
is None
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
async def test_target_temperature_missing():
|
||||
|
||||
controller, qingping, tion = (
|
||||
make_controller()
|
||||
)
|
||||
|
||||
resolution = make_resolution(
|
||||
target_temp=None
|
||||
)
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
assert tion.controller.calls == [
|
||||
("heater_off", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
await test_qingping_heating()
|
||||
|
||||
await test_tion_temperature_fallback()
|
||||
|
||||
await test_no_temperature()
|
||||
|
||||
await test_target_temperature_missing()
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print(
|
||||
"ALL AUTO HEATER PROCESS "
|
||||
"TESTS PASSED"
|
||||
)
|
||||
print("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.auto.config import (
|
||||
TemperatureConfig,
|
||||
)
|
||||
from app.auto.controller import (
|
||||
AutoController,
|
||||
)
|
||||
from app.auto.temperature_policy import (
|
||||
TemperaturePolicy,
|
||||
)
|
||||
|
||||
|
||||
class FakeQingpingService:
|
||||
|
||||
def __init__(self):
|
||||
self.online = True
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
temperature=19.5,
|
||||
)
|
||||
|
||||
|
||||
class FakeTionController:
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def heater_on(self):
|
||||
self.calls.append(
|
||||
("heater_on", None)
|
||||
)
|
||||
|
||||
async def heater_off(self):
|
||||
self.calls.append(
|
||||
("heater_off", None)
|
||||
)
|
||||
|
||||
|
||||
class FakeTionService:
|
||||
|
||||
def __init__(self):
|
||||
self.online = True
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
in_temp=19,
|
||||
)
|
||||
|
||||
self.controller = (
|
||||
FakeTionController()
|
||||
)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
operation,
|
||||
):
|
||||
return await operation(
|
||||
self.controller
|
||||
)
|
||||
|
||||
|
||||
async def test_auto_uses_auto_target_temperature():
|
||||
|
||||
qingping = FakeQingpingService()
|
||||
tion = FakeTionService()
|
||||
|
||||
policy = TemperaturePolicy(
|
||||
TemperatureConfig(
|
||||
hysteresis=0.5,
|
||||
)
|
||||
)
|
||||
|
||||
controller = AutoController(
|
||||
schedule_service=None,
|
||||
qingping_service=qingping,
|
||||
tion_service=tion,
|
||||
temperature_policy=policy,
|
||||
)
|
||||
|
||||
resolution = SimpleNamespace(
|
||||
# Последний SET хотел 23°C.
|
||||
scheduled_settings=SimpleNamespace(
|
||||
target_temp=23,
|
||||
),
|
||||
|
||||
# Но текущий AUTO явно хочет 20°C.
|
||||
auto_target_temp=20,
|
||||
)
|
||||
|
||||
await controller._process_heater(
|
||||
resolution
|
||||
)
|
||||
|
||||
# При 19.5°C и target=20°C:
|
||||
#
|
||||
# heater был OFF,
|
||||
# нижняя граница = 19.5°C.
|
||||
#
|
||||
# Поэтому heater должен остаться OFF.
|
||||
#
|
||||
# Если бы контроллер ошибочно использовал
|
||||
# SET target_temp=23, он бы включил heater.
|
||||
assert tion.controller.calls == [
|
||||
("heater_off", None)
|
||||
]
|
||||
|
||||
assert (
|
||||
controller._auto_heater
|
||||
is False
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature
|
||||
== 19.5
|
||||
)
|
||||
|
||||
assert (
|
||||
controller._temperature_source
|
||||
== "qingping"
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
await test_auto_uses_auto_target_temperature()
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print(
|
||||
"ALL AUTO HEATER TARGET "
|
||||
"TEMPERATURE TESTS PASSED"
|
||||
)
|
||||
print("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,169 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.auto.controller import AutoController
|
||||
|
||||
|
||||
class FakeQingpingService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
online: bool,
|
||||
temperature,
|
||||
):
|
||||
self.online = online
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
|
||||
class FakeTionService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
online: bool,
|
||||
in_temp,
|
||||
):
|
||||
self.online = online
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
in_temp=in_temp,
|
||||
)
|
||||
|
||||
|
||||
def make_controller(
|
||||
*,
|
||||
qingping_online: bool,
|
||||
qingping_temperature,
|
||||
tion_online: bool,
|
||||
tion_temperature,
|
||||
):
|
||||
|
||||
qingping = FakeQingpingService(
|
||||
online=qingping_online,
|
||||
temperature=qingping_temperature,
|
||||
)
|
||||
|
||||
tion = FakeTionService(
|
||||
online=tion_online,
|
||||
in_temp=tion_temperature,
|
||||
)
|
||||
|
||||
return AutoController(
|
||||
schedule_service=None,
|
||||
qingping_service=qingping,
|
||||
tion_service=tion,
|
||||
)
|
||||
|
||||
|
||||
def test_qingping_priority():
|
||||
|
||||
controller = make_controller(
|
||||
qingping_online=True,
|
||||
qingping_temperature=19.7,
|
||||
tion_online=True,
|
||||
tion_temperature=18,
|
||||
)
|
||||
|
||||
temperature, source = (
|
||||
controller._get_temperature()
|
||||
)
|
||||
|
||||
assert temperature == 19.7
|
||||
assert source == "qingping"
|
||||
|
||||
|
||||
def test_tion_fallback():
|
||||
|
||||
controller = make_controller(
|
||||
qingping_online=False,
|
||||
qingping_temperature=19.7,
|
||||
tion_online=True,
|
||||
tion_temperature=18,
|
||||
)
|
||||
|
||||
temperature, source = (
|
||||
controller._get_temperature()
|
||||
)
|
||||
|
||||
assert temperature == 18
|
||||
assert source == "tion"
|
||||
|
||||
|
||||
def test_tion_fallback_when_qingping_temperature_missing():
|
||||
|
||||
controller = make_controller(
|
||||
qingping_online=True,
|
||||
qingping_temperature=None,
|
||||
tion_online=True,
|
||||
tion_temperature=18,
|
||||
)
|
||||
|
||||
temperature, source = (
|
||||
controller._get_temperature()
|
||||
)
|
||||
|
||||
assert temperature == 18
|
||||
assert source == "tion"
|
||||
|
||||
|
||||
def test_offline_tion_is_not_used():
|
||||
|
||||
controller = make_controller(
|
||||
qingping_online=False,
|
||||
qingping_temperature=None,
|
||||
tion_online=False,
|
||||
|
||||
# Значение специально оставляем.
|
||||
# Оно имитирует старый state Tion.
|
||||
tion_temperature=18,
|
||||
)
|
||||
|
||||
temperature, source = (
|
||||
controller._get_temperature()
|
||||
)
|
||||
|
||||
assert temperature is None
|
||||
assert source is None
|
||||
|
||||
|
||||
def test_missing_tion_temperature():
|
||||
|
||||
controller = make_controller(
|
||||
qingping_online=False,
|
||||
qingping_temperature=None,
|
||||
tion_online=True,
|
||||
tion_temperature=None,
|
||||
)
|
||||
|
||||
temperature, source = (
|
||||
controller._get_temperature()
|
||||
)
|
||||
|
||||
assert temperature is None
|
||||
assert source is None
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
test_qingping_priority()
|
||||
|
||||
test_tion_fallback()
|
||||
|
||||
test_tion_fallback_when_qingping_temperature_missing()
|
||||
|
||||
test_offline_tion_is_not_used()
|
||||
|
||||
test_missing_tion_temperature()
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print(
|
||||
"ALL AUTO TEMPERATURE SOURCE "
|
||||
"TESTS PASSED"
|
||||
)
|
||||
print("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -134,7 +134,7 @@ def load_test_schedule():
|
||||
return temp_dir, config
|
||||
|
||||
|
||||
def temperature_calls(calls):
|
||||
def heater_calls(calls):
|
||||
return [
|
||||
call
|
||||
for call in calls
|
||||
@@ -142,7 +142,6 @@ def temperature_calls(calls):
|
||||
"heater_on",
|
||||
"heater_off",
|
||||
"set_heater",
|
||||
"set_target_temperature",
|
||||
}
|
||||
]
|
||||
|
||||
@@ -179,12 +178,7 @@ async def test_auto_does_not_control_heater():
|
||||
# 09:30
|
||||
#
|
||||
# Обычный SET.
|
||||
#
|
||||
# ScheduleService хранит желаемое heater=on,
|
||||
# но физически heater управлять НЕ должен.
|
||||
#
|
||||
# Физический heater будет принадлежать
|
||||
# единому температурному регулятору.
|
||||
# heater=on должен принадлежать ScheduleService.
|
||||
# --------------------------------------------------
|
||||
|
||||
await process_at(
|
||||
@@ -204,13 +198,12 @@ async def test_auto_does_not_control_heater():
|
||||
tion.controller.calls,
|
||||
)
|
||||
|
||||
calls = temperature_calls(
|
||||
calls = heater_calls(
|
||||
tion.controller.calls
|
||||
)
|
||||
|
||||
assert calls == [], (
|
||||
"ScheduleService must not control "
|
||||
"heater or target temperature during SET"
|
||||
assert calls != [], (
|
||||
"SET must control heater"
|
||||
)
|
||||
|
||||
tion.controller.calls.clear()
|
||||
@@ -270,13 +263,13 @@ async def test_auto_does_not_control_heater():
|
||||
tion.controller.calls,
|
||||
)
|
||||
|
||||
calls = temperature_calls(
|
||||
calls = heater_calls(
|
||||
tion.controller.calls
|
||||
)
|
||||
|
||||
assert calls == [], (
|
||||
"ScheduleService must not control "
|
||||
"heater or target temperature during AUTO"
|
||||
"heater during AUTO"
|
||||
)
|
||||
|
||||
tion.controller.calls.clear()
|
||||
@@ -305,13 +298,13 @@ async def test_auto_does_not_control_heater():
|
||||
tion.controller.calls,
|
||||
)
|
||||
|
||||
calls = temperature_calls(
|
||||
calls = heater_calls(
|
||||
tion.controller.calls
|
||||
)
|
||||
|
||||
assert calls == [], (
|
||||
"ScheduleService must not control "
|
||||
"heater or target temperature after AUTO"
|
||||
assert calls != [], (
|
||||
"ScheduleService must regain heater "
|
||||
"control after AUTO"
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
@@ -1,384 +0,0 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import app.api as api
|
||||
|
||||
|
||||
class FakeTionState:
|
||||
|
||||
def __init__(self):
|
||||
# Физическое состояние Tion.
|
||||
#
|
||||
# Специально ставим техническую уставку 30,
|
||||
# чтобы проверить, что API её не покажет.
|
||||
self.heater = False
|
||||
self.heating = False
|
||||
self.target_temp = 30
|
||||
self.in_temp = 14
|
||||
self.fan_speed = 2
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"heater": self.heater,
|
||||
"heating": self.heating,
|
||||
"target_temp": self.target_temp,
|
||||
"in_temp": self.in_temp,
|
||||
"fan_speed": self.fan_speed,
|
||||
}
|
||||
|
||||
|
||||
class FakeTionService:
|
||||
|
||||
def __init__(self):
|
||||
self.state = FakeTionState()
|
||||
|
||||
self.online = True
|
||||
self.running = True
|
||||
self.last_seen = None
|
||||
self.last_error = None
|
||||
|
||||
self.execute_calls = []
|
||||
|
||||
async def execute(self, operation):
|
||||
# При активном расписании температурные команды
|
||||
# НЕ должны идти напрямую сюда.
|
||||
self.execute_calls.append(operation)
|
||||
|
||||
|
||||
class FakeSchedule:
|
||||
|
||||
def __init__(self):
|
||||
self.running = True
|
||||
self.paused = False
|
||||
|
||||
self.config = SimpleNamespace(
|
||||
enabled=True,
|
||||
)
|
||||
|
||||
self.override_active = False
|
||||
|
||||
self.override_settings = SimpleNamespace(
|
||||
heater=None,
|
||||
target_temp=None,
|
||||
speed=None,
|
||||
)
|
||||
|
||||
self.apply_override_calls = []
|
||||
|
||||
def resolve(self):
|
||||
return SimpleNamespace(
|
||||
enabled=True,
|
||||
|
||||
scheduled_settings=SimpleNamespace(
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
),
|
||||
|
||||
auto_active=False,
|
||||
auto_target_temp=None,
|
||||
)
|
||||
|
||||
async def apply_override(self, settings):
|
||||
self.apply_override_calls.append(
|
||||
settings
|
||||
)
|
||||
|
||||
if settings.heater is not None:
|
||||
self.override_settings.heater = (
|
||||
settings.heater
|
||||
)
|
||||
|
||||
if settings.target_temp is not None:
|
||||
self.override_settings.target_temp = (
|
||||
settings.target_temp
|
||||
)
|
||||
|
||||
self.override_active = True
|
||||
|
||||
async def clear_override(self):
|
||||
self.override_active = False
|
||||
|
||||
self.override_settings = SimpleNamespace(
|
||||
heater=None,
|
||||
target_temp=None,
|
||||
speed=None,
|
||||
)
|
||||
|
||||
async def pause(self):
|
||||
self.paused = True
|
||||
|
||||
async def resume(self):
|
||||
self.paused = False
|
||||
|
||||
|
||||
class FakeAutoController:
|
||||
|
||||
def __init__(self, schedule):
|
||||
self.schedule = schedule
|
||||
|
||||
self.manual_heater_enabled = None
|
||||
self.manual_target_temperature = None
|
||||
|
||||
self.reconcile_calls = 0
|
||||
|
||||
def effective_temperature_config(self):
|
||||
|
||||
if self.schedule.paused:
|
||||
return SimpleNamespace(
|
||||
heater_enabled=(
|
||||
self.manual_heater_enabled
|
||||
),
|
||||
target_temp=(
|
||||
self.manual_target_temperature
|
||||
),
|
||||
)
|
||||
|
||||
heater = True
|
||||
target = 24
|
||||
|
||||
if self.schedule.override_active:
|
||||
|
||||
override = (
|
||||
self.schedule.override_settings
|
||||
)
|
||||
|
||||
if override.heater is not None:
|
||||
heater = override.heater
|
||||
|
||||
if override.target_temp is not None:
|
||||
target = override.target_temp
|
||||
|
||||
return SimpleNamespace(
|
||||
heater_enabled=heater,
|
||||
target_temp=target,
|
||||
)
|
||||
|
||||
def set_manual_heater_enabled(
|
||||
self,
|
||||
enabled,
|
||||
):
|
||||
self.manual_heater_enabled = enabled
|
||||
|
||||
def set_manual_target_temperature(
|
||||
self,
|
||||
temperature,
|
||||
):
|
||||
self.manual_target_temperature = (
|
||||
temperature
|
||||
)
|
||||
|
||||
def clear_manual_heater_control(self):
|
||||
self.manual_heater_enabled = None
|
||||
self.manual_target_temperature = None
|
||||
|
||||
async def reconcile_temperature(self):
|
||||
self.reconcile_calls += 1
|
||||
|
||||
def status(self):
|
||||
return {
|
||||
"state": "test",
|
||||
}
|
||||
|
||||
|
||||
class FakeQingping:
|
||||
|
||||
def status(self):
|
||||
return {
|
||||
"online": True,
|
||||
"temperature": 25.5,
|
||||
}
|
||||
|
||||
|
||||
def prepare():
|
||||
|
||||
schedule = FakeSchedule()
|
||||
auto = FakeAutoController(schedule)
|
||||
tion = FakeTionService()
|
||||
|
||||
api.schedule_service = schedule
|
||||
api.auto_controller = auto
|
||||
api.service = tion
|
||||
|
||||
api.qingping_service = FakeQingping()
|
||||
|
||||
# Чтобы тест не зависел от Elica.
|
||||
api.get_elica_status = lambda: {
|
||||
"online": True,
|
||||
}
|
||||
|
||||
# Нам здесь не нужна внутренняя структура
|
||||
# schedule-status.
|
||||
api.get_schedule_status = lambda: {
|
||||
"available": True,
|
||||
"paused": schedule.paused,
|
||||
}
|
||||
|
||||
return schedule, auto, tion
|
||||
|
||||
|
||||
def test_status_uses_logical_temperature():
|
||||
|
||||
schedule, auto, tion = prepare()
|
||||
|
||||
status = api.get_status()
|
||||
|
||||
# Физически Tion:
|
||||
assert tion.state.target_temp == 30
|
||||
assert tion.state.heater is False
|
||||
|
||||
# Но пользователь должен видеть:
|
||||
assert status["tion"]["target_temp"] == 24
|
||||
assert status["tion"]["heater"] is True
|
||||
|
||||
# heating остаётся физическим.
|
||||
assert status["tion"]["heating"] is False
|
||||
|
||||
|
||||
async def test_temperature_creates_override():
|
||||
|
||||
schedule, auto, tion = prepare()
|
||||
|
||||
await api.set_temperature(26)
|
||||
|
||||
assert schedule.override_active is True
|
||||
|
||||
assert (
|
||||
schedule.override_settings.target_temp
|
||||
== 26
|
||||
)
|
||||
|
||||
# Изменение только температуры
|
||||
# не должно само задавать heater.
|
||||
assert (
|
||||
schedule.override_settings.heater
|
||||
is None
|
||||
)
|
||||
|
||||
# Tion напрямую не вызывается.
|
||||
assert tion.execute_calls == []
|
||||
|
||||
# Новый температурный контур
|
||||
# применяется сразу.
|
||||
assert auto.reconcile_calls == 1
|
||||
|
||||
|
||||
async def test_heater_creates_override():
|
||||
|
||||
schedule, auto, tion = prepare()
|
||||
|
||||
await api.set_heater("off")
|
||||
|
||||
assert schedule.override_active is True
|
||||
|
||||
assert (
|
||||
schedule.override_settings.heater
|
||||
is False
|
||||
)
|
||||
|
||||
assert tion.execute_calls == []
|
||||
|
||||
assert auto.reconcile_calls == 1
|
||||
|
||||
|
||||
async def test_pause_uses_logical_state():
|
||||
|
||||
schedule, auto, tion = prepare()
|
||||
|
||||
# Физический heater выключен.
|
||||
assert tion.state.heater is False
|
||||
|
||||
# Но логически отопление разрешено:
|
||||
config = (
|
||||
auto.effective_temperature_config()
|
||||
)
|
||||
|
||||
assert config.heater_enabled is True
|
||||
assert config.target_temp == 24
|
||||
|
||||
await api.pause_schedule()
|
||||
|
||||
assert schedule.paused is True
|
||||
|
||||
# PAUSE должен запомнить ЛОГИЧЕСКОЕ
|
||||
# состояние, а не физический heater=False.
|
||||
assert (
|
||||
auto.manual_heater_enabled
|
||||
is True
|
||||
)
|
||||
|
||||
assert (
|
||||
auto.manual_target_temperature
|
||||
== 24
|
||||
)
|
||||
|
||||
assert auto.reconcile_calls == 1
|
||||
|
||||
|
||||
async def test_resume_clears_manual_state():
|
||||
|
||||
schedule, auto, tion = prepare()
|
||||
|
||||
schedule.paused = True
|
||||
|
||||
auto.manual_heater_enabled = True
|
||||
auto.manual_target_temperature = 25
|
||||
|
||||
await api.resume_schedule()
|
||||
|
||||
assert schedule.paused is False
|
||||
|
||||
assert (
|
||||
auto.manual_heater_enabled
|
||||
is None
|
||||
)
|
||||
|
||||
assert (
|
||||
auto.manual_target_temperature
|
||||
is None
|
||||
)
|
||||
|
||||
assert auto.reconcile_calls == 1
|
||||
|
||||
|
||||
def test_temperature_routes():
|
||||
|
||||
paths = [
|
||||
route.path
|
||||
for route in api.app.routes
|
||||
]
|
||||
|
||||
# increase мы решили удалить полностью.
|
||||
assert (
|
||||
"/api/tion/temperature/increase"
|
||||
not in paths
|
||||
)
|
||||
|
||||
# Основной endpoint должен существовать
|
||||
# ровно один раз.
|
||||
assert (
|
||||
paths.count(
|
||||
"/api/tion/temperature/{temperature}"
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
test_status_uses_logical_temperature()
|
||||
|
||||
await test_temperature_creates_override()
|
||||
await test_heater_creates_override()
|
||||
|
||||
await test_pause_uses_logical_state()
|
||||
await test_resume_clears_manual_state()
|
||||
|
||||
test_temperature_routes()
|
||||
|
||||
print(
|
||||
"ALL TEMPERATURE API TESTS PASSED"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,395 +0,0 @@
|
||||
import asyncio
|
||||
import inspect
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.auto.controller import AutoController
|
||||
from app.my_dataclasses import MAX_TARGET_TEMP
|
||||
|
||||
|
||||
class FakeTionController:
|
||||
|
||||
def __init__(self):
|
||||
self.heater = None
|
||||
self.target_temp = None
|
||||
self.speed = None
|
||||
|
||||
def heater_on(self):
|
||||
self.heater = True
|
||||
|
||||
def heater_off(self):
|
||||
self.heater = False
|
||||
|
||||
def set_target_temperature(
|
||||
self,
|
||||
temperature,
|
||||
):
|
||||
self.target_temp = temperature
|
||||
|
||||
def set_speed(self, speed):
|
||||
self.speed = speed
|
||||
|
||||
|
||||
class FakeTion:
|
||||
|
||||
def __init__(self):
|
||||
self.online = True
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
in_temp=14,
|
||||
)
|
||||
|
||||
self.controller = (
|
||||
FakeTionController()
|
||||
)
|
||||
|
||||
async def execute(self, operation):
|
||||
result = operation(
|
||||
self.controller
|
||||
)
|
||||
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
|
||||
|
||||
class FakeQingping:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
online=True,
|
||||
temperature=25,
|
||||
):
|
||||
self.online = online
|
||||
|
||||
self.state = SimpleNamespace(
|
||||
temperature=temperature,
|
||||
co2=None,
|
||||
)
|
||||
|
||||
|
||||
class FakeTemperaturePolicy:
|
||||
|
||||
def heater_required(
|
||||
self,
|
||||
temperature,
|
||||
target_temp,
|
||||
heater_on,
|
||||
):
|
||||
return temperature < target_temp
|
||||
|
||||
|
||||
class FakeSchedule:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
auto=False,
|
||||
auto_target=None,
|
||||
paused=False,
|
||||
override=None,
|
||||
):
|
||||
self.paused = paused
|
||||
|
||||
self.override_active = (
|
||||
override is not None
|
||||
)
|
||||
|
||||
self.override_settings = (
|
||||
override
|
||||
or SimpleNamespace(
|
||||
heater=None,
|
||||
target_temp=None,
|
||||
)
|
||||
)
|
||||
|
||||
self.resolution = SimpleNamespace(
|
||||
enabled=True,
|
||||
|
||||
scheduled_settings=(
|
||||
SimpleNamespace(
|
||||
heater=heater,
|
||||
target_temp=target_temp,
|
||||
)
|
||||
),
|
||||
|
||||
auto_active=auto,
|
||||
auto_target_temp=auto_target,
|
||||
|
||||
auto_fallback_speed=2,
|
||||
)
|
||||
|
||||
def resolve(self, now=None):
|
||||
return self.resolution
|
||||
|
||||
|
||||
def make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
):
|
||||
|
||||
tion = FakeTion()
|
||||
|
||||
controller = AutoController(
|
||||
schedule_service=schedule,
|
||||
qingping_service=qingping,
|
||||
tion_service=tion,
|
||||
temperature_policy=(
|
||||
FakeTemperaturePolicy()
|
||||
),
|
||||
)
|
||||
|
||||
return controller, tion
|
||||
|
||||
|
||||
async def test_set_online():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=25.9,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == (
|
||||
MAX_TARGET_TEMP
|
||||
)
|
||||
|
||||
assert tion.controller.heater is False
|
||||
|
||||
|
||||
async def test_set_offline():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=False,
|
||||
temperature=None,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == 24
|
||||
assert tion.controller.heater is True
|
||||
|
||||
|
||||
async def test_auto_online():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
auto=True,
|
||||
auto_target=22,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=21,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == (
|
||||
MAX_TARGET_TEMP
|
||||
)
|
||||
|
||||
assert tion.controller.heater is True
|
||||
|
||||
|
||||
async def test_auto_offline():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=True,
|
||||
target_temp=24,
|
||||
auto=True,
|
||||
auto_target=22,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=False,
|
||||
temperature=None,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == 22
|
||||
assert tion.controller.heater is True
|
||||
|
||||
|
||||
async def test_override_temperature_only():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=False,
|
||||
target_temp=24,
|
||||
|
||||
override=SimpleNamespace(
|
||||
heater=None,
|
||||
target_temp=26,
|
||||
),
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=20,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
config = (
|
||||
controller
|
||||
._get_effective_temperature_config(
|
||||
schedule.resolve()
|
||||
)
|
||||
)
|
||||
|
||||
assert config.heater_enabled is False
|
||||
assert config.target_temp == 26
|
||||
|
||||
await controller._process()
|
||||
|
||||
# Изменение только температуры
|
||||
# НЕ включает heater.
|
||||
assert tion.controller.heater is False
|
||||
|
||||
|
||||
async def test_override_heater_only():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=False,
|
||||
target_temp=24,
|
||||
|
||||
override=SimpleNamespace(
|
||||
heater=True,
|
||||
target_temp=None,
|
||||
),
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=23,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == (
|
||||
MAX_TARGET_TEMP
|
||||
)
|
||||
|
||||
assert tion.controller.heater is True
|
||||
|
||||
|
||||
async def test_pause():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
paused=True,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=25,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
controller.set_manual_heater_enabled(
|
||||
True
|
||||
)
|
||||
|
||||
controller.set_manual_target_temperature(
|
||||
24
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.target_temp == (
|
||||
MAX_TARGET_TEMP
|
||||
)
|
||||
|
||||
assert tion.controller.heater is False
|
||||
|
||||
|
||||
async def test_heater_false_priority():
|
||||
|
||||
schedule = FakeSchedule(
|
||||
heater=False,
|
||||
target_temp=30,
|
||||
)
|
||||
|
||||
qingping = FakeQingping(
|
||||
online=True,
|
||||
temperature=10,
|
||||
)
|
||||
|
||||
controller, tion = make_controller(
|
||||
schedule,
|
||||
qingping,
|
||||
)
|
||||
|
||||
await controller._process()
|
||||
|
||||
assert tion.controller.heater is False
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
await test_set_online()
|
||||
await test_set_offline()
|
||||
|
||||
await test_auto_online()
|
||||
await test_auto_offline()
|
||||
|
||||
await test_override_temperature_only()
|
||||
await test_override_heater_only()
|
||||
|
||||
await test_pause()
|
||||
|
||||
await test_heater_false_priority()
|
||||
|
||||
print(
|
||||
"ALL UNIFIED TEMPERATURE "
|
||||
"TESTS PASSED"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 122 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 MiB |
@@ -1,109 +0,0 @@
|
||||
/* Elica-specific layout only.
|
||||
IMPORTANT: body/.widget backgrounds are intentionally NOT overridden here.
|
||||
Both Tion and Elica receive the exact same material from aeroglass-widget.css. */
|
||||
|
||||
.hood-icon svg { width: 1.75rem; height: 1.75rem; filter: drop-shadow(0 0 5px rgba(20,123,213,.18)); }
|
||||
|
||||
.exhaust-widget-speed { min-height: 12.2rem; }
|
||||
.exhaust-widget-hero { grid-template-columns: 3.1rem 1fr 3.1rem; }
|
||||
.hero-spacer { width: 3.1rem; height: 3.1rem; }
|
||||
.exhaust-widget-segments { grid-template-columns: repeat(4, 1fr); }
|
||||
.exhaust-widget-labels { grid-template-columns: repeat(4, 1fr); }
|
||||
|
||||
.external-fan-card { position: relative; overflow: hidden; }
|
||||
.external-fan-card::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: 0;
|
||||
width: 10rem;
|
||||
height: 10rem;
|
||||
right: -4.4rem;
|
||||
bottom: -5.4rem;
|
||||
border-radius: 50%;
|
||||
background: var(--blue-halo);
|
||||
opacity: .16;
|
||||
filter: blur(34px);
|
||||
pointer-events: none;
|
||||
}
|
||||
.external-fan-card > * { position: relative; z-index: 1; }
|
||||
.external-fan-card[data-on="true"] .fan-glyph { animation: exhaust-widget-spin 1.35s linear infinite; }
|
||||
@keyframes exhaust-widget-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.exhaust-actions { display: grid; gap: .55rem; }
|
||||
.exhaust-action-row { display: flex; align-items: center; justify-content: space-between; gap: .65rem; }
|
||||
.exhaust-action-copy { min-width: 0; display: flex; align-items: center; gap: .55rem; }
|
||||
.exhaust-action-copy > span { min-width: 0; display: grid; gap: .08rem; }
|
||||
.exhaust-action-copy b { font-size: .78rem; }
|
||||
.exhaust-action-copy small { color: var(--widget-muted); font-size: .58rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.exhaust-action-copy .section-icon, .bulb-icon { width: 1.55rem; height: 1.55rem; flex: 0 0 auto; }
|
||||
.bulb-icon { color: #d59d17; filter: drop-shadow(0 0 5px rgba(213,157,23,.15)); }
|
||||
.exhaust-divider { display: block; width: 100%; height: 1px; background: linear-gradient(90deg, transparent, var(--tile-edge-soft) 12%, var(--tile-edge-soft) 88%, transparent); }
|
||||
|
||||
.glass-switch.compact { width: 5.1rem; min-height: 2.45rem; font-size: .78rem; }
|
||||
.glass-action {
|
||||
min-height: 2.45rem;
|
||||
padding: .5rem .68rem;
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid var(--tile-edge);
|
||||
border-radius: .76rem;
|
||||
color: var(--widget-ink);
|
||||
background: radial-gradient(circle at 20% -30%, rgba(255,255,255,.46), transparent 48%), linear-gradient(145deg, var(--tile-strong), var(--tile));
|
||||
box-shadow: var(--tile-shadow);
|
||||
cursor: pointer;
|
||||
font-size: .61rem;
|
||||
font-weight: 760;
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
transition: transform .15s ease, filter .15s ease;
|
||||
}
|
||||
.glass-action:hover { transform: translateY(-1px); filter: brightness(1.05); }
|
||||
.glass-action:active { transform: scale(.98); }
|
||||
:root[data-theme="dark"] .glass-action { border-color: rgba(193,228,245,.22); background: radial-gradient(circle at 20% -30%, rgba(208,243,255,.09), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.21), rgba(20,44,59,.26)); }
|
||||
|
||||
.exhaust-widget .open-panel svg { width: 1.45rem; height: 1.45rem; }
|
||||
|
||||
:root[data-widget-layout="horizontal"] .exhaust-widget {
|
||||
width: min(100%, 64rem);
|
||||
grid-template-columns: minmax(0, 1.45fr) minmax(14rem, .92fr) minmax(15rem, .86fr);
|
||||
grid-template-areas:
|
||||
"header header header"
|
||||
"speed switches actions"
|
||||
"open open open";
|
||||
}
|
||||
:root[data-widget-layout="horizontal"] .exhaust-widget-header { grid-area: header; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-widget-speed { grid-area: speed; min-height: 8.8rem; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-switch-grid {
|
||||
grid-area: switches;
|
||||
min-width: 0;
|
||||
display: grid !important;
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: repeat(2, minmax(0, 1fr));
|
||||
gap: .48rem;
|
||||
align-content: stretch;
|
||||
}
|
||||
:root[data-widget-layout="horizontal"] .exhaust-switch-grid > .switch-card {
|
||||
grid-area: auto !important;
|
||||
min-width: 0;
|
||||
min-height: 4.15rem;
|
||||
padding: .55rem .62rem;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: .45rem;
|
||||
}
|
||||
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title,
|
||||
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title > span { min-width: 0; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .glass-switch { min-height: 2.45rem; width: 4.7rem; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-actions { grid-area: actions; align-content: center; padding: .62rem .68rem; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-action-copy small { max-width: 8.5rem; }
|
||||
:root[data-widget-layout="horizontal"] .open-panel { grid-area: open; }
|
||||
:root[data-widget-layout="horizontal"] .exhaust-widget-hero { margin: .45rem 0 .35rem; }
|
||||
|
||||
@media (max-width: 799px) {
|
||||
:root[data-widget-layout="vertical"] .exhaust-widget { width: min(100%, 31.5rem); }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.exhaust-action-copy small { max-width: 10rem; }
|
||||
.glass-action { padding-inline: .55rem; }
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
/* Elica uses the same aeroglass material system as the Tion panel.
|
||||
This file only defines the Elica-specific layout and controls. */
|
||||
|
||||
.exhaust-panel {
|
||||
width: min(100%, 78rem);
|
||||
min-height: auto;
|
||||
display: grid;
|
||||
gap: .75rem;
|
||||
}
|
||||
|
||||
.exhaust-header { padding-bottom: .25rem; }
|
||||
.exhaust-identity { min-width: 0; }
|
||||
.exhaust-identity .identity-copy { min-width: 0; }
|
||||
.exhaust-identity .title-row { display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; }
|
||||
.exhaust-identity .identity-copy > small { display: block; margin-top: .28rem; color: var(--panel-muted); font-size: .7rem; }
|
||||
|
||||
.hood-mark {
|
||||
width: 3.25rem;
|
||||
height: 3.25rem;
|
||||
padding: .68rem;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 auto;
|
||||
border-radius: 1rem;
|
||||
color: #147bd5;
|
||||
}
|
||||
.hood-mark svg { width: 100%; height: 100%; filter: drop-shadow(0 0 6px rgba(20,123,213,.2)); }
|
||||
|
||||
.exhaust-badge { min-width: 19rem; }
|
||||
.exhaust-badge svg { width: 2.25rem; height: 2.25rem; }
|
||||
.panel-link { text-decoration: none; }
|
||||
|
||||
.exhaust-primary {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(19rem, 1.42fr) repeat(2, minmax(13rem, .82fr));
|
||||
grid-template-areas:
|
||||
"speed power fan"
|
||||
"speed action action";
|
||||
gap: .75rem;
|
||||
}
|
||||
|
||||
.exhaust-speed-card { grid-area: speed; min-height: 20rem; }
|
||||
.exhaust-switch-card { min-height: 9.6rem; }
|
||||
.power-card { grid-area: power; }
|
||||
.exhaust-fan-card { grid-area: fan; }
|
||||
.exhaust-action-card { grid-area: action; min-height: 9.6rem; justify-content: center; gap: .75rem; }
|
||||
|
||||
.exhaust-hero-control {
|
||||
grid-template-columns: 3rem 1fr 3rem;
|
||||
margin: auto 0 .9rem;
|
||||
}
|
||||
.hero-spacer { width: 3rem; height: 3rem; }
|
||||
.exhaust-speed-segments { grid-template-columns: repeat(4, 1fr); gap: .2rem; }
|
||||
.exhaust-speed-labels { grid-template-columns: repeat(4, 1fr); }
|
||||
.exhaust-speed-segments button.active { transform: translateY(-1px); }
|
||||
|
||||
.exhaust-fan-card::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: 0;
|
||||
width: 13rem;
|
||||
height: 13rem;
|
||||
right: -5rem;
|
||||
bottom: -7rem;
|
||||
border-radius: 50%;
|
||||
pointer-events: none;
|
||||
filter: blur(44px);
|
||||
background: var(--blue-halo);
|
||||
opacity: .17;
|
||||
}
|
||||
.exhaust-fan-card > * { position: relative; z-index: 1; }
|
||||
.exhaust-fan-card[data-on="true"] .fan-glyph { animation: exhaust-fan-spin 1.35s linear infinite; }
|
||||
@keyframes exhaust-fan-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.action-row { display: flex; align-items: center; justify-content: space-between; gap: .9rem; }
|
||||
.action-copy { display: flex; align-items: center; gap: .7rem; min-width: 0; }
|
||||
.action-copy h2 { margin: 0; font-size: 1rem; line-height: 1.2; }
|
||||
.action-copy p { margin: .18rem 0 0; color: var(--panel-muted); font-size: .68rem; line-height: 1.35; }
|
||||
.bulb-icon { width: 2.1rem; height: 2.1rem; padding: .16rem; flex: 0 0 auto; color: #d59d17; filter: drop-shadow(0 0 6px rgba(213,157,23,.18)); }
|
||||
.glass-divider { height: 1px; background: linear-gradient(90deg, transparent, var(--tile-line-soft) 12%, var(--tile-line-soft) 88%, transparent); }
|
||||
|
||||
.compact-switch {
|
||||
width: 6.2rem;
|
||||
min-height: 3.25rem;
|
||||
flex: 0 0 auto;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.aero-button {
|
||||
min-height: 3rem;
|
||||
padding: .65rem .95rem;
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid var(--tile-line);
|
||||
border-radius: .9rem;
|
||||
color: var(--panel-ink);
|
||||
background:
|
||||
radial-gradient(circle at 20% -25%, rgba(255,255,255,.48), transparent 48%),
|
||||
linear-gradient(145deg, var(--tile-strong), var(--tile));
|
||||
box-shadow: var(--tile-shadow);
|
||||
backdrop-filter: blur(14px) saturate(122%);
|
||||
-webkit-backdrop-filter: blur(14px) saturate(122%);
|
||||
cursor: pointer;
|
||||
font-size: .72rem;
|
||||
font-weight: 760;
|
||||
transition: transform .15s ease, filter .15s ease, box-shadow .15s ease;
|
||||
}
|
||||
.aero-button:hover { transform: translateY(-1px); filter: brightness(1.05); }
|
||||
.aero-button:active { transform: scale(.98); }
|
||||
:root[data-theme="dark"] .aero-button { border-color: rgba(193,228,245,.24); background: radial-gradient(circle at 20% -25%, rgba(208,243,255,.1), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.22), rgba(20,44,59,.27)); }
|
||||
|
||||
.exhaust-status-section { margin-top: 0; }
|
||||
.status-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .55rem; }
|
||||
.status-item { min-height: 5rem; padding: .75rem .85rem; border-radius: .85rem; display: grid; align-content: center; gap: .25rem; }
|
||||
.status-item span { color: var(--panel-muted); font-size: .58rem; text-transform: uppercase; letter-spacing: .07em; font-weight: 800; }
|
||||
.status-item strong { font-size: .78rem; }
|
||||
.status-item strong.good { color: #0a8a50; }
|
||||
.status-item strong.warn { color: #bc6b16; }
|
||||
.status-item strong.bad { color: #bd4050; }
|
||||
:root[data-theme="dark"] .status-item strong.good { color: #7de5ad; }
|
||||
:root[data-theme="dark"] .status-item strong.warn { color: #ffc078; }
|
||||
:root[data-theme="dark"] .status-item strong.bad { color: #ff98a2; }
|
||||
.diagnostic-note { margin: .6rem .25rem .05rem; color: var(--panel-muted); font-size: .63rem; }
|
||||
|
||||
.pending { opacity: .72; }
|
||||
button:disabled { cursor: wait; }
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.exhaust-badge { display: none; }
|
||||
.exhaust-primary {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-areas:
|
||||
"speed speed"
|
||||
"power fan"
|
||||
"action action";
|
||||
}
|
||||
.exhaust-speed-card { min-height: 16rem; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.exhaust-panel { gap: .6rem; }
|
||||
.exhaust-header { align-items: flex-start; }
|
||||
.exhaust-identity .identity-copy > small { display: none; }
|
||||
.hood-mark { width: 2.8rem; height: 2.8rem; border-radius: .9rem; }
|
||||
.exhaust-primary {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-areas: "speed" "power" "fan" "action";
|
||||
}
|
||||
.exhaust-speed-card { min-height: 14.5rem; }
|
||||
.exhaust-switch-card { min-height: 8.2rem; }
|
||||
.status-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.action-row { gap: .55rem; }
|
||||
.action-copy p { font-size: .62rem; }
|
||||
}
|
||||
|
||||
@media (max-width: 430px) {
|
||||
.header-tools { gap: .35rem; }
|
||||
.panel-link { display: none; }
|
||||
.exhaust-speed-card, .exhaust-switch-card, .exhaust-action-card { padding: .8rem; }
|
||||
.compact-switch { width: 5.35rem; min-height: 2.8rem; }
|
||||
.aero-button { padding-inline: .7rem; }
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Elica — виджет</title>
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/elica-widget.css?v=20260927-1">
|
||||
</head>
|
||||
<body>
|
||||
<div class="ambient" aria-hidden="true"></div>
|
||||
<main class="widget exhaust-widget" aria-live="polite">
|
||||
<header class="widget-header exhaust-widget-header">
|
||||
<div class="identity">
|
||||
<span class="brand-icon hood-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</span>
|
||||
<span class="identity-copy">
|
||||
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
|
||||
<small id="header-detail">Вытяжная вентиляция</small>
|
||||
</span>
|
||||
</div>
|
||||
<button id="theme-button" class="theme-button" type="button" title="Сменить тему">
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section class="widget-tile control-card speed-card exhaust-widget-speed" aria-labelledby="speed-title">
|
||||
<div class="card-title">
|
||||
<svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
|
||||
<span><h2 id="speed-title">Скорость вытяжки</h2><p id="speed-note">Фактическая ступень Elica</p></span>
|
||||
</div>
|
||||
<div class="hero-control exhaust-widget-hero">
|
||||
<span class="hero-spacer" aria-hidden="true"></span>
|
||||
<strong id="speed" class="hero-value value skeleton">0</strong>
|
||||
<span class="hero-spacer" aria-hidden="true"></span>
|
||||
</div>
|
||||
<div class="speed-segments exhaust-widget-segments" role="group" aria-label="Выбор скорости">
|
||||
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
|
||||
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
|
||||
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
|
||||
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
|
||||
</div>
|
||||
<div class="scale-labels exhaust-widget-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
|
||||
</section>
|
||||
|
||||
<section class="switch-grid exhaust-switch-grid" aria-label="Управление вентиляцией">
|
||||
<article class="widget-tile switch-card power-card">
|
||||
<div class="switch-title">
|
||||
<svg class="ui-icon switch-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
|
||||
<span><h2>Вытяжка</h2><small id="power-detail">Выключена</small></span>
|
||||
</div>
|
||||
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
|
||||
</article>
|
||||
<article id="external-fan-card" class="widget-tile switch-card external-fan-card" data-on="false">
|
||||
<div class="switch-title">
|
||||
<svg class="ui-icon switch-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
|
||||
<span><h2>Внешний</h2><small id="external-fan-detail">OUT5 · NC</small></span>
|
||||
</div>
|
||||
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="widget-tile info-card exhaust-actions" aria-label="Таймер и свет">
|
||||
<div class="exhaust-action-row">
|
||||
<span class="exhaust-action-copy"><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><span><b>Таймер</b><small id="timer-detail">Выключен</small></span></span>
|
||||
<button id="timer-toggle" class="glass-switch compact green" type="button" aria-pressed="false">OFF</button>
|
||||
</div>
|
||||
<i class="exhaust-divider" aria-hidden="true"></i>
|
||||
<div class="exhaust-action-row">
|
||||
<span class="exhaust-action-copy"><svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg><span><b>Подсветка</b><small>Импульсное управление</small></span></span>
|
||||
<button id="light-toggle" class="glass-action" type="button">Переключить</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button id="open-panel" class="open-panel" type="button">
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
<span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b>
|
||||
</button>
|
||||
</main>
|
||||
<script type="module" src="/ui/static/js/elica-widget.js?v=20260927-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Elica — управление вытяжкой</title>
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/elica.css?v=20260927-1">
|
||||
</head>
|
||||
<body>
|
||||
<div class="ambient" aria-hidden="true"></div>
|
||||
|
||||
<main class="climate-panel exhaust-panel" aria-live="polite">
|
||||
<header class="panel-header exhaust-header">
|
||||
<div class="identity exhaust-identity">
|
||||
<span class="hood-mark glass-tile" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none">
|
||||
<path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="identity-copy">
|
||||
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
|
||||
<small>Кухонная вытяжка и внешний вытяжной вентилятор</small>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="header-tools">
|
||||
<div class="ventilation-badge glass-tile exhaust-badge">
|
||||
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
|
||||
<span><strong>Вытяжная вентиляция</strong><small>Управление Elica и внешним вентилятором</small></span>
|
||||
</div>
|
||||
<a class="icon-button panel-link" href="/ui/tion" title="Открыть Tion 4S" aria-label="Открыть Tion 4S">
|
||||
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#wind"></use></svg>
|
||||
</a>
|
||||
<button id="refresh-button" class="icon-button" type="button" title="Обновить данные">
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 11a8 8 0 1 0-2.34 5.66M20 5v6h-6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</button>
|
||||
<button id="theme-button" class="icon-button" type="button" title="Сменить тему">
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="primary-controls exhaust-primary" aria-label="Основное управление">
|
||||
<article class="control-card glass-tile speed-card exhaust-speed-card">
|
||||
<div class="card-title">
|
||||
<svg class="ui-icon feature-icon fan-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
|
||||
<span><h2>Скорость вытяжки</h2><p id="speed-caption">Скорость определяется по индикаторам Elica</p></span>
|
||||
</div>
|
||||
<div class="hero-control exhaust-hero-control">
|
||||
<span class="hero-spacer" aria-hidden="true"></span>
|
||||
<strong id="speed-value" class="hero-value">—</strong>
|
||||
<span class="hero-spacer" aria-hidden="true"></span>
|
||||
</div>
|
||||
<div class="speed-segments exhaust-speed-segments" role="group" aria-label="Выбор скорости">
|
||||
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
|
||||
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
|
||||
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
|
||||
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
|
||||
</div>
|
||||
<div class="speed-labels exhaust-speed-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
|
||||
</article>
|
||||
|
||||
<article class="switch-card glass-tile power-card exhaust-switch-card">
|
||||
<div class="card-title compact">
|
||||
<svg class="ui-icon feature-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
|
||||
<span><h2>Питание</h2><p id="power-caption">Ожидаем состояние панели</p></span>
|
||||
</div>
|
||||
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
|
||||
</article>
|
||||
|
||||
<article id="external-fan-card" class="switch-card glass-tile exhaust-fan-card exhaust-switch-card" data-on="false">
|
||||
<div class="card-title compact">
|
||||
<svg class="ui-icon feature-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
|
||||
<span><h2>Внешний вентилятор</h2><p id="external-fan-caption">Ожидаем состояние OUT5</p></span>
|
||||
</div>
|
||||
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
|
||||
</article>
|
||||
|
||||
<article class="control-card glass-tile action-card exhaust-action-card">
|
||||
<div class="action-row">
|
||||
<div class="action-copy">
|
||||
<svg class="ui-icon feature-icon orange" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg>
|
||||
<div><h2>Таймер</h2><p id="timer-caption">По миганию индикатора скорости</p></div>
|
||||
</div>
|
||||
<button id="timer-toggle" class="glass-switch orange compact-switch" type="button" aria-pressed="false">OFF</button>
|
||||
</div>
|
||||
<div class="glass-divider"></div>
|
||||
<div class="action-row">
|
||||
<div class="action-copy">
|
||||
<svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
|
||||
<div><h2>Подсветка</h2><p>Без обратной связи по состоянию</p></div>
|
||||
</div>
|
||||
<button id="light-toggle" class="aero-button" type="button">Переключить</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="content-section glass-section exhaust-status-section" aria-labelledby="status-title">
|
||||
<div class="section-title">
|
||||
<div><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#settings"></use></svg><h2 id="status-title">Связь с контроллером</h2></div>
|
||||
<span id="updated-at" class="updated">—</span>
|
||||
</div>
|
||||
<div class="status-grid">
|
||||
<article class="status-item glass-tile"><span>MQTT</span><strong id="mqtt-status">—</strong></article>
|
||||
<article class="status-item glass-tile"><span>ESP32</span><strong id="device-status">—</strong></article>
|
||||
<article class="status-item glass-tile"><span>Панель Elica</span><strong id="feedback-status">—</strong></article>
|
||||
<article class="status-item glass-tile"><span>OUT5 физически</span><strong id="relay5-status">—</strong></article>
|
||||
</div>
|
||||
<p id="diagnostic-note" class="diagnostic-note">Получаем данные…</p>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script type="module" src="/ui/static/js/elica.js?v=20260927-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
+3
-5
@@ -179,9 +179,7 @@ export const api = {
|
||||
export function configureTheme(button) {
|
||||
const allowed = ["auto", "light", "dark"];
|
||||
const explicit = query.get("theme");
|
||||
let mode = allowed.includes(explicit)
|
||||
? explicit
|
||||
: (localStorage.getItem("climate-theme") || localStorage.getItem("tion-theme") || "auto");
|
||||
let mode = allowed.includes(explicit) ? explicit : (localStorage.getItem("tion-theme") || "auto");
|
||||
|
||||
const apply = () => {
|
||||
const dark = mode === "dark" || (mode === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
@@ -198,7 +196,7 @@ export function configureTheme(button) {
|
||||
|
||||
if (button) button.addEventListener("click", () => {
|
||||
mode = allowed[(allowed.indexOf(mode) + 1) % allowed.length];
|
||||
localStorage.setItem("climate-theme", mode);
|
||||
localStorage.setItem("tion-theme", mode);
|
||||
apply();
|
||||
});
|
||||
|
||||
@@ -297,7 +295,7 @@ export function showToast(message, error = false) {
|
||||
}
|
||||
|
||||
export function panelUrl(themeMode = "auto", hash = "") {
|
||||
const url = new URL("/ui/tion", window.location.origin);
|
||||
const url = new URL("/ui/panel", window.location.origin);
|
||||
url.searchParams.set("theme", themeMode);
|
||||
if (isDemo) url.searchParams.set("demo", "1");
|
||||
url.hash = hash;
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
import { configureTheme, showToast } from "./api.js";
|
||||
|
||||
const requestedLayout = new URLSearchParams(window.location.search).get("layout");
|
||||
const layoutMode = ["horizontal", "vertical"].includes(requestedLayout) ? requestedLayout : null;
|
||||
const wideLayout = window.matchMedia("(min-width: 800px)");
|
||||
|
||||
function applyLayout() {
|
||||
document.documentElement.dataset.widgetLayout = layoutMode || (wideLayout.matches ? "horizontal" : "vertical");
|
||||
}
|
||||
|
||||
applyLayout();
|
||||
wideLayout.addEventListener("change", () => !layoutMode && applyLayout());
|
||||
|
||||
const $ = selector => document.querySelector(selector);
|
||||
const $$ = selector => [...document.querySelectorAll(selector)];
|
||||
const themeMode = configureTheme($("#theme-button"));
|
||||
|
||||
let state = null;
|
||||
let busy = false;
|
||||
let polling = false;
|
||||
|
||||
function setPill(label, tone) {
|
||||
const element = $("#connection");
|
||||
element.textContent = label;
|
||||
element.className = `pill ${tone}`;
|
||||
}
|
||||
|
||||
function drawToggle(selector, active, label = null) {
|
||||
const button = $(selector);
|
||||
const enabled = Boolean(active);
|
||||
button.setAttribute("aria-pressed", String(enabled));
|
||||
button.textContent = label || (enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
function ready(status) {
|
||||
return Boolean(status?.running && status?.mqtt_connected && status?.device_online);
|
||||
}
|
||||
|
||||
function feedbackReady(status) {
|
||||
return ready(status) && Boolean(status?.feedback_ready);
|
||||
}
|
||||
|
||||
function drawSpeed(value) {
|
||||
const speed = Math.max(0, Math.min(4, Number(value) || 0));
|
||||
const output = $("#speed");
|
||||
output.textContent = speed || "—";
|
||||
output.classList.remove("skeleton");
|
||||
$$('[data-speed]').forEach(button => {
|
||||
const segment = Number(button.dataset.speed);
|
||||
button.classList.toggle("active", speed > 0 && segment <= speed);
|
||||
button.setAttribute("aria-pressed", String(segment === speed));
|
||||
});
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
state = status;
|
||||
const elica = status?.elica || {};
|
||||
const external = status?.external_fan || {};
|
||||
const controllerOnline = ready(status);
|
||||
const panelOnline = feedbackReady(status);
|
||||
|
||||
if (!status?.running) setPill("Сервис остановлен", "bad");
|
||||
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
|
||||
else if (!status?.device_online) setPill("ESP32 offline", "bad");
|
||||
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
|
||||
else setPill("Online", "good");
|
||||
|
||||
$("#header-detail").textContent = elica.power
|
||||
? `Вытяжка включена${elica.speed ? ` · скорость ${elica.speed}` : ""}`
|
||||
: "Вытяжная вентиляция";
|
||||
|
||||
drawSpeed(elica.speed);
|
||||
$("#speed-note").textContent = panelOnline
|
||||
? (elica.power ? "Фактическая ступень по индикаторам Elica" : "Выбор скорости включит вытяжку")
|
||||
: "Ждём синхронизацию панели Elica";
|
||||
|
||||
drawToggle("#power-toggle", elica.power);
|
||||
$("#power-detail").textContent = elica.power ? "Включена" : "Выключена";
|
||||
|
||||
if (external.available && typeof external.on === "boolean") {
|
||||
drawToggle("#external-fan-toggle", external.on);
|
||||
$("#external-fan-card").dataset.on = String(external.on);
|
||||
$("#external-fan-detail").textContent = external.on ? "Работает · NC замкнут" : "Остановлен · NC разомкнут";
|
||||
} else {
|
||||
drawToggle("#external-fan-toggle", false, "—");
|
||||
$("#external-fan-card").dataset.on = "false";
|
||||
$("#external-fan-detail").textContent = "Ждём OUT5";
|
||||
}
|
||||
|
||||
drawToggle("#timer-toggle", elica.timer);
|
||||
$("#timer-detail").textContent = elica.timer ? "Активен" : "Выключен";
|
||||
|
||||
const hoodDisabled = busy || !panelOnline;
|
||||
$("#power-toggle").disabled = hoodDisabled;
|
||||
$$('[data-speed]').forEach(button => { button.disabled = hoodDisabled; });
|
||||
$("#timer-toggle").disabled = hoodDisabled;
|
||||
$("#light-toggle").disabled = hoodDisabled;
|
||||
$("#external-fan-toggle").disabled = busy || !controllerOnline || !external.available;
|
||||
}
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
...options,
|
||||
});
|
||||
if (!response.ok) {
|
||||
let message = `Ошибка ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body?.detail && typeof body.detail === "object") {
|
||||
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
|
||||
} else message = body?.detail || body?.message || message;
|
||||
} catch (_) {}
|
||||
throw new Error(String(message));
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function refresh(silent = false) {
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try { render(await request("/api/elica/status")); }
|
||||
catch (error) {
|
||||
setPill("API недоступен", "bad");
|
||||
if (!silent) showToast(error.message, true);
|
||||
} finally { polling = false; }
|
||||
}
|
||||
|
||||
async function act(path, source, optimistic = null) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
optimistic?.();
|
||||
if (state) render(state);
|
||||
source?.setAttribute("disabled", "");
|
||||
try { render(await request(path, { method: "POST" })); }
|
||||
catch (error) { showToast(error.message, true); await refresh(true); }
|
||||
finally {
|
||||
busy = false;
|
||||
source?.removeAttribute("disabled");
|
||||
if (state) render(state);
|
||||
}
|
||||
}
|
||||
|
||||
$("#power-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.elica?.power);
|
||||
act(`/api/elica/power/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.elica) state.elica.power = next;
|
||||
drawToggle("#power-toggle", next);
|
||||
});
|
||||
});
|
||||
|
||||
$$('[data-speed]').forEach(button => button.addEventListener("click", () => {
|
||||
const speed = Number(button.dataset.speed);
|
||||
act(`/api/elica/speed/${speed}`, button, () => {
|
||||
if (state?.elica) { state.elica.power = true; state.elica.speed = speed; }
|
||||
drawSpeed(speed);
|
||||
});
|
||||
}));
|
||||
|
||||
$("#timer-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.elica?.timer);
|
||||
act(`/api/elica/timer/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.elica) state.elica.timer = next;
|
||||
drawToggle("#timer-toggle", next);
|
||||
});
|
||||
});
|
||||
|
||||
$("#light-toggle").addEventListener("click", event => {
|
||||
act("/api/elica/light/toggle", event.currentTarget);
|
||||
});
|
||||
|
||||
$("#external-fan-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.external_fan?.on);
|
||||
act(`/api/elica/external-fan/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.external_fan) state.external_fan.on = next;
|
||||
drawToggle("#external-fan-toggle", next);
|
||||
$("#external-fan-card").dataset.on = String(next);
|
||||
});
|
||||
});
|
||||
|
||||
$("#open-panel").addEventListener("click", () => {
|
||||
const url = new URL("/ui/elica", window.location.origin);
|
||||
url.searchParams.set("theme", themeMode());
|
||||
window.open(url.toString(), "_blank", "noopener");
|
||||
});
|
||||
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(true); });
|
||||
refresh();
|
||||
setInterval(() => !document.hidden && !busy && refresh(true), 1500);
|
||||
-241
@@ -1,241 +0,0 @@
|
||||
import { configureTheme, showToast } from "./api.js";
|
||||
|
||||
const $ = selector => document.querySelector(selector);
|
||||
const $$ = selector => [...document.querySelectorAll(selector)];
|
||||
|
||||
const connection = $("#connection");
|
||||
const powerToggle = $("#power-toggle");
|
||||
const powerCaption = $("#power-caption");
|
||||
const speedValue = $("#speed-value");
|
||||
const speedCaption = $("#speed-caption");
|
||||
const speedButtons = $$("[data-speed]");
|
||||
const timerToggle = $("#timer-toggle");
|
||||
const timerCaption = $("#timer-caption");
|
||||
const lightToggle = $("#light-toggle");
|
||||
const externalFanToggle = $("#external-fan-toggle");
|
||||
const externalFanCaption = $("#external-fan-caption");
|
||||
const externalFanCard = $("#external-fan-card");
|
||||
const mqttStatus = $("#mqtt-status");
|
||||
const deviceStatus = $("#device-status");
|
||||
const feedbackStatus = $("#feedback-status");
|
||||
const relay5Status = $("#relay5-status");
|
||||
const diagnosticNote = $("#diagnostic-note");
|
||||
const updatedAt = $("#updated-at");
|
||||
const refreshButton = $("#refresh-button");
|
||||
const themeButton = $("#theme-button");
|
||||
|
||||
configureTheme(themeButton);
|
||||
|
||||
let latest = null;
|
||||
let polling = false;
|
||||
let commandBusy = false;
|
||||
let refreshTimer = null;
|
||||
|
||||
function setTextState(element, text, tone = "") {
|
||||
element.textContent = text;
|
||||
element.className = tone;
|
||||
}
|
||||
|
||||
function setPill(text, tone) {
|
||||
connection.textContent = text;
|
||||
connection.className = `pill ${tone}`;
|
||||
}
|
||||
|
||||
function setToggle(button, enabled, label = null) {
|
||||
const isOn = Boolean(enabled);
|
||||
button.setAttribute("aria-pressed", String(isOn));
|
||||
const text = button.querySelector("span");
|
||||
if (text) text.textContent = label || (isOn ? "ON" : "OFF");
|
||||
else button.textContent = label || (isOn ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
function controllerReady(status) {
|
||||
return Boolean(
|
||||
status?.running &&
|
||||
status?.mqtt_connected &&
|
||||
status?.device_online
|
||||
);
|
||||
}
|
||||
|
||||
function hoodReady(status) {
|
||||
return controllerReady(status) && Boolean(status?.feedback_ready);
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
latest = status;
|
||||
const logical = status?.elica || {};
|
||||
const external = status?.external_fan || {};
|
||||
const ready = controllerReady(status);
|
||||
const feedbackReady = hoodReady(status);
|
||||
|
||||
if (!status?.running) setPill("Сервис остановлен", "bad");
|
||||
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
|
||||
else if (!status?.device_online) setPill("ESP32 offline", "bad");
|
||||
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
|
||||
else setPill("Online", "good");
|
||||
|
||||
setToggle(powerToggle, logical.power);
|
||||
powerCaption.textContent = logical.power
|
||||
? `Включена${logical.speed ? ` · скорость ${logical.speed}` : ""}`
|
||||
: "Вытяжка выключена";
|
||||
|
||||
const speed = Number(logical.speed) || 0;
|
||||
speedValue.textContent = speed || "—";
|
||||
speedButtons.forEach(button => {
|
||||
button.classList.toggle("active", speed > 0 && Number(button.dataset.speed) <= speed);
|
||||
});
|
||||
speedCaption.textContent = feedbackReady
|
||||
? (logical.power ? "Фактическая скорость по индикаторам Elica." : "При выборе скорости вытяжка включится автоматически.")
|
||||
: "Ждём синхронизацию входов панели Elica.";
|
||||
|
||||
setToggle(timerToggle, logical.timer);
|
||||
timerCaption.textContent = logical.timer
|
||||
? "Таймер активен · индикатор скорости мигает"
|
||||
: "Таймер выключен";
|
||||
|
||||
if (external.available && typeof external.on === "boolean") {
|
||||
setToggle(externalFanToggle, external.on);
|
||||
externalFanCard.dataset.on = String(external.on);
|
||||
externalFanCaption.textContent = external.on
|
||||
? "Включён · NC замкнут, OUT5 выключен"
|
||||
: "Выключен · NC разомкнут, OUT5 включен";
|
||||
} else {
|
||||
setToggle(externalFanToggle, false, "—");
|
||||
externalFanCard.dataset.on = "false";
|
||||
externalFanCaption.textContent = "Ждём обратную связь OUT5";
|
||||
}
|
||||
|
||||
setTextState(mqttStatus, status?.mqtt_connected ? "Подключён" : "Нет связи", status?.mqtt_connected ? "good" : "bad");
|
||||
setTextState(deviceStatus, status?.device_online ? "Online" : "Offline", status?.device_online ? "good" : "bad");
|
||||
setTextState(feedbackStatus, status?.feedback_ready ? "Синхронизирована" : "Ожидание", status?.feedback_ready ? "good" : "warn");
|
||||
|
||||
if (external.available) {
|
||||
setTextState(relay5Status, external.relay_on ? "ON · NC открыт" : "OFF · NC закрыт", external.relay_on ? "warn" : "good");
|
||||
} else {
|
||||
setTextState(relay5Status, "Нет данных", "warn");
|
||||
}
|
||||
|
||||
const missing = status?.missing_feedback_inputs || [];
|
||||
diagnosticNote.textContent = missing.length
|
||||
? `Не получены входы Elica: ${missing.join(", ")}.`
|
||||
: "Состояния вытяжки подтверждаются по MQTT и физическим входам ESP32.";
|
||||
|
||||
const stamp = status?.last_message_at ? new Date(status.last_message_at) : new Date();
|
||||
updatedAt.textContent = Number.isNaN(stamp.getTime())
|
||||
? "—"
|
||||
: `Обновлено ${stamp.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`;
|
||||
|
||||
const disableHood = commandBusy || !feedbackReady;
|
||||
powerToggle.disabled = disableHood;
|
||||
speedButtons.forEach(button => { button.disabled = disableHood; });
|
||||
timerToggle.disabled = disableHood;
|
||||
lightToggle.disabled = disableHood;
|
||||
externalFanToggle.disabled = commandBusy || !ready || !external.available;
|
||||
|
||||
document.body.classList.toggle("pending", commandBusy);
|
||||
}
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
...options,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `Ошибка ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body?.detail && typeof body.detail === "object") {
|
||||
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
|
||||
} else {
|
||||
message = body?.detail || body?.message || message;
|
||||
}
|
||||
} catch (_) {}
|
||||
throw new Error(String(message));
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function refresh({ silent = false } = {}) {
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try {
|
||||
render(await request("/api/elica/status"));
|
||||
} catch (error) {
|
||||
setPill("API недоступен", "bad");
|
||||
if (!silent) showToast(error.message, true);
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function command(path, optimistic = null) {
|
||||
if (commandBusy) return;
|
||||
commandBusy = true;
|
||||
if (latest) render(latest);
|
||||
if (optimistic) optimistic();
|
||||
|
||||
try {
|
||||
const status = await request(path, { method: "POST" });
|
||||
render(status);
|
||||
} catch (error) {
|
||||
showToast(error.message, true);
|
||||
await refresh({ silent: true });
|
||||
} finally {
|
||||
commandBusy = false;
|
||||
if (latest) render(latest);
|
||||
}
|
||||
}
|
||||
|
||||
powerToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.elica?.power);
|
||||
command(`/api/elica/power/${next ? "on" : "off"}`, () => {
|
||||
setToggle(powerToggle, next);
|
||||
powerCaption.textContent = next ? "Включаем…" : "Выключаем…";
|
||||
});
|
||||
});
|
||||
|
||||
speedButtons.forEach(button => button.addEventListener("click", () => {
|
||||
const speed = Number(button.dataset.speed);
|
||||
command(`/api/elica/speed/${speed}`, () => {
|
||||
speedValue.textContent = String(speed);
|
||||
speedButtons.forEach(item => item.classList.toggle("active", item === button));
|
||||
speedCaption.textContent = `Устанавливаем скорость ${speed}…`;
|
||||
});
|
||||
}));
|
||||
|
||||
timerToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.elica?.timer);
|
||||
command(`/api/elica/timer/${next ? "on" : "off"}`, () => {
|
||||
setToggle(timerToggle, next);
|
||||
timerCaption.textContent = next ? "Включаем таймер…" : "Выключаем таймер…";
|
||||
});
|
||||
});
|
||||
|
||||
lightToggle.addEventListener("click", () => {
|
||||
command("/api/elica/light/toggle", () => {
|
||||
lightToggle.textContent = "Команда…";
|
||||
setTimeout(() => { lightToggle.textContent = "Переключить"; }, 700);
|
||||
});
|
||||
});
|
||||
|
||||
externalFanToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.external_fan?.on);
|
||||
command(`/api/elica/external-fan/${next ? "on" : "off"}`, () => {
|
||||
setToggle(externalFanToggle, next);
|
||||
externalFanCard.dataset.on = String(next);
|
||||
externalFanCaption.textContent = next ? "Включаем…" : "Выключаем…";
|
||||
});
|
||||
});
|
||||
|
||||
refreshButton.addEventListener("click", () => refresh());
|
||||
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) refresh({ silent: true });
|
||||
});
|
||||
|
||||
refresh();
|
||||
refreshTimer = window.setInterval(() => refresh({ silent: true }), 1000);
|
||||
window.addEventListener("beforeunload", () => window.clearInterval(refreshTimer));
|
||||
@@ -74,7 +74,7 @@ function renderAir(sensor, tion) {
|
||||
airCard.style.setProperty("--air-glow", airPalette.glow);
|
||||
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
|
||||
setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad");
|
||||
text("#room-temp", numberOrDash(sensor.temperature, 1));
|
||||
text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
|
||||
text("#humidity", numberOrDash(sensor.humidity));
|
||||
text("#pm25", numberOrDash(sensor.pm25));
|
||||
text("#pm10", numberOrDash(sensor.pm10));
|
||||
@@ -122,7 +122,7 @@ function render(status) {
|
||||
$("#mode-outside").classList.toggle("active", tion.mode === "outside");
|
||||
$("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation");
|
||||
text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция");
|
||||
text("#outside-temp", numberOrDash(tion.in_temp));
|
||||
text("#outside-temp", numberOrDash(tion.out_temp));
|
||||
text("#filter-remain", numberOrDash(tion.filter_remain));
|
||||
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
|
||||
$("#filter-progress").style.width = `${filterPercent}%`;
|
||||
@@ -83,7 +83,7 @@ function render(status) {
|
||||
airCard.style.setProperty("--air-color", airPalette.color);
|
||||
airCard.style.setProperty("--air-glow", airPalette.glow);
|
||||
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
|
||||
setText("#room-temp", numberOrDash(sensor.temperature, 1));
|
||||
setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
|
||||
setText("#humidity", numberOrDash(sensor.humidity));
|
||||
setText("#current-time", schedule.current_time || tion.device_time || "—");
|
||||
setText("#next-time", schedule.next_time || "—");
|
||||
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Tion 4S — панель управления</title>
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css">
|
||||
<link rel="stylesheet" href="/ui/static/css/panel.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="ambient"></div>
|
||||
@@ -158,6 +158,6 @@
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
<script type="module" src="/ui/static/js/tion.js?v=2"></script>
|
||||
<script type="module" src="/ui/static/js/panel.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Tion 4S — виджет</title>
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1">
|
||||
<link rel="stylesheet" href="/ui/static/css/base.css">
|
||||
<link rel="stylesheet" href="/ui/static/css/widget.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="ambient" aria-hidden="true"></div>
|
||||
@@ -124,6 +124,6 @@
|
||||
</button>
|
||||
<span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span>
|
||||
</main>
|
||||
<script type="module" src="/ui/static/js/tion-widget.js?v=20260927-1"></script>
|
||||
<script type="module" src="/ui/static/js/widget.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user