|
| 1 | +"""Support for Qbus thermostat.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from qbusmqttapi.const import KEY_PROPERTIES_REGIME, KEY_PROPERTIES_SET_TEMPERATURE |
| 7 | +from qbusmqttapi.discovery import QbusMqttOutput |
| 8 | +from qbusmqttapi.state import QbusMqttThermoState, StateType |
| 9 | + |
| 10 | +from homeassistant.components.climate import ( |
| 11 | + ClimateEntity, |
| 12 | + ClimateEntityFeature, |
| 13 | + HVACAction, |
| 14 | + HVACMode, |
| 15 | +) |
| 16 | +from homeassistant.components.mqtt import ReceiveMessage, client as mqtt |
| 17 | +from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature |
| 18 | +from homeassistant.core import HomeAssistant |
| 19 | +from homeassistant.exceptions import ServiceValidationError |
| 20 | +from homeassistant.helpers.debounce import Debouncer |
| 21 | +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback |
| 22 | + |
| 23 | +from .const import DOMAIN |
| 24 | +from .coordinator import QbusConfigEntry |
| 25 | +from .entity import QbusEntity, add_new_outputs |
| 26 | + |
| 27 | +PARALLEL_UPDATES = 0 |
| 28 | + |
| 29 | +STATE_REQUEST_DELAY = 2 |
| 30 | + |
| 31 | +_LOGGER = logging.getLogger(__name__) |
| 32 | + |
| 33 | + |
| 34 | +async def async_setup_entry( |
| 35 | + hass: HomeAssistant, |
| 36 | + entry: QbusConfigEntry, |
| 37 | + async_add_entities: AddConfigEntryEntitiesCallback, |
| 38 | +) -> None: |
| 39 | + """Set up climate entities.""" |
| 40 | + |
| 41 | + coordinator = entry.runtime_data |
| 42 | + added_outputs: list[QbusMqttOutput] = [] |
| 43 | + |
| 44 | + def _check_outputs() -> None: |
| 45 | + add_new_outputs( |
| 46 | + coordinator, |
| 47 | + added_outputs, |
| 48 | + lambda output: output.type == "thermo", |
| 49 | + QbusClimate, |
| 50 | + async_add_entities, |
| 51 | + ) |
| 52 | + |
| 53 | + _check_outputs() |
| 54 | + entry.async_on_unload(coordinator.async_add_listener(_check_outputs)) |
| 55 | + |
| 56 | + |
| 57 | +class QbusClimate(QbusEntity, ClimateEntity): |
| 58 | + """Representation of a Qbus climate entity.""" |
| 59 | + |
| 60 | + _attr_hvac_modes = [HVACMode.HEAT] |
| 61 | + _attr_supported_features = ( |
| 62 | + ClimateEntityFeature.PRESET_MODE | ClimateEntityFeature.TARGET_TEMPERATURE |
| 63 | + ) |
| 64 | + _attr_temperature_unit = UnitOfTemperature.CELSIUS |
| 65 | + |
| 66 | + def __init__(self, mqtt_output: QbusMqttOutput) -> None: |
| 67 | + """Initialize climate entity.""" |
| 68 | + |
| 69 | + super().__init__(mqtt_output) |
| 70 | + |
| 71 | + self._attr_hvac_action = HVACAction.IDLE |
| 72 | + self._attr_hvac_mode = HVACMode.HEAT |
| 73 | + |
| 74 | + set_temp: dict[str, Any] = mqtt_output.properties.get( |
| 75 | + KEY_PROPERTIES_SET_TEMPERATURE, {} |
| 76 | + ) |
| 77 | + current_regime: dict[str, Any] = mqtt_output.properties.get( |
| 78 | + KEY_PROPERTIES_REGIME, {} |
| 79 | + ) |
| 80 | + |
| 81 | + self._attr_min_temp: float = set_temp.get("min", 0) |
| 82 | + self._attr_max_temp: float = set_temp.get("max", 35) |
| 83 | + self._attr_target_temperature_step: float = set_temp.get("step", 0.5) |
| 84 | + self._attr_preset_modes: list[str] = current_regime.get("enumValues", []) |
| 85 | + self._attr_preset_mode: str = ( |
| 86 | + self._attr_preset_modes[0] if len(self._attr_preset_modes) > 0 else "" |
| 87 | + ) |
| 88 | + |
| 89 | + self._request_state_debouncer: Debouncer | None = None |
| 90 | + |
| 91 | + async def async_added_to_hass(self) -> None: |
| 92 | + """Run when entity about to be added to hass.""" |
| 93 | + self._request_state_debouncer = Debouncer( |
| 94 | + self.hass, |
| 95 | + _LOGGER, |
| 96 | + cooldown=STATE_REQUEST_DELAY, |
| 97 | + immediate=False, |
| 98 | + function=self._async_request_state, |
| 99 | + ) |
| 100 | + await super().async_added_to_hass() |
| 101 | + |
| 102 | + async def async_set_preset_mode(self, preset_mode: str) -> None: |
| 103 | + """Set new target preset mode.""" |
| 104 | + |
| 105 | + if preset_mode not in self._attr_preset_modes: |
| 106 | + raise ServiceValidationError( |
| 107 | + translation_domain=DOMAIN, |
| 108 | + translation_key="invalid_preset", |
| 109 | + translation_placeholders={ |
| 110 | + "preset": preset_mode, |
| 111 | + "options": ", ".join(self._attr_preset_modes), |
| 112 | + }, |
| 113 | + ) |
| 114 | + |
| 115 | + state = QbusMqttThermoState(id=self._mqtt_output.id, type=StateType.STATE) |
| 116 | + state.write_regime(preset_mode) |
| 117 | + |
| 118 | + await self._async_publish_output_state(state) |
| 119 | + |
| 120 | + async def async_set_temperature(self, **kwargs: Any) -> None: |
| 121 | + """Set new target temperature.""" |
| 122 | + temperature = kwargs.get(ATTR_TEMPERATURE) |
| 123 | + |
| 124 | + if temperature is not None and isinstance(temperature, float): |
| 125 | + state = QbusMqttThermoState(id=self._mqtt_output.id, type=StateType.STATE) |
| 126 | + state.write_set_temperature(temperature) |
| 127 | + |
| 128 | + await self._async_publish_output_state(state) |
| 129 | + |
| 130 | + async def _state_received(self, msg: ReceiveMessage) -> None: |
| 131 | + state = self._message_factory.parse_output_state( |
| 132 | + QbusMqttThermoState, msg.payload |
| 133 | + ) |
| 134 | + |
| 135 | + if state is None: |
| 136 | + return |
| 137 | + |
| 138 | + if preset_mode := state.read_regime(): |
| 139 | + self._attr_preset_mode = preset_mode |
| 140 | + |
| 141 | + if current_temperature := state.read_current_temperature(): |
| 142 | + self._attr_current_temperature = current_temperature |
| 143 | + |
| 144 | + if target_temperature := state.read_set_temperature(): |
| 145 | + self._attr_target_temperature = target_temperature |
| 146 | + |
| 147 | + self._set_hvac_action() |
| 148 | + |
| 149 | + # When the state type is "event", the payload only contains the changed |
| 150 | + # property. Request the state to get the full payload. However, changing |
| 151 | + # temperature step by step could cause a flood of state requests, so we're |
| 152 | + # holding off a few seconds before requesting the full state. |
| 153 | + if state.type == StateType.EVENT: |
| 154 | + assert self._request_state_debouncer is not None |
| 155 | + await self._request_state_debouncer.async_call() |
| 156 | + |
| 157 | + self.async_schedule_update_ha_state() |
| 158 | + |
| 159 | + def _set_hvac_action(self) -> None: |
| 160 | + if self.target_temperature is None or self.current_temperature is None: |
| 161 | + self._attr_hvac_action = HVACAction.IDLE |
| 162 | + return |
| 163 | + |
| 164 | + self._attr_hvac_action = ( |
| 165 | + HVACAction.HEATING |
| 166 | + if self.target_temperature > self.current_temperature |
| 167 | + else HVACAction.IDLE |
| 168 | + ) |
| 169 | + |
| 170 | + async def _async_request_state(self) -> None: |
| 171 | + request = self._message_factory.create_state_request([self._mqtt_output.id]) |
| 172 | + await mqtt.async_publish(self.hass, request.topic, request.payload) |
0 commit comments