Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for balance data via the Starling Bank API."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 import requests
9 from starlingbank import StarlingAccount
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
14  SensorEntity,
15 )
16 from homeassistant.const import CONF_ACCESS_TOKEN, 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 
22 _LOGGER = logging.getLogger(__name__)
23 
24 BALANCE_TYPES = ["cleared_balance", "effective_balance"]
25 
26 CONF_ACCOUNTS = "accounts"
27 CONF_BALANCE_TYPES = "balance_types"
28 CONF_SANDBOX = "sandbox"
29 
30 DEFAULT_SANDBOX = False
31 DEFAULT_ACCOUNT_NAME = "Starling"
32 
33 
34 SCAN_INTERVAL = timedelta(seconds=180)
35 
36 ACCOUNT_SCHEMA = vol.Schema(
37  {
38  vol.Required(CONF_ACCESS_TOKEN): cv.string,
39  vol.Optional(CONF_BALANCE_TYPES, default=BALANCE_TYPES): vol.All(
40  cv.ensure_list, [vol.In(BALANCE_TYPES)]
41  ),
42  vol.Optional(CONF_NAME, default=DEFAULT_ACCOUNT_NAME): cv.string,
43  vol.Optional(CONF_SANDBOX, default=DEFAULT_SANDBOX): cv.boolean,
44  }
45 )
46 
47 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
48  {vol.Required(CONF_ACCOUNTS): vol.Schema([ACCOUNT_SCHEMA])}
49 )
50 
51 
53  hass: HomeAssistant,
54  config: ConfigType,
55  add_devices: AddEntitiesCallback,
56  discovery_info: DiscoveryInfoType | None = None,
57 ) -> None:
58  """Set up the Sterling Bank sensor platform."""
59 
60  sensors: list[StarlingBalanceSensor] = []
61  for account in config[CONF_ACCOUNTS]:
62  try:
63  starling_account = StarlingAccount(
64  account[CONF_ACCESS_TOKEN], sandbox=account[CONF_SANDBOX]
65  )
66  sensors.extend(
68  starling_account, account[CONF_NAME], balance_type
69  )
70  for balance_type in account[CONF_BALANCE_TYPES]
71  )
72  except requests.exceptions.HTTPError as error:
73  _LOGGER.error(
74  "Unable to set up Starling account '%s': %s", account[CONF_NAME], error
75  )
76 
77  add_devices(sensors, True)
78 
79 
81  """Representation of a Starling balance sensor."""
82 
83  _attr_icon = "mdi:currency-gbp"
84 
85  def __init__(self, starling_account, account_name, balance_data_type):
86  """Initialize the sensor."""
87  self._starling_account_starling_account = starling_account
88  self._balance_data_type_balance_data_type = balance_data_type
89  self._state_state = None
90  self._account_name_account_name = account_name
91 
92  @property
93  def name(self):
94  """Return the name of the sensor."""
95  balance_data_type = self._balance_data_type_balance_data_type.replace("_", " ").capitalize()
96  return f"{self._account_name} {balance_data_type}"
97 
98  @property
99  def native_value(self):
100  """Return the state of the sensor."""
101  return self._state_state
102 
103  @property
105  """Return the unit of measurement."""
106  return self._starling_account_starling_account.currency
107 
108  def update(self) -> None:
109  """Fetch new state data for the sensor."""
110  self._starling_account_starling_account.update_balance_data()
111  if self._balance_data_type_balance_data_type == "cleared_balance":
112  self._state_state = self._starling_account_starling_account.cleared_balance / 100
113  elif self._balance_data_type_balance_data_type == "effective_balance":
114  self._state_state = self._starling_account_starling_account.effective_balance / 100
def __init__(self, starling_account, account_name, balance_data_type)
Definition: sensor.py:85
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_devices, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:57