hass-core/homeassistant/components/notion/__init__.py
Ville Skyttä b4bac0f7a0
Exception chaining and wrapping improvements ()
* Remove unnecessary exception re-wraps

* Preserve exception chains on re-raise

We slap "from cause" to almost all possible cases here. In some cases it
could conceivably be better to do "from None" if we really want to hide
the cause. However those should be in the minority, and "from cause"
should be an improvement over the corresponding raise without a "from"
in all cases anyway.

The only case where we raise from None here is in plex, where the
exception for an original invalid SSL cert is not the root cause for
failure to validate a newly fetched one.

Follow local convention on exception variable names if there is a
consistent one, otherwise `err` to match with majority of codebase.

* Fix mistaken re-wrap in homematicip_cloud/hap.py

Missed the difference between HmipConnectionError and
HmipcConnectionError.

* Do not hide original error on plex new cert validation error

Original is not the cause for the new one, but showing old in the
traceback is useful nevertheless.
2020-08-28 13:50:32 +02:00

290 lines
8.9 KiB
Python

"""Support for Notion."""
import asyncio
from datetime import timedelta
import logging
from aionotion import async_get_client
from aionotion.errors import InvalidCredentialsError, NotionError
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import (
aiohttp_client,
config_validation as cv,
device_registry as dr,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DATA_COORDINATOR, DOMAIN
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["binary_sensor", "sensor"]
ATTR_SYSTEM_MODE = "system_mode"
ATTR_SYSTEM_NAME = "system_name"
DEFAULT_ATTRIBUTION = "Data provided by Notion"
DEFAULT_SCAN_INTERVAL = timedelta(minutes=1)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
},
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Set up the Notion component."""
hass.data[DOMAIN] = {DATA_COORDINATOR: {}}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_USERNAME: conf[CONF_USERNAME],
CONF_PASSWORD: conf[CONF_PASSWORD],
},
)
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Notion as a config entry."""
if not entry.unique_id:
hass.config_entries.async_update_entry(
entry, unique_id=entry.data[CONF_USERNAME]
)
session = aiohttp_client.async_get_clientsession(hass)
try:
client = await async_get_client(
entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], session
)
except InvalidCredentialsError:
_LOGGER.error("Invalid username and/or password")
return False
except NotionError as err:
_LOGGER.error("Config entry failed: %s", err)
raise ConfigEntryNotReady from err
async def async_update():
"""Get the latest data from the Notion API."""
data = {"bridges": {}, "sensors": {}, "tasks": {}}
tasks = {
"bridges": client.bridge.async_all(),
"sensors": client.sensor.async_all(),
"tasks": client.task.async_all(),
}
results = await asyncio.gather(*tasks.values(), return_exceptions=True)
for attr, result in zip(tasks, results):
if isinstance(result, NotionError):
raise UpdateFailed(
f"There was a Notion error while updating {attr}: {result}"
)
if isinstance(result, Exception):
raise UpdateFailed(
f"There was an unknown error while updating {attr}: {result}"
)
for item in result:
if attr == "bridges" and item["id"] not in data["bridges"]:
# If a new bridge is discovered, register it:
hass.async_create_task(async_register_new_bridge(hass, item, entry))
data[attr][item["id"]] = item
return data
coordinator = hass.data[DOMAIN][DATA_COORDINATOR][
entry.entry_id
] = DataUpdateCoordinator(
hass,
_LOGGER,
name=entry.data[CONF_USERNAME],
update_interval=DEFAULT_SCAN_INTERVAL,
update_method=async_update,
)
await coordinator.async_refresh()
for platform in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a Notion config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN][DATA_COORDINATOR].pop(entry.entry_id)
return unload_ok
async def async_register_new_bridge(
hass: HomeAssistant, bridge: dict, entry: ConfigEntry
):
"""Register a new bridge."""
device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, bridge["hardware_id"])},
manufacturer="Silicon Labs",
model=bridge["hardware_revision"],
name=bridge["name"] or bridge["id"],
sw_version=bridge["firmware_version"]["wifi"],
)
class NotionEntity(Entity):
"""Define a base Notion entity."""
def __init__(
self,
coordinator: DataUpdateCoordinator,
task_id: str,
sensor_id: str,
bridge_id: str,
system_id: str,
name: str,
device_class: str,
):
"""Initialize the entity."""
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._bridge_id = bridge_id
self._coordinator = coordinator
self._device_class = device_class
self._name = name
self._sensor_id = sensor_id
self._state = None
self._system_id = system_id
self._task_id = task_id
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
self._coordinator.last_update_success
and self._task_id in self._coordinator.data["tasks"]
)
@property
def device_class(self) -> str:
"""Return the device class."""
return self._device_class
@property
def device_state_attributes(self) -> dict:
"""Return the state attributes."""
return self._attrs
@property
def device_info(self) -> dict:
"""Return device registry information for this entity."""
bridge = self._coordinator.data["bridges"].get(self._bridge_id, {})
sensor = self._coordinator.data["sensors"][self._sensor_id]
return {
"identifiers": {(DOMAIN, sensor["hardware_id"])},
"manufacturer": "Silicon Labs",
"model": sensor["hardware_revision"],
"name": sensor["name"],
"sw_version": sensor["firmware_version"],
"via_device": (DOMAIN, bridge.get("hardware_id")),
}
@property
def name(self) -> str:
"""Return the name of the entity."""
sensor = self._coordinator.data["sensors"][self._sensor_id]
return f'{sensor["name"]}: {self._name}'
@property
def should_poll(self) -> bool:
"""Disable entity polling."""
return False
@property
def unique_id(self) -> str:
"""Return a unique, unchanging string that represents this entity."""
task = self._coordinator.data["tasks"][self._task_id]
return f'{self._sensor_id}_{task["task_type"]}'
async def _async_update_bridge_id(self) -> None:
"""Update the entity's bridge ID if it has changed.
Sensors can move to other bridges based on signal strength, etc.
"""
sensor = self._coordinator.data["sensors"][self._sensor_id]
# If the sensor's bridge ID is the same as what we had before or if it points
# to a bridge that doesn't exist (which can happen due to a Notion API bug),
# return immediately:
if (
self._bridge_id == sensor["bridge"]["id"]
or sensor["bridge"]["id"] not in self._coordinator.data["bridges"]
):
return
self._bridge_id = sensor["bridge"]["id"]
device_registry = await dr.async_get_registry(self.hass)
bridge = self._coordinator.data["bridges"][self._bridge_id]
bridge_device = device_registry.async_get_device(
{DOMAIN: bridge["hardware_id"]}, set()
)
this_device = device_registry.async_get_device(
{DOMAIN: sensor["hardware_id"]}, set()
)
device_registry.async_update_device(
this_device.id, via_device_id=bridge_device.id
)
@callback
def _async_update_from_latest_data(self) -> None:
"""Update the entity from the latest data."""
raise NotImplementedError
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
@callback
def update():
"""Update the state."""
self._async_update_from_latest_data()
self.async_write_ha_state()
self.async_on_remove(self._coordinator.async_add_listener(update))
self._async_update_from_latest_data()