|
| 1 | +"""Plugwise USB Select component for HomeAssistant.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass |
| 6 | +from datetime import timedelta |
| 7 | +from enum import Enum |
| 8 | +import logging |
| 9 | + |
| 10 | +from plugwise_usb.api import MotionSensitivity, NodeEvent, NodeFeature |
| 11 | + |
| 12 | +from homeassistant.components.select import SelectEntity, SelectEntityDescription |
| 13 | +from homeassistant.const import EntityCategory, Platform |
| 14 | +from homeassistant.core import HomeAssistant, callback |
| 15 | +from homeassistant.helpers.entity_platform import AddEntitiesCallback |
| 16 | + |
| 17 | +from .const import NODES, STICK, UNSUB_NODE_LOADED |
| 18 | +from .coordinator import PlugwiseUSBConfigEntry, PlugwiseUSBDataUpdateCoordinator |
| 19 | +from .entity import PlugwiseUSBEntity, PlugwiseUSBEntityDescription |
| 20 | + |
| 21 | +_LOGGER = logging.getLogger(__name__) |
| 22 | +PARALLEL_UPDATES = 2 |
| 23 | +SCAN_INTERVAL = timedelta(seconds=30) |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(kw_only=True) |
| 27 | +class PlugwiseSelectEntityDescription( |
| 28 | + PlugwiseUSBEntityDescription, SelectEntityDescription |
| 29 | +): |
| 30 | + """Describes Plugwise select entity.""" |
| 31 | + |
| 32 | + async_select_fn: str = "" |
| 33 | + options_enum: type[Enum] |
| 34 | + |
| 35 | +SELECT_TYPES: tuple[PlugwiseSelectEntityDescription, ...] = ( |
| 36 | + PlugwiseSelectEntityDescription( |
| 37 | + key="sensitivity_level", |
| 38 | + translation_key="motion_sensitivity_level", |
| 39 | + async_select_fn="set_motion_sensitivity_level", |
| 40 | + entity_category=EntityCategory.CONFIG, |
| 41 | + node_feature=NodeFeature.MOTION_CONFIG, |
| 42 | + options_enum = MotionSensitivity, |
| 43 | + ), |
| 44 | +) |
| 45 | + |
| 46 | + |
| 47 | +async def async_setup_entry( |
| 48 | + _hass: HomeAssistant, |
| 49 | + config_entry: PlugwiseUSBConfigEntry, |
| 50 | + async_add_entities: AddEntitiesCallback, |
| 51 | +) -> None: |
| 52 | + """Set up the USB selects from a config entry.""" |
| 53 | + |
| 54 | + async def async_add_select(node_event: NodeEvent, mac: str) -> None: |
| 55 | + """Initialize DUC for select.""" |
| 56 | + if node_event != NodeEvent.LOADED: |
| 57 | + return |
| 58 | + entities: list[PlugwiseUSBEntity] = [] |
| 59 | + if (node_duc := config_entry.runtime_data[NODES].get(mac)) is not None: |
| 60 | + _LOGGER.debug("Add select entities for node %s", node_duc.node.name) |
| 61 | + entities.extend( |
| 62 | + [ |
| 63 | + PlugwiseUSBSelectEntity(node_duc, entity_description) |
| 64 | + for entity_description in SELECT_TYPES |
| 65 | + if entity_description.node_feature in node_duc.node.features |
| 66 | + ] |
| 67 | + ) |
| 68 | + if entities: |
| 69 | + async_add_entities(entities) |
| 70 | + |
| 71 | + api_stick = config_entry.runtime_data[STICK] |
| 72 | + |
| 73 | + # Listen for loaded nodes |
| 74 | + config_entry.runtime_data[Platform.SELECT] = {} |
| 75 | + config_entry.runtime_data[Platform.SELECT][UNSUB_NODE_LOADED] = ( |
| 76 | + api_stick.subscribe_to_node_events( |
| 77 | + async_add_select, |
| 78 | + (NodeEvent.LOADED,), |
| 79 | + ) |
| 80 | + ) |
| 81 | + |
| 82 | + # load any current nodes |
| 83 | + for mac, node in api_stick.nodes.items(): |
| 84 | + if node.is_loaded: |
| 85 | + await async_add_select(NodeEvent.LOADED, mac) |
| 86 | + |
| 87 | + |
| 88 | +async def async_unload_entry( |
| 89 | + _hass: HomeAssistant, |
| 90 | + config_entry: PlugwiseUSBConfigEntry, |
| 91 | +) -> None: |
| 92 | + """Unload a config entry.""" |
| 93 | + config_entry.runtime_data[Platform.SELECT][UNSUB_NODE_LOADED]() |
| 94 | + |
| 95 | + |
| 96 | +class PlugwiseUSBSelectEntity(PlugwiseUSBEntity, SelectEntity): |
| 97 | + """Representation of a Plugwise USB Data Update Coordinator select.""" |
| 98 | + |
| 99 | + def __init__( |
| 100 | + self, |
| 101 | + node_duc: PlugwiseUSBDataUpdateCoordinator, |
| 102 | + entity_description: PlugwiseSelectEntityDescription, |
| 103 | + ) -> None: |
| 104 | + """Initialize a select entity.""" |
| 105 | + super().__init__(node_duc, entity_description) |
| 106 | + self.async_select_fn = getattr( |
| 107 | + node_duc.node, entity_description.async_select_fn |
| 108 | + ) |
| 109 | + self._attr_options = [o.name.lower() for o in entity_description.options_enum] |
| 110 | + |
| 111 | + @callback |
| 112 | + def _handle_coordinator_update(self) -> None: |
| 113 | + """Handle updated data from the coordinator.""" |
| 114 | + data = self.coordinator.data.get(self.entity_description.node_feature, None) |
| 115 | + if data is None: |
| 116 | + _LOGGER.debug( |
| 117 | + "No %s select data for %s", |
| 118 | + str(self.entity_description.node_feature), |
| 119 | + self._node_info.mac, |
| 120 | + ) |
| 121 | + return |
| 122 | + |
| 123 | + current_option = getattr( |
| 124 | + data, |
| 125 | + self.entity_description.key, |
| 126 | + ) |
| 127 | + self._attr_current_option = current_option.name.lower() |
| 128 | + self.async_write_ha_state() |
| 129 | + |
| 130 | + async def async_select_option(self, option: str) -> None: |
| 131 | + """Change to the selected entity option.""" |
| 132 | + normalized = option.strip().lower() |
| 133 | + if normalized not in self._attr_options: |
| 134 | + raise ValueError(f"Unsupported option: {option}") |
| 135 | + value = self.entity_description.options_enum[normalized.upper()] |
| 136 | + await self.async_select_fn(value) |
| 137 | + self._attr_current_option = normalized |
| 138 | + self.async_write_ha_state() |
0 commit comments