Clean up Efergy (#67755)

* Clean up Efergy

* tweak
This commit is contained in:
Robert Hillis 2022-03-11 23:29:18 -05:00 committed by GitHub
parent 09a85d2a5d
commit 09944d936d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 23 additions and 35 deletions

View File

@ -4,14 +4,14 @@ from __future__ import annotations
from pyefergy import Efergy, exceptions
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, Platform
from homeassistant.const import CONF_API_KEY, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo, Entity
from .const import ATTRIBUTION, DATA_KEY_API, DEFAULT_NAME, DOMAIN
from .const import DEFAULT_NAME, DOMAIN
PLATFORMS = [Platform.SENSOR]
@ -34,7 +34,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"API Key is no longer valid. Please reauthenticate"
) from ex
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {DATA_KEY_API: api}
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = api
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
@ -42,8 +42,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
@ -51,21 +50,17 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
class EfergyEntity(Entity):
"""Representation of a Efergy entity."""
def __init__(
self,
api: Efergy,
server_unique_id: str,
) -> None:
_attr_attribution = "Data provided by Efergy"
def __init__(self, api: Efergy, server_unique_id: str) -> None:
"""Initialize an Efergy entity."""
self.api = api
self._server_unique_id = server_unique_id
self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
self._attr_device_info = DeviceInfo(
configuration_url="https://engage.efergy.com/user/login",
connections={(dr.CONNECTION_NETWORK_MAC, self.api.info["mac"])},
identifiers={(DOMAIN, self._server_unique_id)},
connections={(dr.CONNECTION_NETWORK_MAC, api.info["mac"])},
identifiers={(DOMAIN, server_unique_id)},
manufacturer=DEFAULT_NAME,
name=DEFAULT_NAME,
model=self.api.info["type"],
sw_version=self.api.info["version"],
model=api.info["type"],
sw_version=api.info["version"],
)

View File

@ -1,7 +1,6 @@
"""Config flow for Efergy integration."""
from __future__ import annotations
import logging
from typing import Any
from pyefergy import Efergy, exceptions
@ -12,9 +11,7 @@ from homeassistant.const import CONF_API_KEY
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DEFAULT_NAME, DOMAIN
_LOGGER = logging.getLogger(__name__)
from .const import DEFAULT_NAME, DOMAIN, LOGGER
class EfergyFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
@ -69,6 +66,6 @@ class EfergyFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
except exceptions.InvalidAuth:
return None, "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
LOGGER.exception("Unexpected exception")
return None, "unknown"
return api.info["hid"], None

View File

@ -1,12 +1,13 @@
"""Constants for the Efergy integration."""
from datetime import timedelta
ATTRIBUTION = "Data provided by Efergy"
import logging
from typing import Final
CONF_CURRENT_VALUES = "current_values"
DATA_KEY_API = "api"
DEFAULT_NAME = "Efergy"
DOMAIN = "efergy"
DOMAIN: Final = "efergy"
LOGGER = logging.getLogger(__package__)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)

View File

@ -1,7 +1,6 @@
"""Support for Efergy sensors."""
from __future__ import annotations
import logging
from re import sub
from typing import cast
@ -21,9 +20,7 @@ from homeassistant.helpers import entity_platform
from homeassistant.helpers.typing import StateType
from . import EfergyEntity
from .const import CONF_CURRENT_VALUES, DATA_KEY_API, DOMAIN
_LOGGER = logging.getLogger(__name__)
from .const import CONF_CURRENT_VALUES, DOMAIN, LOGGER
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
@ -112,7 +109,7 @@ async def async_setup_entry(
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up Efergy sensors."""
api: Efergy = hass.data[DOMAIN][entry.entry_id][DATA_KEY_API]
api: Efergy = hass.data[DOMAIN][entry.entry_id]
sensors = []
for description in SENSOR_TYPES:
if description.key != CONF_CURRENT_VALUES:
@ -174,8 +171,8 @@ class EfergySensor(EfergyEntity, SensorEntity):
except (ConnectError, DataError, ServiceError) as ex:
if self._attr_available:
self._attr_available = False
_LOGGER.error("Error getting data: %s", ex)
LOGGER.error("Error getting data: %s", ex)
return
if not self._attr_available:
self._attr_available = True
_LOGGER.info("Connection has resumed")
LOGGER.info("Connection has resumed")

View File

@ -2,7 +2,6 @@
"config": {
"step": {
"user": {
"title": "Efergy",
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
}

View File

@ -13,8 +13,7 @@
"user": {
"data": {
"api_key": "API Key"
},
"title": "Efergy"
}
}
}
}