Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Mealie sensors."""
2 
3 from collections.abc import Callable
4 from dataclasses import dataclass
5 
6 from aiomealie import Statistics
7 
9  SensorEntity,
10  SensorEntityDescription,
11  SensorStateClass,
12 )
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 from homeassistant.helpers.typing import StateType
16 
17 from .coordinator import MealieConfigEntry, MealieStatisticsCoordinator
18 from .entity import MealieEntity
19 
20 
21 @dataclass(frozen=True, kw_only=True)
23  """Describes Mealie Statistics sensor entity."""
24 
25  value_fn: Callable[[Statistics], StateType]
26 
27 
28 SENSOR_TYPES: tuple[MealieStatisticsSensorEntityDescription, ...] = (
30  key="recipes",
31  state_class=SensorStateClass.TOTAL,
32  value_fn=lambda statistics: statistics.total_recipes,
33  ),
35  key="users",
36  state_class=SensorStateClass.TOTAL,
37  value_fn=lambda statistics: statistics.total_users,
38  ),
40  key="categories",
41  state_class=SensorStateClass.TOTAL,
42  value_fn=lambda statistics: statistics.total_categories,
43  ),
45  key="tags",
46  state_class=SensorStateClass.TOTAL,
47  value_fn=lambda statistics: statistics.total_tags,
48  ),
50  key="tools",
51  state_class=SensorStateClass.TOTAL,
52  value_fn=lambda statistics: statistics.total_tools,
53  ),
54 )
55 
56 
58  hass: HomeAssistant,
59  entry: MealieConfigEntry,
60  async_add_entities: AddEntitiesCallback,
61 ) -> None:
62  """Set up Mealie sensors based on a config entry."""
63  coordinator = entry.runtime_data.statistics_coordinator
64 
66  MealieStatisticSensors(coordinator, description) for description in SENSOR_TYPES
67  )
68 
69 
71  """Defines a Mealie sensor."""
72 
73  entity_description: MealieStatisticsSensorEntityDescription
74  coordinator: MealieStatisticsCoordinator
75 
76  def __init__(
77  self,
78  coordinator: MealieStatisticsCoordinator,
79  description: MealieStatisticsSensorEntityDescription,
80  ) -> None:
81  """Initialize Mealie sensor."""
82  super().__init__(coordinator, description.key)
83  self.entity_descriptionentity_description = description
84  self._attr_translation_key_attr_translation_key = description.key
85 
86  @property
87  def native_value(self) -> StateType:
88  """Return the state of the sensor."""
89  return self.entity_descriptionentity_description.value_fn(self.coordinator.data)
None __init__(self, MealieStatisticsCoordinator coordinator, MealieStatisticsSensorEntityDescription description)
Definition: sensor.py:80
None async_setup_entry(HomeAssistant hass, MealieConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:61