core/homeassistant/components/radarr/sensor.py

148 lines
4.6 KiB
Python
Raw Normal View History

"""Support for Radarr."""
from __future__ import annotations
2022-09-23 02:16:24 +00:00
from collections.abc import Callable
from copy import deepcopy
from dataclasses import dataclass
2022-10-07 18:53:34 +00:00
from datetime import datetime, timezone
from typing import Any, Generic
2022-10-07 18:53:34 +00:00
from aiopyarr import Diskspace, RootFolder, SystemStatus
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory, UnitOfInformation
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
2022-09-23 02:16:24 +00:00
from . import RadarrEntity
from .const import DOMAIN
2022-09-23 02:16:24 +00:00
from .coordinator import RadarrDataUpdateCoordinator, T
def get_space(data: list[Diskspace], name: str) -> str:
2022-09-23 02:16:24 +00:00
"""Get space."""
space = [
mount.freeSpace / 1024 ** BYTE_SIZES.index(UnitOfInformation.GIGABYTES)
for mount in data
2022-09-23 02:16:24 +00:00
if name in mount.path
]
return f"{space[0]:.2f}"
def get_modified_description(
2022-10-07 18:53:34 +00:00
description: RadarrSensorEntityDescription[T], mount: RootFolder
) -> tuple[RadarrSensorEntityDescription[T], str]:
2022-09-23 02:16:24 +00:00
"""Return modified description and folder name."""
desc = deepcopy(description)
name = mount.path.rsplit("/")[-1].rsplit("\\")[-1]
desc.key = f"{description.key}_{name}"
desc.name = f"{description.name} {name}".capitalize()
return desc, name
@dataclass
class RadarrSensorEntityDescriptionMixIn(Generic[T]):
"""Mixin for required keys."""
2022-10-07 18:53:34 +00:00
value_fn: Callable[[T, str], str | int | datetime]
2022-09-23 02:16:24 +00:00
@dataclass
class RadarrSensorEntityDescription(
SensorEntityDescription, RadarrSensorEntityDescriptionMixIn[T], Generic[T]
):
"""Class to describe a Radarr sensor."""
description_fn: Callable[
2022-10-07 18:53:34 +00:00
[RadarrSensorEntityDescription[T], RootFolder],
tuple[RadarrSensorEntityDescription[T], str] | None,
] | None = None
2022-09-23 02:16:24 +00:00
2022-10-07 18:53:34 +00:00
SENSOR_TYPES: dict[str, RadarrSensorEntityDescription[Any]] = {
2022-09-23 02:16:24 +00:00
"disk_space": RadarrSensorEntityDescription(
key="disk_space",
name="Disk space",
native_unit_of_measurement=UnitOfInformation.GIGABYTES,
device_class=SensorDeviceClass.DATA_SIZE,
icon="mdi:harddisk",
value_fn=get_space,
2022-09-23 02:16:24 +00:00
description_fn=get_modified_description,
),
2022-10-07 18:53:34 +00:00
"movie": RadarrSensorEntityDescription[int](
key="movies",
translation_key="movies",
native_unit_of_measurement="Movies",
icon="mdi:television",
2022-09-23 02:16:24 +00:00
entity_registry_enabled_default=False,
value_fn=lambda data, _: data,
),
2022-10-07 18:53:34 +00:00
"status": RadarrSensorEntityDescription[SystemStatus](
key="start_time",
translation_key="start_time",
device_class=SensorDeviceClass.TIMESTAMP,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=lambda data, _: data.startTime.replace(tzinfo=timezone.utc),
),
}
BYTE_SIZES = [
UnitOfInformation.BYTES,
UnitOfInformation.KILOBYTES,
UnitOfInformation.MEGABYTES,
UnitOfInformation.GIGABYTES,
]
2022-09-23 02:16:24 +00:00
PARALLEL_UPDATES = 1
2022-09-23 02:16:24 +00:00
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Radarr sensors based on a config entry."""
2022-10-07 18:53:34 +00:00
coordinators: dict[str, RadarrDataUpdateCoordinator[Any]] = hass.data[DOMAIN][
2022-09-23 02:16:24 +00:00
entry.entry_id
]
2022-10-07 18:53:34 +00:00
entities: list[RadarrSensor[Any]] = []
2022-09-23 02:16:24 +00:00
for coordinator_type, description in SENSOR_TYPES.items():
coordinator = coordinators[coordinator_type]
if coordinator_type != "disk_space":
entities.append(RadarrSensor(coordinator, description))
else:
entities.extend(
RadarrSensor(coordinator, *get_modified_description(description, mount))
for mount in coordinator.data
if description.description_fn
)
async_add_entities(entities)
2022-10-07 18:53:34 +00:00
class RadarrSensor(RadarrEntity[T], SensorEntity):
"""Implementation of the Radarr sensor."""
2022-10-07 18:53:34 +00:00
coordinator: RadarrDataUpdateCoordinator[T]
entity_description: RadarrSensorEntityDescription[T]
2022-09-23 02:16:24 +00:00
def __init__(
self,
2022-10-07 18:53:34 +00:00
coordinator: RadarrDataUpdateCoordinator[T],
description: RadarrSensorEntityDescription[T],
2022-09-23 02:16:24 +00:00
folder_name: str = "",
) -> None:
"""Create Radarr entity."""
super().__init__(coordinator, description)
2022-09-23 02:16:24 +00:00
self.folder_name = folder_name
@property
2022-10-07 18:53:34 +00:00
def native_value(self) -> str | int | datetime:
2022-09-23 02:16:24 +00:00
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data, self.folder_name)