Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Nightscout integration."""
2 
3 from aiohttp import ClientError
4 from py_nightscout import Api as NightscoutAPI
5 
6 from homeassistant.config_entries import ConfigEntry
7 from homeassistant.const import CONF_API_KEY, CONF_URL, Platform
8 from homeassistant.core import HomeAssistant
9 from homeassistant.exceptions import ConfigEntryNotReady
10 from homeassistant.helpers import device_registry as dr
11 from homeassistant.helpers.aiohttp_client import async_get_clientsession
12 from homeassistant.helpers.entity import SLOW_UPDATE_WARNING
13 
14 from .const import DOMAIN
15 
16 PLATFORMS = [Platform.SENSOR]
17 _API_TIMEOUT = SLOW_UPDATE_WARNING - 1
18 
19 
20 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
21  """Set up Nightscout from a config entry."""
22  server_url = entry.data[CONF_URL]
23  api_key = entry.data.get(CONF_API_KEY)
24  session = async_get_clientsession(hass)
25  api = NightscoutAPI(server_url, session=session, api_secret=api_key)
26  try:
27  status = await api.get_server_status()
28  except (ClientError, TimeoutError, OSError) as error:
29  raise ConfigEntryNotReady from error
30 
31  hass.data.setdefault(DOMAIN, {})
32  hass.data[DOMAIN][entry.entry_id] = api
33 
34  device_registry = dr.async_get(hass)
35  device_registry.async_get_or_create(
36  config_entry_id=entry.entry_id,
37  identifiers={(DOMAIN, server_url)},
38  manufacturer="Nightscout Foundation",
39  name=status.name,
40  sw_version=status.version,
41  entry_type=dr.DeviceEntryType.SERVICE,
42  )
43 
44  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
45 
46  return True
47 
48 
49 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
50  """Unload a config entry."""
51  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
52  if unload_ok:
53  hass.data[DOMAIN].pop(entry.entry_id)
54 
55  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:20
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:49
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)