Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support gathering ted5000 information."""
2 
3 from __future__ import annotations
4 
5 from contextlib import suppress
6 from datetime import timedelta
7 import logging
8 
9 import requests
10 import voluptuous as vol
11 import xmltodict
12 
14  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
15  SensorDeviceClass,
16  SensorEntity,
17  SensorEntityDescription,
18  SensorStateClass,
19 )
20 from homeassistant.const import (
21  CONF_HOST,
22  CONF_NAME,
23  CONF_PORT,
24  UnitOfElectricPotential,
25  UnitOfPower,
26 )
27 from homeassistant.core import HomeAssistant
28 from homeassistant.helpers import config_validation as cv
29 from homeassistant.helpers.entity_platform import AddEntitiesCallback
30 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
31 from homeassistant.util import Throttle
32 
33 _LOGGER = logging.getLogger(__name__)
34 
35 DEFAULT_NAME = "ted"
36 
37 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
38 
39 
40 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
41  {
42  vol.Required(CONF_HOST): cv.string,
43  vol.Optional(CONF_PORT, default=80): cv.port,
44  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
45  }
46 )
47 
48 SENSORS = [
50  key="power",
51  native_unit_of_measurement=UnitOfPower.WATT,
52  device_class=SensorDeviceClass.POWER,
53  state_class=SensorStateClass.MEASUREMENT,
54  ),
56  key="voltage",
57  native_unit_of_measurement=UnitOfElectricPotential.VOLT,
58  device_class=SensorDeviceClass.VOLTAGE,
59  state_class=SensorStateClass.MEASUREMENT,
60  ),
61 ]
62 
63 
65  hass: HomeAssistant,
66  config: ConfigType,
67  add_entities: AddEntitiesCallback,
68  discovery_info: DiscoveryInfoType | None = None,
69 ) -> None:
70  """Set up the Ted5000 sensor."""
71  host: str = config[CONF_HOST]
72  port: int = config[CONF_PORT]
73  name: str = config[CONF_NAME]
74  url = f"http://{host}:{port}/api/LiveData.xml"
75 
76  gateway = Ted5000Gateway(url)
77 
78  # Get MUT information to create the sensors.
79  gateway.update()
80 
82  Ted5000Sensor(gateway, name, mtu, description)
83  for mtu in gateway.data
84  for description in SENSORS
85  )
86 
87 
89  """Implementation of a Ted5000 sensor."""
90 
91  def __init__(
92  self,
93  gateway: Ted5000Gateway,
94  name: str,
95  mtu: int,
96  description: SensorEntityDescription,
97  ) -> None:
98  """Initialize the sensor."""
99  self._gateway_gateway = gateway
100  self._attr_name_attr_name = f"{name} mtu{mtu} {description.key}"
101  self._mtu_mtu = mtu
102  self.entity_descriptionentity_description = description
103  self.updateupdate()
104 
105  @property
106  def native_value(self) -> int | float | None:
107  """Return the state of the resources."""
108  if unit := self.entity_descriptionentity_description.native_unit_of_measurement:
109  with suppress(KeyError):
110  return self._gateway_gateway.data[self._mtu_mtu][unit]
111  return None
112 
113  def update(self) -> None:
114  """Get the latest data from REST API."""
115  self._gateway_gateway.update()
116 
117 
119  """The class for handling the data retrieval."""
120 
121  def __init__(self, url: str) -> None:
122  """Initialize the data object."""
123  self.urlurl = url
124  self.data: dict[int, dict[str, int | float]] = {}
125 
126  @Throttle(MIN_TIME_BETWEEN_UPDATES)
127  def update(self) -> None:
128  """Get the latest data from the Ted5000 XML API."""
129 
130  try:
131  request = requests.get(self.urlurl, timeout=10)
132  except requests.exceptions.RequestException as err:
133  _LOGGER.error("No connection to endpoint: %s", err)
134  else:
135  doc = xmltodict.parse(request.text)
136  mtus = int(doc["LiveData"]["System"]["NumberMTU"])
137 
138  for mtu in range(1, mtus + 1):
139  power = int(doc["LiveData"]["Power"][f"MTU{mtu}"]["PowerNow"])
140  voltage = int(doc["LiveData"]["Voltage"][f"MTU{mtu}"]["VoltageNow"])
141 
142  self.data[mtu] = {
143  UnitOfPower.WATT: power,
144  UnitOfElectricPotential.VOLT: voltage / 10,
145  }
None __init__(self, Ted5000Gateway gateway, str name, int mtu, SensorEntityDescription description)
Definition: sensor.py:97
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:69