Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helper functions for Samsung TV."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.config_entries import ConfigEntryState
6 from homeassistant.core import HomeAssistant, callback
7 from homeassistant.helpers import device_registry as dr, entity_registry as er
8 from homeassistant.helpers.device_registry import DeviceEntry
9 
10 from . import SamsungTVConfigEntry
11 from .bridge import SamsungTVBridge
12 from .const import DOMAIN
13 
14 
15 @callback
17  hass: HomeAssistant, device_id: str
18 ) -> DeviceEntry:
19  """Get Device Entry from Device Registry by device ID.
20 
21  Raises ValueError if device ID is invalid.
22  """
23  device_reg = dr.async_get(hass)
24  if (device := device_reg.async_get(device_id)) is None:
25  raise ValueError(f"Device {device_id} is not a valid {DOMAIN} device.")
26 
27  return device
28 
29 
30 @callback
31 def async_get_device_id_from_entity_id(hass: HomeAssistant, entity_id: str) -> str:
32  """Get device ID from an entity ID.
33 
34  Raises ValueError if entity or device ID is invalid.
35  """
36  ent_reg = er.async_get(hass)
37  entity_entry = ent_reg.async_get(entity_id)
38 
39  if (
40  entity_entry is None
41  or entity_entry.device_id is None
42  or entity_entry.platform != DOMAIN
43  ):
44  raise ValueError(f"Entity {entity_id} is not a valid {DOMAIN} entity.")
45 
46  return entity_entry.device_id
47 
48 
49 @callback
51  hass: HomeAssistant, device: DeviceEntry
52 ) -> SamsungTVBridge:
53  """Get SamsungTVBridge from Device Registry by device entry.
54 
55  Raises ValueError if client is not found.
56  """
57  entry: SamsungTVConfigEntry | None
58  for config_entry_id in device.config_entries:
59  entry = hass.config_entries.async_get_entry(config_entry_id)
60  if entry and entry.domain == DOMAIN and entry.state is ConfigEntryState.LOADED:
61  return entry.runtime_data.bridge
62 
63  raise ValueError(
64  f"Device {device.id} is not from an existing {DOMAIN} config entry"
65  )
SamsungTVBridge async_get_client_by_device_entry(HomeAssistant hass, DeviceEntry device)
Definition: helpers.py:52
DeviceEntry async_get_device_entry_by_device_id(HomeAssistant hass, str device_id)
Definition: helpers.py:18
str async_get_device_id_from_entity_id(HomeAssistant hass, str entity_id)
Definition: helpers.py:31