Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for OPNSense Routers."""
2 
3 import logging
4 
5 from pyopnsense import diagnostics
6 from pyopnsense.exceptions import APIException
7 import voluptuous as vol
8 
9 from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL, Platform
10 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.discovery import load_platform
13 from homeassistant.helpers.typing import ConfigType
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 CONF_API_SECRET = "api_secret"
18 CONF_TRACKER_INTERFACE = "tracker_interfaces"
19 
20 DOMAIN = "opnsense"
21 
22 OPNSENSE_DATA = DOMAIN
23 
24 CONFIG_SCHEMA = vol.Schema(
25  {
26  DOMAIN: vol.Schema(
27  {
28  vol.Required(CONF_URL): cv.url,
29  vol.Required(CONF_API_KEY): cv.string,
30  vol.Required(CONF_API_SECRET): cv.string,
31  vol.Optional(CONF_VERIFY_SSL, default=False): cv.boolean,
32  vol.Optional(CONF_TRACKER_INTERFACE, default=[]): vol.All(
33  cv.ensure_list, [cv.string]
34  ),
35  }
36  )
37  },
38  extra=vol.ALLOW_EXTRA,
39 )
40 
41 
42 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
43  """Set up the opnsense component."""
44 
45  conf = config[DOMAIN]
46  url = conf[CONF_URL]
47  api_key = conf[CONF_API_KEY]
48  api_secret = conf[CONF_API_SECRET]
49  verify_ssl = conf[CONF_VERIFY_SSL]
50  tracker_interfaces = conf[CONF_TRACKER_INTERFACE]
51 
52  interfaces_client = diagnostics.InterfaceClient(
53  api_key, api_secret, url, verify_ssl, timeout=20
54  )
55  try:
56  interfaces_client.get_arp()
57  except APIException:
58  _LOGGER.exception("Failure while connecting to OPNsense API endpoint")
59  return False
60 
61  if tracker_interfaces:
62  # Verify that specified tracker interfaces are valid
63  netinsight_client = diagnostics.NetworkInsightClient(
64  api_key, api_secret, url, verify_ssl, timeout=20
65  )
66  interfaces = list(netinsight_client.get_interfaces().values())
67  for interface in tracker_interfaces:
68  if interface not in interfaces:
69  _LOGGER.error(
70  "Specified OPNsense tracker interface %s is not found", interface
71  )
72  return False
73 
74  hass.data[OPNSENSE_DATA] = {
75  "interfaces": interfaces_client,
76  CONF_TRACKER_INTERFACE: tracker_interfaces,
77  }
78 
79  load_platform(hass, Platform.DEVICE_TRACKER, DOMAIN, tracker_interfaces, config)
80  return True
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:42
None load_platform(core.HomeAssistant hass, Platform|str component, str platform, DiscoveryInfoType|None discovered, ConfigType hass_config)
Definition: discovery.py:137