Files
haos-hacs-integration-media…/custom_components/remote_media_player/switch.py
T
alexei.dolgolyov 9d277276b8 feat(foreground): foreground process sensors + translation key migration
Adds Home Assistant entities for the foreground-process feature shipped
in the media server, plus migrates existing display entities to use HA
translation keys (strings.json / translations/*) so per-language UI text
flows through the standard locale mechanism.

Foreground entities (all share one HA "Foreground" device linked to the
hub via via_device):
- sensor.foreground_process — process name as state + full payload
  (pid, exec path, window title, fullscreen flag, monitor, geometry,
  is_browser, browser_page_title, browser_url, error) as attributes
- sensor.window_title, sensor.pid, sensor.foreground_monitor,
  sensor.process_started (TIMESTAMP device class)
- binary_sensor.fullscreen, binary_sensor.minimized

Data flow:
- ForegroundCoordinator polls GET /api/foreground every 5s (HTTP fallback)
- media_player's WebSocket receiver forwards `foreground` /
  `foreground_update` push frames into the coordinator via
  apply_websocket_snapshot, so sensors update in near-real-time when WS
  is connected and fall back to polling otherwise

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-18 03:13:23 +03:00

105 lines
3.3 KiB
Python

"""Switch platform for Remote Media Player integration (display power)."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
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 power switch 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 = [
DisplayPowerSwitch(coordinator, client, entry, monitor)
for monitor in coordinator.data.values()
if monitor.get("power_supported", False)
]
if entities:
async_add_entities(entities)
_LOGGER.info("Added %d display power switch entities", len(entities))
class DisplayPowerSwitch(CoordinatorEntity[DisplayCoordinator], SwitchEntity):
"""Switch entity for controlling display power."""
_attr_has_entity_name = True
_attr_device_class = SwitchDeviceClass.SWITCH
_attr_translation_key = "power"
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_unique_id = f"{entry.entry_id}_display_power_{self._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, {})
@property
def is_on(self) -> bool:
return bool(self._monitor.get("power_on", True))
@property
def icon(self) -> str:
return "mdi:monitor" if self.is_on else "mdi:monitor-off"
async def _set_power(self, on: bool) -> None:
try:
result = await self._client.set_display_power(self._monitor_id, on)
except MediaServerError as err:
_LOGGER.error(
"Failed to %s monitor %d: %s",
"turn on" if on else "turn off",
self._monitor_id,
err,
)
return
if not result.get("success"):
_LOGGER.error(
"Failed to %s monitor %d",
"turn on" if on else "turn off",
self._monitor_id,
)
return
self.coordinator.apply_optimistic(self._monitor_id, power_on=on)
async def async_turn_on(self, **kwargs: Any) -> None:
await self._set_power(True)
async def async_turn_off(self, **kwargs: Any) -> None:
await self._set_power(False)