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())