Home Assistant Unofficial Reference 2024.12.1
utils.py
Go to the documentation of this file.
1 """UniFi Protect Integration utils."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Generator, Iterable
6 import contextlib
7 from pathlib import Path
8 import socket
9 from typing import TYPE_CHECKING
10 
11 from aiohttp import CookieJar
12 from uiprotect import ProtectApiClient
13 from uiprotect.data import (
14  Bootstrap,
15  CameraChannel,
16  Light,
17  LightModeEnableType,
18  LightModeType,
19  ProtectAdoptableDeviceModel,
20 )
21 
22 from homeassistant.const import (
23  CONF_HOST,
24  CONF_PASSWORD,
25  CONF_PORT,
26  CONF_USERNAME,
27  CONF_VERIFY_SSL,
28 )
29 from homeassistant.core import HomeAssistant, callback
30 from homeassistant.helpers.aiohttp_client import async_create_clientsession
31 from homeassistant.helpers.storage import STORAGE_DIR
32 
33 from .const import (
34  CONF_ALL_UPDATES,
35  CONF_OVERRIDE_CHOST,
36  DEVICES_FOR_SUBSCRIBE,
37  ModelType,
38 )
39 
40 if TYPE_CHECKING:
41  from .data import UFPConfigEntry
42 
43 
44 @callback
45 def _async_unifi_mac_from_hass(mac: str) -> str:
46  # MAC addresses in UFP are always caps
47  return mac.replace(":", "").upper()
48 
49 
50 @callback
51 def _async_short_mac(mac: str) -> str:
52  """Get the short mac address from the full mac."""
53  return _async_unifi_mac_from_hass(mac)[-6:]
54 
55 
56 async def _async_resolve(hass: HomeAssistant, host: str) -> str | None:
57  """Resolve a hostname to an ip."""
58  with contextlib.suppress(OSError):
59  return next(
60  iter(
61  raw[0]
62  for family, _, _, _, raw in await hass.loop.getaddrinfo(
63  host, None, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP
64  )
65  if family == socket.AF_INET
66  ),
67  None,
68  )
69  return None
70 
71 
72 @callback
74  bootstrap: Bootstrap, device_type: ModelType
75 ) -> dict[str, ProtectAdoptableDeviceModel]:
76  """Get devices by type."""
77  devices: dict[str, ProtectAdoptableDeviceModel]
78  devices = getattr(bootstrap, device_type.devices_key)
79  return devices
80 
81 
82 @callback
84  bootstrap: Bootstrap, model_type: Iterable[ModelType]
85 ) -> Generator[ProtectAdoptableDeviceModel]:
86  """Return all device by type."""
87  return (
88  device
89  for device_type in model_type
90  for device in async_get_devices_by_type(bootstrap, device_type).values()
91  )
92 
93 
94 @callback
95 def async_get_light_motion_current(obj: Light) -> str:
96  """Get light motion mode for Flood Light."""
97 
98  if (
99  obj.light_mode_settings.mode is LightModeType.MOTION
100  and obj.light_mode_settings.enable_at is LightModeEnableType.DARK
101  ):
102  return f"{LightModeType.MOTION.value}Dark"
103  return obj.light_mode_settings.mode.value
104 
105 
106 @callback
108  hass: HomeAssistant, entry: UFPConfigEntry
109 ) -> ProtectApiClient:
110  """Create ProtectApiClient from config entry."""
111 
112  session = async_create_clientsession(hass, cookie_jar=CookieJar(unsafe=True))
113  return ProtectApiClient(
114  host=entry.data[CONF_HOST],
115  port=entry.data[CONF_PORT],
116  username=entry.data[CONF_USERNAME],
117  password=entry.data[CONF_PASSWORD],
118  verify_ssl=entry.data[CONF_VERIFY_SSL],
119  session=session,
120  subscribed_models=DEVICES_FOR_SUBSCRIBE,
121  override_connection_host=entry.options.get(CONF_OVERRIDE_CHOST, False),
122  ignore_stats=not entry.options.get(CONF_ALL_UPDATES, False),
123  ignore_unadopted=False,
124  cache_dir=Path(hass.config.path(STORAGE_DIR, "unifiprotect")),
125  config_dir=Path(hass.config.path(STORAGE_DIR, "unifiprotect")),
126  )
127 
128 
129 @callback
130 def get_camera_base_name(channel: CameraChannel) -> str:
131  """Get base name for cameras channel."""
132 
133  camera_name = channel.name
134  if channel.name != "Package Camera":
135  camera_name = f"{channel.name} resolution channel"
136 
137  return camera_name
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51
str|None _async_resolve(HomeAssistant hass, str host)
Definition: utils.py:56
dict[str, ProtectAdoptableDeviceModel] async_get_devices_by_type(Bootstrap bootstrap, ModelType device_type)
Definition: utils.py:75
str async_get_light_motion_current(Light obj)
Definition: utils.py:95
ProtectApiClient async_create_api_client(HomeAssistant hass, UFPConfigEntry entry)
Definition: utils.py:109
Generator[ProtectAdoptableDeviceModel] async_get_devices(Bootstrap bootstrap, Iterable[ModelType] model_type)
Definition: utils.py:85
str get_camera_base_name(CameraChannel channel)
Definition: utils.py:130