Home Assistant Unofficial Reference 2024.12.1
utils.py
Go to the documentation of this file.
1 """Reusable utilities for the Bond component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any, cast
7 
8 from aiohttp import ClientResponseError
9 from bond_async import Action, Bond, BondType
10 
11 from homeassistant.util.async_ import gather_with_limited_concurrency
12 
13 from .const import BRIDGE_MAKE
14 
15 MAX_REQUESTS = 6
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
20 class BondDevice:
21  """Helper device class to hold ID and attributes together."""
22 
23  def __init__(
24  self,
25  device_id: str,
26  attrs: dict[str, Any],
27  props: dict[str, Any],
28  state: dict[str, Any],
29  ) -> None:
30  """Create a helper device from ID and attributes returned by API."""
31  self.device_iddevice_id = device_id
32  self.propsprops = props
33  self.statestate = state
34  self._attrs_attrs = attrs or {}
35  self._supported_actions: set[str] = set(self._attrs_attrs.get("actions", []))
36 
37  def __repr__(self) -> str:
38  """Return readable representation of a bond device."""
39  return {
40  "device_id": self.device_iddevice_id,
41  "props": self.propsprops,
42  "attrs": self._attrs_attrs,
43  "state": self.statestate,
44  }.__repr__()
45 
46  @property
47  def name(self) -> str:
48  """Get the name of this device."""
49  return cast(str, self._attrs_attrs["name"])
50 
51  @property
52  def type(self) -> str:
53  """Get the type of this device."""
54  return cast(str, self._attrs_attrs["type"])
55 
56  @property
57  def location(self) -> str | None:
58  """Get the location of this device."""
59  return self._attrs_attrs.get("location")
60 
61  @property
62  def template(self) -> str | None:
63  """Return this model template."""
64  return self._attrs_attrs.get("template")
65 
66  @property
67  def branding_profile(self) -> str | None:
68  """Return this branding profile."""
69  return self.propsprops.get("branding_profile")
70 
71  @property
72  def trust_state(self) -> bool:
73  """Check if Trust State is turned on."""
74  return self.propsprops.get("trust_state", False) # type: ignore[no-any-return]
75 
76  def has_action(self, action: str) -> bool:
77  """Check to see if the device supports an actions."""
78  return action in self._supported_actions
79 
80  def _has_any_action(self, actions: set[str]) -> bool:
81  """Check to see if the device supports any of the actions."""
82  return bool(self._supported_actions.intersection(actions))
83 
84  def supports_speed(self) -> bool:
85  """Return True if this device supports any of the speed related commands."""
86  return self._has_any_action_has_any_action({Action.SET_SPEED})
87 
88  def supports_direction(self) -> bool:
89  """Return True if this device supports any of the direction related commands."""
90  return self._has_any_action_has_any_action({Action.SET_DIRECTION})
91 
92  def supports_set_position(self) -> bool:
93  """Return True if this device supports setting the position."""
94  return self._has_any_action_has_any_action({Action.SET_POSITION})
95 
96  def supports_open(self) -> bool:
97  """Return True if this device supports opening."""
98  return self._has_any_action_has_any_action({Action.OPEN})
99 
100  def supports_close(self) -> bool:
101  """Return True if this device supports closing."""
102  return self._has_any_action_has_any_action({Action.CLOSE})
103 
104  def supports_tilt_open(self) -> bool:
105  """Return True if this device supports tilt opening."""
106  return self._has_any_action_has_any_action({Action.TILT_OPEN})
107 
108  def supports_tilt_close(self) -> bool:
109  """Return True if this device supports tilt closing."""
110  return self._has_any_action_has_any_action({Action.TILT_CLOSE})
111 
112  def supports_hold(self) -> bool:
113  """Return True if this device supports hold aka stop."""
114  return self._has_any_action_has_any_action({Action.HOLD})
115 
116  def supports_light(self) -> bool:
117  """Return True if this device supports any of the light related commands."""
118  return self._has_any_action_has_any_action({Action.TURN_LIGHT_ON, Action.TURN_LIGHT_OFF})
119 
120  def supports_up_light(self) -> bool:
121  """Return true if the device has an up light."""
122  return self._has_any_action_has_any_action({Action.TURN_UP_LIGHT_ON, Action.TURN_UP_LIGHT_OFF})
123 
124  def supports_down_light(self) -> bool:
125  """Return true if the device has a down light."""
126  return self._has_any_action_has_any_action(
127  {Action.TURN_DOWN_LIGHT_ON, Action.TURN_DOWN_LIGHT_OFF}
128  )
129 
130  def supports_set_brightness(self) -> bool:
131  """Return True if this device supports setting a light brightness."""
132  return self._has_any_action_has_any_action({Action.SET_BRIGHTNESS})
133 
134 
135 class BondHub:
136  """Hub device representing Bond Bridge."""
137 
138  def __init__(self, bond: Bond, host: str) -> None:
139  """Initialize Bond Hub."""
140  self.bond: Bond = bond
141  self.hosthost = host
142  self._bridge_bridge: dict[str, Any] = {}
143  self._version_version: dict[str, Any] = {}
144  self._devices_devices: list[BondDevice] = []
145 
146  async def setup(self, max_devices: int | None = None) -> None:
147  """Read hub version information."""
148  self._version_version = await self.bond.version()
149  _LOGGER.debug("Bond reported the following version info: %s", self._version_version)
150  # Fetch all available devices using Bond API.
151  device_ids = await self.bond.devices()
152  self._devices_devices = []
153  setup_device_ids = []
154  tasks = []
155  for idx, device_id in enumerate(device_ids):
156  if max_devices is not None and idx >= max_devices:
157  break
158  setup_device_ids.append(device_id)
159  tasks.extend(
160  [
161  self.bond.device(device_id),
162  self.bond.device_properties(device_id),
163  self.bond.device_state(device_id),
164  ]
165  )
166 
167  responses = await gather_with_limited_concurrency(MAX_REQUESTS, *tasks)
168  response_idx = 0
169  for device_id in setup_device_ids:
170  self._devices_devices.append(
171  BondDevice(
172  device_id,
173  responses[response_idx],
174  responses[response_idx + 1],
175  responses[response_idx + 2],
176  )
177  )
178  response_idx += 3
179 
180  _LOGGER.debug("Discovered Bond devices: %s", self._devices_devices)
181  try:
182  # Smart by bond devices do not have a bridge api call
183  self._bridge_bridge = await self.bond.bridge()
184  except ClientResponseError:
185  self._bridge_bridge = {}
186  _LOGGER.debug("Bond reported the following bridge info: %s", self._bridge_bridge)
187 
188  @property
189  def bond_id(self) -> str | None:
190  """Return unique Bond ID for this hub."""
191  # Old firmwares are missing the bondid
192  return self._version_version.get("bondid")
193 
194  @property
195  def target(self) -> str | None:
196  """Return this hub target."""
197  return self._version_version.get("target")
198 
199  @property
200  def model(self) -> str | None:
201  """Return this hub model."""
202  return self._version_version.get("model")
203 
204  @property
205  def make(self) -> str:
206  """Return this hub make."""
207  return self._version_version.get("make", BRIDGE_MAKE) # type: ignore[no-any-return]
208 
209  @property
210  def name(self) -> str:
211  """Get the name of this bridge."""
212  if not self.is_bridgeis_bridge and self._devices_devices:
213  return self._devices_devices[0].name
214  return cast(str, self._bridge_bridge["name"])
215 
216  @property
217  def location(self) -> str | None:
218  """Get the location of this bridge."""
219  if not self.is_bridgeis_bridge and self._devices_devices:
220  return self._devices_devices[0].location
221  return self._bridge_bridge.get("location")
222 
223  @property
224  def fw_ver(self) -> str | None:
225  """Return this hub firmware version."""
226  return self._version_version.get("fw_ver")
227 
228  @property
229  def mcu_ver(self) -> str | None:
230  """Return this hub hardware version."""
231  return self._version_version.get("mcu_ver")
232 
233  @property
234  def devices(self) -> list[BondDevice]:
235  """Return a list of all devices controlled by this hub."""
236  return self._devices_devices
237 
238  @property
239  def is_bridge(self) -> bool:
240  """Return if the Bond is a Bond Bridge."""
241  bondid = self._version_version["bondid"]
242  return bool(BondType.is_bridge_from_serial(bondid))
bool _has_any_action(self, set[str] actions)
Definition: utils.py:80
None __init__(self, str device_id, dict[str, Any] attrs, dict[str, Any] props, dict[str, Any] state)
Definition: utils.py:29
list[BondDevice] devices(self)
Definition: utils.py:234
None setup(self, int|None max_devices=None)
Definition: utils.py:146
None __init__(self, Bond bond, str host)
Definition: utils.py:138
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
Any gather_with_limited_concurrency(int limit, *Any tasks, bool return_exceptions=False)
Definition: async_.py:103