Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Currency exchange rate support that comes from fixer.io."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import Any
8 
9 from fixerio import Fixerio
10 from fixerio.exceptions import FixerioException
11 import voluptuous as vol
12 
14  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
15  SensorEntity,
16 )
17 from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_TARGET
18 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 ATTR_EXCHANGE_RATE = "Exchange rate"
26 ATTR_TARGET = "Target currency"
27 
28 DEFAULT_BASE = "USD"
29 DEFAULT_NAME = "Exchange rate"
30 
31 
32 SCAN_INTERVAL = timedelta(days=1)
33 
34 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
35  {
36  vol.Required(CONF_API_KEY): cv.string,
37  vol.Required(CONF_TARGET): cv.string,
38  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
39  }
40 )
41 
42 
44  hass: HomeAssistant,
45  config: ConfigType,
46  add_entities: AddEntitiesCallback,
47  discovery_info: DiscoveryInfoType | None = None,
48 ) -> None:
49  """Set up the Fixer.io sensor."""
50  api_key = config.get(CONF_API_KEY)
51  name = config.get(CONF_NAME)
52  target = config.get(CONF_TARGET)
53 
54  try:
55  Fixerio(symbols=[target], access_key=api_key).latest()
56  except FixerioException:
57  _LOGGER.error("One of the given currencies is not supported")
58  return
59 
60  data = ExchangeData(target, api_key)
61  add_entities([ExchangeRateSensor(data, name, target)], True)
62 
63 
65  """Representation of a Exchange sensor."""
66 
67  _attr_attribution = "Data provided by the European Central Bank (ECB)"
68  _attr_icon = "mdi:currency-usd"
69 
70  def __init__(self, data, name, target):
71  """Initialize the sensor."""
72  self.datadata = data
73  self._target_target = target
74  self._name_name = name
75  self._state_state = None
76 
77  @property
78  def name(self):
79  """Return the name of the sensor."""
80  return self._name_name
81 
82  @property
84  """Return the unit of measurement of this entity, if any."""
85  return self._target_target
86 
87  @property
88  def native_value(self):
89  """Return the state of the sensor."""
90  return self._state_state
91 
92  @property
93  def extra_state_attributes(self) -> dict[str, Any] | None:
94  """Return the state attributes."""
95  if self.datadata.rate is not None:
96  return {
97  ATTR_EXCHANGE_RATE: self.datadata.rate["rates"][self._target_target],
98  ATTR_TARGET: self._target_target,
99  }
100  return None
101 
102  def update(self) -> None:
103  """Get the latest data and updates the states."""
104  self.datadata.update()
105  self._state_state = round(self.datadata.rate["rates"][self._target_target], 3)
106 
107 
109  """Get the latest data and update the states."""
110 
111  def __init__(self, target_currency, api_key):
112  """Initialize the data object."""
113  self.api_keyapi_key = api_key
114  self.raterate = None
115  self.target_currencytarget_currency = target_currency
116  self.exchangeexchange = Fixerio(symbols=[self.target_currencytarget_currency], access_key=self.api_keyapi_key)
117 
118  def update(self):
119  """Get the latest data from Fixer.io."""
120  self.raterate = self.exchangeexchange.latest()
def __init__(self, target_currency, api_key)
Definition: sensor.py:111
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:48
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40