Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Base class for Cambridge Audio entities."""
2 
3 from collections.abc import Awaitable, Callable, Coroutine
4 from functools import wraps
5 from typing import Any, Concatenate
6 
7 from aiostreammagic import StreamMagicClient
8 from aiostreammagic.models import CallbackType
9 
10 from homeassistant.exceptions import HomeAssistantError
11 from homeassistant.helpers.device_registry import DeviceInfo
12 from homeassistant.helpers.entity import Entity
13 
14 from .const import DOMAIN, STREAM_MAGIC_EXCEPTIONS
15 
16 
17 def command[_EntityT: CambridgeAudioEntity, **_P](
18  func: Callable[Concatenate[_EntityT, _P], Awaitable[None]],
19 ) -> Callable[Concatenate[_EntityT, _P], Coroutine[Any, Any, None]]:
20  """Wrap async calls to raise on request error."""
21 
22  @wraps(func)
23  async def decorator(self: _EntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
24  """Wrap all command methods."""
25  try:
26  await func(self, *args, **kwargs)
27  except STREAM_MAGIC_EXCEPTIONS as exc:
28  raise HomeAssistantError(
29  translation_domain=DOMAIN,
30  translation_key="command_error",
31  translation_placeholders={
32  "function_name": func.__name__,
33  "entity_id": self.entity_id,
34  },
35  ) from exc
36 
37  return decorator
38 
39 
41  """Defines a base Cambridge Audio entity."""
42 
43  _attr_has_entity_name = True
44 
45  def __init__(self, client: StreamMagicClient) -> None:
46  """Initialize Cambridge Audio entity."""
47  self.clientclient = client
48  self._attr_device_info_attr_device_info = DeviceInfo(
49  identifiers={(DOMAIN, client.info.unit_id)},
50  name=client.info.name,
51  manufacturer="Cambridge Audio",
52  model=client.info.model,
53  serial_number=client.info.unit_id,
54  configuration_url=f"http://{client.host}",
55  )
56 
58  self, _client: StreamMagicClient, _callback_type: CallbackType
59  ) -> None:
60  """Call when the device is notified of changes."""
61  self._attr_available_attr_available = _client.is_connected()
62  self.async_write_ha_stateasync_write_ha_state()
63 
64  async def async_added_to_hass(self) -> None:
65  """Register callback handlers."""
66  await self.clientclient.register_state_update_callbacks(self._state_update_callback_state_update_callback)
67 
68  async def async_will_remove_from_hass(self) -> None:
69  """Remove callbacks."""
70  self.clientclient.unregister_state_update_callbacks(self._state_update_callback_state_update_callback)
None _state_update_callback(self, StreamMagicClient _client, CallbackType _callback_type)
Definition: entity.py:59