Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for Soma sensors."""
2 
3 from datetime import timedelta
4 
5 from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
6 from homeassistant.config_entries import ConfigEntry
7 from homeassistant.const import PERCENTAGE
8 from homeassistant.core import HomeAssistant
9 from homeassistant.helpers.entity_platform import AddEntitiesCallback
10 from homeassistant.util import Throttle
11 
12 from .const import API, DEVICES, DOMAIN
13 from .entity import SomaEntity
14 
15 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=30)
16 
17 
19  hass: HomeAssistant,
20  config_entry: ConfigEntry,
21  async_add_entities: AddEntitiesCallback,
22 ) -> None:
23  """Set up the Soma sensor platform."""
24 
25  devices = hass.data[DOMAIN][DEVICES]
26 
28  [SomaSensor(sensor, hass.data[DOMAIN][API]) for sensor in devices], True
29  )
30 
31 
33  """Representation of a Soma cover device."""
34 
35  _attr_device_class = SensorDeviceClass.BATTERY
36  _attr_native_unit_of_measurement = PERCENTAGE
37 
38  @property
39  def native_value(self):
40  """Return the state of the entity."""
41  return self.battery_statebattery_statebattery_state
42 
43  @Throttle(MIN_TIME_BETWEEN_UPDATES)
44  async def async_update(self) -> None:
45  """Update the sensor with the latest data."""
46  response = await self.get_battery_level_from_apiget_battery_level_from_api()
47  _battery = response.get("battery_percentage")
48  if _battery is None:
49  # https://support.somasmarthome.com/hc/en-us/articles/360026064234-HTTP-API
50  # battery_level response is expected to be min = 360, max 410 for
51  # 0-100% levels above 410 are consider 100% and below 360, 0% as the
52  # device considers 360 the minimum to move the motor.
53  _battery = round(2 * (response["battery_level"] - 360))
54  battery = max(min(100, _battery), 0)
55  self.battery_statebattery_statebattery_state = battery
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:22