Home Assistant Unofficial Reference 2024.12.1
number.py
Go to the documentation of this file.
1 """Support for Roborock number."""
2 
3 import asyncio
4 from collections.abc import Callable, Coroutine
5 from dataclasses import dataclass
6 import logging
7 from typing import Any
8 
9 from roborock.command_cache import CacheableAttribute
10 from roborock.exceptions import RoborockException
11 from roborock.version_1_apis.roborock_client_v1 import AttributeCache
12 
13 from homeassistant.components.number import NumberEntity, NumberEntityDescription
14 from homeassistant.const import PERCENTAGE, EntityCategory
15 from homeassistant.core import HomeAssistant
16 from homeassistant.exceptions import HomeAssistantError
17 from homeassistant.helpers.entity_platform import AddEntitiesCallback
18 
19 from . import DOMAIN, RoborockConfigEntry
20 from .coordinator import RoborockDataUpdateCoordinator
21 from .entity import RoborockEntityV1
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 @dataclass(frozen=True, kw_only=True)
28  """Class to describe a Roborock number entity."""
29 
30  # Gets the status of the switch
31  cache_key: CacheableAttribute
32  # Sets the status of the switch
33  update_value: Callable[[AttributeCache, float], Coroutine[Any, Any, None]]
34 
35 
36 NUMBER_DESCRIPTIONS: list[RoborockNumberDescription] = [
38  key="volume",
39  translation_key="volume",
40  native_min_value=0,
41  native_max_value=100,
42  native_unit_of_measurement=PERCENTAGE,
43  cache_key=CacheableAttribute.sound_volume,
44  entity_category=EntityCategory.CONFIG,
45  update_value=lambda cache, value: cache.update_value([int(value)]),
46  )
47 ]
48 
49 
51  hass: HomeAssistant,
52  config_entry: RoborockConfigEntry,
53  async_add_entities: AddEntitiesCallback,
54 ) -> None:
55  """Set up Roborock number platform."""
56  possible_entities: list[
57  tuple[RoborockDataUpdateCoordinator, RoborockNumberDescription]
58  ] = [
59  (coordinator, description)
60  for coordinator in config_entry.runtime_data.v1
61  for description in NUMBER_DESCRIPTIONS
62  ]
63  # We need to check if this function is supported by the device.
64  results = await asyncio.gather(
65  *(
66  coordinator.api.get_from_cache(description.cache_key)
67  for coordinator, description in possible_entities
68  ),
69  return_exceptions=True,
70  )
71  valid_entities: list[RoborockNumberEntity] = []
72  for (coordinator, description), result in zip(
73  possible_entities, results, strict=False
74  ):
75  if result is None or isinstance(result, RoborockException):
76  _LOGGER.debug("Not adding entity because of %s", result)
77  else:
78  valid_entities.append(
80  f"{description.key}_{coordinator.duid_slug}",
81  coordinator,
82  description,
83  )
84  )
85  async_add_entities(valid_entities)
86 
87 
89  """A class to let you set options on a Roborock vacuum where the potential options are fixed."""
90 
91  entity_description: RoborockNumberDescription
92 
93  def __init__(
94  self,
95  unique_id: str,
96  coordinator: RoborockDataUpdateCoordinator,
97  entity_description: RoborockNumberDescription,
98  ) -> None:
99  """Create a number entity."""
100  self.entity_descriptionentity_description = entity_description
101  super().__init__(unique_id, coordinator.device_info, coordinator.api)
102 
103  @property
104  def native_value(self) -> float | None:
105  """Get native value."""
106  val: float = self.get_cacheget_cache(self.entity_descriptionentity_description.cache_key).value
107  return val
108 
109  async def async_set_native_value(self, value: float) -> None:
110  """Set number value."""
111  try:
112  await self.entity_descriptionentity_description.update_value(
113  self.get_cacheget_cache(self.entity_descriptionentity_description.cache_key), value
114  )
115  except RoborockException as err:
116  raise HomeAssistantError(
117  translation_domain=DOMAIN,
118  translation_key="update_options_failed",
119  ) from err
AttributeCache get_cache(self, CacheableAttribute attribute)
Definition: entity.py:52
None __init__(self, str unique_id, RoborockDataUpdateCoordinator coordinator, RoborockNumberDescription entity_description)
Definition: number.py:98
None async_setup_entry(HomeAssistant hass, RoborockConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: number.py:54