Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """The Minecraft Server sensor platform."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from dataclasses import dataclass
7 from typing import Any
8 
9 from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_TYPE, EntityCategory, UnitOfTime
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 from homeassistant.helpers.typing import StateType
15 
16 from .api import MinecraftServerData, MinecraftServerType
17 from .const import DOMAIN, KEY_LATENCY, KEY_MOTD
18 from .coordinator import MinecraftServerCoordinator
19 from .entity import MinecraftServerEntity
20 
21 ATTR_PLAYERS_LIST = "players_list"
22 
23 KEY_EDITION = "edition"
24 KEY_GAME_MODE = "game_mode"
25 KEY_MAP_NAME = "map_name"
26 KEY_PLAYERS_MAX = "players_max"
27 KEY_PLAYERS_ONLINE = "players_online"
28 KEY_PROTOCOL_VERSION = "protocol_version"
29 KEY_VERSION = "version"
30 
31 UNIT_PLAYERS_MAX = "players"
32 UNIT_PLAYERS_ONLINE = "players"
33 
34 
35 @dataclass(frozen=True, kw_only=True)
37  """Class describing Minecraft Server sensor entities."""
38 
39  value_fn: Callable[[MinecraftServerData], StateType]
40  attributes_fn: Callable[[MinecraftServerData], dict[str, Any]] | None
41  supported_server_types: set[MinecraftServerType]
42 
43 
45  data: MinecraftServerData,
46 ) -> dict[str, list[str]]:
47  """Return players list as extra state attributes, if available."""
48  extra_state_attributes: dict[str, Any] = {}
49  players_list = data.players_list
50 
51  if players_list is not None and len(players_list) != 0:
52  extra_state_attributes[ATTR_PLAYERS_LIST] = players_list
53 
54  return extra_state_attributes
55 
56 
57 SENSOR_DESCRIPTIONS = [
59  key=KEY_VERSION,
60  translation_key=KEY_VERSION,
61  value_fn=lambda data: data.version,
62  attributes_fn=None,
63  supported_server_types={
64  MinecraftServerType.JAVA_EDITION,
65  MinecraftServerType.BEDROCK_EDITION,
66  },
67  entity_category=EntityCategory.DIAGNOSTIC,
68  ),
70  key=KEY_PROTOCOL_VERSION,
71  translation_key=KEY_PROTOCOL_VERSION,
72  value_fn=lambda data: data.protocol_version,
73  attributes_fn=None,
74  supported_server_types={
75  MinecraftServerType.JAVA_EDITION,
76  MinecraftServerType.BEDROCK_EDITION,
77  },
78  entity_category=EntityCategory.DIAGNOSTIC,
79  entity_registry_enabled_default=False,
80  ),
82  key=KEY_PLAYERS_MAX,
83  translation_key=KEY_PLAYERS_MAX,
84  native_unit_of_measurement=UNIT_PLAYERS_MAX,
85  value_fn=lambda data: data.players_max,
86  attributes_fn=None,
87  supported_server_types={
88  MinecraftServerType.JAVA_EDITION,
89  MinecraftServerType.BEDROCK_EDITION,
90  },
91  entity_registry_enabled_default=False,
92  ),
94  key=KEY_LATENCY,
95  translation_key=KEY_LATENCY,
96  native_unit_of_measurement=UnitOfTime.MILLISECONDS,
97  suggested_display_precision=0,
98  value_fn=lambda data: data.latency,
99  attributes_fn=None,
100  supported_server_types={
101  MinecraftServerType.JAVA_EDITION,
102  MinecraftServerType.BEDROCK_EDITION,
103  },
104  entity_category=EntityCategory.DIAGNOSTIC,
105  ),
107  key=KEY_MOTD,
108  translation_key=KEY_MOTD,
109  value_fn=lambda data: data.motd,
110  attributes_fn=None,
111  supported_server_types={
112  MinecraftServerType.JAVA_EDITION,
113  MinecraftServerType.BEDROCK_EDITION,
114  },
115  ),
117  key=KEY_PLAYERS_ONLINE,
118  translation_key=KEY_PLAYERS_ONLINE,
119  native_unit_of_measurement=UNIT_PLAYERS_ONLINE,
120  value_fn=lambda data: data.players_online,
121  attributes_fn=get_extra_state_attributes_players_list,
122  supported_server_types={
123  MinecraftServerType.JAVA_EDITION,
124  MinecraftServerType.BEDROCK_EDITION,
125  },
126  ),
128  key=KEY_EDITION,
129  translation_key=KEY_EDITION,
130  value_fn=lambda data: data.edition,
131  attributes_fn=None,
132  supported_server_types={
133  MinecraftServerType.BEDROCK_EDITION,
134  },
135  entity_category=EntityCategory.DIAGNOSTIC,
136  entity_registry_enabled_default=False,
137  ),
139  key=KEY_GAME_MODE,
140  translation_key=KEY_GAME_MODE,
141  value_fn=lambda data: data.game_mode,
142  attributes_fn=None,
143  supported_server_types={
144  MinecraftServerType.BEDROCK_EDITION,
145  },
146  ),
148  key=KEY_MAP_NAME,
149  translation_key=KEY_MAP_NAME,
150  value_fn=lambda data: data.map_name,
151  attributes_fn=None,
152  supported_server_types={
153  MinecraftServerType.BEDROCK_EDITION,
154  },
155  ),
156 ]
157 
158 
160  hass: HomeAssistant,
161  config_entry: ConfigEntry,
162  async_add_entities: AddEntitiesCallback,
163 ) -> None:
164  """Set up the Minecraft Server sensor platform."""
165  coordinator = hass.data[DOMAIN][config_entry.entry_id]
166 
167  # Add sensor entities.
169  [
170  MinecraftServerSensorEntity(coordinator, description, config_entry)
171  for description in SENSOR_DESCRIPTIONS
172  if config_entry.data.get(CONF_TYPE, MinecraftServerType.JAVA_EDITION)
173  in description.supported_server_types
174  ]
175  )
176 
177 
179  """Representation of a Minecraft Server sensor base entity."""
180 
181  entity_description: MinecraftServerSensorEntityDescription
182 
183  def __init__(
184  self,
185  coordinator: MinecraftServerCoordinator,
186  description: MinecraftServerSensorEntityDescription,
187  config_entry: ConfigEntry,
188  ) -> None:
189  """Initialize sensor base entity."""
190  super().__init__(coordinator, config_entry)
191  self.entity_descriptionentity_description = description
192  self._attr_unique_id_attr_unique_id = f"{config_entry.entry_id}-{description.key}"
193  self._update_properties_update_properties()
194 
195  @callback
196  def _handle_coordinator_update(self) -> None:
197  """Handle updated data from the coordinator."""
198  self._update_properties_update_properties()
199  self.async_write_ha_stateasync_write_ha_state()
200 
201  @callback
202  def _update_properties(self) -> None:
203  """Update sensor properties."""
204  self._attr_native_value_attr_native_value = self.entity_descriptionentity_description.value_fn(
205  self.coordinator.data
206  )
207 
208  if func := self.entity_descriptionentity_description.attributes_fn:
209  self._attr_extra_state_attributes_attr_extra_state_attributes = func(self.coordinator.data)
None __init__(self, MinecraftServerCoordinator coordinator, MinecraftServerSensorEntityDescription description, ConfigEntry config_entry)
Definition: sensor.py:188
dict[str, list[str]] get_extra_state_attributes_players_list(MinecraftServerData data)
Definition: sensor.py:46
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:163