Use EntityDescription - efergy (#54210)

pull/56520/head
Robert Hillis 2021-09-21 17:53:35 -04:00 committed by GitHub
parent b7a758bd0c
commit a653da137c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 75 additions and 50 deletions

View File

@ -1,18 +1,31 @@
"""Support for Efergy sensors."""
from __future__ import annotations
import logging
from typing import Any
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import (
CONF_CURRENCY,
CONF_MONITORED_VARIABLES,
CONF_TYPE,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_MONETARY,
DEVICE_CLASS_POWER,
ENERGY_KILO_WATT_HOUR,
POWER_WATT,
)
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
_LOGGER = logging.getLogger(__name__)
_RESOURCE = "https://engage.efergy.com/mobile_proxy/"
@ -31,12 +44,34 @@ CONF_CURRENT_VALUES = "current_values"
DEFAULT_PERIOD = "year"
DEFAULT_UTC_OFFSET = "0"
SENSOR_TYPES = {
CONF_INSTANT: ["Energy Usage", POWER_WATT],
CONF_AMOUNT: ["Energy Consumed", ENERGY_KILO_WATT_HOUR],
CONF_BUDGET: ["Energy Budget", None],
CONF_COST: ["Energy Cost", None],
CONF_CURRENT_VALUES: ["Per-Device Usage", POWER_WATT],
SENSOR_TYPES: dict[str, SensorEntityDescription] = {
CONF_INSTANT: SensorEntityDescription(
key=CONF_INSTANT,
name="Energy Usage",
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_WATT,
),
CONF_AMOUNT: SensorEntityDescription(
key=CONF_AMOUNT,
name="Energy Consumed",
device_class=DEVICE_CLASS_ENERGY,
native_unit_of_measurement=ENERGY_KILO_WATT_HOUR,
),
CONF_BUDGET: SensorEntityDescription(
key=CONF_BUDGET,
name="Energy Budget",
),
CONF_COST: SensorEntityDescription(
key=CONF_COST,
name="Energy Cost",
device_class=DEVICE_CLASS_MONETARY,
),
CONF_CURRENT_VALUES: SensorEntityDescription(
key=CONF_CURRENT_VALUES,
name="Per-Device Usage",
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_WATT,
),
}
TYPES_SCHEMA = vol.In(SENSOR_TYPES)
@ -58,7 +93,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
)
def setup_platform(hass, config, add_entities, discovery_info=None):
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType = None,
) -> None:
"""Set up the Efergy sensor."""
app_token = config.get(CONF_APPTOKEN)
utc_offset = str(config.get(CONF_UTC_OFFSET))
@ -72,21 +112,21 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
sid = sensor["sid"]
dev.append(
EfergySensor(
variable[CONF_TYPE],
app_token,
utc_offset,
variable[CONF_PERIOD],
variable[CONF_CURRENCY],
sid,
SENSOR_TYPES[variable[CONF_TYPE]],
sid=sid,
)
)
dev.append(
EfergySensor(
variable[CONF_TYPE],
app_token,
utc_offset,
variable[CONF_PERIOD],
variable[CONF_CURRENCY],
SENSOR_TYPES[variable[CONF_TYPE]],
)
)
@ -96,59 +136,46 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
class EfergySensor(SensorEntity):
"""Implementation of an Efergy sensor."""
def __init__(self, sensor_type, app_token, utc_offset, period, currency, sid=None):
def __init__(
self,
app_token: Any,
utc_offset: str,
period: str,
currency: str,
description: SensorEntityDescription,
sid: str = None,
) -> None:
"""Initialize the sensor."""
self.entity_description = description
self.sid = sid
if sid:
self._name = f"efergy_{sid}"
else:
self._name = SENSOR_TYPES[sensor_type][0]
self.type = sensor_type
self._attr_name = f"efergy_{sid}"
self.app_token = app_token
self.utc_offset = utc_offset
self._state = None
self.period = period
self.currency = currency
if self.type == "cost":
self._unit_of_measurement = f"{self.currency}/{self.period}"
else:
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
if description.key == CONF_COST:
self._attr_native_unit_of_measurement = f"{currency}/{period}"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def native_value(self):
"""Return the state of the sensor."""
return self._state
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
def update(self) -> None:
"""Get the Efergy monitor data from the web service."""
try:
if self.type == "instant_readings":
if self.entity_description.key == CONF_INSTANT:
url_string = f"{_RESOURCE}getInstant?token={self.app_token}"
response = requests.get(url_string, timeout=10)
self._state = response.json()["reading"]
elif self.type == "amount":
self._attr_native_value = response.json()["reading"]
elif self.entity_description.key == CONF_AMOUNT:
url_string = f"{_RESOURCE}getEnergy?token={self.app_token}&offset={self.utc_offset}&period={self.period}"
response = requests.get(url_string, timeout=10)
self._state = response.json()["sum"]
elif self.type == "budget":
self._attr_native_value = response.json()["sum"]
elif self.entity_description.key == CONF_BUDGET:
url_string = f"{_RESOURCE}getBudget?token={self.app_token}"
response = requests.get(url_string, timeout=10)
self._state = response.json()["status"]
elif self.type == "cost":
self._attr_native_value = response.json()["status"]
elif self.entity_description.key == CONF_COST:
url_string = f"{_RESOURCE}getCost?token={self.app_token}&offset={self.utc_offset}&period={self.period}"
response = requests.get(url_string, timeout=10)
self._state = response.json()["sum"]
elif self.type == "current_values":
self._attr_native_value = response.json()["sum"]
elif self.entity_description.key == CONF_CURRENT_VALUES:
url_string = (
f"{_RESOURCE}getCurrentValuesSummary?token={self.app_token}"
)
@ -156,8 +183,6 @@ class EfergySensor(SensorEntity):
for sensor in response.json():
if self.sid == sensor["sid"]:
measurement = next(iter(sensor["data"][0].values()))
self._state = measurement
else:
self._state = None
self._attr_native_value = measurement
except (requests.RequestException, ValueError, KeyError):
_LOGGER.warning("Could not update status for %s", self.name)