@@ -1,10 +1,13 @@
|
||||
"""Switch platform for AdGuard Control Hub integration."""
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import AdGuardControlHubCoordinator
|
||||
from .api import AdGuardHomeAPI
|
||||
from .const import DOMAIN, ICON_PROTECTION, ICON_PROTECTION_OFF, ICON_CLIENT, MANUFACTURER
|
||||
@@ -12,7 +15,11 @@ from .const import DOMAIN, ICON_PROTECTION, ICON_PROTECTION_OFF, ICON_CLIENT, MA
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback):
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up AdGuard Control Hub switch platform."""
|
||||
coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"]
|
||||
api = hass.data[DOMAIN][config_entry.entry_id]["api"]
|
||||
@@ -32,6 +39,7 @@ class AdGuardBaseSwitch(CoordinatorEntity, SwitchEntity):
|
||||
"""Base class for AdGuard switches."""
|
||||
|
||||
def __init__(self, coordinator: AdGuardControlHubCoordinator, api: AdGuardHomeAPI):
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator)
|
||||
self.api = api
|
||||
self._attr_device_info = {
|
||||
@@ -46,31 +54,64 @@ class AdGuardProtectionSwitch(AdGuardBaseSwitch):
|
||||
"""Switch to control global AdGuard protection."""
|
||||
|
||||
def __init__(self, coordinator: AdGuardControlHubCoordinator, api: AdGuardHomeAPI):
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator, api)
|
||||
self._attr_unique_id = f"{api.host}_{api.port}_protection"
|
||||
self._attr_name = "AdGuard Protection"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if protection is enabled."""
|
||||
return self.coordinator.protection_status.get("protection_enabled", False)
|
||||
|
||||
@property
|
||||
def icon(self) -> str:
|
||||
"""Return the icon for the switch."""
|
||||
return ICON_PROTECTION if self.is_on else ICON_PROTECTION_OFF
|
||||
|
||||
async def async_turn_on(self, **kwargs):
|
||||
await self.api.set_protection(True)
|
||||
await self.coordinator.async_request_refresh()
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return additional state attributes."""
|
||||
status = self.coordinator.protection_status
|
||||
stats = self.coordinator.statistics
|
||||
return {
|
||||
"dns_port": status.get("dns_port", "N/A"),
|
||||
"queries_today": stats.get("num_dns_queries_today", 0),
|
||||
"blocked_today": stats.get("num_blocked_filtering_today", 0),
|
||||
"version": status.get("version", "N/A"),
|
||||
}
|
||||
|
||||
async def async_turn_off(self, **kwargs):
|
||||
await self.api.set_protection(False)
|
||||
await self.coordinator.async_request_refresh()
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn on AdGuard protection."""
|
||||
try:
|
||||
await self.api.set_protection(True)
|
||||
await self.coordinator.async_request_refresh()
|
||||
_LOGGER.info("AdGuard protection enabled")
|
||||
except Exception as err:
|
||||
_LOGGER.error("Failed to enable AdGuard protection: %s", err)
|
||||
raise
|
||||
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn off AdGuard protection."""
|
||||
try:
|
||||
await self.api.set_protection(False)
|
||||
await self.coordinator.async_request_refresh()
|
||||
_LOGGER.info("AdGuard protection disabled")
|
||||
except Exception as err:
|
||||
_LOGGER.error("Failed to disable AdGuard protection: %s", err)
|
||||
raise
|
||||
|
||||
|
||||
class AdGuardClientSwitch(AdGuardBaseSwitch):
|
||||
"""Switch to control client-specific protection."""
|
||||
|
||||
def __init__(self, coordinator: AdGuardControlHubCoordinator, api: AdGuardHomeAPI, client_name: str):
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: AdGuardControlHubCoordinator,
|
||||
api: AdGuardHomeAPI,
|
||||
client_name: str,
|
||||
):
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator, api)
|
||||
self.client_name = client_name
|
||||
self._attr_unique_id = f"{api.host}_{api.port}_client_{client_name}"
|
||||
@@ -78,16 +119,81 @@ class AdGuardClientSwitch(AdGuardBaseSwitch):
|
||||
self._attr_icon = ICON_CLIENT
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if client protection is enabled."""
|
||||
client = self.coordinator.clients.get(self.client_name, {})
|
||||
return client.get("filtering_enabled", True)
|
||||
|
||||
async def async_turn_on(self, **kwargs):
|
||||
# This would update client settings - simplified for basic functionality
|
||||
_LOGGER.info("Would enable protection for %s", self.client_name)
|
||||
await self.coordinator.async_request_refresh()
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return additional state attributes."""
|
||||
client = self.coordinator.clients.get(self.client_name, {})
|
||||
blocked_services = client.get("blocked_services", {})
|
||||
|
||||
async def async_turn_off(self, **kwargs):
|
||||
# This would update client settings - simplified for basic functionality
|
||||
_LOGGER.info("Would disable protection for %s", self.client_name)
|
||||
await self.coordinator.async_request_refresh()
|
||||
if isinstance(blocked_services, dict):
|
||||
service_ids = blocked_services.get("ids", [])
|
||||
else:
|
||||
service_ids = blocked_services if blocked_services else []
|
||||
|
||||
return {
|
||||
"client_ids": client.get("ids", []),
|
||||
"mac": client.get("mac", ""),
|
||||
"use_global_settings": client.get("use_global_settings", True),
|
||||
"safebrowsing_enabled": client.get("safebrowsing_enabled", False),
|
||||
"parental_enabled": client.get("parental_enabled", False),
|
||||
"safesearch_enabled": client.get("safesearch_enabled", False),
|
||||
"blocked_services": service_ids,
|
||||
"blocked_services_count": len(service_ids),
|
||||
}
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Enable protection for this client."""
|
||||
try:
|
||||
# Get current client data
|
||||
client = await self.api.get_client_by_name(self.client_name)
|
||||
if not client:
|
||||
_LOGGER.error("Client %s not found", self.client_name)
|
||||
return
|
||||
|
||||
# Update client with filtering enabled
|
||||
update_data = {
|
||||
"name": self.client_name,
|
||||
"data": {
|
||||
**client,
|
||||
"filtering_enabled": True,
|
||||
}
|
||||
}
|
||||
|
||||
await self.api.update_client(update_data)
|
||||
await self.coordinator.async_request_refresh()
|
||||
_LOGGER.info("Enabled protection for client %s", self.client_name)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Failed to enable protection for %s: %s", self.client_name, err)
|
||||
raise
|
||||
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Disable protection for this client."""
|
||||
try:
|
||||
# Get current client data
|
||||
client = await self.api.get_client_by_name(self.client_name)
|
||||
if not client:
|
||||
_LOGGER.error("Client %s not found", self.client_name)
|
||||
return
|
||||
|
||||
# Update client with filtering disabled
|
||||
update_data = {
|
||||
"name": self.client_name,
|
||||
"data": {
|
||||
**client,
|
||||
"filtering_enabled": False,
|
||||
}
|
||||
}
|
||||
|
||||
await self.api.update_client(update_data)
|
||||
await self.coordinator.async_request_refresh()
|
||||
_LOGGER.info("Disabled protection for client %s", self.client_name)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Failed to disable protection for %s: %s", self.client_name, err)
|
||||
raise
|
||||
|
Reference in New Issue
Block a user