mirror of
https://github.com/home-assistant/core.git
synced 2025-07-11 07:17:12 +00:00
Move envoy last reported attribute to its own sensor (#68360)
This commit is contained in:
parent
2f7aeb64d2
commit
3d378449e8
@ -11,7 +11,7 @@ import httpx
|
|||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
|
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
|
||||||
from homeassistant.helpers.httpx_client import get_async_client
|
from homeassistant.helpers.httpx_client import get_async_client
|
||||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||||
|
|
||||||
@ -38,7 +38,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
|
|
||||||
async def async_update_data():
|
async def async_update_data():
|
||||||
"""Fetch data from API endpoint."""
|
"""Fetch data from API endpoint."""
|
||||||
data = {}
|
|
||||||
async with async_timeout.timeout(30):
|
async with async_timeout.timeout(30):
|
||||||
try:
|
try:
|
||||||
await envoy_reader.getData()
|
await envoy_reader.getData()
|
||||||
@ -47,15 +46,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
except httpx.HTTPError as err:
|
except httpx.HTTPError as err:
|
||||||
raise UpdateFailed(f"Error communicating with API: {err}") from err
|
raise UpdateFailed(f"Error communicating with API: {err}") from err
|
||||||
|
|
||||||
for description in SENSORS:
|
data = {
|
||||||
if description.key != "inverters":
|
description.key: await getattr(envoy_reader, description.key)()
|
||||||
data[description.key] = await getattr(
|
for description in SENSORS
|
||||||
envoy_reader, description.key
|
}
|
||||||
)()
|
data["inverters_production"] = await envoy_reader.inverters_production()
|
||||||
else:
|
|
||||||
data[
|
|
||||||
"inverters_production"
|
|
||||||
] = await envoy_reader.inverters_production()
|
|
||||||
|
|
||||||
_LOGGER.debug("Retrieved data from API: %s", data)
|
_LOGGER.debug("Retrieved data from API: %s", data)
|
||||||
|
|
||||||
@ -78,8 +73,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
if not entry.unique_id:
|
if not entry.unique_id:
|
||||||
try:
|
try:
|
||||||
serial = await envoy_reader.get_full_serial_number()
|
serial = await envoy_reader.get_full_serial_number()
|
||||||
except httpx.HTTPError:
|
except httpx.HTTPError as ex:
|
||||||
pass
|
raise ConfigEntryNotReady(
|
||||||
|
f"Could not obtain serial number from envoy: {ex}"
|
||||||
|
) from ex
|
||||||
else:
|
else:
|
||||||
hass.config_entries.async_update_entry(entry, unique_id=serial)
|
hass.config_entries.async_update_entry(entry, unique_id=serial)
|
||||||
|
|
||||||
|
@ -71,10 +71,4 @@ SENSORS = (
|
|||||||
state_class=SensorStateClass.TOTAL_INCREASING,
|
state_class=SensorStateClass.TOTAL_INCREASING,
|
||||||
device_class=SensorDeviceClass.ENERGY,
|
device_class=SensorDeviceClass.ENERGY,
|
||||||
),
|
),
|
||||||
SensorEntityDescription(
|
|
||||||
key="inverters",
|
|
||||||
name="Inverter",
|
|
||||||
native_unit_of_measurement=POWER_WATT,
|
|
||||||
state_class=SensorStateClass.MEASUREMENT,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
@ -1,16 +1,77 @@
|
|||||||
"""Support for Enphase Envoy solar energy monitor."""
|
"""Support for Enphase Envoy solar energy monitor."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from homeassistant.components.sensor import SensorEntity
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from homeassistant.components.sensor import (
|
||||||
|
SensorDeviceClass,
|
||||||
|
SensorEntity,
|
||||||
|
SensorEntityDescription,
|
||||||
|
SensorStateClass,
|
||||||
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
|
from homeassistant.const import POWER_WATT
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.helpers.entity import DeviceInfo
|
from homeassistant.helpers.entity import DeviceInfo
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import (
|
||||||
|
CoordinatorEntity,
|
||||||
|
DataUpdateCoordinator,
|
||||||
|
)
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
from .const import COORDINATOR, DOMAIN, NAME, SENSORS
|
from .const import COORDINATOR, DOMAIN, NAME, SENSORS
|
||||||
|
|
||||||
ICON = "mdi:flash"
|
ICON = "mdi:flash"
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
INVERTERS_KEY = "inverters"
|
||||||
|
LAST_REPORTED_KEY = "last_reported"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EnvoyRequiredKeysMixin:
|
||||||
|
"""Mixin for required keys."""
|
||||||
|
|
||||||
|
value_fn: Callable[[tuple[float, str]], datetime.datetime | float | None]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EnvoySensorEntityDescription(SensorEntityDescription, EnvoyRequiredKeysMixin):
|
||||||
|
"""Describes an Envoy inverter sensor entity."""
|
||||||
|
|
||||||
|
|
||||||
|
def _inverter_last_report_time(
|
||||||
|
watt_report_time: tuple[float, str]
|
||||||
|
) -> datetime.datetime | None:
|
||||||
|
if (report_time := watt_report_time[1]) is None:
|
||||||
|
return None
|
||||||
|
if (last_reported_dt := dt_util.parse_datetime(report_time)) is None:
|
||||||
|
return None
|
||||||
|
if last_reported_dt.tzinfo is None:
|
||||||
|
return last_reported_dt.replace(tzinfo=dt_util.UTC)
|
||||||
|
return last_reported_dt
|
||||||
|
|
||||||
|
|
||||||
|
INVERTER_SENSORS = (
|
||||||
|
EnvoySensorEntityDescription(
|
||||||
|
key=INVERTERS_KEY,
|
||||||
|
native_unit_of_measurement=POWER_WATT,
|
||||||
|
state_class=SensorStateClass.MEASUREMENT,
|
||||||
|
value_fn=lambda watt_report_time: watt_report_time[0],
|
||||||
|
),
|
||||||
|
EnvoySensorEntityDescription(
|
||||||
|
key=LAST_REPORTED_KEY,
|
||||||
|
name="Last Reported",
|
||||||
|
device_class=SensorDeviceClass.TIMESTAMP,
|
||||||
|
entity_registry_enabled_default=False,
|
||||||
|
value_fn=_inverter_last_report_time,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
@ -19,129 +80,116 @@ async def async_setup_entry(
|
|||||||
async_add_entities: AddEntitiesCallback,
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up envoy sensor platform."""
|
"""Set up envoy sensor platform."""
|
||||||
data = hass.data[DOMAIN][config_entry.entry_id]
|
data: dict = hass.data[DOMAIN][config_entry.entry_id]
|
||||||
coordinator = data[COORDINATOR]
|
coordinator: DataUpdateCoordinator = data[COORDINATOR]
|
||||||
name = data[NAME]
|
envoy_data: dict = coordinator.data
|
||||||
|
envoy_name: str = data[NAME]
|
||||||
|
envoy_serial_num = config_entry.unique_id
|
||||||
|
assert envoy_serial_num is not None
|
||||||
|
_LOGGER.debug("Envoy data: %s", envoy_data)
|
||||||
|
|
||||||
entities = []
|
entities: list[Envoy | EnvoyInverter] = []
|
||||||
for sensor_description in SENSORS:
|
for description in SENSORS:
|
||||||
if (
|
sensor_data = envoy_data.get(description.key)
|
||||||
sensor_description.key == "inverters"
|
if isinstance(sensor_data, str) and "not available" in sensor_data:
|
||||||
and coordinator.data.get("inverters_production") is not None
|
|
||||||
):
|
|
||||||
for inverter in coordinator.data["inverters_production"]:
|
|
||||||
entity_name = f"{name} {sensor_description.name} {inverter}"
|
|
||||||
split_name = entity_name.split(" ")
|
|
||||||
serial_number = split_name[-1]
|
|
||||||
entities.append(
|
|
||||||
Envoy(
|
|
||||||
sensor_description,
|
|
||||||
entity_name,
|
|
||||||
name,
|
|
||||||
config_entry.unique_id,
|
|
||||||
serial_number,
|
|
||||||
coordinator,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
elif sensor_description.key != "inverters":
|
|
||||||
data = coordinator.data.get(sensor_description.key)
|
|
||||||
if isinstance(data, str) and "not available" in data:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
entity_name = f"{name} {sensor_description.name}"
|
|
||||||
entities.append(
|
entities.append(
|
||||||
Envoy(
|
Envoy(
|
||||||
sensor_description,
|
|
||||||
entity_name,
|
|
||||||
name,
|
|
||||||
config_entry.unique_id,
|
|
||||||
None,
|
|
||||||
coordinator,
|
coordinator,
|
||||||
|
description,
|
||||||
|
envoy_name,
|
||||||
|
envoy_serial_num,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if production := envoy_data.get("inverters_production"):
|
||||||
|
entities.extend(
|
||||||
|
EnvoyInverter(
|
||||||
|
coordinator,
|
||||||
|
description,
|
||||||
|
envoy_name,
|
||||||
|
envoy_serial_num,
|
||||||
|
str(inverter),
|
||||||
|
)
|
||||||
|
for description in INVERTER_SENSORS
|
||||||
|
for inverter in production
|
||||||
|
)
|
||||||
|
|
||||||
async_add_entities(entities)
|
async_add_entities(entities)
|
||||||
|
|
||||||
|
|
||||||
class Envoy(CoordinatorEntity, SensorEntity):
|
class Envoy(CoordinatorEntity, SensorEntity):
|
||||||
"""Envoy entity."""
|
"""Envoy inverter entity."""
|
||||||
|
|
||||||
|
_attr_icon = ICON
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
description,
|
coordinator: DataUpdateCoordinator,
|
||||||
name,
|
description: SensorEntityDescription,
|
||||||
device_name,
|
envoy_name: str,
|
||||||
device_serial_number,
|
envoy_serial_num: str,
|
||||||
serial_number,
|
) -> None:
|
||||||
coordinator,
|
|
||||||
):
|
|
||||||
"""Initialize Envoy entity."""
|
"""Initialize Envoy entity."""
|
||||||
self.entity_description = description
|
self.entity_description = description
|
||||||
self._name = name
|
self._attr_name = f"{envoy_name} {description.name}"
|
||||||
self._serial_number = serial_number
|
self._attr_unique_id = f"{envoy_serial_num}_{description.key}"
|
||||||
self._device_name = device_name
|
self._attr_device_info = DeviceInfo(
|
||||||
self._device_serial_number = device_serial_number
|
identifiers={(DOMAIN, envoy_serial_num)},
|
||||||
|
manufacturer="Enphase",
|
||||||
|
model="Envoy",
|
||||||
|
name=envoy_name,
|
||||||
|
)
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def native_value(self) -> float | None:
|
||||||
"""Return the name of the sensor."""
|
|
||||||
return self._name
|
|
||||||
|
|
||||||
@property
|
|
||||||
def unique_id(self):
|
|
||||||
"""Return the unique id of the sensor."""
|
|
||||||
if self._serial_number:
|
|
||||||
return self._serial_number
|
|
||||||
if self._device_serial_number:
|
|
||||||
return f"{self._device_serial_number}_{self.entity_description.key}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def native_value(self):
|
|
||||||
"""Return the state of the sensor."""
|
"""Return the state of the sensor."""
|
||||||
if self.entity_description.key != "inverters":
|
if (value := self.coordinator.data.get(self.entity_description.key)) is None:
|
||||||
value = self.coordinator.data.get(self.entity_description.key)
|
|
||||||
|
|
||||||
elif (
|
|
||||||
self.entity_description.key == "inverters"
|
|
||||||
and self.coordinator.data.get("inverters_production") is not None
|
|
||||||
):
|
|
||||||
value = self.coordinator.data.get("inverters_production").get(
|
|
||||||
self._serial_number
|
|
||||||
)[0]
|
|
||||||
else:
|
|
||||||
return None
|
return None
|
||||||
|
return cast(float, value)
|
||||||
|
|
||||||
return value
|
|
||||||
|
|
||||||
@property
|
class EnvoyInverter(CoordinatorEntity, SensorEntity):
|
||||||
def icon(self):
|
"""Envoy inverter entity."""
|
||||||
"""Icon to use in the frontend, if any."""
|
|
||||||
return ICON
|
|
||||||
|
|
||||||
@property
|
_attr_icon = ICON
|
||||||
def extra_state_attributes(self):
|
entity_description: EnvoySensorEntityDescription
|
||||||
"""Return the state attributes."""
|
|
||||||
if (
|
|
||||||
self.entity_description.key == "inverters"
|
|
||||||
and self.coordinator.data.get("inverters_production") is not None
|
|
||||||
):
|
|
||||||
value = self.coordinator.data.get("inverters_production").get(
|
|
||||||
self._serial_number
|
|
||||||
)[1]
|
|
||||||
return {"last_reported": value}
|
|
||||||
|
|
||||||
return None
|
def __init__(
|
||||||
|
self,
|
||||||
@property
|
coordinator: DataUpdateCoordinator,
|
||||||
def device_info(self) -> DeviceInfo | None:
|
description: EnvoySensorEntityDescription,
|
||||||
"""Return the device_info of the device."""
|
envoy_name: str,
|
||||||
if not self._device_serial_number:
|
envoy_serial_num: str,
|
||||||
return None
|
serial_number: str,
|
||||||
return DeviceInfo(
|
) -> None:
|
||||||
identifiers={(DOMAIN, str(self._device_serial_number))},
|
"""Initialize Envoy inverter entity."""
|
||||||
manufacturer="Enphase",
|
self.entity_description = description
|
||||||
model="Envoy",
|
self._serial_number = serial_number
|
||||||
name=self._device_name,
|
if description.name:
|
||||||
|
self._attr_name = (
|
||||||
|
f"{envoy_name} Inverter {serial_number} {description.name}"
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
self._attr_name = f"{envoy_name} Inverter {serial_number}"
|
||||||
|
if description.key == INVERTERS_KEY:
|
||||||
|
self._attr_unique_id = serial_number
|
||||||
|
else:
|
||||||
|
self._attr_unique_id = f"{serial_number}_{description.key}"
|
||||||
|
self._attr_device_info = DeviceInfo(
|
||||||
|
identifiers={(DOMAIN, serial_number)},
|
||||||
|
name=f"Inverter {serial_number}",
|
||||||
|
manufacturer="Enphase",
|
||||||
|
model="Inverter",
|
||||||
|
via_device=(DOMAIN, envoy_serial_num),
|
||||||
|
)
|
||||||
|
super().__init__(coordinator)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def native_value(self) -> datetime.datetime | float | None:
|
||||||
|
"""Return the state of the sensor."""
|
||||||
|
watt_report_time: tuple[float, str] = self.coordinator.data[
|
||||||
|
"inverters_production"
|
||||||
|
][self._serial_number]
|
||||||
|
return self.entity_description.value_fn(watt_report_time)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user