Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Flick Electric Pricing data."""
2 
3 import asyncio
4 from datetime import timedelta
5 import logging
6 from typing import Any
7 
8 from pyflick import FlickAPI, FlickPrice
9 
10 from homeassistant.components.sensor import SensorEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CURRENCY_CENT, UnitOfEnergy
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 from homeassistant.util.dt import utcnow
16 
17 from .const import ATTR_COMPONENTS, ATTR_END_AT, ATTR_START_AT, DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 SCAN_INTERVAL = timedelta(minutes=5)
22 
23 
25  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
26 ) -> None:
27  """Flick Sensor Setup."""
28  api: FlickAPI = hass.data[DOMAIN][entry.entry_id]
29 
31 
32 
34  """Entity object for Flick Electric sensor."""
35 
36  _attr_attribution = "Data provided by Flick Electric"
37  _attr_native_unit_of_measurement = f"{CURRENCY_CENT}/{UnitOfEnergy.KILO_WATT_HOUR}"
38  _attr_has_entity_name = True
39  _attr_translation_key = "power_price"
40  _attributes: dict[str, Any] = {}
41 
42  def __init__(self, api: FlickAPI) -> None:
43  """Entity object for Flick Electric sensor."""
44  self._api: FlickAPI = api
45  self._price_price: FlickPrice = None
46 
47  @property
48  def native_value(self):
49  """Return the state of the sensor."""
50  return self._price_price.price
51 
52  @property
54  """Return the state attributes."""
55  return self._attributes
56 
57  async def async_update(self) -> None:
58  """Get the Flick Pricing data from the web service."""
59  if self._price_price and self._price_price.end_at >= utcnow():
60  return # Power price data is still valid
61 
62  async with asyncio.timeout(60):
63  self._price_price = await self._api.getPricing()
64 
65  _LOGGER.debug("Pricing data: %s", self._price_price)
66 
67  self._attributes[ATTR_START_AT] = self._price_price.start_at
68  self._attributes[ATTR_END_AT] = self._price_price.end_at
69  for component in self._price_price.components:
70  if component.charge_setter not in ATTR_COMPONENTS:
71  _LOGGER.warning("Found unknown component: %s", component.charge_setter)
72  continue
73 
74  self._attributes[component.charge_setter] = float(component.value)
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:26