From bd98fc231d6fc9ec5a2aa19fcebfc747c6d7c5ba Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 29 Dec 2021 14:52:08 +0100 Subject: [PATCH] Gracefully handle unknown HVAC mode in Tuya (#62984) Co-authored-by: Martin Hjelmare --- homeassistant/components/tuya/climate.py | 24 +++++++++++++++++++++--- homeassistant/components/tuya/const.py | 2 ++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/tuya/climate.py b/homeassistant/components/tuya/climate.py index cb70fc5515a..83d635701db 100644 --- a/homeassistant/components/tuya/climate.py +++ b/homeassistant/components/tuya/climate.py @@ -32,7 +32,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import HomeAssistantTuyaData from .base import EnumTypeData, IntegerTypeData, TuyaEntity -from .const import DOMAIN, TUYA_DISCOVERY_NEW, DPCode +from .const import DOMAIN, LOGGER, TUYA_DISCOVERY_NEW, DPCode TUYA_HVAC_TO_HA = { "auto": HVAC_MODE_HEAT_COOL, @@ -298,6 +298,21 @@ class TuyaClimateEntity(TuyaEntity, ClimateEntity): if DPCode.SWITCH_VERTICAL in device.function: self._attr_swing_modes.append(SWING_VERTICAL) + async def async_added_to_hass(self) -> None: + """Call when entity is added to hass.""" + await super().async_added_to_hass() + + # Log unknown modes + if DPCode.MODE in self.device.function: + data_type = EnumTypeData.from_json(self.device.function[DPCode.MODE].values) + for tuya_mode in data_type.range: + if tuya_mode not in TUYA_HVAC_TO_HA: + LOGGER.warning( + "Unknown HVAC mode '%s' for device %s; assuming it as off", + tuya_mode, + self.device.name, + ) + def set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" commands = [{"code": DPCode.SWITCH, "value": hvac_mode != HVAC_MODE_OFF}] @@ -436,8 +451,11 @@ class TuyaClimateEntity(TuyaEntity, ClimateEntity): return self.entity_description.switch_only_hvac_mode return HVAC_MODE_OFF - if self.device.status.get(DPCode.MODE) is not None: - return TUYA_HVAC_TO_HA[self.device.status[DPCode.MODE]] + if ( + mode := self.device.status.get(DPCode.MODE) + ) is not None and mode in TUYA_HVAC_TO_HA: + return TUYA_HVAC_TO_HA[mode] + return HVAC_MODE_OFF @property diff --git a/homeassistant/components/tuya/const.py b/homeassistant/components/tuya/const.py index f19109e4104..4911f5e83a1 100644 --- a/homeassistant/components/tuya/const.py +++ b/homeassistant/components/tuya/const.py @@ -4,6 +4,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass, field from enum import Enum +import logging from tuya_iot import TuyaCloudOpenAPIEndpoint @@ -39,6 +40,7 @@ from homeassistant.const import ( ) DOMAIN = "tuya" +LOGGER = logging.getLogger(__package__) CONF_AUTH_TYPE = "auth_type" CONF_PROJECT_TYPE = "tuya_project_type"