hass-core/homeassistant/components/nightscout/__init__.py
Marcio Granzotto Rodrigues 761067559d
Add Nightscout integration (#38615)
* Implement NightScout sensor integration

* Add tests for NightScout integration

* Fix Nightscout captalization

* Change quality scale for Nightscout

* Trigger actions

* Add missing tests

* Fix stale comments

* Fix Nightscout manufacturer

* Add entry type service

* Change host to URL on nightscout config flow

* Add ConfigEntryNotReady exception to nighscout init

* Remote platform_schema from nightscout sensor

* Update homeassistant/components/nightscout/config_flow.py

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

Co-authored-by: Chris Talkington <chris@talkingtontech.com>
2020-08-09 13:15:56 -05:00

73 lines
2.1 KiB
Python

"""The Nightscout integration."""
import asyncio
from asyncio import TimeoutError as AsyncIOTimeoutError
import logging
from aiohttp import ClientError
from py_nightscout import Api as NightscoutAPI
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.entity import SLOW_UPDATE_WARNING
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor"]
_API_TIMEOUT = SLOW_UPDATE_WARNING - 1
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Nightscout component."""
hass.data.setdefault(DOMAIN, {})
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Nightscout from a config entry."""
server_url = entry.data[CONF_URL]
api = NightscoutAPI(server_url)
try:
status = await api.get_server_status()
except (ClientError, AsyncIOTimeoutError, OSError) as error:
raise ConfigEntryNotReady from error
hass.data[DOMAIN][entry.entry_id] = api
device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, server_url)},
manufacturer="Nightscout Foundation",
name=status.name,
sw_version=status.version,
entry_type="service",
)
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok