diff --git a/homeassistant/components/sofar/helpers.py b/homeassistant/components/sofar/helpers.py index a16e388a6b47..88d065f9e64a 100644 --- a/homeassistant/components/sofar/helpers.py +++ b/homeassistant/components/sofar/helpers.py @@ -1,6 +1,7 @@ """Helpers for the Sofar integration.""" from collections.abc import Mapping +from enum import IntEnum from typing import Any from modbus_connection import ModbusSerialParams, ModbusTcpParams @@ -19,3 +20,18 @@ def create_modbus_params( device=data[CONF_DEVICE], baudrate=data[CONF_BAUDRATE] ) return ModbusTcpParams(host=data[CONF_HOST], port=data[CONF_PORT]) + + +def option_slug(member: IntEnum) -> str: + """Return the option slug of a device enum member.""" + return member.name.lower() + + +def enum_options(enum_type: type[IntEnum]) -> list[str]: + """Return the option slugs of a device enum.""" + return [option_slug(member) for member in enum_type] + + +def enum_member[E: IntEnum](enum_type: type[E], option: str) -> E: + """Return the device enum member an option slug names.""" + return enum_type[option.upper()] diff --git a/homeassistant/components/sofar/select.py b/homeassistant/components/sofar/select.py index ef70ac32ade4..6687e3087342 100644 --- a/homeassistant/components/sofar/select.py +++ b/homeassistant/components/sofar/select.py @@ -15,22 +15,17 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import SofarConfigEntry from .entity import SofarEntity, SofarEntityDescription, async_remove_unserved_entities +from .helpers import enum_member, enum_options, option_slug PARALLEL_UPDATES = 1 -def _enum_options(enum_type: type[IntEnum]) -> list[str]: - """The select options a device enum maps to.""" - return [member.name.lower() for member in enum_type] - - @dataclass(frozen=True, kw_only=True) class SofarSelectEntityDescription(SelectEntityDescription, SofarEntityDescription): """Describe a Sofar select entity.""" - options_enum: type[IntEnum] value_fn: Callable[[SofarInverter], IntEnum | None] - write_fn: Callable[[SofarInverter, int], Awaitable[None]] + write_fn: Callable[[SofarInverter, str], Awaitable[None]] SELECT_DESCRIPTIONS: tuple[SofarSelectEntityDescription, ...] = ( @@ -38,22 +33,20 @@ SELECT_DESCRIPTIONS: tuple[SofarSelectEntityDescription, ...] = ( key="charger_use_mode", component="charger", translation_key="charger_use_mode", - options=_enum_options(ChargerUseMode), - options_enum=ChargerUseMode, + options=enum_options(ChargerUseMode), value_fn=lambda device: device.charger.charger_use_mode, - write_fn=lambda device, value: device.charger.async_write_mode( - ChargerUseMode(value) + write_fn=lambda device, option: device.charger.async_write_mode( + enum_member(ChargerUseMode, option) ), ), SofarSelectEntityDescription( key="eps_control", component="eps", translation_key="eps_control", - options=_enum_options(EpsControlMode), - options_enum=EpsControlMode, + options=enum_options(EpsControlMode), value_fn=lambda device: device.eps.eps_control, - write_fn=lambda device, value: device.eps.async_write_control( - EpsControlMode(value) + write_fn=lambda device, option: device.eps.async_write_control( + enum_member(EpsControlMode, option) ), ), ) @@ -85,11 +78,10 @@ class SofarSelect(SofarEntity, SelectEntity): def current_option(self) -> str | None: """Return the currently selected option.""" value = self.entity_description.value_fn(self.coordinator.device) - return value.name.lower() if value is not None else None + return option_slug(value) if value is not None else None @override async def async_select_option(self, option: str) -> None: """Write the selected option to the device.""" - value = self.entity_description.options_enum[option.upper()] - await self.entity_description.write_fn(self.coordinator.device, value.value) + await self.entity_description.write_fn(self.coordinator.device, option) await self.coordinator.async_request_refresh() diff --git a/homeassistant/components/sofar/sensor.py b/homeassistant/components/sofar/sensor.py index 18de476c2668..b75517d9f63f 100644 --- a/homeassistant/components/sofar/sensor.py +++ b/homeassistant/components/sofar/sensor.py @@ -57,6 +57,7 @@ from .entity import ( async_remove_unserved_entities, battery_pack_identifier, ) +from .helpers import enum_options, option_slug PARALLEL_UPDATES = 0 @@ -162,7 +163,7 @@ class SofarSensor(SofarEntity, SensorEntity): value = self.entity_description.value_fn(self.coordinator.device) # IntEnum stringifies as the raw int; use the option slug. if isinstance(value, IntEnum): - return value.name.lower() + return option_slug(value) return value @@ -418,7 +419,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="state", translation_key="system_state", device_class=SensorDeviceClass.ENUM, - options=[state.name.lower() for state in SystemState], + options=enum_options(SystemState), value_fn=lambda device: device.state.system_state, ), SofarSensorDescription( @@ -1376,7 +1377,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="battery_config_id", translation_key="bat_config_protocol", device_class=SensorDeviceClass.ENUM, - options=[protocol.name.lower() for protocol in BatConfigProtocol], + options=enum_options(BatConfigProtocol), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.battery_config_id.bat_config_protocol, @@ -1495,7 +1496,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="battery_config", translation_key="bat_config_cell_type", device_class=SensorDeviceClass.ENUM, - options=[cell_type.name.lower() for cell_type in BatConfigCellType], + options=enum_options(BatConfigCellType), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.battery_config.bat_config_cell_type, @@ -1571,7 +1572,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="rtc_sync", translation_key="sync_rtc_result", device_class=SensorDeviceClass.ENUM, - options=[result.name.lower() for result in SyncRtcResult], + options=enum_options(SyncRtcResult), entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda device: device.rtc_sync.sync_rtc_result, ), @@ -1580,7 +1581,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="feed_in", translation_key="feedin_limitation_mode", device_class=SensorDeviceClass.ENUM, - options=[mode.name.lower() for mode in FeedinLimitationMode], + options=enum_options(FeedinLimitationMode), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.feed_in.feedin_limitation_mode, @@ -1619,7 +1620,7 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( component="passive", translation_key="passive_mode_timeout_action", device_class=SensorDeviceClass.ENUM, - options=[action.name.lower() for action in PassiveModeTimeoutAction], + options=enum_options(PassiveModeTimeoutAction), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.passive.passive_mode_timeout_action, diff --git a/homeassistant/components/sofar/services.py b/homeassistant/components/sofar/services.py index 5f6f62421cb7..c7a4158840ff 100644 --- a/homeassistant/components/sofar/services.py +++ b/homeassistant/components/sofar/services.py @@ -18,6 +18,7 @@ from homeassistant.helpers.service import ( from .const import DOMAIN from .coordinator import SofarConfigEntry +from .helpers import enum_member, enum_options class SofarService(StrEnum): @@ -58,7 +59,7 @@ _POWER_RANGE = probatio.All(int, probatio.Range(min=-100000, max=100000)) SET_FEED_IN_LIMIT_SCHEMA = _ENTRY_SCHEMA.extend( { probatio.Required(SofarServiceArgument.MODE): probatio.In( - [mode.name.lower() for mode in FeedinLimitationMode] + enum_options(FeedinLimitationMode) ), # Not cv.positive_int: it would let 3000.9 pass as 3000. probatio.Required(SofarServiceArgument.MAX_POWER): probatio.All( @@ -82,7 +83,7 @@ SET_PASSIVE_MODE_TIMEOUT_SCHEMA = _ENTRY_SCHEMA.extend( cv.positive_int, probatio.Range(max=65535) ), probatio.Required(SofarServiceArgument.ACTION): probatio.In( - [action.name.lower() for action in PassiveModeTimeoutAction] + enum_options(PassiveModeTimeoutAction) ), } ) @@ -162,7 +163,7 @@ def async_setup_services(hass: HomeAssistant) -> None: await _write( entry, device.feed_in.async_write_limit( - FeedinLimitationMode[call.data[SofarServiceArgument.MODE].upper()], + enum_member(FeedinLimitationMode, call.data[SofarServiceArgument.MODE]), int(max_power), ), ) @@ -185,9 +186,9 @@ def async_setup_services(hass: HomeAssistant) -> None: entry, device.passive.async_write_timeout( call.data[SofarServiceArgument.TIMEOUT], - PassiveModeTimeoutAction[ - call.data[SofarServiceArgument.ACTION].upper() - ], + enum_member( + PassiveModeTimeoutAction, call.data[SofarServiceArgument.ACTION] + ), ), )