async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Tado from a config entry.""" _async_import_options_from_data_if_missing(hass, entry) username = entry.data[CONF_USERNAME] password = entry.data[CONF_PASSWORD] fallback = entry.options.get(CONF_FALLBACK, True) tadoconnector = TadoConnector(hass, username, password, fallback) try: await hass.async_add_executor_job(tadoconnector.setup) except KeyError: _LOGGER.error("Failed to login to tado") return False except RuntimeError as exc: _LOGGER.error("Failed to setup tado: %s", exc) return False except requests.exceptions.Timeout as ex: raise ConfigEntryNotReady from ex except requests.exceptions.HTTPError as ex: if ex.response.status_code > 400 and ex.response.status_code < 500: _LOGGER.error("Failed to login to tado: %s", ex) return False raise ConfigEntryNotReady from ex # Do first update await hass.async_add_executor_job(tadoconnector.update) # Poll for updates in the background update_track = async_track_time_interval( hass, lambda now: tadoconnector.update(), SCAN_INTERVAL, ) update_listener = entry.add_update_listener(_async_update_listener) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA: tadoconnector, UPDATE_TRACK: update_track, UPDATE_LISTENER: update_listener, } hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Google from a config entry.""" hass.data.setdefault(DOMAIN, {}) async_upgrade_entry(hass, entry) implementation = ( await config_entry_oauth2_flow.async_get_config_entry_implementation( hass, entry ) ) session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation) # Force a token refresh to fix a bug where tokens were persisted with # expires_in (relative time delta) and expires_at (absolute time) swapped. # A google session token typically only lasts a few days between refresh. now = datetime.now() if session.token["expires_at"] >= (now + timedelta(days=365)).timestamp(): session.token["expires_in"] = 0 session.token["expires_at"] = now.timestamp() try: await session.async_ensure_token_valid() except aiohttp.ClientResponseError as err: if 400 <= err.status < 500: raise ConfigEntryAuthFailed from err raise ConfigEntryNotReady from err except aiohttp.ClientError as err: raise ConfigEntryNotReady from err access = FeatureAccess[entry.options[CONF_CALENDAR_ACCESS]] token_scopes = session.token.get("scope", []) if access.scope not in token_scopes: _LOGGER.debug("Scope '%s' not in scopes '%s'", access.scope, token_scopes) raise ConfigEntryAuthFailed( "Required scopes are not available, reauth required" ) calendar_service = GoogleCalendarService( ApiAuthImpl(async_get_clientsession(hass), session) ) hass.data[DOMAIN][DATA_SERVICE] = calendar_service await async_setup_services(hass, calendar_service) # Only expose the add event service if we have the correct permissions if access is FeatureAccess.read_write: await async_setup_add_event_service(hass, calendar_service) hass.config_entries.async_setup_platforms(entry, PLATFORMS) # Reload entry when options are updated entry.async_on_unload(entry.add_update_listener(async_reload_entry)) return True
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up forked-daapd from a config entry.""" host = config_entry.data[CONF_HOST] port = config_entry.data[CONF_PORT] password = config_entry.data[CONF_PASSWORD] forked_daapd_api = ForkedDaapdAPI( async_get_clientsession(hass), host, port, password ) forked_daapd_master = ForkedDaapdMaster( clientsession=async_get_clientsession(hass), api=forked_daapd_api, ip_address=host, api_port=port, api_password=password, config_entry=config_entry, ) @callback def async_add_zones(api, outputs): zone_entities = [] for output in outputs: zone_entities.append(ForkedDaapdZone(api, output, config_entry.entry_id)) async_add_entities(zone_entities, False) remove_add_zones_listener = async_dispatcher_connect( hass, SIGNAL_ADD_ZONES.format(config_entry.entry_id), async_add_zones ) remove_entry_listener = config_entry.add_update_listener(update_listener) if not hass.data.get(DOMAIN): hass.data[DOMAIN] = {config_entry.entry_id: {}} hass.data[DOMAIN][config_entry.entry_id] = { HASS_DATA_REMOVE_LISTENERS_KEY: [ remove_add_zones_listener, remove_entry_listener, ] } async_add_entities([forked_daapd_master], False) forked_daapd_updater = ForkedDaapdUpdater( hass, forked_daapd_api, config_entry.entry_id ) await forked_daapd_updater.async_init() hass.data[DOMAIN][config_entry.entry_id][ HASS_DATA_UPDATER_KEY ] = forked_daapd_updater
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up pvpc hourly pricing from a config entry.""" if len(entry.data) == 2: defaults = { ATTR_TARIFF: _DEFAULT_TARIFF, ATTR_POWER: DEFAULT_POWER_KW, ATTR_POWER_P3: DEFAULT_POWER_KW, } data = {**entry.data, **defaults} hass.config_entries.async_update_entry(entry, unique_id=_DEFAULT_TARIFF, data=data, options=defaults) @callback def update_unique_id(reg_entry): """Change unique id for sensor entity, pointing to new tariff.""" return {"new_unique_id": _DEFAULT_TARIFF} try: await async_migrate_entries(hass, entry.entry_id, update_unique_id) _LOGGER.warning( "Migrating PVPC sensor from old tariff '%s' to new '%s'. " "Configure the integration to set your contracted power, " "and select prices for Ceuta/Melilla, " "if that is your case", entry.data[ATTR_TARIFF], _DEFAULT_TARIFF, ) except ValueError: # there were multiple sensors (with different old tariffs, up to 3), # so we leave just one and remove the others ent_reg: EntityRegistry = async_get(hass) for entity_id, reg_entry in ent_reg.entities.items(): if reg_entry.config_entry_id == entry.entry_id: ent_reg.async_remove(entity_id) _LOGGER.warning( "Old PVPC Sensor %s is removed " "(another one already exists, using the same tariff)", entity_id, ) break await hass.config_entries.async_remove(entry.entry_id) return False hass.config_entries.async_setup_platforms(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(async_update_options)) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) session = async_get_clientsession(hass) client = PollenApi(session, entry.data[CONF_URL]) coordinator = PollenprognosDataUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_device_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ): """Set up the Xiaomi Miio device component from a config entry.""" platforms = get_platforms(entry) await async_create_miio_device_and_coordinator(hass, entry) if not platforms: return False entry.async_on_unload(entry.add_update_listener(update_listener)) hass.config_entries.async_setup_platforms(entry, platforms) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) latitude = entry.data.get(CONF_LAT) longitude = entry.data.get(CONF_LONG) place = entry.data.get(CONF_PLACE) session = async_get_clientsession(hass) client = NorwegianWeatherApiClient(place, latitude, longitude, session) coordinator = NorwegianWeatherDataUpdateCoordinator( hass, entry=entry, client=client ) await coordinator.async_refresh() coordinator._create_entitites() if not coordinator.last_update_success: raise ConfigEntryNotReady # hass.data[DOMAIN]["coordinator"] = coordinator hass.data[DOMAIN][entry.entry_id] = coordinator hass.data[DOMAIN]["entities"] = [] for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform) ) entry.add_update_listener(async_reload_entry) await coordinator.add_schedulers() return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the Axis integration.""" hass.data.setdefault(AXIS_DOMAIN, {}) try: api = await get_axis_device(hass, config_entry.data) except CannotConnect as err: raise ConfigEntryNotReady from err except AuthenticationRequired as err: raise ConfigEntryAuthFailed from err device = AxisNetworkDevice(hass, config_entry, api) hass.data[AXIS_DOMAIN][config_entry.unique_id] = device await device.async_update_device_registry() await hass.config_entries.async_forward_entry_setups( config_entry, PLATFORMS) device.async_setup_events() config_entry.add_update_listener(device.async_new_address_callback) config_entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.shutdown)) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up wiffi from a config entry, config_entry contains data from config entry database.""" if not entry.update_listeners: entry.add_update_listener(async_update_options) # create api object api = WiffiIntegrationApi(hass) api.async_setup(entry) # store api object hass.data.setdefault(DOMAIN, {})[entry.entry_id] = api try: await api.server.start_server() except OSError as exc: if exc.errno != errno.EADDRINUSE: _LOGGER.error("Start_server failed, errno: %d", exc.errno) return False _LOGGER.error("Port %s already in use", entry.data[CONF_PORT]) raise ConfigEntryNotReady from exc hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up MusicCast from a config entry.""" client = MusicCastDevice(entry.data[CONF_HOST], async_get_clientsession(hass)) coordinator = MusicCastDataUpdateCoordinator(hass, client=client) await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) return True
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, index: int): """Initialize a Hubitat manager.""" if CONF_HOST not in entry.data: raise ValueError("Missing host in config entry") if CONF_APP_ID not in entry.data: raise ValueError("Missing app ID in config entry") if CONF_ACCESS_TOKEN not in entry.data: raise ValueError("Missing access token in config entry") self.hass = hass self.config_entry = entry self.entities: List["HubitatEntity"] = [] self.event_emitters: List["HubitatEventEmitter"] = [] self._temperature_unit = (entry.options.get( CONF_TEMPERATURE_UNIT, entry.data.get(CONF_TEMPERATURE_UNIT)) or TEMP_F) if index == 1: self._hub_entity_id = "hubitat.hub" else: self._hub_entity_id = f"hubitat.hub_{index}" entry.add_update_listener(self.async_update_options)
async def async_setup_entry(self, config_entry: ConfigEntry) -> bool: """Create a DMS device connection from a config entry.""" assert config_entry.unique_id async with self.lock: source_id = self._generate_source_id(config_entry.title) device = DmsDeviceSource(self.hass, config_entry, source_id) self.devices[config_entry.unique_id] = device self.sources[device.source_id] = device # Update the device when the associated config entry is modified config_entry.async_on_unload( config_entry.add_update_listener(self.async_update_entry)) await device.async_added_to_hass() return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Coinbase from a config entry.""" instance = await hass.async_add_executor_job(create_and_update_instance, entry) entry.async_on_unload(entry.add_update_listener(update_listener)) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = instance hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Support two kind of enties - MiCloud and Gateway.""" # entry for MiCloud login if 'servers' in entry.data: return await _setup_micloud_entry(hass, entry) # migrate data (also after first setup) to options if entry.data: hass.config_entries.async_update_entry(entry, data={}, options=entry.data) await _setup_logger(hass) # add options handler if not entry.update_listeners: entry.add_update_listener(async_update_options) hass.data[DOMAIN][entry.entry_id] = Gateway3(**entry.options) hass.async_create_task(_setup_domains(hass, entry)) return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): """Set up blitzortung from a config entry.""" hass.data.setdefault(DOMAIN, {}) config = hass.data[DOMAIN].get("config") or {} latitude = config_entry.options.get(CONF_LATITUDE, hass.config.latitude) longitude = config_entry.options.get(CONF_LONGITUDE, hass.config.longitude) radius = config_entry.options.get(CONF_RADIUS, DEFAULT_RADIUS) idle_reset_seconds = config_entry.options.get( CONF_IDLE_RESET_TIMEOUT, DEFAULT_IDLE_RESET_TIMEOUT) * 60 coordinator = BlitzortungDataUpdateCoordinator( hass, latitude, longitude, radius, idle_reset_seconds, DEFAULT_UPDATE_INTERVAL, server_stats=config.get(const.SERVER_STATS), ) hass.data[DOMAIN][config_entry.entry_id] = coordinator async def start_platforms(): await asyncio.gather(*[ hass.config_entries.async_forward_entry_setup( config_entry, component) for component in PLATFORMS ]) await coordinator.connect() hass.async_create_task(start_platforms()) if not config_entry.update_listeners: config_entry.add_update_listener(async_update_options) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) host = entry.data.get(CONF_HOST) port = entry.data.get(CONF_PORT) version = entry.data.get(CONF_VERSION) _LOGGER.info("Creating coordinator") coordinator = InelsDataUpdateCoordinator( hass, host=host, port=port, version=version ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady _LOGGER.info("Loading platforms with entries ") _LOGGER.info(entry) hass.data[DOMAIN][entry.entry_id] = coordinator hass.data[DOMAIN][DOMAIN_DATA] = coordinator.api.getAllDevices() for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform) ) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): _LOGGER.debug(f"Setting up entry for device: {entry.data[CONF_DEVICE_ID]}") config = {**entry.data, **entry.options, "name": entry.title} setup_device(hass, config) device_conf = get_config(config[CONF_TYPE]) if device_conf is None: _LOGGER.error(f"COnfiguration file for {config[CONF_TYPE]} not found.") return False entities = {} e = device_conf.primary_entity if config.get(e.config_id, False): entities[e.entity] = True for e in device_conf.secondary_entities(): if config.get(e.config_id, False): entities[e.entity] = True for e in entities: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, e)) entry.add_update_listener(async_update_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Freedompro from a config entry.""" hass.data.setdefault(DOMAIN, {}) api_key = entry.data[CONF_API_KEY] coordinator = FreedomproDataUpdateCoordinator(hass, api_key) await coordinator.async_config_entry_first_refresh() entry.async_on_unload(entry.add_update_listener(update_listener)) hass.data[DOMAIN][entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the UpCloud config entry.""" manager = upcloud_api.CloudManager(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) try: await hass.async_add_executor_job(manager.authenticate) except upcloud_api.UpCloudAPIError: _LOGGER.error("Authentication failed", exc_info=True) return False except requests.exceptions.RequestException as err: _LOGGER.error("Failed to connect", exc_info=True) raise ConfigEntryNotReady from err if entry.options.get(CONF_SCAN_INTERVAL): update_interval = timedelta(seconds=entry.options[CONF_SCAN_INTERVAL]) else: update_interval = DEFAULT_SCAN_INTERVAL coordinator = UpCloudDataUpdateCoordinator( hass, update_interval=update_interval, cloud_manager=manager, username=entry.data[CONF_USERNAME], ) # Call the UpCloud API to refresh data await coordinator.async_config_entry_first_refresh() # Listen to config entry updates entry.async_on_unload( entry.add_update_listener(_async_signal_options_update)) entry.async_on_unload( async_dispatcher_connect( hass, _config_entry_update_signal_name(entry), coordinator.async_update_config, )) hass.data[DATA_UPCLOUD] = UpCloudHassData() hass.data[DATA_UPCLOUD].coordinators[ entry.data[CONF_USERNAME]] = coordinator # Forward entry setup hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up kmtronic from a config entry.""" session = aiohttp_client.async_get_clientsession(hass) auth = Auth( session, f"http://{entry.data[CONF_HOST]}", entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], ) hub = KMTronicHubAPI(auth) async def async_update_data(): try: async with async_timeout.timeout(10): await hub.async_update_relays() except aiohttp.client_exceptions.ClientResponseError as err: raise UpdateFailed(f"Wrong credentials: {err}") from err except ( asyncio.TimeoutError, aiohttp.client_exceptions.ClientConnectorError, ) as err: raise UpdateFailed(f"Error communicating with API: {err}") from err coordinator = DataUpdateCoordinator( hass, _LOGGER, name=f"{MANUFACTURER} {hub.name}", update_method=async_update_data, update_interval=timedelta(seconds=30), ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = { DATA_HUB: hub, DATA_COORDINATOR: coordinator, } for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) update_listener = entry.add_update_listener(async_update_options) hass.data[DOMAIN][entry.entry_id][UPDATE_LISTENER] = update_listener return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up HASL entries""" logger.debug(f"[setup_entry] Entering for {entry.entry_id}") try: device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create(config_entry_id=entry.entry_id, identifiers={(DOMAIN, DEVICE_GUID) }, name=DEVICE_NAME, model=DEVICE_MODEL, sw_version=HASL_VERSION, manufacturer=DEVICE_MANUFACTURER, entry_type=DEVICE_TYPE) logger.debug("[setup_entry] Created device") except Exception as e: logger.error("[setup_entry] Failed to create device") return False try: hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, "sensor")) hass.async_add_job( hass.config_entries.async_forward_entry_setup( entry, "binary_sensor")) logger.debug("[setup_entry] Forward entry setup succeeded") except Exception as e: logger.error("[setup_entry] Forward entry setup failed") return False updater = None try: updater = entry.add_update_listener(reload_entry) except Exception as e: logger.error("[setup_entry] Update listener setup failed") return False try: hass.data[DOMAIN]["worker"].instances.add(entry.entry_id, updater) logger.debug("[setup_entry] Worker registration succeeded") except Exception as e: logger.error(f"[setup_entry] Worker registration failed: {str(e)}") return False logger.debug("[setup_entry] Completed") return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Reolink from a config entry.""" hass.data.setdefault(DOMAIN, {}) base = ReolinkBase(hass, entry.data, entry.options) base.sync_functions.append(entry.add_update_listener(update_listener)) if not await base.connect_api(): return False webhook_id = await register_webhook(hass, base.event_id) webhook_url = "{}{}".format( get_url(hass, prefer_external=False), hass.components.webhook.async_generate_path(webhook_id)) await base.subscribe(webhook_url) hass.data[DOMAIN][entry.entry_id] = {BASE: base} async def async_update_data(): """Perform the actual updates.""" async with async_timeout.timeout(base.timeout): await base.renew() await base.update_states() coordinator = DataUpdateCoordinator( hass, _LOGGER, name="reolink", update_method=async_update_data, update_interval=SCAN_INTERVAL, ) # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) hass.data[DOMAIN][entry.entry_id][COORDINATOR] = coordinator hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, base.stop()) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up GIOS as config entry.""" station_id = entry.data[CONF_STATION_ID] # For backwards compat, set unique ID if entry.unique_id is None: hass.config_entries.async_update_entry(entry, unique_id=station_id) # We used to use int as config_entry unique_id, convert this to str. if isinstance(entry.unique_id, int): # type: ignore[unreachable] hass.config_entries.async_update_entry( entry, unique_id=str(station_id)) # type: ignore[unreachable] # We used to use int in device_entry identifiers, convert this to str. device_registry = await async_get_registry(hass) old_ids = (DOMAIN, station_id) device_entry = device_registry.async_get_device( {old_ids}) # type: ignore[arg-type] if device_entry and entry.entry_id in device_entry.config_entries: new_ids = (DOMAIN, str(station_id)) device_registry.async_update_device(device_entry.id, new_identifiers={new_ids}) try: scan_interval = timedelta(seconds=entry.options[CONF_SCAN_INTERVAL]) except KeyError: scan_interval = timedelta(seconds=DEFAULT_SCAN_INTERVAL) _LOGGER.debug("Using station_id: %s", station_id) websession = async_get_clientsession(hass) coordinator = GiosDataUpdateCoordinator(hass, websession, station_id, scan_interval) await coordinator.async_config_entry_first_refresh() undo_listener = entry.add_update_listener(update_listener) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { COORDINATOR: coordinator, UNDO_UPDATE_LISTENER: undo_listener, } for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform)) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set the config entry up.""" host = entry.data[CONF_HOST] key = entry.data[CONF_CLIENT_SECRET] wrapper = WebOsClientWrapper(host, client_key=key) await wrapper.connect() async def async_service_handler(service: ServiceCall) -> None: method = SERVICE_TO_METHOD[service.service] data = service.data.copy() data["method"] = method["method"] async_dispatcher_send(hass, DOMAIN, data) for service, method in SERVICE_TO_METHOD.items(): schema = method["schema"] hass.services.async_register(DOMAIN, service, async_service_handler, schema=schema) hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id] = wrapper await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) # set up notify platform, no entry support for notify component yet, # have to use discovery to load platform. hass.async_create_task( discovery.async_load_platform( hass, "notify", DOMAIN, { CONF_NAME: entry.title, ATTR_CONFIG_ENTRY_ID: entry.entry_id, }, hass.data[DOMAIN][DATA_HASS_CONFIG], )) if not entry.update_listeners: entry.async_on_unload(entry.add_update_listener(async_update_options)) async def async_on_stop(_event: Event) -> None: """Unregister callbacks and disconnect.""" await wrapper.shutdown() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_on_stop)) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Ezviz from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_FFMPEG_ARGUMENTS: DEFAULT_FFMPEG_ARGUMENTS, CONF_TIMEOUT: DEFAULT_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) if entry.data.get(CONF_TYPE) == ATTR_TYPE_CAMERA: if hass.data.get(DOMAIN): # Should only execute on addition of new camera entry. # Fetch Entry id of main account and reload it. for item in hass.config_entries.async_entries(): if item.data.get(CONF_TYPE) == ATTR_TYPE_CLOUD: _LOGGER.info("Reload Ezviz integration with new camera rtsp entry") await hass.config_entries.async_reload(item.entry_id) return True try: ezviz_client = await hass.async_add_executor_job( _get_ezviz_client_instance, entry ) except (InvalidURL, HTTPError, PyEzvizError) as error: _LOGGER.error("Unable to connect to Ezviz service: %s", str(error)) raise ConfigEntryNotReady from error coordinator = EzvizDataUpdateCoordinator( hass, api=ezviz_client, api_timeout=entry.options[CONF_TIMEOUT] ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady undo_listener = entry.add_update_listener(_async_update_listener) hass.data[DOMAIN][entry.entry_id] = { DATA_COORDINATOR: coordinator, DATA_UNDO_UPDATE_LISTENER: undo_listener, } hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool: """Set up platform from a ConfigEntry.""" hass.data.setdefault(DOMAIN, {}) hass_data = dict(entry.data) # Registers update listener to update config entry when options are updated. unsub_options_update_listener = entry.add_update_listener( options_update_listener) # Store a reference to the unsubscribe function to cleanup if an entry is unloaded. hass_data["unsub_options_update_listener"] = unsub_options_update_listener hass.data[DOMAIN][entry.entry_id] = hass_data # Forward the setup to the sensor platform. hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "light")) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Yale from a config entry.""" coordinator = YaleDataUpdateCoordinator(hass, entry) if not await hass.async_add_executor_job(coordinator.get_updates): raise ConfigEntryAuthFailed await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { COORDINATOR: coordinator, } hass.config_entries.async_setup_platforms(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(update_listener)) return True
def _setup_reload(hass: HomeAssistantType, entry: ConfigEntry, context: IntegrationContext): """Set up listeners of reload triggers.""" # Listen for config entry changes and reload when changed. context.unsubscribe_list.append( entry.add_update_listener(_async_config_entry_changed)) @callback async def async_trap_list_changed(event: EventType): _LOGGER.info("Trap list hast changed (%s). Reload integration.", event.data) await hass.config_entries.async_reload(entry.entry_id) # Listen for trap list changes and reload when changed (new traps etc.) hass.bus.async_listen_once(EVENT_TRAP_LIST_CHANGED, async_trap_list_changed)
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[List[Any], bool], None], ): """Set up the component sensors from a config entry.""" if DOMAIN_DATA not in hass.data: hass.data[DOMAIN_DATA] = {} async_add_entities( [EventSensor(config_entry.unique_id, config_entry.data)], False) # add an update listener to enable edition by OptionsFlow hass.data[DOMAIN_DATA][ config_entry.entry_id] = config_entry.add_update_listener( update_listener)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a bridge from a config entry.""" LOGGER.debug("Setting up entry %s", entry.data) bridge = DynaliteBridge(hass, convert_config(entry.data)) # need to do it before the listener hass.data[DOMAIN][entry.entry_id] = bridge entry.async_on_unload(entry.add_update_listener(async_entry_changed)) if not await bridge.async_setup(): LOGGER.error("Could not set up bridge for entry %s", entry.data) hass.data[DOMAIN][entry.entry_id] = None raise ConfigEntryNotReady await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True