Home Assistant Unofficial Reference 2024.12.1
device_tracker.py
Go to the documentation of this file.
1 """Support for French FAI Bouygues Bbox routers."""
2 
3 from __future__ import annotations
4 
5 from collections import namedtuple
6 from datetime import timedelta
7 import logging
8 
9 import pybbox
10 import voluptuous as vol
11 
13  DOMAIN as DEVICE_TRACKER_DOMAIN,
14  PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
15  DeviceScanner,
16 )
17 from homeassistant.const import CONF_HOST
18 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.typing import ConfigType
21 from homeassistant.util import Throttle
22 import homeassistant.util.dt as dt_util
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 DEFAULT_HOST = "192.168.1.254"
27 
28 MIN_TIME_BETWEEN_SCANS = timedelta(seconds=60)
29 
30 PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend(
31  {vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string}
32 )
33 
34 
35 def get_scanner(hass: HomeAssistant, config: ConfigType) -> BboxDeviceScanner | None:
36  """Validate the configuration and return a Bbox scanner."""
37  scanner = BboxDeviceScanner(config[DEVICE_TRACKER_DOMAIN])
38 
39  return scanner if scanner.success_init else None
40 
41 
42 Device = namedtuple("Device", ["mac", "name", "ip", "last_update"]) # noqa: PYI024
43 
44 
45 class BboxDeviceScanner(DeviceScanner):
46  """Scanner for devices connected to the bbox."""
47 
48  def __init__(self, config):
49  """Get host from config."""
50 
51  self.hosthost = config[CONF_HOST]
52 
53  """Initialize the scanner."""
54  self.last_resultslast_results: list[Device] = []
55 
56  self.success_initsuccess_init = self._update_info_update_info()
57 
58  def scan_devices(self):
59  """Scan for new devices and return a list with found device IDs."""
60  self._update_info_update_info()
61 
62  return [device.mac for device in self.last_resultslast_results]
63 
64  def get_device_name(self, device):
65  """Return the name of the given device or None if we don't know."""
66  filter_named = [
67  result.name for result in self.last_resultslast_results if result.mac == device
68  ]
69 
70  if filter_named:
71  return filter_named[0]
72  return None
73 
74  @Throttle(MIN_TIME_BETWEEN_SCANS)
75  def _update_info(self):
76  """Check the Bbox for devices.
77 
78  Returns boolean if scanning successful.
79  """
80  _LOGGER.debug("Scanning")
81 
82  box = pybbox.Bbox(ip=self.hosthost)
83  result = box.get_all_connected_devices()
84 
85  now = dt_util.now()
86  last_results = []
87  for device in result:
88  if device["active"] != 1:
89  continue
90  last_results.append(
91  Device(
92  device["macaddress"], device["hostname"], device["ipaddress"], now
93  )
94  )
95 
96  self.last_resultslast_results = last_results
97 
98  _LOGGER.debug("Scan successful")
99  return True
BboxDeviceScanner|None get_scanner(HomeAssistant hass, ConfigType config)