Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for Netgear routers."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import Any
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_PORT, CONF_SSL
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryNotReady
13 from homeassistant.helpers import device_registry as dr, entity_registry as er
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
15 
16 from .const import (
17  DOMAIN,
18  KEY_COORDINATOR,
19  KEY_COORDINATOR_FIRMWARE,
20  KEY_COORDINATOR_LINK,
21  KEY_COORDINATOR_SPEED,
22  KEY_COORDINATOR_TRAFFIC,
23  KEY_COORDINATOR_UTIL,
24  KEY_ROUTER,
25  PLATFORMS,
26 )
27 from .errors import CannotLoginException
28 from .router import NetgearRouter
29 
30 _LOGGER = logging.getLogger(__name__)
31 
32 SCAN_INTERVAL = timedelta(seconds=30)
33 SPEED_TEST_INTERVAL = timedelta(hours=2)
34 SCAN_INTERVAL_FIRMWARE = timedelta(hours=5)
35 
36 
37 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
38  """Set up Netgear component."""
39  router = NetgearRouter(hass, entry)
40  try:
41  if not await router.async_setup():
42  raise ConfigEntryNotReady
43  except CannotLoginException as ex:
44  raise ConfigEntryNotReady from ex
45 
46  port = entry.data.get(CONF_PORT)
47  ssl = entry.data.get(CONF_SSL)
48  if port != router.port or ssl != router.ssl:
49  data = {**entry.data, CONF_PORT: router.port, CONF_SSL: router.ssl}
50  hass.config_entries.async_update_entry(entry, data=data)
51  _LOGGER.warning(
52  (
53  "Netgear port-SSL combination updated from (%i, %r) to (%i, %r), "
54  "this should only occur after a firmware update"
55  ),
56  port,
57  ssl,
58  router.port,
59  router.ssl,
60  )
61 
62  hass.data.setdefault(DOMAIN, {})
63 
64  entry.async_on_unload(entry.add_update_listener(update_listener))
65 
66  async def async_update_devices() -> bool:
67  """Fetch data from the router."""
68  if router.track_devices:
69  return await router.async_update_device_trackers()
70  return False
71 
72  async def async_update_traffic_meter() -> dict[str, Any] | None:
73  """Fetch data from the router."""
74  return await router.async_get_traffic_meter()
75 
76  async def async_update_speed_test() -> dict[str, Any] | None:
77  """Fetch data from the router."""
78  return await router.async_get_speed_test()
79 
80  async def async_check_firmware() -> dict[str, Any] | None:
81  """Check for new firmware of the router."""
82  return await router.async_check_new_firmware()
83 
84  async def async_update_utilization() -> dict[str, Any] | None:
85  """Fetch data from the router."""
86  return await router.async_get_utilization()
87 
88  async def async_check_link_status() -> dict[str, Any] | None:
89  """Fetch data from the router."""
90  return await router.async_get_link_status()
91 
92  # Create update coordinators
93  coordinator = DataUpdateCoordinator(
94  hass,
95  _LOGGER,
96  config_entry=entry,
97  name=f"{router.device_name} Devices",
98  update_method=async_update_devices,
99  update_interval=SCAN_INTERVAL,
100  )
101  coordinator_traffic_meter = DataUpdateCoordinator(
102  hass,
103  _LOGGER,
104  config_entry=entry,
105  name=f"{router.device_name} Traffic meter",
106  update_method=async_update_traffic_meter,
107  update_interval=SCAN_INTERVAL,
108  )
109  coordinator_speed_test = DataUpdateCoordinator(
110  hass,
111  _LOGGER,
112  config_entry=entry,
113  name=f"{router.device_name} Speed test",
114  update_method=async_update_speed_test,
115  update_interval=SPEED_TEST_INTERVAL,
116  )
117  coordinator_firmware = DataUpdateCoordinator(
118  hass,
119  _LOGGER,
120  config_entry=entry,
121  name=f"{router.device_name} Firmware",
122  update_method=async_check_firmware,
123  update_interval=SCAN_INTERVAL_FIRMWARE,
124  )
125  coordinator_utilization = DataUpdateCoordinator(
126  hass,
127  _LOGGER,
128  config_entry=entry,
129  name=f"{router.device_name} Utilization",
130  update_method=async_update_utilization,
131  update_interval=SCAN_INTERVAL,
132  )
133  coordinator_link = DataUpdateCoordinator(
134  hass,
135  _LOGGER,
136  config_entry=entry,
137  name=f"{router.device_name} Ethernet Link Status",
138  update_method=async_check_link_status,
139  update_interval=SCAN_INTERVAL,
140  )
141 
142  if router.track_devices:
143  await coordinator.async_config_entry_first_refresh()
144  await coordinator_traffic_meter.async_config_entry_first_refresh()
145  await coordinator_firmware.async_config_entry_first_refresh()
146  await coordinator_utilization.async_config_entry_first_refresh()
147  await coordinator_link.async_config_entry_first_refresh()
148 
149  hass.data[DOMAIN][entry.entry_id] = {
150  KEY_ROUTER: router,
151  KEY_COORDINATOR: coordinator,
152  KEY_COORDINATOR_TRAFFIC: coordinator_traffic_meter,
153  KEY_COORDINATOR_SPEED: coordinator_speed_test,
154  KEY_COORDINATOR_FIRMWARE: coordinator_firmware,
155  KEY_COORDINATOR_UTIL: coordinator_utilization,
156  KEY_COORDINATOR_LINK: coordinator_link,
157  }
158 
159  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
160 
161  return True
162 
163 
164 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
165  """Unload a config entry."""
166  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
167 
168  router = hass.data[DOMAIN][entry.entry_id][KEY_ROUTER]
169 
170  if unload_ok:
171  hass.data[DOMAIN].pop(entry.entry_id)
172  if not hass.data[DOMAIN]:
173  hass.data.pop(DOMAIN)
174 
175  if not router.track_devices:
176  router_id = None
177  # Remove devices that are no longer tracked
178  device_registry = dr.async_get(hass)
179  devices = dr.async_entries_for_config_entry(device_registry, entry.entry_id)
180  for device_entry in devices:
181  if device_entry.via_device_id is None:
182  router_id = device_entry.id
183  continue # do not remove the router itself
184  device_registry.async_update_device(
185  device_entry.id, remove_config_entry_id=entry.entry_id
186  )
187  # Remove entities that are no longer tracked
188  entity_registry = er.async_get(hass)
189  entries = er.async_entries_for_config_entry(entity_registry, entry.entry_id)
190  for entity_entry in entries:
191  if entity_entry.device_id is not router_id:
192  entity_registry.async_remove(entity_entry.entity_id)
193 
194  return unload_ok
195 
196 
197 async def update_listener(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
198  """Handle options update."""
199  await hass.config_entries.async_reload(config_entry.entry_id)
200 
201 
203  hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry
204 ) -> bool:
205  """Remove a device from a config entry."""
206  router = hass.data[DOMAIN][config_entry.entry_id][KEY_ROUTER]
207 
208  device_mac = None
209  for connection in device_entry.connections:
210  if connection[0] == dr.CONNECTION_NETWORK_MAC:
211  device_mac = connection[1]
212  break
213 
214  if device_mac is None:
215  return False
216 
217  if device_mac not in router.devices:
218  return True
219 
220  return not router.devices[device_mac]["active"]
None update_listener(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:197
bool async_remove_config_entry_device(HomeAssistant hass, ConfigEntry config_entry, dr.DeviceEntry device_entry)
Definition: __init__.py:204
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:37
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:164