feat(displays): per-display devices + DDC/CI capability entities

Restructure how displays are exposed in Home Assistant:

Each physical monitor is now its own HA device linked to the media-server
hub via `via_device`. The hub keeps the media_player + script buttons; per-
display devices hold the power switch, brightness slider, and the new
capability entities. This lets users place displays in their own area/room
and keeps related entities grouped together in the UI.

New platforms:
- sensor: DisplayResolutionSensor (diagnostic, from EDID)
- binary_sensor: DisplayPrimaryBinarySensor + DisplayPowerControlBinarySensor
  (both diagnostic; help users see why a power switch is or isn't created)
- select: DisplayInputSourceSelect (HDMI1/DP1/...), DisplayColorPresetSelect
  (color temperature), DisplayPictureModeSelect (VCP 0xDC scene modes)
- number: added DisplayContrastNumber alongside brightness

Other changes:
- display_device helper centralises the per-display DeviceInfo; pulls real
  manufacturer/model from EDID; device name no longer prepends the hub
  title since via_device already shows the hierarchy.
- api_client gains set_display_{contrast,input_source,color_preset,picture_mode}
  and stops forcing `?refresh=true` on every poll so HA can ride the
  server's TTL cache instead of triggering full DDC/CI probes per entity.
- select / number entities now check the server's `success` flag and re-
  sync from the actual monitor state when a write was silently rejected
  (some monitors honor reads but ignore writes for certain DDC/CI codes).

Bumps manifest.json to 0.3.0 - the device topology change is user-visible
and existing brightness/power entities migrate to per-display devices on
first reload (unique_ids are preserved).
This commit is contained in:
2026-05-15 14:46:50 +03:00
parent b0d98a9d45
commit 4156dedf5e
10 changed files with 583 additions and 58 deletions
+66 -31
View File
@@ -8,11 +8,11 @@ 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 import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .api_client import MediaServerClient, MediaServerError
from .const import DOMAIN
from .display_device import display_device_info
_LOGGER = logging.getLogger(__name__)
@@ -22,7 +22,7 @@ async def async_setup_entry(
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up display brightness number entities from a config entry."""
"""Set up display brightness + contrast number entities from a config entry."""
client: MediaServerClient = hass.data[DOMAIN][entry.entry_id]["client"]
try:
@@ -31,25 +31,23 @@ async def async_setup_entry(
_LOGGER.error("Failed to fetch display monitors: %s", err)
return
entities = [
DisplayBrightnessNumber(
client=client,
entry=entry,
monitor=monitor,
)
for monitor in monitors
if monitor.get("brightness") is not None
]
entities: list[Any] = []
for monitor in monitors:
if monitor.get("brightness") is not None:
entities.append(DisplayBrightnessNumber(client, entry, monitor))
if monitor.get("contrast_supported"):
entities.append(DisplayContrastNumber(client, entry, monitor))
if entities:
async_add_entities(entities)
_LOGGER.info("Added %d display brightness entities", len(entities))
_LOGGER.info("Added %d display number entities", len(entities))
class DisplayBrightnessNumber(NumberEntity):
"""Number entity for controlling display brightness."""
_attr_has_entity_name = True
_attr_name = "Brightness"
_attr_native_min_value = 0
_attr_native_max_value = 100
_attr_native_step = 1
@@ -67,27 +65,9 @@ class DisplayBrightnessNumber(NumberEntity):
self._client = client
self._entry = entry
self._monitor_id: int = monitor["id"]
self._monitor_name: str = monitor.get("name", f"Monitor {monitor['id']}")
self._resolution: str | None = monitor.get("resolution")
self._attr_native_value = monitor.get("brightness")
# Use resolution in name to disambiguate same-name monitors
display_name = self._monitor_name
if self._resolution:
display_name = f"{self._monitor_name} ({self._resolution})"
self._attr_unique_id = f"{entry.entry_id}_display_brightness_{self._monitor_id}"
self._attr_name = f"Display {display_name} Brightness"
@property
def device_info(self) -> DeviceInfo:
"""Return device info."""
return DeviceInfo(
identifiers={(DOMAIN, self._entry.entry_id)},
name=self._entry.title,
manufacturer="Remote Media Player",
model="Media Server",
)
self._attr_device_info = display_device_info(entry, monitor)
async def async_set_native_value(self, value: float) -> None:
"""Set the brightness value."""
@@ -108,3 +88,58 @@ class DisplayBrightnessNumber(NumberEntity):
break
except MediaServerError as err:
_LOGGER.error("Failed to update brightness for monitor %d: %s", self._monitor_id, err)
class DisplayContrastNumber(NumberEntity):
"""Number entity for controlling DDC/CI display contrast."""
_attr_has_entity_name = True
_attr_name = "Contrast"
_attr_native_min_value = 0
_attr_native_max_value = 100
_attr_native_step = 1
_attr_native_unit_of_measurement = "%"
_attr_mode = NumberMode.SLIDER
_attr_icon = "mdi:contrast-circle"
def __init__(
self,
client: MediaServerClient,
entry: ConfigEntry,
monitor: dict[str, Any],
) -> None:
"""Initialize the display contrast entity."""
self._client = client
self._monitor_id: int = monitor["id"]
self._attr_native_value = monitor.get("contrast")
self._attr_unique_id = f"{entry.entry_id}_display_contrast_{self._monitor_id}"
self._attr_device_info = display_device_info(entry, monitor)
async def async_set_native_value(self, value: float) -> None:
"""Set the contrast value."""
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"):
_LOGGER.warning(
"Monitor %d rejected contrast %d (DDC/CI silently dropped)",
self._monitor_id, int(value),
)
await self.async_update()
self.async_write_ha_state()
return
self._attr_native_value = int(value)
self.async_write_ha_state()
async def async_update(self) -> None:
"""Fetch updated contrast from the server."""
try:
monitors = await self._client.get_display_monitors()
for monitor in monitors:
if monitor["id"] == self._monitor_id:
self._attr_native_value = monitor.get("contrast")
break
except MediaServerError as err:
_LOGGER.error("Failed to update contrast for monitor %d: %s", self._monitor_id, err)