From c6c063e8c52612a524e387400e6f4a919ac77a57 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 15 Jul 2022 12:38:20 +0200 Subject: [PATCH] Various cleanups in AdGuard Home (#75250) Co-authored-by: Martin Hjelmare --- .coveragerc | 1 + homeassistant/components/adguard/__init__.py | 101 +------------------ homeassistant/components/adguard/const.py | 3 + homeassistant/components/adguard/entity.py | 69 +++++++++++++ homeassistant/components/adguard/sensor.py | 14 +-- homeassistant/components/adguard/switch.py | 27 ++--- 6 files changed, 86 insertions(+), 129 deletions(-) create mode 100644 homeassistant/components/adguard/entity.py diff --git a/.coveragerc b/.coveragerc index 94b9eceb11b..cfc51dc700d 100644 --- a/.coveragerc +++ b/.coveragerc @@ -23,6 +23,7 @@ omit = homeassistant/components/adax/climate.py homeassistant/components/adguard/__init__.py homeassistant/components/adguard/const.py + homeassistant/components/adguard/entity.py homeassistant/components/adguard/sensor.py homeassistant/components/adguard/switch.py homeassistant/components/ads/* diff --git a/homeassistant/components/adguard/__init__.py b/homeassistant/components/adguard/__init__.py index e27aef6389d..fbcbea61316 100644 --- a/homeassistant/components/adguard/__init__.py +++ b/homeassistant/components/adguard/__init__.py @@ -1,12 +1,10 @@ """Support for AdGuard Home.""" from __future__ import annotations -import logging - -from adguardhome import AdGuardHome, AdGuardHomeConnectionError, AdGuardHomeError +from adguardhome import AdGuardHome, AdGuardHomeConnectionError import voluptuous as vol -from homeassistant.config_entries import SOURCE_HASSIO, ConfigEntry +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_NAME, @@ -22,13 +20,10 @@ from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession -from homeassistant.helpers.device_registry import DeviceEntryType -from homeassistant.helpers.entity import DeviceInfo, Entity from .const import ( CONF_FORCE, DATA_ADGUARD_CLIENT, - DATA_ADGUARD_VERSION, DOMAIN, SERVICE_ADD_URL, SERVICE_DISABLE_URL, @@ -37,8 +32,6 @@ from .const import ( SERVICE_REMOVE_URL, ) -_LOGGER = logging.getLogger(__name__) - SERVICE_URL_SCHEMA = vol.Schema({vol.Required(CONF_URL): cv.url}) SERVICE_ADD_URL_SCHEMA = vol.Schema( {vol.Required(CONF_NAME): cv.string, vol.Required(CONF_URL): cv.url} @@ -127,93 +120,3 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: del hass.data[DOMAIN] return unload_ok - - -class AdGuardHomeEntity(Entity): - """Defines a base AdGuard Home entity.""" - - _attr_has_entity_name = True - - def __init__( - self, - adguard: AdGuardHome, - entry: ConfigEntry, - name: str | None, - icon: str | None, - enabled_default: bool = True, - ) -> None: - """Initialize the AdGuard Home entity.""" - self._available = True - self._enabled_default = enabled_default - self._icon = icon - self._name = name - self._entry = entry - self.adguard = adguard - - @property - def name(self) -> str | None: - """Return the name of the entity.""" - return self._name - - @property - def icon(self) -> str | None: - """Return the mdi icon of the entity.""" - return self._icon - - @property - def entity_registry_enabled_default(self) -> bool: - """Return if the entity should be enabled when first added to the entity registry.""" - return self._enabled_default - - @property - def available(self) -> bool: - """Return True if entity is available.""" - return self._available - - async def async_update(self) -> None: - """Update AdGuard Home entity.""" - if not self.enabled: - return - - try: - await self._adguard_update() - self._available = True - except AdGuardHomeError: - if self._available: - _LOGGER.debug( - "An error occurred while updating AdGuard Home sensor", - exc_info=True, - ) - self._available = False - - async def _adguard_update(self) -> None: - """Update AdGuard Home entity.""" - raise NotImplementedError() - - -class AdGuardHomeDeviceEntity(AdGuardHomeEntity): - """Defines a AdGuard Home device entity.""" - - @property - def device_info(self) -> DeviceInfo: - """Return device information about this AdGuard Home instance.""" - if self._entry.source == SOURCE_HASSIO: - config_url = "homeassistant://hassio/ingress/a0d7b954_adguard" - else: - if self.adguard.tls: - config_url = f"https://{self.adguard.host}:{self.adguard.port}" - else: - config_url = f"http://{self.adguard.host}:{self.adguard.port}" - - return DeviceInfo( - entry_type=DeviceEntryType.SERVICE, - identifiers={ - (DOMAIN, self.adguard.host, self.adguard.port, self.adguard.base_path) # type: ignore[arg-type] - }, - manufacturer="AdGuard Team", - name="AdGuard Home", - sw_version=self.hass.data[DOMAIN][self._entry.entry_id].get( - DATA_ADGUARD_VERSION - ), - configuration_url=config_url, - ) diff --git a/homeassistant/components/adguard/const.py b/homeassistant/components/adguard/const.py index 8bfa5b49fc6..a4ccde68539 100644 --- a/homeassistant/components/adguard/const.py +++ b/homeassistant/components/adguard/const.py @@ -1,7 +1,10 @@ """Constants for the AdGuard Home integration.""" +import logging DOMAIN = "adguard" +LOGGER = logging.getLogger(__package__) + DATA_ADGUARD_CLIENT = "adguard_client" DATA_ADGUARD_VERSION = "adguard_version" diff --git a/homeassistant/components/adguard/entity.py b/homeassistant/components/adguard/entity.py new file mode 100644 index 00000000000..7d6bf099366 --- /dev/null +++ b/homeassistant/components/adguard/entity.py @@ -0,0 +1,69 @@ +"""AdGuard Home base entity.""" +from __future__ import annotations + +from adguardhome import AdGuardHome, AdGuardHomeError + +from homeassistant.config_entries import SOURCE_HASSIO, ConfigEntry +from homeassistant.helpers.device_registry import DeviceEntryType +from homeassistant.helpers.entity import DeviceInfo, Entity + +from .const import DATA_ADGUARD_VERSION, DOMAIN, LOGGER + + +class AdGuardHomeEntity(Entity): + """Defines a base AdGuard Home entity.""" + + _attr_has_entity_name = True + _attr_available = True + + def __init__( + self, + adguard: AdGuardHome, + entry: ConfigEntry, + ) -> None: + """Initialize the AdGuard Home entity.""" + self._entry = entry + self.adguard = adguard + + async def async_update(self) -> None: + """Update AdGuard Home entity.""" + if not self.enabled: + return + + try: + await self._adguard_update() + self._attr_available = True + except AdGuardHomeError: + if self._attr_available: + LOGGER.debug( + "An error occurred while updating AdGuard Home sensor", + exc_info=True, + ) + self._attr_available = False + + async def _adguard_update(self) -> None: + """Update AdGuard Home entity.""" + raise NotImplementedError() + + @property + def device_info(self) -> DeviceInfo: + """Return device information about this AdGuard Home instance.""" + if self._entry.source == SOURCE_HASSIO: + config_url = "homeassistant://hassio/ingress/a0d7b954_adguard" + elif self.adguard.tls: + config_url = f"https://{self.adguard.host}:{self.adguard.port}" + else: + config_url = f"http://{self.adguard.host}:{self.adguard.port}" + + return DeviceInfo( + entry_type=DeviceEntryType.SERVICE, + identifiers={ + (DOMAIN, self.adguard.host, self.adguard.port, self.adguard.base_path) # type: ignore[arg-type] + }, + manufacturer="AdGuard Team", + name="AdGuard Home", + sw_version=self.hass.data[DOMAIN][self._entry.entry_id].get( + DATA_ADGUARD_VERSION + ), + configuration_url=config_url, + ) diff --git a/homeassistant/components/adguard/sensor.py b/homeassistant/components/adguard/sensor.py index 19ed0b96801..07a483f03c4 100644 --- a/homeassistant/components/adguard/sensor.py +++ b/homeassistant/components/adguard/sensor.py @@ -15,8 +15,8 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.entity_platform import AddEntitiesCallback -from . import AdGuardHomeDeviceEntity from .const import DATA_ADGUARD_CLIENT, DATA_ADGUARD_VERSION, DOMAIN +from .entity import AdGuardHomeEntity SCAN_INTERVAL = timedelta(seconds=300) PARALLEL_UPDATES = 4 @@ -118,7 +118,7 @@ async def async_setup_entry( ) -class AdGuardHomeSensor(AdGuardHomeDeviceEntity, SensorEntity): +class AdGuardHomeSensor(AdGuardHomeEntity, SensorEntity): """Defines a AdGuard Home sensor.""" entity_description: AdGuardHomeEntityDescription @@ -130,8 +130,8 @@ class AdGuardHomeSensor(AdGuardHomeDeviceEntity, SensorEntity): description: AdGuardHomeEntityDescription, ) -> None: """Initialize AdGuard Home sensor.""" + super().__init__(adguard, entry) self.entity_description = description - self._attr_unique_id = "_".join( [ DOMAIN, @@ -142,14 +142,6 @@ class AdGuardHomeSensor(AdGuardHomeDeviceEntity, SensorEntity): ] ) - super().__init__( - adguard, - entry, - description.name, - description.icon, - description.entity_registry_enabled_default, - ) - async def _adguard_update(self) -> None: """Update AdGuard Home entity.""" value = await self.entity_description.value_fn(self.adguard)() diff --git a/homeassistant/components/adguard/switch.py b/homeassistant/components/adguard/switch.py index efbd5c7fa38..a359bf86c2d 100644 --- a/homeassistant/components/adguard/switch.py +++ b/homeassistant/components/adguard/switch.py @@ -4,7 +4,6 @@ from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from datetime import timedelta -import logging from typing import Any from adguardhome import AdGuardHome, AdGuardHomeConnectionError, AdGuardHomeError @@ -15,10 +14,8 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.entity_platform import AddEntitiesCallback -from . import AdGuardHomeDeviceEntity -from .const import DATA_ADGUARD_CLIENT, DATA_ADGUARD_VERSION, DOMAIN - -_LOGGER = logging.getLogger(__name__) +from .const import DATA_ADGUARD_CLIENT, DATA_ADGUARD_VERSION, DOMAIN, LOGGER +from .entity import AdGuardHomeEntity SCAN_INTERVAL = timedelta(seconds=10) PARALLEL_UPDATES = 1 @@ -113,7 +110,7 @@ async def async_setup_entry( ) -class AdGuardHomeSwitch(AdGuardHomeDeviceEntity, SwitchEntity): +class AdGuardHomeSwitch(AdGuardHomeEntity, SwitchEntity): """Defines a AdGuard Home switch.""" entity_description: AdGuardHomeSwitchEntityDescription @@ -125,35 +122,27 @@ class AdGuardHomeSwitch(AdGuardHomeDeviceEntity, SwitchEntity): description: AdGuardHomeSwitchEntityDescription, ) -> None: """Initialize AdGuard Home switch.""" + super().__init__(adguard, entry) self.entity_description = description - self._attr_unique_id = "_".join( [DOMAIN, adguard.host, str(adguard.port), "switch", description.key] ) - super().__init__( - adguard, - entry, - description.name, - description.icon, - description.entity_registry_enabled_default, - ) - async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the switch.""" try: await self.entity_description.turn_off_fn(self.adguard)() except AdGuardHomeError: - _LOGGER.error("An error occurred while turning off AdGuard Home switch") - self._available = False + LOGGER.error("An error occurred while turning off AdGuard Home switch") + self._attr_available = False async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the switch.""" try: await self.entity_description.turn_on_fn(self.adguard)() except AdGuardHomeError: - _LOGGER.error("An error occurred while turning on AdGuard Home switch") - self._available = False + LOGGER.error("An error occurred while turning on AdGuard Home switch") + self._attr_available = False async def _adguard_update(self) -> None: """Update AdGuard Home entity."""