ab0585278c
- Introduce DisplayCoordinator polling /api/display/monitors once per cycle and fan out to all per-display entities via CoordinatorEntity. Removes ~9x redundant requests per polling cycle that came from each binary_sensor/number/select/sensor/switch entity calling get_display_monitors() in its own async_update. - Optimistic write-through via coordinator.apply_optimistic(...) keeps sibling entities in sync after slider/select writes without an extra network round-trip. - Make CONF_TOKEN optional. The media server already supports running without auth (auth_enabled() returns False when api_tokens is empty), so the integration omits the Authorization header and ?token= query from REST/WS/album-art URLs when no token is configured. Server-side auth-enabled rejections still surface as invalid_auth in the UI. - Bump manifest version to 0.3.2. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
143 lines
5.0 KiB
Python
143 lines
5.0 KiB
Python
"""Number platform for Remote Media Player integration (display brightness)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
from homeassistant.components.number import NumberEntity, NumberMode
|
|
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 .api_client import MediaServerClient, MediaServerError
|
|
from .const import DOMAIN
|
|
from .display_coordinator import DisplayCoordinator
|
|
from .display_device import display_device_info
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
async def async_setup_entry(
|
|
hass: HomeAssistant,
|
|
entry: ConfigEntry,
|
|
async_add_entities: AddEntitiesCallback,
|
|
) -> None:
|
|
"""Set up display brightness + contrast number entities from a config entry."""
|
|
data = hass.data[DOMAIN][entry.entry_id]
|
|
client: MediaServerClient = data["client"]
|
|
coordinator: DisplayCoordinator = data["display_coordinator"]
|
|
|
|
if not coordinator.data:
|
|
return
|
|
|
|
entities: list[Any] = []
|
|
for monitor in coordinator.data.values():
|
|
if monitor.get("brightness") is not None:
|
|
entities.append(DisplayBrightnessNumber(coordinator, client, entry, monitor))
|
|
if monitor.get("contrast_supported"):
|
|
entities.append(DisplayContrastNumber(coordinator, client, entry, monitor))
|
|
|
|
if entities:
|
|
async_add_entities(entities)
|
|
_LOGGER.info("Added %d display number entities", len(entities))
|
|
|
|
|
|
class _DisplayNumberBase(CoordinatorEntity[DisplayCoordinator], NumberEntity):
|
|
"""Shared boilerplate for per-display number entities."""
|
|
|
|
_attr_has_entity_name = True
|
|
_attr_native_min_value = 0
|
|
_attr_native_max_value = 100
|
|
_attr_native_step = 1
|
|
_attr_native_unit_of_measurement = "%"
|
|
_attr_mode = NumberMode.SLIDER
|
|
|
|
def __init__(
|
|
self,
|
|
coordinator: DisplayCoordinator,
|
|
client: MediaServerClient,
|
|
entry: ConfigEntry,
|
|
monitor: dict[str, Any],
|
|
) -> None:
|
|
super().__init__(coordinator)
|
|
self._client = client
|
|
self._monitor_id: int = monitor["id"]
|
|
self._attr_device_info = display_device_info(entry, monitor)
|
|
|
|
@property
|
|
def _monitor(self) -> dict[str, Any]:
|
|
if self.coordinator.data is None:
|
|
return {}
|
|
return self.coordinator.data.get(self._monitor_id, {})
|
|
|
|
|
|
class DisplayBrightnessNumber(_DisplayNumberBase):
|
|
"""Number entity for controlling display brightness."""
|
|
|
|
_attr_name = "Brightness"
|
|
_attr_icon = "mdi:brightness-6"
|
|
|
|
def __init__(
|
|
self,
|
|
coordinator: DisplayCoordinator,
|
|
client: MediaServerClient,
|
|
entry: ConfigEntry,
|
|
monitor: dict[str, Any],
|
|
) -> None:
|
|
super().__init__(coordinator, client, entry, monitor)
|
|
self._attr_unique_id = f"{entry.entry_id}_display_brightness_{self._monitor_id}"
|
|
|
|
@property
|
|
def native_value(self) -> float | None:
|
|
value = self._monitor.get("brightness")
|
|
return None if value is None else float(value)
|
|
|
|
async def async_set_native_value(self, value: float) -> None:
|
|
try:
|
|
await self._client.set_display_brightness(self._monitor_id, int(value))
|
|
except MediaServerError as err:
|
|
_LOGGER.error("Failed to set brightness for monitor %d: %s", self._monitor_id, err)
|
|
return
|
|
self.coordinator.apply_optimistic(self._monitor_id, brightness=int(value))
|
|
|
|
|
|
class DisplayContrastNumber(_DisplayNumberBase):
|
|
"""Number entity for controlling DDC/CI display contrast."""
|
|
|
|
_attr_name = "Contrast"
|
|
_attr_icon = "mdi:contrast-circle"
|
|
|
|
def __init__(
|
|
self,
|
|
coordinator: DisplayCoordinator,
|
|
client: MediaServerClient,
|
|
entry: ConfigEntry,
|
|
monitor: dict[str, Any],
|
|
) -> None:
|
|
super().__init__(coordinator, client, entry, monitor)
|
|
self._attr_unique_id = f"{entry.entry_id}_display_contrast_{self._monitor_id}"
|
|
|
|
@property
|
|
def native_value(self) -> float | None:
|
|
value = self._monitor.get("contrast")
|
|
return None if value is None else float(value)
|
|
|
|
async def async_set_native_value(self, value: float) -> None:
|
|
try:
|
|
result = await self._client.set_display_contrast(self._monitor_id, int(value))
|
|
except MediaServerError as err:
|
|
_LOGGER.error("Failed to set contrast for monitor %d: %s", self._monitor_id, err)
|
|
return
|
|
if not result.get("success"):
|
|
# DDC/CI silently dropped the write — pull authoritative state from
|
|
# the server instead of trusting our optimistic value.
|
|
_LOGGER.warning(
|
|
"Monitor %d rejected contrast %d (DDC/CI silently dropped)",
|
|
self._monitor_id, int(value),
|
|
)
|
|
await self.coordinator.async_request_refresh()
|
|
return
|
|
self.coordinator.apply_optimistic(self._monitor_id, contrast=int(value))
|