Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for monitoring energy usage using the DTE energy bridge."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import logging
7 
8 import requests
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
13  SensorDeviceClass,
14  SensorEntity,
15  SensorStateClass,
16 )
17 from homeassistant.const import CONF_NAME, UnitOfPower
18 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.entity_platform import AddEntitiesCallback
21 from homeassistant.helpers.issue_registry import IssueSeverity, create_issue
22 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 CONF_IP_ADDRESS = "ip"
27 CONF_VERSION = "version"
28 
29 DEFAULT_NAME = "Current Energy Usage"
30 DEFAULT_VERSION = 1
31 DOMAIN = "dte_energy_bridge"
32 
33 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
34  {
35  vol.Required(CONF_IP_ADDRESS): cv.string,
36  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
37  vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.All(
38  vol.Coerce(int), vol.Any(1, 2)
39  ),
40  }
41 )
42 
43 
45  hass: HomeAssistant,
46  config: ConfigType,
47  add_entities: AddEntitiesCallback,
48  discovery_info: DiscoveryInfoType | None = None,
49 ) -> None:
50  """Set up the DTE energy bridge sensor."""
52  hass,
53  DOMAIN,
54  "deprecated_integration",
55  breaks_in_ha_version="2025.1.0",
56  is_fixable=False,
57  issue_domain=DOMAIN,
58  severity=IssueSeverity.WARNING,
59  translation_key="deprecated_integration",
60  translation_placeholders={"domain": DOMAIN},
61  )
62 
63  name = config[CONF_NAME]
64  ip_address = config[CONF_IP_ADDRESS]
65  version = config[CONF_VERSION]
66 
67  add_entities([DteEnergyBridgeSensor(ip_address, name, version)], True)
68 
69 
71  """Implementation of the DTE Energy Bridge sensors."""
72 
73  _attr_device_class = SensorDeviceClass.POWER
74  _attr_native_unit_of_measurement = UnitOfPower.KILO_WATT
75  _attr_state_class = SensorStateClass.MEASUREMENT
76 
77  def __init__(self, ip_address, name, version):
78  """Initialize the sensor."""
79  self._version_version = version
80 
81  if self._version_version == 1:
82  self._url_url = f"http://{ip_address}/instantaneousdemand"
83  elif self._version_version == 2:
84  self._url_url = f"http://{ip_address}:8888/zigbee/se/instantaneousdemand"
85 
86  self._attr_name_attr_name = name
87 
88  def update(self) -> None:
89  """Get the energy usage data from the DTE energy bridge."""
90  try:
91  response = requests.get(self._url_url, timeout=5)
92  except (requests.exceptions.RequestException, ValueError):
93  _LOGGER.warning(
94  "Could not update status for DTE Energy Bridge (%s)", self._attr_name_attr_name
95  )
96  return
97 
98  if response.status_code != HTTPStatus.OK:
99  _LOGGER.warning(
100  "Invalid status_code from DTE Energy Bridge: %s (%s)",
101  response.status_code,
102  self._attr_name_attr_name,
103  )
104  return
105 
106  response_split = response.text.split()
107 
108  if len(response_split) != 2:
109  _LOGGER.warning(
110  'Invalid response from DTE Energy Bridge: "%s" (%s)',
111  response.text,
112  self._attr_name_attr_name,
113  )
114  return
115 
116  val = float(response_split[0])
117 
118  # A workaround for a bug in the DTE energy bridge.
119  # The returned value can randomly be in W or kW. Checking for a
120  # a decimal seems to be a reliable way to determine the units.
121  # Limiting to version 1 because version 2 apparently always returns
122  # values in the format 000000.000 kW, but the scaling is Watts
123  # NOT kWatts
124  if self._version_version == 1 and "." in response_split[0]:
125  self._attr_native_value_attr_native_value = val
126  else:
127  self._attr_native_value_attr_native_value = val / 1000
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:49
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None create_issue(HomeAssistant hass, str domain, str issue_id, *str|None breaks_in_ha_version=None, dict[str, str|int|float|None]|None data=None, bool is_fixable, bool is_persistent=False, str|None issue_domain=None, str|None learn_more_url=None, IssueSeverity severity, str translation_key, dict[str, str]|None translation_placeholders=None)