Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for the Hive devices and services."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Awaitable, Callable, Coroutine
6 from functools import wraps
7 import logging
8 from typing import Any, Concatenate
9 
10 from aiohttp.web_exceptions import HTTPException
11 from apyhiveapi import Auth, Hive
12 from apyhiveapi.helper.hive_exceptions import HiveReauthRequired
13 import voluptuous as vol
14 
15 from homeassistant import config_entries
16 from homeassistant.config_entries import ConfigEntry
17 from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME
18 from homeassistant.core import HomeAssistant
19 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
20 from homeassistant.helpers import aiohttp_client, config_validation as cv
21 from homeassistant.helpers.device_registry import DeviceEntry
22 from homeassistant.helpers.dispatcher import async_dispatcher_send
23 from homeassistant.helpers.typing import ConfigType
24 
25 from .const import DOMAIN, PLATFORM_LOOKUP, PLATFORMS
26 from .entity import HiveEntity
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 CONFIG_SCHEMA = vol.Schema(
31  vol.All(
32  cv.deprecated(DOMAIN),
33  {
34  DOMAIN: vol.Schema(
35  {
36  vol.Required(CONF_PASSWORD): cv.string,
37  vol.Required(CONF_USERNAME): cv.string,
38  vol.Optional(CONF_SCAN_INTERVAL, default=2): cv.positive_int,
39  },
40  )
41  },
42  ),
43  extra=vol.ALLOW_EXTRA,
44 )
45 
46 
47 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
48  """Hive configuration setup."""
49  hass.data[DOMAIN] = {}
50 
51  if DOMAIN not in config:
52  return True
53 
54  conf = config[DOMAIN]
55 
56  if not hass.config_entries.async_entries(DOMAIN):
57  hass.async_create_task(
58  hass.config_entries.flow.async_init(
59  DOMAIN,
60  context={"source": config_entries.SOURCE_IMPORT},
61  data={
62  CONF_USERNAME: conf[CONF_USERNAME],
63  CONF_PASSWORD: conf[CONF_PASSWORD],
64  },
65  )
66  )
67  return True
68 
69 
70 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
71  """Set up Hive from a config entry."""
72 
73  web_session = aiohttp_client.async_get_clientsession(hass)
74  hive_config = dict(entry.data)
75  hive = Hive(web_session)
76 
77  hive_config["options"] = {}
78  hive_config["options"].update(
79  {CONF_SCAN_INTERVAL: dict(entry.options).get(CONF_SCAN_INTERVAL, 120)}
80  )
81  hass.data[DOMAIN][entry.entry_id] = hive
82 
83  try:
84  devices = await hive.session.startSession(hive_config)
85  except HTTPException as error:
86  _LOGGER.error("Could not connect to the internet: %s", error)
87  raise ConfigEntryNotReady from error
88  except HiveReauthRequired as err:
89  raise ConfigEntryAuthFailed from err
90 
91  await hass.config_entries.async_forward_entry_setups(
92  entry,
93  [
94  ha_type
95  for ha_type, hive_type in PLATFORM_LOOKUP.items()
96  if devices.get(hive_type)
97  ],
98  )
99 
100  return True
101 
102 
103 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
104  """Unload a config entry."""
105  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
106  if unload_ok:
107  hass.data[DOMAIN].pop(entry.entry_id)
108 
109  return unload_ok
110 
111 
112 async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
113  """Remove a config entry."""
114  hive = Auth(entry.data["username"], entry.data["password"])
115  await hive.forget_device(
116  entry.data["tokens"]["AuthenticationResult"]["AccessToken"],
117  entry.data["device_data"][1],
118  )
119 
120 
122  hass: HomeAssistant, config_entry: ConfigEntry, device_entry: DeviceEntry
123 ) -> bool:
124  """Remove a config entry from a device."""
125  return True
126 
127 
128 def refresh_system[_HiveEntityT: HiveEntity, **_P](
129  func: Callable[Concatenate[_HiveEntityT, _P], Awaitable[Any]],
130 ) -> Callable[Concatenate[_HiveEntityT, _P], Coroutine[Any, Any, None]]:
131  """Force update all entities after state change."""
132 
133  @wraps(func)
134  async def wrapper(self: _HiveEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None:
135  await func(self, *args, **kwargs)
136  async_dispatcher_send(self.hass, DOMAIN)
137 
138  return wrapper
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:70
None async_remove_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:112
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:103
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:47
bool async_remove_config_entry_device(HomeAssistant hass, ConfigEntry config_entry, DeviceEntry device_entry)
Definition: __init__.py:123
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193