Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Monitors home energy use for the ELIQ Online service."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 import eliqonline
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
13  SensorDeviceClass,
14  SensorEntity,
15  SensorStateClass,
16 )
17 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME, UnitOfPower
18 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21 from homeassistant.helpers.entity_platform import AddEntitiesCallback
22 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 CONF_CHANNEL_ID = "channel_id"
27 
28 DEFAULT_NAME = "ELIQ Online"
29 
30 SCAN_INTERVAL = timedelta(seconds=60)
31 
32 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
33  {
34  vol.Required(CONF_ACCESS_TOKEN): cv.string,
35  vol.Required(CONF_CHANNEL_ID): cv.positive_int,
36  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
37  }
38 )
39 
40 
42  hass: HomeAssistant,
43  config: ConfigType,
44  async_add_entities: AddEntitiesCallback,
45  discovery_info: DiscoveryInfoType | None = None,
46 ) -> None:
47  """Set up the ELIQ Online sensor."""
48  access_token = config.get(CONF_ACCESS_TOKEN)
49  name = config.get(CONF_NAME, DEFAULT_NAME)
50  channel_id = config.get(CONF_CHANNEL_ID)
51  session = async_get_clientsession(hass)
52 
53  api = eliqonline.API(session=session, access_token=access_token)
54 
55  try:
56  _LOGGER.debug("Probing for access to ELIQ Online API")
57  await api.get_data_now(channelid=channel_id)
58  except OSError as error:
59  _LOGGER.error("Could not access the ELIQ Online API: %s", error)
60  return
61 
62  async_add_entities([EliqSensor(api, channel_id, name)], True)
63 
64 
66  """Implementation of an ELIQ Online sensor."""
67 
68  _attr_device_class = SensorDeviceClass.POWER
69  _attr_native_unit_of_measurement = UnitOfPower.WATT
70  _attr_state_class = SensorStateClass.MEASUREMENT
71 
72  def __init__(self, api, channel_id, name):
73  """Initialize the sensor."""
74  self._attr_name_attr_name = name
75  self._api_api = api
76  self._channel_id_channel_id = channel_id
77 
78  async def async_update(self) -> None:
79  """Get the latest data."""
80  try:
81  response = await self._api_api.get_data_now(channelid=self._channel_id_channel_id)
82  self._attr_native_value_attr_native_value = int(response["power"])
83  _LOGGER.debug("Updated power from server %d W", self.native_valuenative_value)
84  except KeyError:
85  _LOGGER.warning("Invalid response from ELIQ Online API")
86  except (OSError, TimeoutError) as error:
87  _LOGGER.warning("Could not connect to the ELIQ Online API: %s", error)
def __init__(self, api, channel_id, name)
Definition: sensor.py:72
StateType|date|datetime|Decimal native_value(self)
Definition: __init__.py:460
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:46
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)