Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensor for Steam account status."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime
6 from time import localtime, mktime
7 from typing import cast
8 
9 from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 from homeassistant.helpers.typing import StateType
13 from homeassistant.util.dt import utc_from_timestamp
14 
15 from . import SteamConfigEntry
16 from .const import (
17  CONF_ACCOUNTS,
18  STEAM_API_URL,
19  STEAM_HEADER_IMAGE_FILE,
20  STEAM_ICON_URL,
21  STEAM_MAIN_IMAGE_FILE,
22  STEAM_STATUSES,
23 )
24 from .coordinator import SteamDataUpdateCoordinator
25 from .entity import SteamEntity
26 
27 PARALLEL_UPDATES = 1
28 
29 
31  hass: HomeAssistant,
32  entry: SteamConfigEntry,
33  async_add_entities: AddEntitiesCallback,
34 ) -> None:
35  """Set up the Steam platform."""
37  SteamSensor(entry.runtime_data, account)
38  for account in entry.options[CONF_ACCOUNTS]
39  )
40 
41 
43  """A class for the Steam account."""
44 
45  def __init__(self, coordinator: SteamDataUpdateCoordinator, account: str) -> None:
46  """Initialize the sensor."""
47  super().__init__(coordinator)
48  self.entity_descriptionentity_description = SensorEntityDescription(
49  key=account,
50  name=f"steam_{account}",
51  icon="mdi:steam",
52  )
53  self._attr_unique_id_attr_unique_id = f"sensor.steam_{account}"
54 
55  @property
56  def native_value(self) -> StateType:
57  """Return the state of the sensor."""
58  if self.entity_descriptionentity_description.key in self.coordinator.data:
59  player = self.coordinator.data[self.entity_descriptionentity_description.key]
60  return STEAM_STATUSES[cast(int, player["personastate"])]
61  return None
62 
63  @property
64  def extra_state_attributes(self) -> dict[str, str | int | datetime]:
65  """Return the state attributes of the sensor."""
66  if self.entity_descriptionentity_description.key not in self.coordinator.data:
67  return {}
68  player = self.coordinator.data[self.entity_descriptionentity_description.key]
69 
70  attrs: dict[str, str | int | datetime] = {}
71  if game := player.get("gameextrainfo"):
72  attrs["game"] = game
73  if game_id := player.get("gameid"):
74  attrs["game_id"] = game_id
75  game_url = f"{STEAM_API_URL}{player['gameid']}/"
76  attrs["game_image_header"] = f"{game_url}{STEAM_HEADER_IMAGE_FILE}"
77  attrs["game_image_main"] = f"{game_url}{STEAM_MAIN_IMAGE_FILE}"
78  if info := self._get_game_icon_get_game_icon(player):
79  attrs["game_icon"] = f"{STEAM_ICON_URL}{game_id}/{info}.jpg"
80  self._attr_name_attr_name = str(player["personaname"]) or None
81  self._attr_entity_picture_attr_entity_picture = str(player["avatarmedium"]) or None
82  if last_online := cast(int | None, player.get("lastlogoff")):
83  attrs["last_online"] = utc_from_timestamp(mktime(localtime(last_online)))
84  if level := self.coordinator.data[self.entity_descriptionentity_description.key]["level"]:
85  attrs["level"] = level
86  return attrs
87 
88  def _get_game_icon(self, player: dict) -> str | None:
89  """Get game icon identifier."""
90  if player.get("gameid") in self.coordinator.game_icons:
91  return self.coordinator.game_icons[player["gameid"]]
92  # Reset game icons to have coordinator get id for new game
93  self.coordinator.game_icons = {}
94  return None
None __init__(self, SteamDataUpdateCoordinator coordinator, str account)
Definition: sensor.py:45
dict[str, str|int|datetime] extra_state_attributes(self)
Definition: sensor.py:64
None async_setup_entry(HomeAssistant hass, SteamConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:34