Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for information from HP iLO sensors."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 import hpilo
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
13  SensorEntity,
14 )
15 from homeassistant.const import (
16  CONF_HOST,
17  CONF_MONITORED_VARIABLES,
18  CONF_NAME,
19  CONF_PASSWORD,
20  CONF_PORT,
21  CONF_SENSOR_TYPE,
22  CONF_UNIT_OF_MEASUREMENT,
23  CONF_USERNAME,
24  CONF_VALUE_TEMPLATE,
25 )
26 from homeassistant.core import HomeAssistant
28 from homeassistant.helpers.entity_platform import AddEntitiesCallback
29 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
30 from homeassistant.util import Throttle
31 
32 _LOGGER = logging.getLogger(__name__)
33 
34 DEFAULT_NAME = "HP ILO"
35 DEFAULT_PORT = 443
36 
37 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)
38 
39 SENSOR_TYPES = {
40  "server_name": ["Server Name", "get_server_name"],
41  "server_fqdn": ["Server FQDN", "get_server_fqdn"],
42  "server_host_data": ["Server Host Data", "get_host_data"],
43  "server_oa_info": ["Server Onboard Administrator Info", "get_oa_info"],
44  "server_power_status": ["Server Power state", "get_host_power_status"],
45  "server_power_readings": ["Server Power readings", "get_power_readings"],
46  "server_power_on_time": ["Server Power On time", "get_server_power_on_time"],
47  "server_asset_tag": ["Server Asset Tag", "get_asset_tag"],
48  "server_uid_status": ["Server UID light", "get_uid_status"],
49  "server_health": ["Server Health", "get_embedded_health"],
50  "network_settings": ["Network Settings", "get_network_settings"],
51 }
52 
53 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
54  {
55  vol.Required(CONF_HOST): cv.string,
56  vol.Required(CONF_USERNAME): cv.string,
57  vol.Required(CONF_PASSWORD): cv.string,
58  vol.Optional(CONF_MONITORED_VARIABLES, default=[]): vol.All(
59  cv.ensure_list,
60  [
61  vol.Schema(
62  {
63  vol.Required(CONF_NAME): cv.string,
64  vol.Required(CONF_SENSOR_TYPE): vol.All(
65  cv.string, vol.In(SENSOR_TYPES)
66  ),
67  vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
68  vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
69  }
70  )
71  ],
72  ),
73  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
74  vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
75  }
76 )
77 
78 
80  hass: HomeAssistant,
81  config: ConfigType,
82  add_entities: AddEntitiesCallback,
83  discovery_info: DiscoveryInfoType | None = None,
84 ) -> None:
85  """Set up the HP iLO sensors."""
86  hostname = config[CONF_HOST]
87  port = config[CONF_PORT]
88  login = config[CONF_USERNAME]
89  password = config[CONF_PASSWORD]
90  monitored_variables = config[CONF_MONITORED_VARIABLES]
91 
92  # Create a data fetcher to support all of the configured sensors. Then make
93  # the first call to init the data and confirm we can connect.
94  try:
95  hp_ilo_data = HpIloData(hostname, port, login, password)
96  except ValueError as error:
97  _LOGGER.error(error)
98  return
99 
100  # Initialize and add all of the sensors.
101  devices = []
102  for monitored_variable in monitored_variables:
103  new_device = HpIloSensor(
104  hass=hass,
105  hp_ilo_data=hp_ilo_data,
106  sensor_name=f"{config[CONF_NAME]} {monitored_variable[CONF_NAME]}",
107  sensor_type=monitored_variable[CONF_SENSOR_TYPE],
108  sensor_value_template=monitored_variable.get(CONF_VALUE_TEMPLATE),
109  unit_of_measurement=monitored_variable.get(CONF_UNIT_OF_MEASUREMENT),
110  )
111  devices.append(new_device)
112 
113  add_entities(devices, True)
114 
115 
117  """Representation of a HP iLO sensor."""
118 
119  def __init__(
120  self,
121  hass,
122  hp_ilo_data,
123  sensor_type,
124  sensor_name,
125  sensor_value_template,
126  unit_of_measurement,
127  ):
128  """Initialize the HP iLO sensor."""
129  self._hass_hass = hass
130  self._name_name = sensor_name
131  self._unit_of_measurement_unit_of_measurement = unit_of_measurement
132  self._ilo_function_ilo_function = SENSOR_TYPES[sensor_type][1]
133  self.hp_ilo_datahp_ilo_data = hp_ilo_data
134  self._sensor_value_template_sensor_value_template = sensor_value_template
135 
136  self._state_state = None
137  self._state_attributes_state_attributes = None
138 
139  _LOGGER.debug("Created HP iLO sensor %r", self)
140 
141  @property
142  def name(self):
143  """Return the name of the sensor."""
144  return self._name_name
145 
146  @property
148  """Return the unit of measurement of the sensor."""
149  return self._unit_of_measurement_unit_of_measurement
150 
151  @property
152  def native_value(self):
153  """Return the state of the sensor."""
154  return self._state_state
155 
156  @property
158  """Return the device state attributes."""
159  return self._state_attributes_state_attributes
160 
161  def update(self) -> None:
162  """Get the latest data from HP iLO and updates the states."""
163  # Call the API for new data. Each sensor will re-trigger this
164  # same exact call, but that's fine. Results should be cached for
165  # a short period of time to prevent hitting API limits.
166  self.hp_ilo_datahp_ilo_data.update()
167  ilo_data = getattr(self.hp_ilo_datahp_ilo_data.data, self._ilo_function_ilo_function)()
168 
169  if self._sensor_value_template_sensor_value_template is not None:
170  ilo_data = self._sensor_value_template_sensor_value_template.render(
171  ilo_data=ilo_data, parse_result=False
172  )
173 
174  self._state_state = ilo_data
175 
176 
177 class HpIloData:
178  """Gets the latest data from HP iLO."""
179 
180  def __init__(self, host, port, login, password):
181  """Initialize the data object."""
182  self._host_host = host
183  self._port_port = port
184  self._login_login = login
185  self._password_password = password
186 
187  self.datadata = None
188 
189  self.updateupdate()
190 
191  @Throttle(MIN_TIME_BETWEEN_UPDATES)
192  def update(self):
193  """Get the latest data from HP iLO."""
194  try:
195  self.datadata = hpilo.Ilo(
196  hostname=self._host_host,
197  login=self._login_login,
198  password=self._password_password,
199  port=self._port_port,
200  )
201  except (
202  hpilo.IloError,
203  hpilo.IloCommunicationError,
204  hpilo.IloLoginFailed,
205  ) as error:
206  raise ValueError(f"Unable to init HP ILO, {error}") from error
def __init__(self, host, port, login, password)
Definition: sensor.py:180
def __init__(self, hass, hp_ilo_data, sensor_type, sensor_name, sensor_value_template, unit_of_measurement)
Definition: sensor.py:127
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:84
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40