feat: shared DisplayCoordinator + optional API token

- 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>
This commit is contained in:
2026-05-17 23:46:26 +03:00
parent 68e338de4e
commit ab0585278c
14 changed files with 313 additions and 252 deletions
+50 -67
View File
@@ -9,9 +9,11 @@ from homeassistant.components.select import SelectEntity
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__)
@@ -23,43 +25,50 @@ async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up per-display select entities."""
client: MediaServerClient = hass.data[DOMAIN][entry.entry_id]["client"]
data = hass.data[DOMAIN][entry.entry_id]
client: MediaServerClient = data["client"]
coordinator: DisplayCoordinator = data["display_coordinator"]
try:
monitors = await client.get_display_monitors()
except MediaServerError as err:
_LOGGER.error("Failed to fetch display monitors: %s", err)
if not coordinator.data:
return
entities: list[Any] = []
for monitor in monitors:
for monitor in coordinator.data.values():
if monitor.get("input_source_supported") and monitor.get("available_input_sources"):
entities.append(DisplayInputSourceSelect(client, entry, monitor))
entities.append(DisplayInputSourceSelect(coordinator, client, entry, monitor))
if monitor.get("color_preset_supported") and monitor.get("available_color_presets"):
entities.append(DisplayColorPresetSelect(client, entry, monitor))
entities.append(DisplayColorPresetSelect(coordinator, client, entry, monitor))
if monitor.get("picture_mode_supported") and monitor.get("available_picture_modes"):
entities.append(DisplayPictureModeSelect(client, entry, monitor))
entities.append(DisplayPictureModeSelect(coordinator, client, entry, monitor))
if entities:
async_add_entities(entities)
_LOGGER.info("Added %d display select entities", len(entities))
class _DisplaySelectBase(SelectEntity):
class _DisplaySelectBase(CoordinatorEntity[DisplayCoordinator], SelectEntity):
"""Shared base for per-display selects."""
_attr_has_entity_name = True
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 DisplayInputSourceSelect(_DisplaySelectBase):
"""Switch the monitor's active input (HDMI1, DP1, ...)."""
@@ -69,15 +78,21 @@ class DisplayInputSourceSelect(_DisplaySelectBase):
def __init__(
self,
coordinator: DisplayCoordinator,
client: MediaServerClient,
entry: ConfigEntry,
monitor: dict[str, Any],
) -> None:
super().__init__(client, entry, monitor)
super().__init__(coordinator, client, entry, monitor)
self._attr_unique_id = f"{entry.entry_id}_display_input_{self._monitor_id}"
# Available inputs are a static EDID/DDC capability — capturing them
# at discovery avoids re-allocating the option list on every poll.
self._attr_options = list(monitor.get("available_input_sources") or [])
current = monitor.get("input_source")
self._attr_current_option = current if current in self._attr_options else None
@property
def current_option(self) -> str | None:
current = self._monitor.get("input_source")
return current if current in self._attr_options else None
async def async_select_option(self, option: str) -> None:
try:
@@ -90,23 +105,9 @@ class DisplayInputSourceSelect(_DisplaySelectBase):
"Monitor %d rejected input source %s (DDC/CI silently dropped)",
self._monitor_id, option,
)
# Re-read so the entity state reflects what the monitor actually did.
await self.async_update()
self.async_write_ha_state()
await self.coordinator.async_request_refresh()
return
self._attr_current_option = option
self.async_write_ha_state()
async def async_update(self) -> None:
try:
monitors = await self._client.get_display_monitors()
for monitor in monitors:
if monitor["id"] == self._monitor_id:
current = monitor.get("input_source")
self._attr_current_option = current if current in self._attr_options else None
break
except MediaServerError as err:
_LOGGER.error("Failed to refresh input source for monitor %d: %s", self._monitor_id, err)
self.coordinator.apply_optimistic(self._monitor_id, input_source=option)
class DisplayColorPresetSelect(_DisplaySelectBase):
@@ -117,15 +118,19 @@ class DisplayColorPresetSelect(_DisplaySelectBase):
def __init__(
self,
coordinator: DisplayCoordinator,
client: MediaServerClient,
entry: ConfigEntry,
monitor: dict[str, Any],
) -> None:
super().__init__(client, entry, monitor)
super().__init__(coordinator, client, entry, monitor)
self._attr_unique_id = f"{entry.entry_id}_display_color_preset_{self._monitor_id}"
self._attr_options = list(monitor.get("available_color_presets") or [])
current = monitor.get("color_preset")
self._attr_current_option = current if current in self._attr_options else None
@property
def current_option(self) -> str | None:
current = self._monitor.get("color_preset")
return current if current in self._attr_options else None
async def async_select_option(self, option: str) -> None:
try:
@@ -138,29 +143,16 @@ class DisplayColorPresetSelect(_DisplaySelectBase):
"Monitor %d rejected color preset %s (DDC/CI silently dropped)",
self._monitor_id, option,
)
await self.async_update()
self.async_write_ha_state()
await self.coordinator.async_request_refresh()
return
self._attr_current_option = option
self.async_write_ha_state()
async def async_update(self) -> None:
try:
monitors = await self._client.get_display_monitors()
for monitor in monitors:
if monitor["id"] == self._monitor_id:
current = monitor.get("color_preset")
self._attr_current_option = current if current in self._attr_options else None
break
except MediaServerError as err:
_LOGGER.error("Failed to refresh color preset for monitor %d: %s", self._monitor_id, err)
self.coordinator.apply_optimistic(self._monitor_id, color_preset=option)
class DisplayPictureModeSelect(_DisplaySelectBase):
"""Switch the monitor's picture/scene mode via VCP 0xDC.
The server returns options as `[{code: int, label: str}, ...]`. We use
labels as the user-facing options and keep a label→code map for writes.
The server returns options as ``[{code: int, label: str}, ...]``. Labels
are exposed as user-facing options and a label→code map drives writes.
"""
_attr_name = "Picture mode"
@@ -168,11 +160,12 @@ class DisplayPictureModeSelect(_DisplaySelectBase):
def __init__(
self,
coordinator: DisplayCoordinator,
client: MediaServerClient,
entry: ConfigEntry,
monitor: dict[str, Any],
) -> None:
super().__init__(client, entry, monitor)
super().__init__(coordinator, client, entry, monitor)
self._attr_unique_id = f"{entry.entry_id}_display_picture_mode_{self._monitor_id}"
modes = monitor.get("available_picture_modes") or []
@@ -182,8 +175,11 @@ class DisplayPictureModeSelect(_DisplaySelectBase):
if "label" in mode and "code" in mode
}
self._attr_options = list(self._label_to_code.keys())
current = monitor.get("picture_mode")
self._attr_current_option = current if current in self._attr_options else None
@property
def current_option(self) -> str | None:
current = self._monitor.get("picture_mode")
return current if current in self._attr_options else None
async def async_select_option(self, option: str) -> None:
code = self._label_to_code.get(option)
@@ -201,19 +197,6 @@ class DisplayPictureModeSelect(_DisplaySelectBase):
" implementation of VCP 0xDC may be incomplete",
self._monitor_id, option, code,
)
await self.async_update()
self.async_write_ha_state()
await self.coordinator.async_request_refresh()
return
self._attr_current_option = option
self.async_write_ha_state()
async def async_update(self) -> None:
try:
monitors = await self._client.get_display_monitors()
for monitor in monitors:
if monitor["id"] == self._monitor_id:
current = monitor.get("picture_mode")
self._attr_current_option = current if current in self._attr_options else None
break
except MediaServerError as err:
_LOGGER.error("Failed to refresh picture mode for monitor %d: %s", self._monitor_id, err)
self.coordinator.apply_optimistic(self._monitor_id, picture_mode=option)