Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for OhmConnect."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 import defusedxml.ElementTree as ET
9 import requests
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
14  SensorEntity,
15 )
16 from homeassistant.const import CONF_ID, CONF_NAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 from homeassistant.util import Throttle
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 DEFAULT_NAME = "OhmConnect Status"
26 
27 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
28 
29 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
30  {
31  vol.Required(CONF_ID): cv.string,
32  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
33  }
34 )
35 
36 
38  hass: HomeAssistant,
39  config: ConfigType,
40  add_entities: AddEntitiesCallback,
41  discovery_info: DiscoveryInfoType | None = None,
42 ) -> None:
43  """Set up the OhmConnect sensor."""
44  name = config.get(CONF_NAME)
45  ohmid = config.get(CONF_ID)
46 
47  add_entities([OhmconnectSensor(name, ohmid)], True)
48 
49 
51  """Representation of a OhmConnect sensor."""
52 
53  def __init__(self, name, ohmid):
54  """Initialize the sensor."""
55  self._name_name = name
56  self._ohmid_ohmid = ohmid
57  self._data_data = {}
58  self._attr_unique_id_attr_unique_id = ohmid
59 
60  @property
61  def name(self):
62  """Return the name of the sensor."""
63  return self._name_name
64 
65  @property
66  def native_value(self):
67  """Return the state of the sensor."""
68  if self._data_data.get("active") == "True":
69  return "Active"
70  return "Inactive"
71 
72  @property
74  """Return the state attributes."""
75  return {"Address": self._data_data.get("address"), "ID": self._ohmid_ohmid}
76 
77  @Throttle(MIN_TIME_BETWEEN_UPDATES)
78  def update(self) -> None:
79  """Get the latest data from OhmConnect."""
80  try:
81  url = f"https://login.ohmconnect.com/verify-ohm-hour/{self._ohmid}"
82  response = requests.get(url, timeout=10)
83  root = ET.fromstring(response.text)
84 
85  for child in root:
86  self._data_data[child.tag] = child.text
87  except requests.exceptions.ConnectionError:
88  _LOGGER.error("No route to host/endpoint: %s", url)
89  self._data_data = {}
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
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:42