Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for monitoring Repetier Server Sensors."""
2 
3 from __future__ import annotations
4 
5 import logging
6 import time
7 
8 from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
9 from homeassistant.core import HomeAssistant, callback
10 from homeassistant.helpers.dispatcher import async_dispatcher_connect
11 from homeassistant.helpers.entity_platform import AddEntitiesCallback
12 from homeassistant.helpers.typing import UNDEFINED, ConfigType, DiscoveryInfoType
13 from homeassistant.util import dt as dt_util
14 
15 from . import REPETIER_API, SENSOR_TYPES, UPDATE_SIGNAL, RepetierSensorEntityDescription
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
21  hass: HomeAssistant,
22  config: ConfigType,
23  add_entities: AddEntitiesCallback,
24  discovery_info: DiscoveryInfoType | None = None,
25 ) -> None:
26  """Set up the available Repetier Server sensors."""
27  if discovery_info is None:
28  return
29 
30  sensor_map = {
31  "bed_temperature": RepetierTempSensor,
32  "extruder_temperature": RepetierTempSensor,
33  "chamber_temperature": RepetierTempSensor,
34  "current_state": RepetierSensor,
35  "current_job": RepetierJobSensor,
36  "job_end": RepetierJobEndSensor,
37  "job_start": RepetierJobStartSensor,
38  }
39 
40  sensors_info: list[dict] = discovery_info["sensors"]
41  entities = []
42  for info in sensors_info:
43  printer_name = info["printer_name"]
44  api = hass.data[REPETIER_API][printer_name]
45  printer_id = info["printer_id"]
46  sensor_type = info["sensor_type"]
47  temp_id = info["temp_id"]
48  description = SENSOR_TYPES[sensor_type]
49  name_suffix = "" if description.name is UNDEFINED else description.name
50  name = f"{info['name']}{name_suffix}"
51  if temp_id is not None:
52  _LOGGER.debug("%s Temp_id: %s", sensor_type, temp_id)
53  name = f"{name}{temp_id}"
54  sensor_class = sensor_map[sensor_type]
55  entity = sensor_class(api, temp_id, name, printer_id, description)
56  entities.append(entity)
57 
58  add_entities(entities, True)
59 
60 
62  """Class to create and populate a Repetier Sensor."""
63 
64  entity_description: RepetierSensorEntityDescription
65  _attr_should_poll = False
66 
67  def __init__(
68  self,
69  api,
70  temp_id,
71  name,
72  printer_id,
73  description: RepetierSensorEntityDescription,
74  ) -> None:
75  """Init new sensor."""
76  self.entity_descriptionentity_description = description
77  self._api_api = api
78  self._attributes: dict = {}
79  self._temp_id_temp_id = temp_id
80  self._printer_id_printer_id = printer_id
81  self._state_state = None
82 
83  self._attr_name_attr_name = name
84  self._attr_available_attr_available = False
85 
86  @property
88  """Return sensor attributes."""
89  return self._attributes
90 
91  @property
92  def native_value(self):
93  """Return sensor state."""
94  return self._state_state
95 
96  @callback
97  def update_callback(self):
98  """Get new data and update state."""
99  self.async_schedule_update_ha_stateasync_schedule_update_ha_state(True)
100 
101  async def async_added_to_hass(self):
102  """Connect update callbacks."""
103  self.async_on_removeasync_on_remove(
104  async_dispatcher_connect(self.hasshass, UPDATE_SIGNAL, self.update_callbackupdate_callback)
105  )
106 
107  def _get_data(self):
108  """Return new data from the api cache."""
109  sensor_type = self.entity_descriptionentity_description.key
110  data = self._api_api.get_data(self._printer_id_printer_id, sensor_type, self._temp_id_temp_id)
111  if data is None:
112  _LOGGER.debug("Data not found for %s and %s", sensor_type, self._temp_id_temp_id)
113  self._attr_available_attr_available = False
114  return None
115  self._attr_available_attr_available = True
116  return data
117 
118  def update(self):
119  """Update the sensor."""
120  if (data := self._get_data_get_data()) is None:
121  return
122  state = data.pop("state")
123  _LOGGER.debug("Printer %s State %s", self.namename, state)
124  self._attributes.update(data)
125  self._state_state = state
126 
127 
129  """Represent a Repetier temp sensor."""
130 
131  @property
132  def native_value(self):
133  """Return sensor state."""
134  if self._state_state_state is None:
135  return None
136  return round(self._state_state_state, 2)
137 
138  def update(self):
139  """Update the sensor."""
140  if (data := self._get_data_get_data()) is None:
141  return
142  state = data.pop("state")
143  temp_set = data["temp_set"]
144  _LOGGER.debug("Printer %s Setpoint: %s, Temp: %s", self.namename, temp_set, state)
145  self._attributes.update(data)
146  self._state_state_state = state
147 
148 
150  """Represent a Repetier job sensor."""
151 
152  @property
153  def native_value(self):
154  """Return sensor state."""
155  if self._state_state is None:
156  return None
157  return round(self._state_state, 2)
158 
159 
161  """Class to create and populate a Repetier Job End timestamp Sensor."""
162 
163  _attr_device_class = SensorDeviceClass.TIMESTAMP
164 
165  def update(self):
166  """Update the sensor."""
167  if (data := self._get_data_get_data()) is None:
168  return
169  job_name = data["job_name"]
170  start = data["start"]
171  print_time = data["print_time"]
172  from_start = data["from_start"]
173  time_end = start + round(print_time, 0)
174  self._state_state_state = dt_util.utc_from_timestamp(time_end)
175  remaining = print_time - from_start
176  remaining_secs = int(round(remaining, 0))
177  _LOGGER.debug(
178  "Job %s remaining %s",
179  job_name,
180  time.strftime("%H:%M:%S", time.gmtime(remaining_secs)),
181  )
182 
183 
185  """Class to create and populate a Repetier Job Start timestamp Sensor."""
186 
187  _attr_device_class = SensorDeviceClass.TIMESTAMP
188 
189  def update(self):
190  """Update the sensor."""
191  if (data := self._get_data_get_data()) is None:
192  return
193  job_name = data["job_name"]
194  start = data["start"]
195  from_start = data["from_start"]
196  self._state_state_state = dt_util.utc_from_timestamp(start)
197  elapsed_secs = int(round(from_start, 0))
198  _LOGGER.debug(
199  "Job %s elapsed %s",
200  job_name,
201  time.strftime("%H:%M:%S", time.gmtime(elapsed_secs)),
202  )
None __init__(self, api, temp_id, name, printer_id, RepetierSensorEntityDescription description)
Definition: sensor.py:74
None async_schedule_update_ha_state(self, bool force_refresh=False)
Definition: entity.py:1265
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
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:25
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103