Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for monitoring an OpenEVSE Charger."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import openevsewifi
8 from requests import RequestException
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
13  SensorDeviceClass,
14  SensorEntity,
15  SensorEntityDescription,
16  SensorStateClass,
17 )
18 from homeassistant.const import (
19  CONF_HOST,
20  CONF_MONITORED_VARIABLES,
21  UnitOfEnergy,
22  UnitOfTemperature,
23  UnitOfTime,
24 )
25 from homeassistant.core import HomeAssistant
27 from homeassistant.helpers.entity_platform import AddEntitiesCallback
28 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
29 
30 _LOGGER = logging.getLogger(__name__)
31 
32 SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
34  key="status",
35  name="Charging Status",
36  ),
38  key="charge_time",
39  name="Charge Time Elapsed",
40  native_unit_of_measurement=UnitOfTime.MINUTES,
41  device_class=SensorDeviceClass.DURATION,
42  state_class=SensorStateClass.MEASUREMENT,
43  ),
45  key="ambient_temp",
46  name="Ambient Temperature",
47  native_unit_of_measurement=UnitOfTemperature.CELSIUS,
48  device_class=SensorDeviceClass.TEMPERATURE,
49  state_class=SensorStateClass.MEASUREMENT,
50  ),
52  key="ir_temp",
53  name="IR Temperature",
54  native_unit_of_measurement=UnitOfTemperature.CELSIUS,
55  device_class=SensorDeviceClass.TEMPERATURE,
56  state_class=SensorStateClass.MEASUREMENT,
57  ),
59  key="rtc_temp",
60  name="RTC Temperature",
61  native_unit_of_measurement=UnitOfTemperature.CELSIUS,
62  device_class=SensorDeviceClass.TEMPERATURE,
63  state_class=SensorStateClass.MEASUREMENT,
64  ),
66  key="usage_session",
67  name="Usage this Session",
68  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
69  device_class=SensorDeviceClass.ENERGY,
70  state_class=SensorStateClass.TOTAL_INCREASING,
71  ),
73  key="usage_total",
74  name="Total Usage",
75  native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
76  device_class=SensorDeviceClass.ENERGY,
77  state_class=SensorStateClass.TOTAL_INCREASING,
78  ),
79 )
80 
81 SENSOR_KEYS: list[str] = [desc.key for desc in SENSOR_TYPES]
82 
83 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
84  {
85  vol.Required(CONF_HOST): cv.string,
86  vol.Optional(CONF_MONITORED_VARIABLES, default=["status"]): vol.All(
87  cv.ensure_list, [vol.In(SENSOR_KEYS)]
88  ),
89  }
90 )
91 
92 
94  hass: HomeAssistant,
95  config: ConfigType,
96  add_entities: AddEntitiesCallback,
97  discovery_info: DiscoveryInfoType | None = None,
98 ) -> None:
99  """Set up the OpenEVSE sensor."""
100  host = config[CONF_HOST]
101  monitored_variables = config[CONF_MONITORED_VARIABLES]
102 
103  charger = openevsewifi.Charger(host)
104 
105  entities = [
106  OpenEVSESensor(charger, description)
107  for description in SENSOR_TYPES
108  if description.key in monitored_variables
109  ]
110 
111  add_entities(entities, True)
112 
113 
115  """Implementation of an OpenEVSE sensor."""
116 
117  def __init__(self, charger, description: SensorEntityDescription) -> None:
118  """Initialize the sensor."""
119  self.entity_descriptionentity_description = description
120  self.chargercharger = charger
121 
122  def update(self) -> None:
123  """Get the monitored data from the charger."""
124  try:
125  sensor_type = self.entity_descriptionentity_description.key
126  if sensor_type == "status":
127  self._attr_native_value_attr_native_value = self.chargercharger.getStatus()
128  elif sensor_type == "charge_time":
129  self._attr_native_value_attr_native_value = self.chargercharger.getChargeTimeElapsed() / 60
130  elif sensor_type == "ambient_temp":
131  self._attr_native_value_attr_native_value = self.chargercharger.getAmbientTemperature()
132  elif sensor_type == "ir_temp":
133  self._attr_native_value_attr_native_value = self.chargercharger.getIRTemperature()
134  elif sensor_type == "rtc_temp":
135  self._attr_native_value_attr_native_value = self.chargercharger.getRTCTemperature()
136  elif sensor_type == "usage_session":
137  self._attr_native_value_attr_native_value = float(self.chargercharger.getUsageSession()) / 1000
138  elif sensor_type == "usage_total":
139  self._attr_native_value_attr_native_value = float(self.chargercharger.getUsageTotal()) / 1000
140  else:
141  self._attr_native_value_attr_native_value = "Unknown"
142  except (RequestException, ValueError, KeyError):
143  _LOGGER.warning("Could not update status for %s", self.namename)
None __init__(self, charger, SensorEntityDescription description)
Definition: sensor.py:117
str|UndefinedType|None name(self)
Definition: entity.py:738
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:98