Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Mastodon platform for sensor components."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
10  SensorEntity,
11  SensorEntityDescription,
12  SensorStateClass,
13 )
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers.entity_platform import AddEntitiesCallback
16 from homeassistant.helpers.typing import StateType
17 
18 from . import MastodonConfigEntry
19 from .const import (
20  ACCOUNT_FOLLOWERS_COUNT,
21  ACCOUNT_FOLLOWING_COUNT,
22  ACCOUNT_STATUSES_COUNT,
23 )
24 from .entity import MastodonEntity
25 
26 
27 @dataclass(frozen=True, kw_only=True)
29  """Describes Mastodon sensor entity."""
30 
31  value_fn: Callable[[dict[str, Any]], StateType]
32 
33 
34 ENTITY_DESCRIPTIONS = (
36  key="followers",
37  translation_key="followers",
38  state_class=SensorStateClass.TOTAL,
39  value_fn=lambda data: data.get(ACCOUNT_FOLLOWERS_COUNT),
40  ),
42  key="following",
43  translation_key="following",
44  state_class=SensorStateClass.TOTAL,
45  value_fn=lambda data: data.get(ACCOUNT_FOLLOWING_COUNT),
46  ),
48  key="posts",
49  translation_key="posts",
50  state_class=SensorStateClass.TOTAL,
51  value_fn=lambda data: data.get(ACCOUNT_STATUSES_COUNT),
52  ),
53 )
54 
55 
57  hass: HomeAssistant,
58  entry: MastodonConfigEntry,
59  async_add_entities: AddEntitiesCallback,
60 ) -> None:
61  """Set up the sensor platform for entity."""
62  coordinator = entry.runtime_data.coordinator
63 
66  coordinator=coordinator,
67  entity_description=entity_description,
68  data=entry,
69  )
70  for entity_description in ENTITY_DESCRIPTIONS
71  )
72 
73 
75  """A Mastodon sensor entity."""
76 
77  entity_description: MastodonSensorEntityDescription
78 
79  @property
80  def native_value(self) -> StateType:
81  """Return the native value of the sensor."""
82  return self.entity_descriptionentity_description.value_fn(self.coordinator.data)
None async_setup_entry(HomeAssistant hass, MastodonConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:60