Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for the Tank Utility propane monitor."""
2 
3 from __future__ import annotations
4 
5 import datetime
6 import logging
7 
8 import requests
9 from tank_utility import auth, device as tank_monitor
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
14  SensorEntity,
15 )
16 from homeassistant.const import CONF_DEVICES, CONF_EMAIL, CONF_PASSWORD, PERCENTAGE
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 SCAN_INTERVAL = datetime.timedelta(hours=1)
25 
26 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
27  {
28  vol.Required(CONF_EMAIL): cv.string,
29  vol.Required(CONF_PASSWORD): cv.string,
30  vol.Required(CONF_DEVICES): vol.All(cv.ensure_list, vol.Length(min=1)),
31  }
32 )
33 
34 SENSOR_TYPE = "tank"
35 SENSOR_ROUNDING_PRECISION = 1
36 SENSOR_ATTRS = [
37  "name",
38  "address",
39  "capacity",
40  "fuelType",
41  "orientation",
42  "status",
43  "time",
44  "time_iso",
45 ]
46 
47 
49  hass: HomeAssistant,
50  config: ConfigType,
51  add_entities: AddEntitiesCallback,
52  discovery_info: DiscoveryInfoType | None = None,
53 ) -> None:
54  """Set up the Tank Utility sensor."""
55 
56  email = config[CONF_EMAIL]
57  password = config[CONF_PASSWORD]
58  devices = config[CONF_DEVICES]
59 
60  try:
61  token = auth.get_token(email, password)
62  except requests.exceptions.HTTPError as http_error:
63  if http_error.response.status_code == requests.codes.unauthorized:
64  _LOGGER.error("Invalid credentials")
65  return
66 
67  all_sensors = []
68  for device in devices:
69  sensor = TankUtilitySensor(email, password, token, device)
70  all_sensors.append(sensor)
71  add_entities(all_sensors, True)
72 
73 
75  """Representation of a Tank Utility sensor."""
76 
77  def __init__(self, email, password, token, device):
78  """Initialize the sensor."""
79  self._email_email = email
80  self._password_password = password
81  self._token_token = token
82  self._device_device = device
83  self._state_state = None
84  self._name_name = f"Tank Utility {self.device}"
85  self._unit_of_measurement_unit_of_measurement = PERCENTAGE
86  self._attributes_attributes = {}
87 
88  @property
89  def device(self):
90  """Return the device identifier."""
91  return self._device_device
92 
93  @property
94  def native_value(self):
95  """Return the state of the device."""
96  return self._state_state
97 
98  @property
99  def name(self):
100  """Return the name of the device."""
101  return self._name_name
102 
103  @property
105  """Return the unit of measurement of the device."""
106  return self._unit_of_measurement_unit_of_measurement
107 
108  @property
110  """Return the attributes of the device."""
111  return self._attributes_attributes
112 
113  def get_data(self):
114  """Get data from the device.
115 
116  Flatten dictionary to map device to map of device data.
117 
118  """
119 
120  data = {}
121  try:
122  data = tank_monitor.get_device_data(self._token_token, self.devicedevice)
123  except requests.exceptions.HTTPError as http_error:
124  if http_error.response.status_code in (
125  requests.codes.unauthorized,
126  requests.codes.bad_request,
127  ):
128  _LOGGER.debug("Getting new token")
129  self._token_token = auth.get_token(self._email_email, self._password_password, force=True)
130  data = tank_monitor.get_device_data(self._token_token, self.devicedevice)
131  else:
132  raise
133  data.update(data.pop("device", {}))
134  data.update(data.pop("lastReading", {}))
135  return data
136 
137  def update(self) -> None:
138  """Set the device state and attributes."""
139  data = self.get_dataget_data()
140  self._state_state = round(data[SENSOR_TYPE], SENSOR_ROUNDING_PRECISION)
141  self._attributes_attributes = {k: v for k, v in data.items() if k in SENSOR_ATTRS}
def __init__(self, email, password, token, device)
Definition: sensor.py:77
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:53