work: исправил архитектуру управления температурой. Теперь отдельный контроллер отвечает за нагрев для всех режимов авто ручной или временный ручной. Раньше в каждом режиме была своя логика.

This commit is contained in:
2026-09-29 22:49:31 +03:00
parent ba8151305a
commit 2a7d2a0b8b
41 changed files with 1632 additions and 2768 deletions
-37
View File
@@ -1,37 +0,0 @@
import asyncio
import logging
from app.my_dataclasses import TION_MAC
from app.tion import TionController, TionService
# Убираем служебное логирование библиотек
async def main():
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("bleak").setLevel(logging.WARNING)
logging.getLogger("tion_btle").setLevel(logging.WARNING)
controller = TionController(TION_MAC)
service = TionService(
controller,
poll_interval=3,
)
async with service:
for seconds in range(0, 91, 3):
print(
f"{seconds:02d}s | "
f"online={service.online} | "
f"last_seen={service.last_seen} | "
f"error={service.last_error}"
)
await asyncio.sleep(3)
if __name__ == "__main__":
asyncio.run(main())
-30
View File
@@ -1,30 +0,0 @@
import asyncio
import logging
from bleak import BleakScanner
from app.my_dataclasses import TION_MAC
logging.disable(logging.CRITICAL)
async def main():
print("Ищу Tion...")
device = await BleakScanner.find_device_by_address(
TION_MAC,
timeout=10,
)
if device is None:
print("Tion НЕ найден сканером")
else:
print("Tion найден:")
print(f" name: {device.name}")
print(f" address: {device.address}")
print(f" details: {device.details}")
if __name__ == "__main__":
asyncio.run(main())
-59
View File
@@ -1,59 +0,0 @@
#d1749bebeea6
import asyncio
import json
import logging
from tion_btle import TionS4
from app.my_dataclasses import *
def print_state(state: dict):
print(json.dumps(
state,
indent=2,
ensure_ascii=False
))
async def main():
# Убираем лишнее логирование
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("bleak").setLevel(logging.WARNING)
logging.getLogger("tion_btle").setLevel(logging.WARNING)
tion = TionS4(TION_MAC)
print("=== Подключение к Tion ===")
await tion.connect()
try:
# 1. Получаем исходное состояние
print("\n=== Исходное состояние ===")
state = await tion.get()
print_state(state)
# 2. Включаем Tion и устанавливаем скорость 2
print("\n=== Включаю Tion, скорость 2 ===")
await tion.set({
"state": "on",
"fan_speed": 2
})
await asyncio.sleep(1)
# 3. Повторно читаем реальное состояние
print("\n=== Состояние после команды ===")
state = await tion.get()
print_state(state)
finally:
print("\n=== Отключение ===")
await tion.disconnect()
if __name__ == "__main__":
asyncio.run(main())
+134
View File
@@ -0,0 +1,134 @@
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()
@@ -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())
-304
View File
@@ -1,304 +0,0 @@
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())
@@ -1,138 +0,0 @@
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())
-169
View File
@@ -1,169 +0,0 @@
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()
-27
View File
@@ -1,27 +0,0 @@
import asyncio
from bleak import BleakScanner
async def main():
print("Scanning for 20 seconds...")
devices = await BleakScanner.discover(
timeout=20.0,
return_adv=True,
)
print()
print(f"Found: {len(devices)} devices")
print()
for address, (device, adv) in devices.items():
print("ADDRESS:", address)
print("NAME:", device.name)
print("RSSI:", adv.rssi)
print("UUIDS:", adv.service_uuids)
print("SERVICE DATA:", adv.service_data)
print("-" * 60)
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())
-368
View File
@@ -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())
-335
View File
@@ -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())
-112
View File
@@ -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())
-248
View File
@@ -1,248 +0,0 @@
from app.auto.controller import AutoController
def print_state(
title: str,
controller: AutoController,
) -> None:
print()
print(title)
print(
{
"enabled": (
controller.manual_heater_enabled
),
"target_temp": (
controller.manual_target_temperature
),
"heating": (
controller._manual_heating
),
}
)
def main() -> None:
controller = object.__new__(
AutoController
)
controller._manual_heater_enabled = None
controller._manual_target_temperature = None
controller._manual_heating = None
# ==================================================
# 1. Исходное состояние.
# ==================================================
print_state(
"1. Initial:",
controller,
)
assert (
controller.manual_heater_enabled
is None
)
assert (
controller.manual_target_temperature
is None
)
assert controller._manual_heating is None
# ==================================================
# 2. Пользователь входит в ручной режим.
#
# Представим, что на момент перехода:
# heater был выключен,
# пользовательская температура = 23.
# ==================================================
controller.set_manual_heater_enabled(
False
)
controller.set_manual_target_temperature(
23
)
print_state(
"2. Enter manual mode:",
controller,
)
assert (
controller.manual_heater_enabled
is False
)
assert (
controller.manual_target_temperature
== 23
)
# ==================================================
# 3. Пользователь включает обогрев.
# ==================================================
controller.set_manual_heater_enabled(
True
)
print_state(
"3. Heater ON:",
controller,
)
assert (
controller.manual_heater_enabled
is True
)
assert (
controller.manual_target_temperature
== 23
)
# Пока реальный регулятор Qingping ещё
# не реализован, heating остаётся None.
assert controller._manual_heating is False
# ==================================================
# 4. Пользователь увеличивает температуру.
#
# 23 -> 24.
# ==================================================
controller.set_manual_target_temperature(
24
)
print_state(
"4. Temperature 23 -> 24:",
controller,
)
assert (
controller.manual_target_temperature
== 24
)
assert (
controller.manual_heater_enabled
is True
)
# ==================================================
# 5. Пользователь уменьшает температуру.
#
# 24 -> 23.
# ==================================================
controller.set_manual_target_temperature(
23
)
print_state(
"5. Temperature 24 -> 23:",
controller,
)
assert (
controller.manual_target_temperature
== 23
)
assert (
controller.manual_heater_enabled
is True
)
# ==================================================
# 6. Пользователь выключает обогрев.
# ==================================================
controller.set_manual_heater_enabled(
False
)
print_state(
"6. Heater OFF:",
controller,
)
assert (
controller.manual_heater_enabled
is False
)
# Уставка пользователя должна сохраниться.
assert (
controller.manual_target_temperature
== 23
)
# При явном выключении heater мы уже
# установили manual_heating=False.
assert controller._manual_heating is False
# ==================================================
# 7. Пользователь снова включает heater.
#
# Проверяем, что сохранённая температура 23
# не потерялась.
# ==================================================
controller.set_manual_heater_enabled(
True
)
print_state(
"7. Heater ON again:",
controller,
)
assert (
controller.manual_heater_enabled
is True
)
assert (
controller.manual_target_temperature
== 23
)
# ==================================================
# 8. Resume расписания.
#
# API при resume вызывает
# clear_manual_heater_control().
# ==================================================
controller.clear_manual_heater_control()
print_state(
"8. Resume schedule:",
controller,
)
assert (
controller.manual_heater_enabled
is None
)
assert (
controller.manual_target_temperature
is None
)
assert controller._manual_heating is None
print()
print("TEST PASSED")
if __name__ == "__main__":
main()
-366
View File
@@ -1,366 +0,0 @@
import asyncio
import inspect
from app.auto.controller import AutoController
from app.my_dataclasses import MAX_TARGET_TEMP
class FakeTionController:
def __init__(self) -> None:
self.heater = False
self.target_temp = 23
def heater_on(self) -> None:
self.heater = True
def heater_off(self) -> None:
self.heater = False
def set_target_temperature(
self,
temperature: int,
) -> None:
self.target_temp = temperature
class FakeTionState:
def __init__(self) -> None:
self.in_temp = 22
class FakeTionService:
def __init__(self) -> None:
self.online = True
self.state = FakeTionState()
self.controller = FakeTionController()
self.commands: list[str] = []
async def execute(self, operation):
result = operation(self.controller)
if inspect.isawaitable(result):
await result
self.commands.append(
(
f"heater={self.controller.heater}, "
f"target={self.controller.target_temp}"
)
)
class FakeQingpingState:
def __init__(self) -> None:
self.temperature = 21.0
class FakeQingpingService:
def __init__(self) -> None:
self.online = True
self.state = FakeQingpingState()
class FakeTemperaturePolicy:
"""
Для этого теста нас интересует именно
интеграция Manual Heater с источниками
температуры и Tion.
Поэтому policy делаем простой и
детерминированной.
"""
def heater_required(
self,
temperature,
target_temp,
heater_on,
) -> bool:
return temperature < target_temp
def print_state(
title: str,
controller: AutoController,
tion: FakeTionService,
) -> None:
print()
print(title)
print(
{
"manual_enabled": (
controller.manual_heater_enabled
),
"user_target": (
controller.manual_target_temperature
),
"manual_heating": (
controller._manual_heating
),
"temperature": (
controller._temperature
),
"temperature_source": (
controller._temperature_source
),
"tion_heater": (
tion.controller.heater
),
"tion_target": (
tion.controller.target_temp
),
}
)
async def main() -> None:
tion = FakeTionService()
qingping = FakeQingpingService()
controller = AutoController(
schedule_service=object(),
qingping_service=qingping,
tion_service=tion,
temperature_policy=(
FakeTemperaturePolicy()
),
)
controller.set_manual_heater_enabled(
True
)
controller.set_manual_target_temperature(
23
)
# ==================================================
# 1. Qingping доступен.
# Комната холоднее цели.
#
# 21 < 23
#
# Ожидаем:
# - управление по Qingping;
# - heater ON;
# - физическая уставка Tion = MAX;
# - manual_heating=True.
# ==================================================
qingping.online = True
qingping.state.temperature = 21.0
await controller._process_manual_heater()
print_state(
"1. Qingping OK, room 21°C:",
controller,
tion,
)
assert (
controller._temperature_source
== "qingping"
)
assert controller._temperature == 21.0
assert controller._manual_heating is True
assert tion.controller.heater is True
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
assert (
controller.manual_target_temperature
== 23
)
# ==================================================
# 2. Температура достигла цели.
#
# 23 >= 23
#
# Ожидаем:
# - heater OFF;
# - внешний регулятор остаётся активным;
# - физическая уставка Tion остаётся MAX.
# ==================================================
qingping.state.temperature = 23.0
await controller._process_manual_heater()
print_state(
"2. Room reached 23°C:",
controller,
tion,
)
assert (
controller._temperature_source
== "qingping"
)
assert controller._temperature == 23.0
assert controller._manual_heating is False
assert tion.controller.heater is False
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
# ==================================================
# 3. Qingping пропал.
#
# Ожидаем:
# - внешний регулятор отключается;
# - manual_heating=None;
# - Tion получает пользовательские 23°C;
# - heater разрешается;
# - дальше решение принимает встроенный
# термостат Tion.
# ==================================================
qingping.online = False
tion.state.in_temp = 22
await controller._process_manual_heater()
print_state(
"3. Qingping OFFLINE:",
controller,
tion,
)
assert controller._manual_heating is None
assert tion.controller.heater is True
assert tion.controller.target_temp == 23
assert controller._temperature == 22
assert (
controller._temperature_source
== "tion"
)
# ==================================================
# 4. Qingping снова появился.
#
# Комната 22°C при цели 23°C.
#
# Ожидаем автоматический возврат
# внешнего регулирования.
# ==================================================
qingping.online = True
qingping.state.temperature = 22.0
await controller._process_manual_heater()
print_state(
"4. Qingping recovered, room 22°C:",
controller,
tion,
)
assert (
controller._temperature_source
== "qingping"
)
assert controller._temperature == 22.0
assert controller._manual_heating is True
assert tion.controller.heater is True
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
# ==================================================
# 5. После восстановления снова достигаем цели.
# ==================================================
qingping.state.temperature = 23.0
await controller._process_manual_heater()
print_state(
"5. Target reached after recovery:",
controller,
tion,
)
assert controller._manual_heating is False
assert tion.controller.heater is False
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
# ==================================================
# 6. Пользователь выключает heater.
#
# Даже при холодной комнате нагрев должен
# остаться выключенным.
# ==================================================
qingping.state.temperature = 18.0
controller.set_manual_heater_enabled(
False
)
await controller._process_manual_heater()
print_state(
"6. User heater OFF:",
controller,
tion,
)
assert (
controller.manual_heater_enabled
is False
)
assert controller._manual_heating is False
assert tion.controller.heater is False
# Пользовательская температура при этом
# должна сохраниться.
assert (
controller.manual_target_temperature
== 23
)
print()
print("Commands sent to fake Tion:")
for command in tion.commands:
print(" ", command)
print()
print("TEST PASSED")
if __name__ == "__main__":
asyncio.run(main())
@@ -1,279 +0,0 @@
class FakeTion:
"""
Модель Tion.
target_temp:
реальная температура, отправленная в Tion.
heater:
разрешён ли нагреватель физически.
"""
def __init__(self) -> None:
self.heater = False
self.target_temp = 23
def set_heater(
self,
enabled: bool,
) -> None:
self.heater = enabled
def set_target_temperature(
self,
temperature: int,
) -> None:
self.target_temp = temperature
class ManualHeaterModel:
"""
Эталонная модель будущего ручного
температурного регулятора.
user_target:
температура, которую задал пользователь.
heating:
решение внешнего регулятора:
True -> сейчас хотим греть;
False -> сейчас не хотим греть;
None -> внешний регулятор не работает,
управление отдано Tion.
"""
def __init__(
self,
tion: FakeTion,
user_target: int,
) -> None:
self.tion = tion
self.user_target = user_target
self.heating: bool | None = None
def update(
self,
qingping_available: bool,
room_temperature: float | None,
) -> None:
# ----------------------------------------------
# Qingping недоступен.
#
# Возвращаем штатное управление Tion:
#
# heater = ON
# target = пользовательская температура.
#
# Дальше встроенный термостат Tion сам
# решает, когда реально нагревать.
# ----------------------------------------------
if (
not qingping_available
or room_temperature is None
):
self.heating = None
self.tion.set_target_temperature(
self.user_target
)
self.tion.set_heater(
True
)
return
# ----------------------------------------------
# Qingping доступен.
#
# Чтобы внутренний термостат Tion
# не выключил нагрев раньше комнатного
# датчика, ставим техническую уставку 30°C.
# ----------------------------------------------
self.tion.set_target_temperature(
30
)
# Комната холоднее цели.
if room_temperature < self.user_target:
self.heating = True
self.tion.set_heater(
True
)
return
# Температура достигнута.
self.heating = False
self.tion.set_heater(
False
)
def print_state(
title: str,
model: ManualHeaterModel,
) -> None:
print()
print(title)
print(
{
"user_target": model.user_target,
"manual_heating": model.heating,
"tion_heater": model.tion.heater,
"tion_target": model.tion.target_temp,
}
)
def main() -> None:
tion = FakeTion()
model = ManualHeaterModel(
tion=tion,
user_target=23,
)
# ==================================================
# 1. Qingping доступен.
# В комнате холодно: 21°C при цели 23°C.
#
# Ожидаем:
# - внешний регулятор активен;
# - heater ON;
# - техническая уставка Tion = 30°C.
# ==================================================
model.update(
qingping_available=True,
room_temperature=21.0,
)
print_state(
"1. Qingping available, room 21°C:",
model,
)
assert model.heating is True
assert tion.heater is True
assert tion.target_temp == 30
# Пользовательская цель не должна
# измениться.
assert model.user_target == 23
# ==================================================
# 2. Температура комнаты достигла цели.
#
# 23°C при цели 23°C.
#
# Ожидаем:
# - нагрев выключается;
# - Tion остаётся с технической уставкой 30,
# потому что управление всё ещё внешнее.
# ==================================================
model.update(
qingping_available=True,
room_temperature=23.0,
)
print_state(
"2. Room reached target 23°C:",
model,
)
assert model.heating is False
assert tion.heater is False
assert tion.target_temp == 30
assert model.user_target == 23
# ==================================================
# 3. Qingping пропал.
#
# Ожидаем немедленный fallback:
#
# - внешний регулятор прекращает принимать
# решения;
# - heater разрешаем;
# - возвращаем физическую уставку Tion = 23;
# - дальше работает встроенный термостат Tion.
# ==================================================
model.update(
qingping_available=False,
room_temperature=None,
)
print_state(
"3. Qingping unavailable:",
model,
)
assert model.heating is None
assert tion.heater is True
assert (
tion.target_temp
== model.user_target
== 23
)
# ==================================================
# 4. Qingping снова появился.
#
# В комнате снова холоднее цели.
#
# Ожидаем возврат внешнего управления:
#
# target Tion 23 -> 30
# heater ON
# heating True
# ==================================================
model.update(
qingping_available=True,
room_temperature=22.0,
)
print_state(
"4. Qingping recovered, room 22°C:",
model,
)
assert model.heating is True
assert tion.heater is True
assert tion.target_temp == 30
assert model.user_target == 23
# ==================================================
# 5. После восстановления снова достигаем цели.
# ==================================================
model.update(
qingping_available=True,
room_temperature=23.0,
)
print_state(
"5. Target reached after recovery:",
model,
)
assert model.heating is False
assert tion.heater is False
assert tion.target_temp == 30
assert model.user_target == 23
print()
print("TEST PASSED")
if __name__ == "__main__":
main()
-107
View File
@@ -1,107 +0,0 @@
from app.auto.controller import AutoController
def main() -> None:
controller = object.__new__(
AutoController
)
controller._manual_heater_enabled = None
controller._manual_target_temperature = None
controller._manual_heating = None
print("Initial:")
print(
{
"enabled": controller._manual_heater_enabled,
"target_temp": controller._manual_target_temperature,
"heating": controller._manual_heating,
}
)
controller.set_manual_heater_enabled(
True
)
controller.set_manual_target_temperature(
23
)
print("After enable + target 23:")
print(
{
"enabled": controller.manual_heater_enabled,
"target_temp": controller.manual_target_temperature,
"heating": controller._manual_heating,
}
)
assert (
controller.manual_heater_enabled
is True
)
assert (
controller.manual_target_temperature
== 23
)
assert (
controller._manual_heating
is None
)
controller.set_manual_heater_enabled(
False
)
print("After heater OFF:")
print(
{
"enabled": controller.manual_heater_enabled,
"target_temp": controller.manual_target_temperature,
"heating": controller._manual_heating,
}
)
assert (
controller.manual_heater_enabled
is False
)
assert (
controller._manual_heating
is False
)
controller.clear_manual_heater_control()
print("After clear:")
print(
{
"enabled": controller.manual_heater_enabled,
"target_temp": controller.manual_target_temperature,
"heating": controller._manual_heating,
}
)
assert (
controller.manual_heater_enabled
is None
)
assert (
controller.manual_target_temperature
is None
)
assert (
controller._manual_heating
is None
)
print("TEST PASSED")
if __name__ == "__main__":
main()
-326
View File
@@ -1,326 +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) -> None:
# Имитируем состояние до ручного изменения:
# AUTO ранее разрешил нагрев.
self.heater = True
self.target_temp = MAX_TARGET_TEMP
def heater_on(self) -> None:
self.heater = True
def heater_off(self) -> None:
self.heater = False
def set_target_temperature(
self,
temperature: int,
) -> None:
self.target_temp = temperature
class FakeTionState:
def __init__(self) -> None:
self.heater = True
self.in_temp = 18
class FakeTionService:
def __init__(self) -> None:
self.online = True
self.state = FakeTionState()
self.controller = FakeTionController()
async def execute(self, operation):
result = operation(self.controller)
if inspect.isawaitable(result):
await result
class FakeQingpingState:
def __init__(self) -> None:
self.temperature = 25.8
self.co2 = 900
class FakeQingpingService:
def __init__(self) -> None:
self.online = True
self.state = FakeQingpingState()
class FakeTemperaturePolicy:
def heater_required(
self,
temperature,
target_temp,
heater_on,
) -> bool:
return temperature < target_temp
class FakeSchedule:
def __init__(self) -> None:
self.paused = False
self.override_active = True
# Пользователь во время AUTO
# изменил только температуру:
#
# AUTO target = 25
# manual override target = 23
self.override_settings = SimpleNamespace(
target_temp=23,
heater=None,
)
def resolve(self, now=None):
# _process() вызывает resolve() ещё до
# проверки override_active.
#
# Для самого override содержимое resolution
# использоваться не должно.
return SimpleNamespace(
enabled=True,
auto_active=True,
auto_fallback_speed=2,
auto_target_temp=25,
)
def print_state(
title: str,
controller: AutoController,
tion: FakeTionService,
qingping: FakeQingpingService,
) -> None:
print()
print(title)
print(
{
"controller_state": controller._state,
"reason": controller._reason,
"qingping_online": qingping.online,
"qingping_temp": (
qingping.state.temperature
),
"manual_enabled": (
controller.manual_heater_enabled
),
"manual_target": (
controller.manual_target_temperature
),
"manual_heating": (
controller._manual_heating
),
"temperature": controller._temperature,
"temperature_source": (
controller._temperature_source
),
"tion_in_temp": tion.state.in_temp,
"tion_heater": tion.controller.heater,
"tion_target": (
tion.controller.target_temp
),
}
)
async def main() -> None:
schedule = FakeSchedule()
tion = FakeTionService()
qingping = FakeQingpingService()
controller = AutoController(
schedule_service=schedule,
qingping_service=qingping,
tion_service=tion,
temperature_policy=FakeTemperaturePolicy(),
)
# ==================================================
# 1. Регрессионный тест найденного бага.
#
# Было:
#
# AUTO target = 25
# Qingping = 25.8
# Tion heater = ON
#
# Пользователь вручную ставит 23.
#
# Несмотря на то, что встроенный датчик Tion
# показывает только 18°C, главным должен остаться
# Qingping:
#
# 25.8 > 23
# -> heater OFF.
# ==================================================
await controller._process()
print_state(
"1. Override target 23, Qingping 25.8:",
controller,
tion,
qingping,
)
assert controller._state == "suspended"
assert controller._reason == "manual_override"
assert (
controller.manual_target_temperature
== 23
)
assert (
controller.manual_heater_enabled
is True
)
assert (
controller._temperature_source
== "qingping"
)
assert controller._temperature == 25.8
assert controller._manual_heating is False
# КЛЮЧЕВАЯ ПРОВЕРКА БАГА:
assert tion.controller.heater is False
# Внешний регулятор активен,
# поэтому физическая уставка Tion остаётся MAX.
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
# ==================================================
# 2. Qingping пропадает во время того же override.
#
# Должны:
#
# target Tion -> 23
# heater -> ON
#
# И дальше встроенный термостат Tion решает,
# нужен ли фактический нагрев.
# ==================================================
qingping.online = False
qingping.state.temperature = None
await controller._process()
print_state(
"2. Same override, Qingping OFFLINE:",
controller,
tion,
qingping,
)
assert (
controller.manual_target_temperature
== 23
)
assert controller._manual_heating is None
assert tion.controller.target_temp == 23
assert tion.controller.heater is True
assert (
controller._temperature_source
== "tion"
)
assert controller._temperature == 18
# ==================================================
# 3. Qingping восстанавливается.
#
# Комната = 22°C, цель override = 23°C.
#
# Внешний регулятор автоматически должен
# снова забрать управление:
#
# target Tion -> MAX
# heater -> ON
# source -> Qingping
# ==================================================
qingping.online = True
qingping.state.temperature = 22.0
await controller._process()
print_state(
"3. Qingping recovered, room 22:",
controller,
tion,
qingping,
)
assert (
controller._temperature_source
== "qingping"
)
assert controller._temperature == 22.0
assert controller._manual_heating is True
assert tion.controller.heater is True
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
# ==================================================
# 4. Температура снова выше ручной цели.
#
# Проверяем, что heater снова отключается.
# ==================================================
qingping.state.temperature = 24.0
await controller._process()
print_state(
"4. Qingping 24, override target 23:",
controller,
tion,
qingping,
)
assert controller._manual_heating is False
assert tion.controller.heater is False
assert (
tion.controller.target_temp
== MAX_TARGET_TEMP
)
print()
print("TEST PASSED")
if __name__ == "__main__":
asyncio.run(main())
-128
View File
@@ -1,128 +0,0 @@
from unittest.mock import MagicMock, patch
import app.api as api
class FakeTionState:
def __init__(
self,
heater: bool,
target_temp: int,
):
self.heater = heater
self.target_temp = target_temp
def to_dict(self) -> dict:
return {
"power": True,
"heater": self.heater,
"heating": True,
"mode": "outside",
"out_temp": 10,
"in_temp": 21,
"target_temp": self.target_temp,
"fan_speed": 3,
}
def main() -> None:
# --------------------------------------------------
# Физическое состояние Tion:
# heater ON
# target = 30°C
#
# Но пользователь в ручном режиме хочет 23°C.
# --------------------------------------------------
tion_state = FakeTionState(
heater=True,
target_temp=30,
)
fake_service = MagicMock()
fake_service.state = tion_state
fake_service.online = True
fake_service.running = True
fake_service.last_seen = None
fake_service.last_error = None
fake_schedule = MagicMock()
fake_schedule.paused = True
fake_schedule.override_active = False
fake_auto = MagicMock()
fake_auto.manual_heater_enabled = True
fake_auto.manual_target_temperature = 23
fake_auto.status.return_value = {
"manual_heater": {
"enabled": True,
"target_temp": 23,
"heating": None,
}
}
print("Physical Tion:")
print(tion_state.to_dict())
with (
patch.object(
api,
"service",
fake_service,
),
patch.object(
api,
"schedule_service",
fake_schedule,
),
patch.object(
api,
"auto_controller",
fake_auto,
),
):
status = api.get_status()
print()
print("Public API Tion:")
print(status["tion"])
print()
print("Auto:")
print(status["auto"])
# --------------------------------------------------
# Главная проверка.
# --------------------------------------------------
assert tion_state.target_temp == 30
assert (
status["tion"]["target_temp"]
== 23
)
assert (
status["tion"]["heater"]
is True
)
print()
print(
"Physical target:",
tion_state.target_temp,
)
print(
"Public target:",
status["tion"]["target_temp"],
)
print()
print("TEST PASSED")
if __name__ == "__main__":
main()
-32
View File
@@ -1,32 +0,0 @@
import asyncio
import json
from app.qingping.service import QingpingService
async def main():
service = QingpingService(
host="192.168.7.3",
port=1883,
mac="CCB5D131BA93",
)
await service.start()
try:
while True:
await asyncio.sleep(15)
print(
json.dumps(
service.status(),
indent=2,
ensure_ascii=False,
)
)
finally:
await service.stop()
asyncio.run(main())
-60
View File
@@ -1,60 +0,0 @@
import json
import paho.mqtt.client as mqtt
HOST = "192.168.7.3"
PORT = 1883
TOPIC = "qingping/CCB5D131BA93/up"
def on_connect(client, userdata, flags, reason_code, properties):
print("Connected:", reason_code)
client.subscribe(TOPIC)
def on_message(client, userdata, message):
try:
payload = json.loads(message.payload.decode("utf-8"))
except Exception:
print("RAW:", message.payload)
return
message_type = str(payload.get("type"))
message_id = payload.get("id")
message_timestamp = payload.get("timestamp")
sensor_timestamps = []
sensor_data = payload.get("sensorData")
if isinstance(sensor_data, list):
for sample in sensor_data:
timestamp = sample.get("timestamp")
if isinstance(timestamp, dict):
timestamp = timestamp.get("value")
sensor_timestamps.append(timestamp)
print(
f"id={message_id!s:<4} "
f"type={message_type:<3} "
f"msg_ts={message_timestamp!s:<12} "
f"samples={sensor_timestamps}"
)
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id="qingping-raw-debug",
)
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, keepalive=60)
print(f"Listening: {TOPIC}")
client.loop_forever()
-30
View File
@@ -1,30 +0,0 @@
import asyncio
from app.my_dataclasses import QINGPING_MAC
from app.qingping.service import QingpingService
async def main():
service = QingpingService(
QINGPING_MAC
)
async with service:
print("Qingping service started")
while True:
state = service.state
print(
"online:",
service.online,
"| state:",
state.to_dict()
if state
else None,
)
await asyncio.sleep(5)
asyncio.run(main())
+18 -11
View File
@@ -134,7 +134,7 @@ def load_test_schedule():
return temp_dir, config
def heater_calls(calls):
def temperature_calls(calls):
return [
call
for call in calls
@@ -142,6 +142,7 @@ def heater_calls(calls):
"heater_on",
"heater_off",
"set_heater",
"set_target_temperature",
}
]
@@ -178,7 +179,12 @@ async def test_auto_does_not_control_heater():
# 09:30
#
# Обычный SET.
# heater=on должен принадлежать ScheduleService.
#
# ScheduleService хранит желаемое heater=on,
# но физически heater управлять НЕ должен.
#
# Физический heater будет принадлежать
# единому температурному регулятору.
# --------------------------------------------------
await process_at(
@@ -198,12 +204,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls != [], (
"SET must control heater"
assert calls == [], (
"ScheduleService must not control "
"heater or target temperature during SET"
)
tion.controller.calls.clear()
@@ -263,13 +270,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls == [], (
"ScheduleService must not control "
"heater during AUTO"
"heater or target temperature during AUTO"
)
tion.controller.calls.clear()
@@ -298,13 +305,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls != [], (
"ScheduleService must regain heater "
"control after AUTO"
assert calls == [], (
"ScheduleService must not control "
"heater or target temperature after AUTO"
)
finally:
-72
View File
@@ -1,72 +0,0 @@
import asyncio
import logging
from pathlib import Path
import datetime
from app.my_dataclasses import TION_MAC
from app.tion import TionController, TionService
from schedule import (
ScheduleService,
load_schedule,
)
logging.disable(logging.CRITICAL)
PROJECT_ROOT = Path(__file__).resolve().parents[1]
SCHEDULE_FILE = (
PROJECT_ROOT
/ "config"
/ "schedule.yaml"
)
async def main():
config = load_schedule(SCHEDULE_FILE)
controller = TionController(TION_MAC)
tion = TionService(
controller,
poll_interval=5,
)
schedule = ScheduleService(
config,
tion,
check_interval=5,
)
await tion.start()
await schedule.start()
print("Schedule started. Ctrl+C to stop.")
try:
while True:
await asyncio.sleep(5)
if tion.state:
print(
f"{datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")} "
f"power={tion.state.power} "
f"speed={tion.state.fan_speed} "
f"heater={tion.state.heater} "
f"target_temp={tion.state.target_temp} "
f"last_error={tion.last_error} "
)
finally:
await schedule.stop()
await tion.stop()
if __name__ == "__main__":
asyncio.run(main())
-119
View File
@@ -1,119 +0,0 @@
import asyncio
import logging
from datetime import datetime
from pathlib import Path
from app.my_dataclasses import TION_MAC
from app.tion import TionController, TionService
from schedule import (
ScheduleService,
ScheduledSettings,
load_schedule,
)
logging.disable(logging.CRITICAL)
PROJECT_ROOT = Path(__file__).resolve().parents[1]
SCHEDULE_FILE = (
PROJECT_ROOT
/ "config"
/ "schedule.yaml"
)
async def main():
config = load_schedule(SCHEDULE_FILE)
controller = TionController(TION_MAC)
tion = TionService(
controller,
poll_interval=5,
)
schedule = ScheduleService(
config,
tion,
check_interval=5,
)
await tion.start()
await schedule.start()
try:
print()
print("Schedule started")
resolution = schedule.resolve()
print(
f"Current: "
f"{resolution.current.when if resolution.current else None}"
)
print(
f"Next: "
f"{resolution.next.when if resolution.next else None}"
)
# print()
# print("Applying temporary override:")
# print("speed=6")
# print()
#
# await schedule.apply_override(
# ScheduledSettings(
# speed=6,
# )
# )
while True:
await asyncio.sleep(5)
if ( datetime.now() > datetime(2026, 9, 18, 20, 30, 30)
and datetime.now() < datetime(2026, 9, 18, 20, 30, 36) ):
print("Applying temporary override:")
print("heater=True")
print("target_temp=25")
await schedule.apply_override(
ScheduledSettings(
heater=True,
target_temp=25,
)
)
now = datetime.now().strftime(
"%y-%m-%d %H:%M:%S"
)
state = tion.state
if state is None:
print(
f"{now} state=None"
)
continue
print(
f"{now} "
f"power={state.power} "
f"speed={state.fan_speed} "
f"heater={state.heater} "
f"target_temp={state.target_temp} "
f"override={schedule.override_active} "
f"until={schedule.override_until}"
)
finally:
await schedule.stop()
await tion.stop()
if __name__ == "__main__":
asyncio.run(main())
+384
View File
@@ -0,0 +1,384 @@
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())
+395
View File
@@ -0,0 +1,395 @@
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())
-85
View File
@@ -1,85 +0,0 @@
import asyncio
import json
import logging
from app.tion import TionController
from app.my_dataclasses import *
def print_state(title: str, state) -> None:
print()
print("=" * 50)
print(title)
print("=" * 50)
print(json.dumps(
state.to_dict(),
indent=2,
ensure_ascii=False
))
async def main():
# Убираем лишнее логирование
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("bleak").setLevel(logging.WARNING)
logging.getLogger("tion_btle").setLevel(logging.WARNING)
tion = TionController(TION_MAC)
print("Подключение к Tion...")
async with tion:
print(f"Connected: {tion.connected}")
# Читаем исходное состояние
state = await tion.get_state()
print_state("Исходное состояние", state)
# Включаем
state = await tion.power_on()
print_state("После POWER ON", state)
await asyncio.sleep(1)
# Скорость 2
state = await tion.set_speed(2)
print_state("После SPEED 2", state)
await asyncio.sleep(1)
# Скорость 3
state = await tion.set_speed(3)
print_state("После SPEED 3", state)
state = await tion.set_target_temperature(20)
print_state("TARGET TEMP 20°C", state)
state = await tion.set_air_mode("recirculation")
print_state("RECIRCULATION", state)
await asyncio.sleep(3)
state = await tion.set_air_mode("outside")
print_state("RECIRCULATION", state)
await asyncio.sleep(3)
state = await tion.sound_off()
print_state("SOUND OFF", state)
state = await tion.sound_on()
print_state("SOUND ON", state)
state = await tion.light_off()
print_state("LIGHT OFF", state)
state = await tion.light_on()
print_state("LIGHT ON", state)
print()
print(f"Connected after exit: {tion.connected}")
if __name__ == "__main__":
asyncio.run(main())
-84
View File
@@ -1,84 +0,0 @@
import asyncio
import json
import logging
from app.tion import (
TionController,
TionService,
)
from app.my_dataclasses import *
def print_service(service: TionService) -> None:
print()
print("=" * 60)
print(f"Running: {service.running}")
print(f"Online: {service.online}")
print(f"Last seen: {service.last_seen}")
print(f"Last error: {service.last_error}")
if service.state is not None:
print()
print(json.dumps(
service.state.to_dict(),
indent=2,
ensure_ascii=False,
))
async def main():
# Убираем лишнее логирование
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("bleak").setLevel(logging.WARNING)
logging.getLogger("tion_btle").setLevel(logging.WARNING)
controller = TionController(TION_MAC)
service = TionService(
controller,
poll_interval=3,
)
async with service:
print("=== После запуска ===")
print_service(service)
print()
print("Ждём несколько циклов polling...")
await asyncio.sleep(60)
print_service(service)
print()
print("=== Устанавливаем скорость 2 ===")
state = await service.execute(
lambda tion: tion.set_speed(2)
)
print(json.dumps(
state.to_dict(),
indent=2,
ensure_ascii=False,
))
print()
print("=== Устанавливаем температуру 20°C ===")
await service.execute(
lambda tion: tion.set_target_temperature(20)
)
print_service(service)
print()
print("=== После stop ===")
print_service(service)
if __name__ == "__main__":
asyncio.run(main())