Home Assistant Unofficial Reference 2024.12.1
device_tracker.py
Go to the documentation of this file.
1 """Support for Unifi AP direct access."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from unifi_ap import UniFiAP, UniFiAPConnectionException, UniFiAPDataException
9 import voluptuous as vol
10 
12  DOMAIN as DEVICE_TRACKER_DOMAIN,
13  PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
14  DeviceScanner,
15 )
16 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.typing import ConfigType
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 DEFAULT_SSH_PORT = 22
24 
25 PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend(
26  {
27  vol.Required(CONF_HOST): cv.string,
28  vol.Required(CONF_PASSWORD): cv.string,
29  vol.Required(CONF_USERNAME): cv.string,
30  vol.Optional(CONF_PORT, default=DEFAULT_SSH_PORT): cv.port,
31  }
32 )
33 
34 
35 def get_scanner(hass: HomeAssistant, config: ConfigType) -> UnifiDeviceScanner | None:
36  """Validate the configuration and return a Unifi direct scanner."""
37  scanner = UnifiDeviceScanner(config[DEVICE_TRACKER_DOMAIN])
38  return scanner if scanner.update_clients() else None
39 
40 
41 class UnifiDeviceScanner(DeviceScanner):
42  """Class which queries Unifi wireless access point."""
43 
44  def __init__(self, config: ConfigType) -> None:
45  """Initialize the scanner."""
46  self.clientsclients: dict[str, dict[str, Any]] = {}
47  self.apap = UniFiAP(
48  target=config[CONF_HOST],
49  username=config[CONF_USERNAME],
50  password=config[CONF_PASSWORD],
51  port=config[CONF_PORT],
52  )
53 
54  def scan_devices(self) -> list[str]:
55  """Scan for new devices and return a list with found device IDs."""
56  self.update_clientsupdate_clients()
57  return list(self.clientsclients)
58 
59  def get_device_name(self, device: str) -> str | None:
60  """Return the name of the given device or None if we don't know."""
61  client_info = self.clientsclients.get(device)
62  if client_info:
63  return client_info.get("hostname")
64  return None
65 
66  def update_clients(self) -> bool:
67  """Update the client info from AP."""
68  try:
69  self.clientsclients = self.apap.get_clients()
70  except UniFiAPConnectionException as e:
71  _LOGGER.error("Failed to connect to accesspoint: %s", str(e))
72  return False
73  except UniFiAPDataException as e:
74  _LOGGER.error("Failed to get proper response from accesspoint: %s", str(e))
75  return False
76 
77  return True
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
UnifiDeviceScanner|None get_scanner(HomeAssistant hass, ConfigType config)