Files
Rafal Zielinski d4cdcc04c0
Some checks failed
Tests / test (3.13) (push) Failing after 23s
Tests / lint (push) Failing after 20s
Tests / hacs (push) Failing after 52s
Initial commit
Signed-off-by: Rafal Zielinski <sq4ind@gmail.com>
2025-10-02 16:00:15 +01:00

99 lines
3.2 KiB
Python

"""AdGuard Control Hub sensor platform."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, SENSORS
from .coordinator import AdGuardDataUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up AdGuard Control Hub sensor based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
entities = []
for sensor_type, sensor_info in SENSORS.items():
entities.append(
AdGuardSensor(
coordinator,
entry,
sensor_type,
sensor_info,
)
)
async_add_entities(entities)
class AdGuardSensor(CoordinatorEntity[AdGuardDataUpdateCoordinator], SensorEntity):
"""Representation of an AdGuard Control Hub sensor."""
def __init__(
self,
coordinator: AdGuardDataUpdateCoordinator,
entry: ConfigEntry,
sensor_type: str,
sensor_info: dict[str, Any],
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self._sensor_type = sensor_type
self._sensor_info = sensor_info
self._entry = entry
self._attr_name = sensor_info["name"]
self._attr_icon = sensor_info["icon"]
self._attr_native_unit_of_measurement = sensor_info.get("unit")
self._attr_unique_id = f"{entry.entry_id}_{sensor_type}"
# Set state class for numeric sensors
if sensor_info.get("unit") in ["queries", "rules", "ms"]:
self._attr_state_class = SensorStateClass.MEASUREMENT
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this AdGuard Home instance."""
return DeviceInfo(
identifiers={(DOMAIN, self._entry.entry_id)},
name="AdGuard Control Hub",
manufacturer="AdGuard",
model="AdGuard Home",
sw_version=self.coordinator.data.get("status", {}).get("version"),
configuration_url=f"http://{self._entry.data['host']}:{self._entry.data['port']}",
)
@property
def native_value(self) -> str | int | float | None:
"""Return the native value of the sensor."""
if self.coordinator.data is None:
return None
stats_data = self.coordinator.data.get("stats", {})
api_key = self._sensor_info["api_key"]
value = stats_data.get(api_key)
# Handle special cases
if self._sensor_type == "blocked_percentage":
return value
elif self._sensor_type == "avg_processing_time":
# Convert to milliseconds if needed
if value is not None:
return round(value, 2)
return value