core/homeassistant/components/deconz/__init__.py

131 lines
4.2 KiB
Python
Raw Normal View History

"""Support for deCONZ devices."""
from __future__ import annotations
from typing import cast
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_PORT,
EVENT_HOMEASSISTANT_STOP,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
import homeassistant.helpers.entity_registry as er
Add deCONZ component (#10321) * Base implementation of component, no sensors yet * Added senor files * First fully working chain of sensors and binary sensors going from hardware in to hass * Clean up * Clean up * Added light platform * Turning lights on and off and set brightness now works * Pydeconz is now a proper pypi package Stop sessions when Home Assistant is shutting down Use a simpler websocket client * Updated pydocstrings Followed recommendations from pylint and flake8 * Clean up * Updated requirements_all.txt * Updated Codeowners to include deconz.py Also re-added the Axis component since it had gotten removed * Bump requirement * Bumped to v2 Reran script/gen_requirements * Removed global DECONZ since it wasn't relevant any more * Username and password is only relevant in the context of getting a API key * Add support for additional sensors * Added support for groups * Moved import of component library to inside of methods * Moved the need for device id to library * Bump pydeconz to v5 * Add support for colored lights * Pylint and flake8 import improvements * DATA_DECONZ TO DECONZ_DATA * Add support for transition time * Add support for flash * Bump to v7 * ZHASwitch devices will now only generate events by default, instead of being a sensor entity * Clean up * Add battery sensor when device signals through an event * Third-party library communicates with service * Add support for effect colorloop * Bump to pydeconz v8 * Same domain everywhere * Clean up * Updated requirements_all * Generated API key will now be stored in a config file * Change battery sensor to register to callback since library now supports multiple callbacks Move DeconzEvent to hub Bump to v9 * Improve entity attributes * Change end of battery name to battery level No need for static icon variable when using battery level helper * Bump requirement to v10 * Improve pydocstring for DeconzEvent Rename TYPE_AS_EVENT to CONF_TYPE_AS_EVENT * Allow separate brightness to override RGB brightness * Expose device.reachable in entity available property * Bump requirement to 11 (it goes up to 11!) * Pylint comment * Binary sensors don't have unit of measurement * Removed service to generate API key in favor of just generating it as a last resort of no API key is specified in configuration.yaml or deconz.conf * Replace clear text to attribute definitions * Use more constants * Bump requirements to v12 * Color temp requires xy color support * Only ZHASwitch should be an event * Bump requirements to v13 * Added effect_list property * Add attribute to battery sensor to easy find event id * Bump requirements to v14 * Fix hound comment * Bumped requirements_all information to v14 * Add service to configure devices on deCONZ * Add initial support for scenes * Bump requirements to v15 * Fix review comments * Python doc string improvement * Improve setup and error handling during setup * Changed how to evaluate light features * Remove 'ghost' events by not triggering updates if the signal originates from a config event Bump requirement to v17 * Fix pylint issue by moving scene ownership in to groups in requirement pydeconz Bump requirement to v18 * Added configurator option to register to deCONZ when unlocking gateway through settings Bump requirement to v20 * Improve async configurator * No user interaction for deconz.conf * No file management in event loop * Improve readability of load platform * Fewer entity attributes * Use values() instead of items() for dicts where applicable * Do one add devices per platform * Clean up of unused attributes * Make sure that discovery info is not None * Only register configure service and shutdown service when deconz has been setup properly * Move description * Fix lines longer than 80 * Moved deconz services to a separate file and moved hub to deconz/__init__.py * Remove option to configure switch as entity * Moved DeconzEvent to sensor since it is only Switch buttonpress that will be sent as event * Added support for automatic discovery of deconz Thanks to Kroimon for adding support to netdisco * Use markup for configuration description * Fix coveragerc * Remove deCONZ support from Hue component * Improved docstrings and readability * Remove unnecessary extra name for storing in hass.data, using domain instead * Improve readability by renaming all async methods Bump to v21 - improved async naming on methods * Fix first line not being in imperative mood * Added logo to configurator Let deconz.conf be visible since it will be the main config for the component after initial setup * Removed bridge_type from new unit tests as part of removing deconz support from hue component * Capitalize first letters of Battery Level * Properly update state of sensor as well as reachable and battery Bump dependency to v22 * Fix flake8 Multi-line docstring closing quotes should be on a separate line * Fix martinhjelmares comments Bump dependency to v23 Use only HASS aiohttp session Change when to use 'deconz' or domain or deconz data Clean up unused logger defines Remove unnecessary return values Fix faulty references to component documentation Move callback registration to after entity has been initialized by HASS Less inception style on pydocs ;) Simplify loading platforms by using a for loop Added voluptous schema for service Yaml file is for deconz only, no need to have the domain present Remove domain constraint when creating event title
2018-01-01 16:08:13 +00:00
from .config_flow import get_master_gateway
from .const import CONF_GROUP_ID_BASE, CONF_MASTER_GATEWAY, DOMAIN, PLATFORMS
from .deconz_event import async_setup_events, async_unload_events
from .errors import AuthenticationRequired, CannotConnect
from .gateway import DeconzGateway, get_deconz_session
from .services import async_setup_services, async_unload_services
Add deCONZ component (#10321) * Base implementation of component, no sensors yet * Added senor files * First fully working chain of sensors and binary sensors going from hardware in to hass * Clean up * Clean up * Added light platform * Turning lights on and off and set brightness now works * Pydeconz is now a proper pypi package Stop sessions when Home Assistant is shutting down Use a simpler websocket client * Updated pydocstrings Followed recommendations from pylint and flake8 * Clean up * Updated requirements_all.txt * Updated Codeowners to include deconz.py Also re-added the Axis component since it had gotten removed * Bump requirement * Bumped to v2 Reran script/gen_requirements * Removed global DECONZ since it wasn't relevant any more * Username and password is only relevant in the context of getting a API key * Add support for additional sensors * Added support for groups * Moved import of component library to inside of methods * Moved the need for device id to library * Bump pydeconz to v5 * Add support for colored lights * Pylint and flake8 import improvements * DATA_DECONZ TO DECONZ_DATA * Add support for transition time * Add support for flash * Bump to v7 * ZHASwitch devices will now only generate events by default, instead of being a sensor entity * Clean up * Add battery sensor when device signals through an event * Third-party library communicates with service * Add support for effect colorloop * Bump to pydeconz v8 * Same domain everywhere * Clean up * Updated requirements_all * Generated API key will now be stored in a config file * Change battery sensor to register to callback since library now supports multiple callbacks Move DeconzEvent to hub Bump to v9 * Improve entity attributes * Change end of battery name to battery level No need for static icon variable when using battery level helper * Bump requirement to v10 * Improve pydocstring for DeconzEvent Rename TYPE_AS_EVENT to CONF_TYPE_AS_EVENT * Allow separate brightness to override RGB brightness * Expose device.reachable in entity available property * Bump requirement to 11 (it goes up to 11!) * Pylint comment * Binary sensors don't have unit of measurement * Removed service to generate API key in favor of just generating it as a last resort of no API key is specified in configuration.yaml or deconz.conf * Replace clear text to attribute definitions * Use more constants * Bump requirements to v12 * Color temp requires xy color support * Only ZHASwitch should be an event * Bump requirements to v13 * Added effect_list property * Add attribute to battery sensor to easy find event id * Bump requirements to v14 * Fix hound comment * Bumped requirements_all information to v14 * Add service to configure devices on deCONZ * Add initial support for scenes * Bump requirements to v15 * Fix review comments * Python doc string improvement * Improve setup and error handling during setup * Changed how to evaluate light features * Remove 'ghost' events by not triggering updates if the signal originates from a config event Bump requirement to v17 * Fix pylint issue by moving scene ownership in to groups in requirement pydeconz Bump requirement to v18 * Added configurator option to register to deCONZ when unlocking gateway through settings Bump requirement to v20 * Improve async configurator * No user interaction for deconz.conf * No file management in event loop * Improve readability of load platform * Fewer entity attributes * Use values() instead of items() for dicts where applicable * Do one add devices per platform * Clean up of unused attributes * Make sure that discovery info is not None * Only register configure service and shutdown service when deconz has been setup properly * Move description * Fix lines longer than 80 * Moved deconz services to a separate file and moved hub to deconz/__init__.py * Remove option to configure switch as entity * Moved DeconzEvent to sensor since it is only Switch buttonpress that will be sent as event * Added support for automatic discovery of deconz Thanks to Kroimon for adding support to netdisco * Use markup for configuration description * Fix coveragerc * Remove deCONZ support from Hue component * Improved docstrings and readability * Remove unnecessary extra name for storing in hass.data, using domain instead * Improve readability by renaming all async methods Bump to v21 - improved async naming on methods * Fix first line not being in imperative mood * Added logo to configurator Let deconz.conf be visible since it will be the main config for the component after initial setup * Removed bridge_type from new unit tests as part of removing deconz support from hue component * Capitalize first letters of Battery Level * Properly update state of sensor as well as reachable and battery Bump dependency to v22 * Fix flake8 Multi-line docstring closing quotes should be on a separate line * Fix martinhjelmares comments Bump dependency to v23 Use only HASS aiohttp session Change when to use 'deconz' or domain or deconz data Clean up unused logger defines Remove unnecessary return values Fix faulty references to component documentation Move callback registration to after entity has been initialized by HASS Less inception style on pydocs ;) Simplify loading platforms by using a for loop Added voluptous schema for service Yaml file is for deconz only, no need to have the domain present Remove domain constraint when creating event title
2018-01-01 16:08:13 +00:00
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up a deCONZ bridge for a config entry.
Add deCONZ component (#10321) * Base implementation of component, no sensors yet * Added senor files * First fully working chain of sensors and binary sensors going from hardware in to hass * Clean up * Clean up * Added light platform * Turning lights on and off and set brightness now works * Pydeconz is now a proper pypi package Stop sessions when Home Assistant is shutting down Use a simpler websocket client * Updated pydocstrings Followed recommendations from pylint and flake8 * Clean up * Updated requirements_all.txt * Updated Codeowners to include deconz.py Also re-added the Axis component since it had gotten removed * Bump requirement * Bumped to v2 Reran script/gen_requirements * Removed global DECONZ since it wasn't relevant any more * Username and password is only relevant in the context of getting a API key * Add support for additional sensors * Added support for groups * Moved import of component library to inside of methods * Moved the need for device id to library * Bump pydeconz to v5 * Add support for colored lights * Pylint and flake8 import improvements * DATA_DECONZ TO DECONZ_DATA * Add support for transition time * Add support for flash * Bump to v7 * ZHASwitch devices will now only generate events by default, instead of being a sensor entity * Clean up * Add battery sensor when device signals through an event * Third-party library communicates with service * Add support for effect colorloop * Bump to pydeconz v8 * Same domain everywhere * Clean up * Updated requirements_all * Generated API key will now be stored in a config file * Change battery sensor to register to callback since library now supports multiple callbacks Move DeconzEvent to hub Bump to v9 * Improve entity attributes * Change end of battery name to battery level No need for static icon variable when using battery level helper * Bump requirement to v10 * Improve pydocstring for DeconzEvent Rename TYPE_AS_EVENT to CONF_TYPE_AS_EVENT * Allow separate brightness to override RGB brightness * Expose device.reachable in entity available property * Bump requirement to 11 (it goes up to 11!) * Pylint comment * Binary sensors don't have unit of measurement * Removed service to generate API key in favor of just generating it as a last resort of no API key is specified in configuration.yaml or deconz.conf * Replace clear text to attribute definitions * Use more constants * Bump requirements to v12 * Color temp requires xy color support * Only ZHASwitch should be an event * Bump requirements to v13 * Added effect_list property * Add attribute to battery sensor to easy find event id * Bump requirements to v14 * Fix hound comment * Bumped requirements_all information to v14 * Add service to configure devices on deCONZ * Add initial support for scenes * Bump requirements to v15 * Fix review comments * Python doc string improvement * Improve setup and error handling during setup * Changed how to evaluate light features * Remove 'ghost' events by not triggering updates if the signal originates from a config event Bump requirement to v17 * Fix pylint issue by moving scene ownership in to groups in requirement pydeconz Bump requirement to v18 * Added configurator option to register to deCONZ when unlocking gateway through settings Bump requirement to v20 * Improve async configurator * No user interaction for deconz.conf * No file management in event loop * Improve readability of load platform * Fewer entity attributes * Use values() instead of items() for dicts where applicable * Do one add devices per platform * Clean up of unused attributes * Make sure that discovery info is not None * Only register configure service and shutdown service when deconz has been setup properly * Move description * Fix lines longer than 80 * Moved deconz services to a separate file and moved hub to deconz/__init__.py * Remove option to configure switch as entity * Moved DeconzEvent to sensor since it is only Switch buttonpress that will be sent as event * Added support for automatic discovery of deconz Thanks to Kroimon for adding support to netdisco * Use markup for configuration description * Fix coveragerc * Remove deCONZ support from Hue component * Improved docstrings and readability * Remove unnecessary extra name for storing in hass.data, using domain instead * Improve readability by renaming all async methods Bump to v21 - improved async naming on methods * Fix first line not being in imperative mood * Added logo to configurator Let deconz.conf be visible since it will be the main config for the component after initial setup * Removed bridge_type from new unit tests as part of removing deconz support from hue component * Capitalize first letters of Battery Level * Properly update state of sensor as well as reachable and battery Bump dependency to v22 * Fix flake8 Multi-line docstring closing quotes should be on a separate line * Fix martinhjelmares comments Bump dependency to v23 Use only HASS aiohttp session Change when to use 'deconz' or domain or deconz data Clean up unused logger defines Remove unnecessary return values Fix faulty references to component documentation Move callback registration to after entity has been initialized by HASS Less inception style on pydocs ;) Simplify loading platforms by using a for loop Added voluptous schema for service Yaml file is for deconz only, no need to have the domain present Remove domain constraint when creating event title
2018-01-01 16:08:13 +00:00
Load config, group, light and sensor data for server information.
Start websocket for push notification of state changes from deCONZ.
"""
hass.data.setdefault(DOMAIN, {})
await async_update_group_unique_id(hass, config_entry)
if not config_entry.options:
await async_update_master_gateway(hass, config_entry)
try:
api = await get_deconz_session(hass, config_entry.data)
except CannotConnect as err:
raise ConfigEntryNotReady from err
except AuthenticationRequired as err:
raise ConfigEntryAuthFailed from err
gateway = hass.data[DOMAIN][config_entry.entry_id] = DeconzGateway(
hass, config_entry, api
)
await gateway.async_update_device_registry()
config_entry.add_update_listener(gateway.async_config_entry_updated)
await async_setup_events(gateway)
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
if len(hass.data[DOMAIN]) == 1:
async_setup_services(hass)
api.start()
2021-04-20 16:14:11 +00:00
config_entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, gateway.shutdown)
)
Add deCONZ component (#10321) * Base implementation of component, no sensors yet * Added senor files * First fully working chain of sensors and binary sensors going from hardware in to hass * Clean up * Clean up * Added light platform * Turning lights on and off and set brightness now works * Pydeconz is now a proper pypi package Stop sessions when Home Assistant is shutting down Use a simpler websocket client * Updated pydocstrings Followed recommendations from pylint and flake8 * Clean up * Updated requirements_all.txt * Updated Codeowners to include deconz.py Also re-added the Axis component since it had gotten removed * Bump requirement * Bumped to v2 Reran script/gen_requirements * Removed global DECONZ since it wasn't relevant any more * Username and password is only relevant in the context of getting a API key * Add support for additional sensors * Added support for groups * Moved import of component library to inside of methods * Moved the need for device id to library * Bump pydeconz to v5 * Add support for colored lights * Pylint and flake8 import improvements * DATA_DECONZ TO DECONZ_DATA * Add support for transition time * Add support for flash * Bump to v7 * ZHASwitch devices will now only generate events by default, instead of being a sensor entity * Clean up * Add battery sensor when device signals through an event * Third-party library communicates with service * Add support for effect colorloop * Bump to pydeconz v8 * Same domain everywhere * Clean up * Updated requirements_all * Generated API key will now be stored in a config file * Change battery sensor to register to callback since library now supports multiple callbacks Move DeconzEvent to hub Bump to v9 * Improve entity attributes * Change end of battery name to battery level No need for static icon variable when using battery level helper * Bump requirement to v10 * Improve pydocstring for DeconzEvent Rename TYPE_AS_EVENT to CONF_TYPE_AS_EVENT * Allow separate brightness to override RGB brightness * Expose device.reachable in entity available property * Bump requirement to 11 (it goes up to 11!) * Pylint comment * Binary sensors don't have unit of measurement * Removed service to generate API key in favor of just generating it as a last resort of no API key is specified in configuration.yaml or deconz.conf * Replace clear text to attribute definitions * Use more constants * Bump requirements to v12 * Color temp requires xy color support * Only ZHASwitch should be an event * Bump requirements to v13 * Added effect_list property * Add attribute to battery sensor to easy find event id * Bump requirements to v14 * Fix hound comment * Bumped requirements_all information to v14 * Add service to configure devices on deCONZ * Add initial support for scenes * Bump requirements to v15 * Fix review comments * Python doc string improvement * Improve setup and error handling during setup * Changed how to evaluate light features * Remove 'ghost' events by not triggering updates if the signal originates from a config event Bump requirement to v17 * Fix pylint issue by moving scene ownership in to groups in requirement pydeconz Bump requirement to v18 * Added configurator option to register to deCONZ when unlocking gateway through settings Bump requirement to v20 * Improve async configurator * No user interaction for deconz.conf * No file management in event loop * Improve readability of load platform * Fewer entity attributes * Use values() instead of items() for dicts where applicable * Do one add devices per platform * Clean up of unused attributes * Make sure that discovery info is not None * Only register configure service and shutdown service when deconz has been setup properly * Move description * Fix lines longer than 80 * Moved deconz services to a separate file and moved hub to deconz/__init__.py * Remove option to configure switch as entity * Moved DeconzEvent to sensor since it is only Switch buttonpress that will be sent as event * Added support for automatic discovery of deconz Thanks to Kroimon for adding support to netdisco * Use markup for configuration description * Fix coveragerc * Remove deCONZ support from Hue component * Improved docstrings and readability * Remove unnecessary extra name for storing in hass.data, using domain instead * Improve readability by renaming all async methods Bump to v21 - improved async naming on methods * Fix first line not being in imperative mood * Added logo to configurator Let deconz.conf be visible since it will be the main config for the component after initial setup * Removed bridge_type from new unit tests as part of removing deconz support from hue component * Capitalize first letters of Battery Level * Properly update state of sensor as well as reachable and battery Bump dependency to v22 * Fix flake8 Multi-line docstring closing quotes should be on a separate line * Fix martinhjelmares comments Bump dependency to v23 Use only HASS aiohttp session Change when to use 'deconz' or domain or deconz data Clean up unused logger defines Remove unnecessary return values Fix faulty references to component documentation Move callback registration to after entity has been initialized by HASS Less inception style on pydocs ;) Simplify loading platforms by using a for loop Added voluptous schema for service Yaml file is for deconz only, no need to have the domain present Remove domain constraint when creating event title
2018-01-01 16:08:13 +00:00
return True
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload deCONZ config entry."""
gateway: DeconzGateway = hass.data[DOMAIN].pop(config_entry.entry_id)
async_unload_events(gateway)
if not hass.data[DOMAIN]:
async_unload_services(hass)
elif gateway.master:
await async_update_master_gateway(hass, config_entry)
new_master_gateway = next(iter(hass.data[DOMAIN].values()))
await async_update_master_gateway(hass, new_master_gateway.config_entry)
return await gateway.async_reset()
async def async_update_master_gateway(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Update master gateway boolean.
Called by setup_entry and unload_entry.
Makes sure there is always one master available.
"""
try:
master_gateway = get_master_gateway(hass)
master = master_gateway.config_entry == config_entry
except ValueError:
master = True
options = {**config_entry.options, CONF_MASTER_GATEWAY: master}
hass.config_entries.async_update_entry(config_entry, options=options)
async def async_update_group_unique_id(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Update unique ID entities based on deCONZ groups."""
if not (group_id_base := config_entry.data.get(CONF_GROUP_ID_BASE)):
return
old_unique_id = cast(str, group_id_base)
new_unique_id = cast(str, config_entry.unique_id)
@callback
def update_unique_id(entity_entry: er.RegistryEntry) -> dict[str, str] | None:
"""Update unique ID of entity entry."""
if f"{old_unique_id}-" not in entity_entry.unique_id:
return None
return {
"new_unique_id": entity_entry.unique_id.replace(
old_unique_id, new_unique_id
)
}
await er.async_migrate_entries(hass, config_entry.entry_id, update_unique_id)
data = {
CONF_API_KEY: config_entry.data[CONF_API_KEY],
CONF_HOST: config_entry.data[CONF_HOST],
CONF_PORT: config_entry.data[CONF_PORT],
}
hass.config_entries.async_update_entry(config_entry, data=data)