Home Assistant Unofficial Reference 2024.12.1
device.py
Go to the documentation of this file.
1 """Code to handle a Xiaomi Device."""
2 
3 import logging
4 
5 from construct.core import ChecksumError
6 from miio import Device, DeviceException
7 
8 from .const import AuthException, SetupException
9 
10 _LOGGER = logging.getLogger(__name__)
11 
12 
14  """Class to async connect to a Xiaomi Device."""
15 
16  def __init__(self, hass):
17  """Initialize the entity."""
18  self._hass_hass = hass
19  self._device_device = None
20  self._device_info_device_info = None
21 
22  @property
23  def device(self):
24  """Return the class containing all connections to the device."""
25  return self._device_device
26 
27  @property
28  def device_info(self):
29  """Return the class containing device info."""
30  return self._device_info_device_info
31 
32  async def async_connect_device(self, host, token):
33  """Connect to the Xiaomi Device."""
34  _LOGGER.debug("Initializing with host %s (token %s...)", host, token[:5])
35 
36  try:
37  self._device_device = Device(host, token)
38  # get the device info
39  self._device_info_device_info = await self._hass_hass.async_add_executor_job(
40  self._device_device.info
41  )
42  except DeviceException as error:
43  if isinstance(error.__cause__, ChecksumError):
44  raise AuthException(error) from error
45 
46  raise SetupException(
47  f"DeviceException during setup of xiaomi device with host {host}"
48  ) from error
49 
50  _LOGGER.debug(
51  "%s %s %s detected",
52  self._device_info_device_info.model,
53  self._device_info_device_info.firmware_version,
54  self._device_info_device_info.hardware_version,
55  )