Files
haos-hacs-integration-media…/custom_components/remote_media_player/number.py
T
alexei.dolgolyov 4156dedf5e 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).
2026-05-15 14:46:50 +03:00

146 lines
5.3 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 .api_client import MediaServerClient, MediaServerError
from .const import DOMAIN
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."""
client: MediaServerClient = hass.data[DOMAIN][entry.entry_id]["client"]
try:
monitors = await client.get_display_monitors()
except MediaServerError as err:
_LOGGER.error("Failed to fetch display monitors: %s", err)
return
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 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
_attr_native_unit_of_measurement = "%"
_attr_mode = NumberMode.SLIDER
_attr_icon = "mdi:brightness-6"
def __init__(
self,
client: MediaServerClient,
entry: ConfigEntry,
monitor: dict[str, Any],
) -> None:
"""Initialize the display brightness entity."""
self._client = client
self._entry = entry
self._monitor_id: int = monitor["id"]
self._attr_native_value = monitor.get("brightness")
self._attr_unique_id = f"{entry.entry_id}_display_brightness_{self._monitor_id}"
self._attr_device_info = display_device_info(entry, monitor)
async def async_set_native_value(self, value: float) -> None:
"""Set the brightness value."""
try:
await self._client.set_display_brightness(self._monitor_id, int(value))
self._attr_native_value = int(value)
self.async_write_ha_state()
except MediaServerError as err:
_LOGGER.error("Failed to set brightness for monitor %d: %s", self._monitor_id, err)
async def async_update(self) -> None:
"""Fetch updated brightness 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("brightness")
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)