Home Assistant Unofficial Reference 2024.12.1
data.py
Go to the documentation of this file.
1 """Data for the D-Link Power Plug integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime
6 import logging
7 import urllib
8 
9 from pyW215.pyW215 import SmartPlug
10 
11 from homeassistant.util import dt as dt_util
12 
13 _LOGGER = logging.getLogger(__name__)
14 
15 
17  """Get the latest data from smart plug."""
18 
19  def __init__(self, smartplug: SmartPlug) -> None:
20  """Initialize the data object."""
21  self.smartplugsmartplug = smartplug
22  self.statestate: str | None = None
23  self.temperaturetemperature: str = ""
24  self.current_consumptioncurrent_consumption: str = ""
25  self.total_consumptiontotal_consumption: str = ""
26  self.availableavailable = False
27  self._n_tried_n_tried = 0
28  self._last_tried_last_tried: datetime | None = None
29 
30  def update(self) -> None:
31  """Get the latest data from the smart plug."""
32  if self._last_tried_last_tried is not None:
33  last_try_s = (dt_util.now() - self._last_tried_last_tried).total_seconds() / 60
34  retry_seconds = min(self._n_tried_n_tried * 2, 10) - last_try_s
35  if self._n_tried_n_tried > 0 and retry_seconds > 0:
36  _LOGGER.warning("Waiting %s s to retry", retry_seconds)
37  return
38 
39  _state = "unknown"
40 
41  try:
42  self._last_tried_last_tried = dt_util.now()
43  _state = self.smartplugsmartplug.state
44  except urllib.error.HTTPError:
45  _LOGGER.error("D-Link connection problem")
46  if _state == "unknown":
47  self._n_tried_n_tried += 1
48  self.availableavailable = False
49  _LOGGER.warning("Failed to connect to D-Link switch")
50  return
51 
52  self.statestate = _state
53  self.availableavailable = True
54 
55  self.temperaturetemperature = self.smartplugsmartplug.temperature
56  self.current_consumptioncurrent_consumption = self.smartplugsmartplug.current_consumption
57  self.total_consumptiontotal_consumption = self.smartplugsmartplug.total_consumption
58  self._n_tried_n_tried = 0