diff --git a/homeassistant/components/my_pv/button.py b/homeassistant/components/my_pv/button.py index 9e5e703049c5..6bfb4b7b3eec 100644 --- a/homeassistant/components/my_pv/button.py +++ b/homeassistant/components/my_pv/button.py @@ -1,7 +1,6 @@ -# pylint: disable=duplicate-code -"""Creates Button entities for the my-PV Home Assistant integration.""" +"""Creates Button entities for the my-PV integration.""" -from typing import Any, override +from typing import Any, Final, override from homeassistant.components.button import ( ButtonDeviceClass, @@ -17,6 +16,14 @@ from .const import DOMAIN from .coordinator import MyPVConfigEntry from .entity import MyPVBaseEntity +PARALLEL_UPDATES = 0 + +REBOOT_DEVICE_DESCRIPTION: Final = ButtonEntityDescription( + key="reboot_device", + device_class=ButtonDeviceClass.RESTART, + entity_category=EntityCategory.DIAGNOSTIC, +) + async def async_setup_entry( hass: HomeAssistant, @@ -25,24 +32,10 @@ async def async_setup_entry( ) -> None: """Set up the my-PV button.""" coordinator = config_entry.runtime_data - entities = [] - config = coordinator.device.get_command_configuration("reboot_device") + config = coordinator.device.get_command_configuration(REBOOT_DEVICE_DESCRIPTION.key) if config and config.get("type") in ["any", "fixed"]: - entity_description = ButtonEntityDescription( - key="reboot_device", - device_class=ButtonDeviceClass.RESTART, - entity_category=EntityCategory.DIAGNOSTIC, - ) - entities.append( - MyPVCommandButton( - coordinator, - entity_description, - coordinator.device.serial_number, - ) - ) - - async_add_entities(entities) + async_add_entities([MyPVCommandButton(coordinator, REBOOT_DEVICE_DESCRIPTION)]) class MyPVCommandButton(MyPVBaseEntity, ButtonEntity): diff --git a/homeassistant/components/my_pv/config_flow.py b/homeassistant/components/my_pv/config_flow.py index 36738bb1619e..b1b4512b82db 100644 --- a/homeassistant/components/my_pv/config_flow.py +++ b/homeassistant/components/my_pv/config_flow.py @@ -149,15 +149,15 @@ class MyPVConfigFlow(ConfigFlow, domain=DOMAIN): finally: await device.disconnect() - if not errors and password_needed: - self._host = host - self._device_model = device.model - return await self.async_step_auth() - if not errors: await self.async_set_unique_id(device.serial_number) self._abort_if_unique_id_configured() + if password_needed: + self._host = host + self._device_model = device.model + return await self.async_step_auth() + title = f"my-PV {device.model} {device.serial_number[6:]}" data = { CONF_HOST: host, diff --git a/homeassistant/components/my_pv/coordinator.py b/homeassistant/components/my_pv/coordinator.py index dd42e65f7b2a..60e9ba999532 100644 --- a/homeassistant/components/my_pv/coordinator.py +++ b/homeassistant/components/my_pv/coordinator.py @@ -4,7 +4,7 @@ from collections.abc import Callable, Coroutine from datetime import timedelta import functools import logging -from typing import Any, Final, override +from typing import Any, Concatenate, Final, override from my_pv import MyPVDevice from my_pv.exceptions import ( @@ -26,11 +26,13 @@ _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(seconds=5) -def _my_pv_connection[T]( - func: Callable[..., Coroutine[Any, Any, bool]], -) -> Callable[..., Coroutine[Any, Any, bool]]: +def _handle_device_errors[**P]( + func: Callable[Concatenate[MyPVCoordinator, P], Coroutine[Any, Any, bool]], +) -> Callable[Concatenate[MyPVCoordinator, P], Coroutine[Any, Any, bool]]: + """Connect if needed and handle device errors.""" + @functools.wraps(func) - async def wrapper(self, *args: Any, **kwargs: Any) -> bool: + async def wrapper(self: MyPVCoordinator, *args: P.args, **kwargs: P.kwargs) -> bool: try: if not self.device.connected and not await self.device.connect(): raise HomeAssistantError( @@ -44,6 +46,7 @@ def _my_pv_connection[T]( translation_domain=DOMAIN, translation_key="rate_limiting" ) from exc except MyPVAuthenticationError as exc: + self.config_entry.async_start_reauth(self.hass) raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="auth_error", @@ -52,7 +55,7 @@ def _my_pv_connection[T]( raise HomeAssistantError( translation_domain=DOMAIN, translation_key="device_unavailable", - translation_placeholders={"uri": self.device.uri}, + translation_placeholders={"uri": str(self.device.uri)}, ) from exc return wrapper @@ -141,21 +144,21 @@ class MyPVCoordinator(DataUpdateCoordinator[None]): translation_placeholders={"uri": self.device.uri}, ) from exc - @_my_pv_connection + @_handle_device_errors async def set_setup_value(self, key: str, value: Any) -> bool: """Set a setup value.""" result = await self.device.set_setup_value(key, value) self.async_update_listeners() return result - @_my_pv_connection + @_handle_device_errors async def set_target_temperature(self, temperature: float) -> bool: """Set target temperature.""" result = await self.device.set_target_temperature(temperature) self.async_update_listeners() return result - @_my_pv_connection + @_handle_device_errors async def send_command( self, key: str, value: bool | float | str | None = None ) -> bool: @@ -164,21 +167,21 @@ class MyPVCoordinator(DataUpdateCoordinator[None]): self.async_update_listeners() return result - @_my_pv_connection + @_handle_device_errors async def turn_on(self) -> bool: """Turn on the device.""" result = await self.device.turn_on() self.async_update_listeners() return result - @_my_pv_connection + @_handle_device_errors async def turn_off(self) -> bool: """Turn off the device.""" result = await self.device.turn_off() self.async_update_listeners() return result - @_my_pv_connection + @_handle_device_errors async def update_firmware(self) -> bool: """Send command.""" result = await self.device.update_firmware() diff --git a/homeassistant/components/my_pv/entity.py b/homeassistant/components/my_pv/entity.py index ae7aeb23f846..16d4cc6ff7e5 100644 --- a/homeassistant/components/my_pv/entity.py +++ b/homeassistant/components/my_pv/entity.py @@ -17,13 +17,14 @@ class MyPVBaseEntity(CoordinatorEntity[MyPVCoordinator]): self, coordinator: MyPVCoordinator, entity_description: EntityDescription, - serial_number: str, ) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = coordinator.device_info - self._attr_unique_id = f"{serial_number}-{entity_description.key}" + self._attr_unique_id = ( + f"{coordinator.device.serial_number}-{entity_description.key}" + ) self.entity_description = entity_description @@ -53,7 +54,7 @@ class MyPVDataEntity(MyPVBaseEntity): class MyPVSetupEntity(MyPVBaseEntity): - """The my-PV data entity.""" + """The my-PV setup entity.""" @property @override diff --git a/homeassistant/components/my_pv/manifest.json b/homeassistant/components/my_pv/manifest.json index 75a414e01534..4f45b32cc0e9 100644 --- a/homeassistant/components/my_pv/manifest.json +++ b/homeassistant/components/my_pv/manifest.json @@ -16,7 +16,7 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["my_pv"], - "quality_scale": "bronze", + "quality_scale": "silver", "requirements": ["my-pv==0.0.14"], "zeroconf": ["_mypv._tcp.local."] } diff --git a/homeassistant/components/my_pv/number.py b/homeassistant/components/my_pv/number.py index c588b591ecf9..ce10c4bb8524 100644 --- a/homeassistant/components/my_pv/number.py +++ b/homeassistant/components/my_pv/number.py @@ -1,5 +1,4 @@ -# pylint: disable=duplicate-code -"""Creates Number entities for the my-PV Home Assistant integration.""" +"""Creates Number entities for the my-PV integration.""" from typing import Any, Final, override @@ -14,33 +13,39 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN -from .coordinator import MyPVConfigEntry +from .coordinator import MyPVConfigEntry, MyPVCoordinator from .entity import MyPVSetupEntity -NUMBER_DESCRIPTIONS: Final[dict[str, dict[str, Any]]] = { - "bsttemp": { - "device_class": NumberDeviceClass.TEMPERATURE, - "entity_category": EntityCategory.CONFIG, - "translation_key": "ww1boost", - }, - "ww1boost": { - "device_class": NumberDeviceClass.TEMPERATURE, - "entity_category": EntityCategory.CONFIG, - "translation_key": "ww1boost", - }, - "ww_boost_h": { - "device_class": NumberDeviceClass.TEMPERATURE_DELTA, - "entity_category": EntityCategory.CONFIG, - "enabled": False, - "translation_key": "ww_boost_h", - }, - "ww_targ_h": { - "device_class": NumberDeviceClass.TEMPERATURE_DELTA, - "entity_category": EntityCategory.CONFIG, - "enabled": False, - "translation_key": "ww_targ_h", - }, -} +PARALLEL_UPDATES = 0 + +ENTITY_DESCRIPTIONS: Final[tuple[NumberEntityDescription, ...]] = ( + NumberEntityDescription( + key="bsttemp", + device_class=NumberDeviceClass.TEMPERATURE, + entity_category=EntityCategory.CONFIG, + translation_key="ww1boost", + ), + NumberEntityDescription( + key="ww1boost", + device_class=NumberDeviceClass.TEMPERATURE, + entity_category=EntityCategory.CONFIG, + translation_key="ww1boost", + ), + NumberEntityDescription( + key="ww_boost_h", + device_class=NumberDeviceClass.TEMPERATURE_DELTA, + entity_category=EntityCategory.CONFIG, + entity_registry_enabled_default=False, + translation_key="ww_boost_h", + ), + NumberEntityDescription( + key="ww_targ_h", + device_class=NumberDeviceClass.TEMPERATURE_DELTA, + entity_category=EntityCategory.CONFIG, + entity_registry_enabled_default=False, + translation_key="ww_targ_h", + ), +) async def async_setup_entry( @@ -50,36 +55,38 @@ async def async_setup_entry( ) -> None: """Set up the my-PV number.""" coordinator = config_entry.runtime_data - entities = [] - for key, config in coordinator.device.get_setup_configurations().items(): - if config.get("type") == "number" and key in NUMBER_DESCRIPTIONS: - number_description: dict = NUMBER_DESCRIPTIONS[key] - entity_description = NumberEntityDescription( - key=key, - device_class=number_description.get("device_class"), - entity_category=number_description.get("entity_category"), - translation_key=number_description.get("translation_key"), - native_unit_of_measurement=config.get("unit"), - native_min_value=config.get("min", 0), - native_max_value=config.get("max"), - native_step=config.get("step"), - entity_registry_enabled_default=number_description.get("enabled", True), - ) - entities.append( - MyPVNumber( - coordinator, - entity_description, - coordinator.device.serial_number, - ) - ) - - async_add_entities(entities) + async_add_entities( + MyPVNumber(coordinator, entity_description, config) + for entity_description in ENTITY_DESCRIPTIONS + if ( + config := coordinator.device.get_setup_configuration(entity_description.key) + ) + and config.get("type") == "number" + ) class MyPVNumber(MyPVSetupEntity, NumberEntity): """my-PV number.""" + entity_description: NumberEntityDescription + + def __init__( + self, + coordinator: MyPVCoordinator, + entity_description: NumberEntityDescription, + config: dict[str, Any], + ) -> None: + """Initialize the number.""" + super().__init__(coordinator, entity_description) + + self._attr_native_unit_of_measurement = config.get("unit") + self._attr_native_min_value = config.get("min", 0) + if (max_value := config.get("max")) is not None: + self._attr_native_max_value = max_value + if (step := config.get("step")) is not None: + self._attr_native_step = step + @property @override def native_value(self) -> float | None: diff --git a/homeassistant/components/my_pv/quality_scale.yaml b/homeassistant/components/my_pv/quality_scale.yaml index 87a42b5e1a2c..7936f8ed9fbe 100644 --- a/homeassistant/components/my_pv/quality_scale.yaml +++ b/homeassistant/components/my_pv/quality_scale.yaml @@ -40,10 +40,10 @@ rules: docs-installation-parameters: done entity-unavailable: done integration-owner: done - log-when-unavailable: todo - parallel-updates: todo + log-when-unavailable: done + parallel-updates: done reauthentication-flow: done - test-coverage: todo + test-coverage: done # Gold tier rules devices: done @@ -51,25 +51,21 @@ rules: discovery-update-info: done discovery: done docs-data-update: done - docs-examples: todo - docs-known-limitations: todo + docs-examples: done + docs-known-limitations: done docs-supported-devices: done - docs-supported-functions: todo - docs-troubleshooting: todo - docs-use-cases: todo - dynamic-devices: todo + docs-supported-functions: done + docs-troubleshooting: done + docs-use-cases: done + dynamic-devices: + status: exempt + comment: Each config entry represents a single device; the integration does not manage a dynamic set of devices. entity-category: done - entity-device-class: - status: exempt - comment: The water heater entity does not provide a device class. - entity-disabled-by-default: todo - entity-translations: - status: exempt - comment: The only entity uses the device name. + entity-device-class: done + entity-disabled-by-default: done + entity-translations: done exception-translations: done - icon-translations: - status: exempt - comment: There are no entities that require icons. + icon-translations: done reconfiguration-flow: todo repair-issues: status: exempt diff --git a/homeassistant/components/my_pv/select.py b/homeassistant/components/my_pv/select.py index f5700dfd1b6a..842d69a3022c 100644 --- a/homeassistant/components/my_pv/select.py +++ b/homeassistant/components/my_pv/select.py @@ -1,6 +1,6 @@ -"""Creates Select entities for the my-PV Home Assistant integration.""" +"""Creates Select entities for the my-PV integration.""" -from typing import override +from typing import Any, Final, override from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.const import EntityCategory @@ -9,9 +9,19 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN -from .coordinator import MyPVConfigEntry +from .coordinator import MyPVConfigEntry, MyPVCoordinator from .entity import MyPVSetupEntity +PARALLEL_UPDATES = 0 + +ENTITY_DESCRIPTIONS: Final[tuple[SelectEntityDescription, ...]] = ( + SelectEntityDescription( + key="bstmode", + entity_category=EntityCategory.CONFIG, + translation_key="bstmode", + ), +) + async def async_setup_entry( hass: HomeAssistant, @@ -20,30 +30,33 @@ async def async_setup_entry( ) -> None: """Set up the my-PV select.""" coordinator = config_entry.runtime_data - entities = [] - config = coordinator.device.get_setup_configuration("bstmode") - if config and config.get("type") == "enumeration": - entity_description = SelectEntityDescription( - key="bstmode", - entity_category=EntityCategory.CONFIG, - translation_key="bstmode", - options=list(config.get("options", {}).keys()), + async_add_entities( + MyPVSelect(coordinator, entity_description, config) + for entity_description in ENTITY_DESCRIPTIONS + if ( + config := coordinator.device.get_setup_configuration(entity_description.key) ) - entities.append( - MyPVSelect( - coordinator, - entity_description, - coordinator.device.serial_number, - ) - ) - - async_add_entities(entities) + and config.get("type") == "enumeration" + ) class MyPVSelect(MyPVSetupEntity, SelectEntity): """my-PV select.""" + entity_description: SelectEntityDescription + + def __init__( + self, + coordinator: MyPVCoordinator, + entity_description: SelectEntityDescription, + config: dict[str, Any], + ) -> None: + """Initialize the select.""" + super().__init__(coordinator, entity_description) + + self._attr_options = list(config.get("options", {}).keys()) + @property @override def current_option(self) -> str | None: diff --git a/homeassistant/components/my_pv/sensor.py b/homeassistant/components/my_pv/sensor.py index 148f32b5498e..636d31c19870 100644 --- a/homeassistant/components/my_pv/sensor.py +++ b/homeassistant/components/my_pv/sensor.py @@ -1,4 +1,4 @@ -"""Creates Sensor entities for the my-PV Home Assistant integration.""" +"""Creates Sensor entities for the my-PV integration.""" from datetime import date, datetime from decimal import Decimal @@ -15,138 +15,181 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType -from .coordinator import MyPVConfigEntry +from .coordinator import MyPVConfigEntry, MyPVCoordinator from .entity import MyPVDataEntity -SENSOR_DESCRIPTIONS: Final[dict[str, dict[str, Any]]] = { - "cur_eth_mode": { - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "cur_eth_mode", - }, - "curr_l1": { - "device_class": SensorDeviceClass.CURRENT, - "translation_key": "curr_l1", - }, - "curr_l2": { - "device_class": SensorDeviceClass.CURRENT, - "translation_key": "curr_l2", - }, - "curr_l3": { - "device_class": SensorDeviceClass.CURRENT, - "translation_key": "curr_l3", - }, - "curr_mains": { - "device_class": SensorDeviceClass.CURRENT, - "suggested_display_precision": 1, - "translation_key": "curr_l1", - }, - "freq": { - "device_class": SensorDeviceClass.FREQUENCY, - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "suggested_display_precision": 2, - "translation_key": "freq", - }, - "power": {"device_class": SensorDeviceClass.POWER}, - "power_ac9": {"device_class": SensorDeviceClass.POWER}, - "power_act": {"device_class": SensorDeviceClass.POWER}, - "power_elwa2": {"device_class": SensorDeviceClass.POWER}, - "power_grid": {"device_class": SensorDeviceClass.POWER}, - "power_solar": { - "device_class": SensorDeviceClass.POWER, - "translation_key": "power_solar", - }, - "screen_mode_flag": {"translation_key": "screen_mode_flag"}, - "temp1": { - "device_class": SensorDeviceClass.TEMPERATURE, - "suggested_display_precision": 1, - "translation_key": "temp1", - }, - "temp2": { - "device_class": SensorDeviceClass.TEMPERATURE, - "suggested_display_precision": 1, - "translation_key": "temp2", - }, - "temp3": { - "device_class": SensorDeviceClass.TEMPERATURE, - "suggested_display_precision": 1, - "translation_key": "temp3", - }, - "temp4": { - "device_class": SensorDeviceClass.TEMPERATURE, - "suggested_display_precision": 1, - "translation_key": "temp4", - }, - "temp_ps": { - "device_class": SensorDeviceClass.TEMPERATURE, - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "suggested_display_precision": 1, - "translation_key": "temp_ps", - }, - "uptime": { - "device_class": SensorDeviceClass.DURATION, - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "state_class": SensorStateClass.TOTAL_INCREASING, - "translation_key": "uptime", - }, - "volt_l1": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "volt_l1", - }, - "volt_l2": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "volt_l2", - }, - "volt_l3": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "volt_l3", - }, - "volt_mains": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "volt_l1", - }, - "volt_mains_l1": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "suggested_display_precision": 1, - "translation_key": "volt_l1", - }, - "volt_mains_l2": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "suggested_display_precision": 1, - "translation_key": "volt_l2", - }, - "volt_mains_l3": { - "device_class": SensorDeviceClass.VOLTAGE, - "entity_category": EntityCategory.DIAGNOSTIC, - "suggested_display_precision": 1, - "translation_key": "volt_l3", - }, - "volt_solar": { - "device_class": SensorDeviceClass.VOLTAGE, - "translation_key": "volt_solar", - }, - "wifi_signal": { - "device_class": SensorDeviceClass.SIGNAL_STRENGTH, - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "wifi_signal", - }, - "wifi_signal_strength": { - "device_class": SensorDeviceClass.SIGNAL_STRENGTH, - "enabled": False, - "entity_category": EntityCategory.DIAGNOSTIC, - "translation_key": "wifi_signal_strength", - }, -} +PARALLEL_UPDATES = 0 + +ENTITY_DESCRIPTIONS: Final[tuple[SensorEntityDescription, ...]] = ( + SensorEntityDescription( + key="cur_eth_mode", + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + translation_key="cur_eth_mode", + ), + SensorEntityDescription( + key="curr_l1", + device_class=SensorDeviceClass.CURRENT, + translation_key="curr_l1", + ), + SensorEntityDescription( + key="curr_l2", + device_class=SensorDeviceClass.CURRENT, + translation_key="curr_l2", + ), + SensorEntityDescription( + key="curr_l3", + device_class=SensorDeviceClass.CURRENT, + translation_key="curr_l3", + ), + SensorEntityDescription( + key="curr_mains", + device_class=SensorDeviceClass.CURRENT, + suggested_display_precision=1, + translation_key="curr_l1", + ), + SensorEntityDescription( + key="freq", + device_class=SensorDeviceClass.FREQUENCY, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + suggested_display_precision=2, + translation_key="freq", + ), + SensorEntityDescription( + key="power", + device_class=SensorDeviceClass.POWER, + ), + SensorEntityDescription( + key="power_ac9", + device_class=SensorDeviceClass.POWER, + ), + SensorEntityDescription( + key="power_act", + device_class=SensorDeviceClass.POWER, + ), + SensorEntityDescription( + key="power_elwa2", + device_class=SensorDeviceClass.POWER, + ), + SensorEntityDescription( + key="power_grid", + device_class=SensorDeviceClass.POWER, + ), + SensorEntityDescription( + key="power_solar", + device_class=SensorDeviceClass.POWER, + translation_key="power_solar", + ), + SensorEntityDescription( + key="screen_mode_flag", + translation_key="screen_mode_flag", + ), + SensorEntityDescription( + key="temp1", + device_class=SensorDeviceClass.TEMPERATURE, + suggested_display_precision=1, + translation_key="temp1", + ), + SensorEntityDescription( + key="temp2", + device_class=SensorDeviceClass.TEMPERATURE, + suggested_display_precision=1, + translation_key="temp2", + ), + SensorEntityDescription( + key="temp3", + device_class=SensorDeviceClass.TEMPERATURE, + suggested_display_precision=1, + translation_key="temp3", + ), + SensorEntityDescription( + key="temp4", + device_class=SensorDeviceClass.TEMPERATURE, + suggested_display_precision=1, + translation_key="temp4", + ), + SensorEntityDescription( + key="temp_ps", + device_class=SensorDeviceClass.TEMPERATURE, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + suggested_display_precision=1, + translation_key="temp_ps", + ), + SensorEntityDescription( + key="uptime", + device_class=SensorDeviceClass.DURATION, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + state_class=SensorStateClass.TOTAL_INCREASING, + translation_key="uptime", + ), + SensorEntityDescription( + key="volt_l1", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + translation_key="volt_l1", + ), + SensorEntityDescription( + key="volt_l2", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + translation_key="volt_l2", + ), + SensorEntityDescription( + key="volt_l3", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + translation_key="volt_l3", + ), + SensorEntityDescription( + key="volt_mains", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + translation_key="volt_l1", + ), + SensorEntityDescription( + key="volt_mains_l1", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + suggested_display_precision=1, + translation_key="volt_l1", + ), + SensorEntityDescription( + key="volt_mains_l2", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + suggested_display_precision=1, + translation_key="volt_l2", + ), + SensorEntityDescription( + key="volt_mains_l3", + device_class=SensorDeviceClass.VOLTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + suggested_display_precision=1, + translation_key="volt_l3", + ), + SensorEntityDescription( + key="volt_solar", + device_class=SensorDeviceClass.VOLTAGE, + translation_key="volt_solar", + ), + SensorEntityDescription( + key="wifi_signal", + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + translation_key="wifi_signal", + ), + SensorEntityDescription( + key="wifi_signal_strength", + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + translation_key="wifi_signal_strength", + ), +) async def async_setup_entry( @@ -156,72 +199,58 @@ async def async_setup_entry( ) -> None: """Set up the my-PV sensor.""" coordinator = config_entry.runtime_data - entities = [] - for key, config in coordinator.device.get_data_configurations().items(): - if config.get("type") != "boolean" and key in SENSOR_DESCRIPTIONS: - sensor_description: dict = SENSOR_DESCRIPTIONS[key] - - device_class = None - options = None - state_class = None - if config.get("type") == "enumeration": - device_class = SensorDeviceClass.ENUM - options = list(config["options"].keys()) - elif config.get("type") == "string": - device_class = sensor_description.get("device_class") - else: - device_class = sensor_description.get("device_class") - state_class = sensor_description.get( - "state_class", SensorStateClass.MEASUREMENT - ) - - translation_key: str | None = sensor_description.get("translation_key") - if ( - ( - key - in ( - "curr_mains", - "curr_l1", - ) - and not coordinator.device.supports_data("curr_l2") - ) - or ( - key in ("volt_mains", "volt_mains_l1", "volt_l1") - and not coordinator.device.supports_data("volt_l2") - and not coordinator.device.supports_data("volt_mains_l2") - ) - or (key == "temp1" and not coordinator.device.supports_data("temp2")) - ): - translation_key = None - - entity_description = SensorEntityDescription( - key=key, - device_class=device_class, - entity_category=sensor_description.get("entity_category"), - translation_key=translation_key, - native_unit_of_measurement=config.get("unit"), - options=options, - state_class=state_class, - suggested_display_precision=sensor_description.get( - "suggested_display_precision" - ), - entity_registry_enabled_default=sensor_description.get("enabled", True), - ) - entities.append( - MyPVSensor( - coordinator, - entity_description, - coordinator.device.serial_number, - ) - ) - - async_add_entities(entities) + async_add_entities( + MyPVSensor(coordinator, entity_description, config) + for entity_description in ENTITY_DESCRIPTIONS + if (config := coordinator.device.get_data_configuration(entity_description.key)) + and config.get("type") != "boolean" + ) class MyPVSensor(MyPVDataEntity, SensorEntity): """Base my-PV Sensor.""" + entity_description: SensorEntityDescription + + def __init__( + self, + coordinator: MyPVCoordinator, + entity_description: SensorEntityDescription, + config: dict[str, Any], + ) -> None: + """Initialize the sensor.""" + super().__init__(coordinator, entity_description) + + self._attr_native_unit_of_measurement = config.get("unit") + + match config.get("type"): + case "enumeration": + self._attr_device_class = SensorDeviceClass.ENUM + self._attr_options = list(config["options"].keys()) + self._attr_state_class = None + case "string": + self._attr_state_class = None + case _: + self._attr_state_class = ( + entity_description.state_class or SensorStateClass.MEASUREMENT + ) + + # On single phase devices, or devices with a single temperature sensor, + # use the device class name instead of a numbered name. + device = coordinator.device + key = entity_description.key + if ( + (key in ("curr_mains", "curr_l1") and not device.supports_data("curr_l2")) + or ( + key in ("volt_mains", "volt_mains_l1", "volt_l1") + and not device.supports_data("volt_l2") + and not device.supports_data("volt_mains_l2") + ) + or (key == "temp1" and not device.supports_data("temp2")) + ): + self._attr_translation_key = None + @property @override def native_value(self) -> StateType | date | datetime | Decimal: diff --git a/homeassistant/components/my_pv/switch.py b/homeassistant/components/my_pv/switch.py index 45458c030b82..293b09063c2c 100644 --- a/homeassistant/components/my_pv/switch.py +++ b/homeassistant/components/my_pv/switch.py @@ -1,4 +1,4 @@ -"""Creates Switch entities for the my-PV Home Assistant integration.""" +"""Creates Switch entities for the my-PV integration.""" from typing import Any, Final, override @@ -18,18 +18,21 @@ from .const import DOMAIN from .coordinator import MyPVConfigEntry from .entity import MyPVBaseEntity, MyPVSetupEntity -ENTITY_DESCRIPTIONS: Final[dict[str, SwitchEntityDescription]] = { - "bstmode": SwitchEntityDescription( +PARALLEL_UPDATES = 0 + +ENTITY_DESCRIPTIONS: Final[tuple[SwitchEntityDescription, ...]] = ( + SwitchEntityDescription( key="bstmode", entity_category=EntityCategory.CONFIG, device_class=SwitchDeviceClass.SWITCH, translation_key="bstmode", ), - "devmode": SwitchEntityDescription( - key="devmode", - device_class=SwitchDeviceClass.SWITCH, - ), -} +) + +DEVMODE_DESCRIPTION: Final = SwitchEntityDescription( + key="devmode", + device_class=SwitchDeviceClass.SWITCH, +) async def async_setup_entry( @@ -39,17 +42,14 @@ async def async_setup_entry( ) -> None: """Set up the my-PV switch.""" coordinator = config_entry.runtime_data - entities: list[SwitchEntity] = [] - - config = coordinator.device.get_setup_configuration("bstmode") - if config and config.get("type") == "boolean": - entities.append( - MyPVSwitch( - coordinator, - ENTITY_DESCRIPTIONS["bstmode"], - coordinator.device.serial_number, - ) + entities: list[SwitchEntity] = [ + MyPVSwitch(coordinator, entity_description) + for entity_description in ENTITY_DESCRIPTIONS + if ( + config := coordinator.device.get_setup_configuration(entity_description.key) ) + and config.get("type") == "boolean" + ] if ( coordinator.device.supports_main_mode(MyPVDeviceMainMode.HOT_WATER) @@ -58,8 +58,7 @@ async def async_setup_entry( entities.append( MyPVWaterHeaterSwitch( coordinator, - ENTITY_DESCRIPTIONS["devmode"], - coordinator.device.serial_number, + DEVMODE_DESCRIPTION, ) ) diff --git a/homeassistant/components/my_pv/update.py b/homeassistant/components/my_pv/update.py index 4c3cddf09447..0534dd1711ab 100644 --- a/homeassistant/components/my_pv/update.py +++ b/homeassistant/components/my_pv/update.py @@ -1,7 +1,6 @@ -"""Creates Update entities for the my-PV Home Assistant integration.""" +"""Creates Update entities for the my-PV integration.""" -import logging -from typing import Any, override +from typing import Any, Final, override from homeassistant.components.update import ( UpdateDeviceClass, @@ -17,7 +16,12 @@ from .const import DOMAIN from .coordinator import MyPVConfigEntry from .entity import MyPVBaseEntity -_LOGGER = logging.getLogger(__name__) +PARALLEL_UPDATES = 0 + +FIRMWARE_UPDATE_DESCRIPTION: Final = UpdateEntityDescription( + key="firmware_update", + device_class=UpdateDeviceClass.FIRMWARE, +) async def async_setup_entry( @@ -27,25 +31,19 @@ async def async_setup_entry( ) -> None: """Set up the my-PV update.""" coordinator = config_entry.runtime_data - entities = [] if ( coordinator.device.firmware_version and coordinator.device.latest_firmware_version ): - entity_description = UpdateEntityDescription( - key="firmware_update", - device_class=UpdateDeviceClass.FIRMWARE, + async_add_entities( + [ + MyPVFirmwareUpdate( + coordinator, + FIRMWARE_UPDATE_DESCRIPTION, + ) + ] ) - entities.append( - MyPVFirmwareUpdate( - coordinator, - entity_description, - coordinator.device.serial_number, - ) - ) - - async_add_entities(entities) class MyPVFirmwareUpdate(MyPVBaseEntity, UpdateEntity): diff --git a/homeassistant/components/my_pv/water_heater.py b/homeassistant/components/my_pv/water_heater.py index 6d00811f51a5..cf3590a00cee 100644 --- a/homeassistant/components/my_pv/water_heater.py +++ b/homeassistant/components/my_pv/water_heater.py @@ -1,4 +1,4 @@ -"""Creates Water Heater entities for the my-PV Home Assistant integration.""" +"""Creates Water Heater entities for the my-PV integration.""" from typing import Any, override @@ -19,6 +19,8 @@ from .const import DOMAIN from .coordinator import MyPVConfigEntry, MyPVCoordinator from .entity import MyPVBaseEntity +PARALLEL_UPDATES = 0 + async def async_setup_entry( hass: HomeAssistant, @@ -27,26 +29,21 @@ async def async_setup_entry( ) -> None: """Set up the my-PV water heater.""" coordinator = config_entry.runtime_data - entities = [] if ( coordinator.device.supports_main_mode(MyPVDeviceMainMode.HOT_WATER) and coordinator.device.current_temperature is not None and (configuration := coordinator.device.get_setup_configuration("ww1target")) ): - entity_description = WaterHeaterEntityDescription( - key="temp1", + async_add_entities( + [ + MyPVWaterHeater( + coordinator, + WaterHeaterEntityDescription(key="temp1"), + configuration=configuration, + ) + ] ) - entities.append( - MyPVWaterHeater( - coordinator, - entity_description, - coordinator.device.serial_number, - configuration=configuration, - ) - ) - - async_add_entities(entities) class MyPVWaterHeater(MyPVBaseEntity, WaterHeaterEntity): @@ -64,11 +61,10 @@ class MyPVWaterHeater(MyPVBaseEntity, WaterHeaterEntity): self, coordinator: MyPVCoordinator, entity_description: WaterHeaterEntityDescription, - serial_number: str, configuration: dict[str, Any], ) -> None: """Initialize the water_heater.""" - super().__init__(coordinator, entity_description, serial_number) + super().__init__(coordinator, entity_description) self._attr_target_temperature_step = configuration["step"] self._attr_native_temperature_unit = configuration["unit"] diff --git a/tests/components/my_pv/conftest.py b/tests/components/my_pv/conftest.py index a0406dade594..e17f740b7384 100644 --- a/tests/components/my_pv/conftest.py +++ b/tests/components/my_pv/conftest.py @@ -161,6 +161,7 @@ def mock_my_pv_client( client.is_on = True client.send_command = AsyncMock(return_value=True) client.get_data_configurations = Mock(return_value=DATA_CONFIGURATION) + client.get_data_configuration = Mock(side_effect=DATA_CONFIGURATION.get) client.get_data_value = Mock(side_effect=_data_value_lookup) client.supports_data = Mock(side_effect=DATA_CONFIGURATION.__contains__)