Normalize async_setup_entry (#51161)

This commit is contained in:
tkdrob 2021-05-27 09:56:20 -04:00 committed by GitHub
parent 701c4ee624
commit c0656878db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 259 additions and 273 deletions

View File

@ -19,13 +19,13 @@ from .weather_update_coordinator import WeatherUpdateCoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up AEMET OpenData as config entry.""" """Set up AEMET OpenData as config entry."""
name = config_entry.data[CONF_NAME] name = entry.data[CONF_NAME]
api_key = config_entry.data[CONF_API_KEY] api_key = entry.data[CONF_API_KEY]
latitude = config_entry.data[CONF_LATITUDE] latitude = entry.data[CONF_LATITUDE]
longitude = config_entry.data[CONF_LONGITUDE] longitude = entry.data[CONF_LONGITUDE]
station_updates = config_entry.options.get(CONF_STATION_UPDATES, True) station_updates = entry.options.get(CONF_STATION_UPDATES, True)
aemet = AEMET(api_key) aemet = AEMET(api_key)
weather_coordinator = WeatherUpdateCoordinator( weather_coordinator = WeatherUpdateCoordinator(
@ -35,30 +35,28 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
await weather_coordinator.async_config_entry_first_refresh() await weather_coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = { hass.data[DOMAIN][entry.entry_id] = {
ENTRY_NAME: name, ENTRY_NAME: name,
ENTRY_WEATHER_COORDINATOR: weather_coordinator, ENTRY_WEATHER_COORDINATOR: weather_coordinator,
} }
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
config_entry.async_on_unload(config_entry.add_update_listener(async_update_options)) entry.async_on_unload(entry.add_update_listener(async_update_options))
return True return True
async def async_update_options(hass: HomeAssistant, config_entry: ConfigEntry) -> None: async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update options.""" """Update options."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms( unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
config_entry, PLATFORMS
)
if unload_ok: if unload_ok:
hass.data[DOMAIN].pop(config_entry.entry_id) hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok return unload_ok

View File

@ -11,9 +11,9 @@ import async_timeout
from pyalmond import AbstractAlmondWebAuth, AlmondLocalAuth, WebAlmondAPI from pyalmond import AbstractAlmondWebAuth, AlmondLocalAuth, WebAlmondAPI
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries
from homeassistant.auth.const import GROUP_ID_ADMIN from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components import conversation from homeassistant.components import conversation
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
CONF_CLIENT_ID, CONF_CLIENT_ID,
CONF_CLIENT_SECRET, CONF_CLIENT_SECRET,
@ -94,14 +94,14 @@ async def async_setup(hass, config):
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
context={"source": config_entries.SOURCE_IMPORT}, context={"source": SOURCE_IMPORT},
data={"type": TYPE_LOCAL, "host": conf[CONF_HOST]}, data={"type": TYPE_LOCAL, "host": conf[CONF_HOST]},
) )
) )
return True return True
async def async_setup_entry(hass: HomeAssistant, entry: config_entries.ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Almond config entry.""" """Set up Almond config entry."""
websession = aiohttp_client.async_get_clientsession(hass) websession = aiohttp_client.async_get_clientsession(hass)
@ -150,7 +150,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: config_entries.ConfigEnt
async def _configure_almond_for_ha( async def _configure_almond_for_ha(
hass: HomeAssistant, entry: config_entries.ConfigEntry, api: WebAlmondAPI hass: HomeAssistant, entry: ConfigEntry, api: WebAlmondAPI
): ):
"""Configure Almond to connect to HA.""" """Configure Almond to connect to HA."""
try: try:
@ -248,7 +248,7 @@ class AlmondAgent(conversation.AbstractConversationAgent):
"""Almond conversation agent.""" """Almond conversation agent."""
def __init__( def __init__(
self, hass: HomeAssistant, api: WebAlmondAPI, entry: config_entries.ConfigEntry self, hass: HomeAssistant, api: WebAlmondAPI, entry: ConfigEntry
) -> None: ) -> None:
"""Initialize the agent.""" """Initialize the agent."""
self.hass = hass self.hass = hass

View File

@ -7,7 +7,7 @@ from arcam.fmj import ConnectionFailed
from arcam.fmj.client import Client from arcam.fmj.client import Client
import async_timeout import async_timeout
from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -51,7 +51,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType):
return True return True
async def async_setup_entry(hass: HomeAssistant, entry: config_entries.ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up config entry.""" """Set up config entry."""
entries = hass.data[DOMAIN_DATA_ENTRIES] entries = hass.data[DOMAIN_DATA_ENTRIES]
tasks = hass.data[DOMAIN_DATA_TASKS] tasks = hass.data[DOMAIN_DATA_TASKS]

View File

@ -11,10 +11,10 @@ import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .const import ( from .const import (
@ -56,7 +56,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
"""Set up buienradar radar-loop camera component.""" """Set up buienradar radar-loop camera component."""
config = entry.data config = entry.data

View File

@ -109,19 +109,19 @@ def _set_update_interval(hass: HomeAssistant, current_entry: ConfigEntry) -> tim
return interval return interval
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up ClimaCell API from a config entry.""" """Set up ClimaCell API from a config entry."""
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
params = {} params = {}
# If config entry options not set up, set them up # If config entry options not set up, set them up
if not config_entry.options: if not entry.options:
params["options"] = { params["options"] = {
CONF_TIMESTEP: DEFAULT_TIMESTEP, CONF_TIMESTEP: DEFAULT_TIMESTEP,
} }
else: else:
# Use valid timestep if it's invalid # Use valid timestep if it's invalid
timestep = config_entry.options[CONF_TIMESTEP] timestep = entry.options[CONF_TIMESTEP]
if timestep not in (1, 5, 15, 30): if timestep not in (1, 5, 15, 30):
if timestep <= 2: if timestep <= 2:
timestep = 1 timestep = 1
@ -131,38 +131,38 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
timestep = 15 timestep = 15
else: else:
timestep = 30 timestep = 30
new_options = config_entry.options.copy() new_options = entry.options.copy()
new_options[CONF_TIMESTEP] = timestep new_options[CONF_TIMESTEP] = timestep
params["options"] = new_options params["options"] = new_options
# Add API version if not found # Add API version if not found
if CONF_API_VERSION not in config_entry.data: if CONF_API_VERSION not in entry.data:
new_data = config_entry.data.copy() new_data = entry.data.copy()
new_data[CONF_API_VERSION] = 3 new_data[CONF_API_VERSION] = 3
params["data"] = new_data params["data"] = new_data
if params: if params:
hass.config_entries.async_update_entry(config_entry, **params) hass.config_entries.async_update_entry(entry, **params)
api_class = ClimaCellV3 if config_entry.data[CONF_API_VERSION] == 3 else ClimaCellV4 api_class = ClimaCellV3 if entry.data[CONF_API_VERSION] == 3 else ClimaCellV4
api = api_class( api = api_class(
config_entry.data[CONF_API_KEY], entry.data[CONF_API_KEY],
config_entry.data.get(CONF_LATITUDE, hass.config.latitude), entry.data.get(CONF_LATITUDE, hass.config.latitude),
config_entry.data.get(CONF_LONGITUDE, hass.config.longitude), entry.data.get(CONF_LONGITUDE, hass.config.longitude),
session=async_get_clientsession(hass), session=async_get_clientsession(hass),
) )
coordinator = ClimaCellDataUpdateCoordinator( coordinator = ClimaCellDataUpdateCoordinator(
hass, hass,
config_entry, entry,
api, api,
_set_update_interval(hass, config_entry), _set_update_interval(hass, entry),
) )
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][config_entry.entry_id] = coordinator hass.data[DOMAIN][entry.entry_id] = coordinator
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True

View File

@ -9,6 +9,7 @@ from typing import Any, final
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ATTR_TEMPERATURE, ATTR_TEMPERATURE,
PRECISION_TENTHS, PRECISION_TENTHS,
@ -157,7 +158,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, entry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a config entry.""" """Set up a config entry."""
return await hass.data[DOMAIN].async_setup_entry(entry) return await hass.data[DOMAIN].async_setup_entry(entry)

View File

@ -40,6 +40,6 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
return unload_ok return unload_ok
async def async_update_options(hass: HomeAssistant, config_entry: ConfigEntry): async def async_update_options(hass: HomeAssistant, entry: ConfigEntry):
"""Update options.""" """Update options."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)

View File

@ -36,26 +36,26 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
return unload_ok return unload_ok
async def async_migrate_entry(hass, config_entry: ConfigEntry): async def async_migrate_entry(hass, entry: ConfigEntry):
"""Migrate old entry.""" """Migrate old entry."""
LOGGER.debug("Migrating from version %s", config_entry.version) LOGGER.debug("Migrating from version %s", entry.version)
if config_entry.version == 1: if entry.version == 1:
# Change unique id # Change unique id
@callback @callback
def update_unique_id(entry): def update_unique_id(entry):
return {"new_unique_id": config_entry.entry_id} return {"new_unique_id": entry.entry_id}
await async_migrate_entries(hass, config_entry.entry_id, update_unique_id) await async_migrate_entries(hass, entry.entry_id, update_unique_id)
config_entry.unique_id = None entry.unique_id = None
# Get RTSP port from the camera or use the fallback one and store it in data # Get RTSP port from the camera or use the fallback one and store it in data
camera = FoscamCamera( camera = FoscamCamera(
config_entry.data[CONF_HOST], entry.data[CONF_HOST],
config_entry.data[CONF_PORT], entry.data[CONF_PORT],
config_entry.data[CONF_USERNAME], entry.data[CONF_USERNAME],
config_entry.data[CONF_PASSWORD], entry.data[CONF_PASSWORD],
verbose=False, verbose=False,
) )
@ -66,11 +66,11 @@ async def async_migrate_entry(hass, config_entry: ConfigEntry):
if ret != 0: if ret != 0:
rtsp_port = response.get("rtspPort") or response.get("mediaPort") rtsp_port = response.get("rtspPort") or response.get("mediaPort")
config_entry.data = {**config_entry.data, CONF_RTSP_PORT: rtsp_port} entry.data = {**entry.data, CONF_RTSP_PORT: rtsp_port}
# Change entry version # Change entry version
config_entry.version = 2 entry.version = 2
LOGGER.info("Migration to version %s successful", config_entry.version) LOGGER.info("Migration to version %s successful", entry.version)
return True return True

View File

@ -12,18 +12,16 @@ PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Google Maps Travel Time from a config entry.""" """Set up Google Maps Travel Time from a config entry."""
if config_entry.unique_id is not None: if entry.unique_id is not None:
hass.config_entries.async_update_entry(config_entry, unique_id=None) hass.config_entries.async_update_entry(entry, unique_id=None)
ent_reg = async_get(hass) ent_reg = async_get(hass)
for entity in async_entries_for_config_entry(ent_reg, config_entry.entry_id): for entity in async_entries_for_config_entry(ent_reg, entry.entry_id):
ent_reg.async_update_entity( ent_reg.async_update_entity(entity.entity_id, new_unique_id=entry.entry_id)
entity.entity_id, new_unique_id=config_entry.entry_id
)
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True

View File

@ -1,6 +1,7 @@
"""Support for the GPSLogger device tracking.""" """Support for the GPSLogger device tracking."""
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ATTR_BATTERY_LEVEL, ATTR_BATTERY_LEVEL,
ATTR_GPS_ACCURACY, ATTR_GPS_ACCURACY,
@ -22,7 +23,9 @@ from .const import (
) )
async def async_setup_entry(hass: HomeAssistant, entry, async_add_entities): async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Configure a dispatcher connection based on a config entry.""" """Configure a dispatcher connection based on a config entry."""
@callback @callback

View File

@ -66,22 +66,20 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Legrand Home+ Control from a config entry.""" """Set up Legrand Home+ Control from a config entry."""
hass_entry_data = hass.data[DOMAIN].setdefault(config_entry.entry_id, {}) hass_entry_data = hass.data[DOMAIN].setdefault(entry.entry_id, {})
# Retrieve the registered implementation # Retrieve the registered implementation
implementation = ( implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation( await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, config_entry hass, entry
) )
) )
# Using an aiohttp-based API lib, so rely on async framework # Using an aiohttp-based API lib, so rely on async framework
# Add the API object to the domain's data in HA # Add the API object to the domain's data in HA
api = hass_entry_data[API] = HomePlusControlAsyncApi( api = hass_entry_data[API] = HomePlusControlAsyncApi(hass, entry, implementation)
hass, config_entry, implementation
)
# Set of entity unique identifiers of this integration # Set of entity unique identifiers of this integration
uids = hass_entry_data[ENTITY_UIDS] = set() uids = hass_entry_data[ENTITY_UIDS] = set()
@ -143,7 +141,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"""Continue setting up the platforms.""" """Continue setting up the platforms."""
await asyncio.gather( await asyncio.gather(
*[ *[
hass.config_entries.async_forward_entry_setup(config_entry, platform) hass.config_entries.async_forward_entry_setup(entry, platform)
for platform in PLATFORMS for platform in PLATFORMS
] ]
) )

View File

@ -297,7 +297,7 @@ async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry):
await hass.config_entries.async_reload(entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
dismiss_setup_message(hass, entry.entry_id) dismiss_setup_message(hass, entry.entry_id)
homekit = hass.data[DOMAIN][entry.entry_id][HOMEKIT] homekit = hass.data[DOMAIN][entry.entry_id][HOMEKIT]

View File

@ -304,9 +304,9 @@ class HuaweiLteData:
routers: dict[str, Router] = attr.ib(init=False, factory=dict) routers: dict[str, Router] = attr.ib(init=False, factory=dict)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Huawei LTE component from config entry.""" """Set up Huawei LTE component from config entry."""
url = config_entry.data[CONF_URL] url = entry.data[CONF_URL]
# Override settings from YAML config, but only if they're changed in it # Override settings from YAML config, but only if they're changed in it
# Old values are stored as *_from_yaml in the config entry # Old values are stored as *_from_yaml in the config entry
@ -317,30 +317,29 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
for key in CONF_USERNAME, CONF_PASSWORD: for key in CONF_USERNAME, CONF_PASSWORD:
if key in yaml_config: if key in yaml_config:
value = yaml_config[key] value = yaml_config[key]
if value != config_entry.data.get(f"{key}_from_yaml"): if value != entry.data.get(f"{key}_from_yaml"):
new_data[f"{key}_from_yaml"] = value new_data[f"{key}_from_yaml"] = value
new_data[key] = value new_data[key] = value
# Options # Options
new_options = {} new_options = {}
yaml_recipient = yaml_config.get(NOTIFY_DOMAIN, {}).get(CONF_RECIPIENT) yaml_recipient = yaml_config.get(NOTIFY_DOMAIN, {}).get(CONF_RECIPIENT)
if yaml_recipient is not None and yaml_recipient != config_entry.options.get( if yaml_recipient is not None and yaml_recipient != entry.options.get(
f"{CONF_RECIPIENT}_from_yaml" f"{CONF_RECIPIENT}_from_yaml"
): ):
new_options[f"{CONF_RECIPIENT}_from_yaml"] = yaml_recipient new_options[f"{CONF_RECIPIENT}_from_yaml"] = yaml_recipient
new_options[CONF_RECIPIENT] = yaml_recipient new_options[CONF_RECIPIENT] = yaml_recipient
yaml_notify_name = yaml_config.get(NOTIFY_DOMAIN, {}).get(CONF_NAME) yaml_notify_name = yaml_config.get(NOTIFY_DOMAIN, {}).get(CONF_NAME)
if ( if yaml_notify_name is not None and yaml_notify_name != entry.options.get(
yaml_notify_name is not None f"{CONF_NAME}_from_yaml"
and yaml_notify_name != config_entry.options.get(f"{CONF_NAME}_from_yaml")
): ):
new_options[f"{CONF_NAME}_from_yaml"] = yaml_notify_name new_options[f"{CONF_NAME}_from_yaml"] = yaml_notify_name
new_options[CONF_NAME] = yaml_notify_name new_options[CONF_NAME] = yaml_notify_name
# Update entry if overrides were found # Update entry if overrides were found
if new_data or new_options: if new_data or new_options:
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
config_entry, entry,
data={**config_entry.data, **new_data}, data={**entry.data, **new_data},
options={**config_entry.options, **new_options}, options={**entry.options, **new_options},
) )
# Get MAC address for use in unique ids. Being able to use something # Get MAC address for use in unique ids. Being able to use something
@ -363,8 +362,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
Authorized one if username/pass specified (even if empty), unauthorized one otherwise. Authorized one if username/pass specified (even if empty), unauthorized one otherwise.
""" """
username = config_entry.data.get(CONF_USERNAME) username = entry.data.get(CONF_USERNAME)
password = config_entry.data.get(CONF_PASSWORD) password = entry.data.get(CONF_PASSWORD)
if username or password: if username or password:
connection: Connection = AuthorizedConnection( connection: Connection = AuthorizedConnection(
url, username=username, password=password, timeout=CONNECTION_TIMEOUT url, username=username, password=password, timeout=CONNECTION_TIMEOUT
@ -383,7 +382,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
raise ConfigEntryNotReady from ex raise ConfigEntryNotReady from ex
# Set up router and store reference to it # Set up router and store reference to it
router = Router(config_entry, connection, url, mac, signal_update) router = Router(entry, connection, url, mac, signal_update)
hass.data[DOMAIN].routers[url] = router hass.data[DOMAIN].routers[url] = router
# Do initial data update # Do initial data update
@ -409,7 +408,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
device_data["sw_version"] = sw_version device_data["sw_version"] = sw_version
device_registry = await dr.async_get_registry(hass) device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=entry.entry_id,
connections=router.device_connections, connections=router.device_connections,
identifiers=router.device_identifiers, identifiers=router.device_identifiers,
name=router.device_name, name=router.device_name,
@ -418,7 +417,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
) )
# Forward config entry setup to platforms # Forward config entry setup to platforms
hass.config_entries.async_setup_platforms(config_entry, CONFIG_ENTRY_PLATFORMS) hass.config_entries.async_setup_platforms(entry, CONFIG_ENTRY_PLATFORMS)
# Notify doesn't support config entry setup yet, load with discovery for now # Notify doesn't support config entry setup yet, load with discovery for now
await discovery.async_load_platform( await discovery.async_load_platform(
@ -427,8 +426,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
DOMAIN, DOMAIN,
{ {
CONF_URL: url, CONF_URL: url,
CONF_NAME: config_entry.options.get(CONF_NAME, DEFAULT_NOTIFY_SERVICE_NAME), CONF_NAME: entry.options.get(CONF_NAME, DEFAULT_NOTIFY_SERVICE_NAME),
CONF_RECIPIENT: config_entry.options.get(CONF_RECIPIENT), CONF_RECIPIENT: entry.options.get(CONF_RECIPIENT),
}, },
hass.data[DOMAIN].hass_config, hass.data[DOMAIN].hass_config,
) )
@ -442,12 +441,12 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
router.update() router.update()
# Set up periodic update # Set up periodic update
config_entry.async_on_unload( entry.async_on_unload(
async_track_time_interval(hass, _update_router, SCAN_INTERVAL) async_track_time_interval(hass, _update_router, SCAN_INTERVAL)
) )
# Clean up at end # Clean up at end
config_entry.async_on_unload( entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, router.cleanup) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, router.cleanup)
) )

View File

@ -136,11 +136,11 @@ def listen_for_instance_updates(
) )
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Hyperion from a config entry.""" """Set up Hyperion from a config entry."""
host = config_entry.data[CONF_HOST] host = entry.data[CONF_HOST]
port = config_entry.data[CONF_PORT] port = entry.data[CONF_PORT]
token = config_entry.data.get(CONF_TOKEN) token = entry.data.get(CONF_TOKEN)
hyperion_client = await async_create_connect_hyperion_client( hyperion_client = await async_create_connect_hyperion_client(
host, port, token=token, raw_connection=True host, port, token=token, raw_connection=True
@ -190,7 +190,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
# We need 1 root client (to manage instances being removed/added) and then 1 client # We need 1 root client (to manage instances being removed/added) and then 1 client
# per Hyperion server instance which is shared for all entities associated with # per Hyperion server instance which is shared for all entities associated with
# that instance. # that instance.
hass.data[DOMAIN][config_entry.entry_id] = { hass.data[DOMAIN][entry.entry_id] = {
CONF_ROOT_CLIENT: hyperion_client, CONF_ROOT_CLIENT: hyperion_client,
CONF_INSTANCE_CLIENTS: {}, CONF_INSTANCE_CLIENTS: {},
CONF_ON_UNLOAD: [], CONF_ON_UNLOAD: [],
@ -207,10 +207,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
device_registry = dr.async_get(hass) device_registry = dr.async_get(hass)
running_instances: set[int] = set() running_instances: set[int] = set()
stopped_instances: set[int] = set() stopped_instances: set[int] = set()
existing_instances = hass.data[DOMAIN][config_entry.entry_id][ existing_instances = hass.data[DOMAIN][entry.entry_id][CONF_INSTANCE_CLIENTS]
CONF_INSTANCE_CLIENTS server_id = cast(str, entry.unique_id)
]
server_id = cast(str, config_entry.unique_id)
# In practice, an instance can be in 3 states as seen by this function: # In practice, an instance can be in 3 states as seen by this function:
# #
@ -239,7 +237,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
instance_name = instance.get(hyperion_const.KEY_FRIENDLY_NAME, DEFAULT_NAME) instance_name = instance.get(hyperion_const.KEY_FRIENDLY_NAME, DEFAULT_NAME)
async_dispatcher_send( async_dispatcher_send(
hass, hass,
SIGNAL_INSTANCE_ADD.format(config_entry.entry_id), SIGNAL_INSTANCE_ADD.format(entry.entry_id),
instance_num, instance_num,
instance_name, instance_name,
) )
@ -248,7 +246,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
for instance_num in set(existing_instances) - running_instances: for instance_num in set(existing_instances) - running_instances:
del existing_instances[instance_num] del existing_instances[instance_num]
async_dispatcher_send( async_dispatcher_send(
hass, SIGNAL_INSTANCE_REMOVE.format(config_entry.entry_id), instance_num hass, SIGNAL_INSTANCE_REMOVE.format(entry.entry_id), instance_num
) )
# Ensure every device associated with this config entry is still in the list of # Ensure every device associated with this config entry is still in the list of
@ -258,7 +256,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
for instance_num in running_instances | stopped_instances for instance_num in running_instances | stopped_instances
} }
for device_entry in dr.async_entries_for_config_entry( for device_entry in dr.async_entries_for_config_entry(
device_registry, config_entry.entry_id device_registry, entry.entry_id
): ):
for (kind, key) in device_entry.identifiers: for (kind, key) in device_entry.identifiers:
if kind == DOMAIN and key in known_devices: if kind == DOMAIN and key in known_devices:
@ -275,15 +273,15 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
async def setup_then_listen() -> None: async def setup_then_listen() -> None:
await asyncio.gather( await asyncio.gather(
*[ *[
hass.config_entries.async_forward_entry_setup(config_entry, platform) hass.config_entries.async_forward_entry_setup(entry, platform)
for platform in PLATFORMS for platform in PLATFORMS
] ]
) )
assert hyperion_client assert hyperion_client
if hyperion_client.instances is not None: if hyperion_client.instances is not None:
await async_instances_to_clients_raw(hyperion_client.instances) await async_instances_to_clients_raw(hyperion_client.instances)
hass.data[DOMAIN][config_entry.entry_id][CONF_ON_UNLOAD].append( hass.data[DOMAIN][entry.entry_id][CONF_ON_UNLOAD].append(
config_entry.add_update_listener(_async_entry_updated) entry.add_update_listener(_async_entry_updated)
) )
hass.async_create_task(setup_then_listen()) hass.async_create_task(setup_then_listen())

View File

@ -29,22 +29,22 @@ PLATFORMS = [BINARY_SENSOR_DOMAIN, DEVICE_TRACKER_DOMAIN]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the component.""" """Set up the component."""
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
async_add_defaults(hass, config_entry) async_add_defaults(hass, entry)
router = KeeneticRouter(hass, config_entry) router = KeeneticRouter(hass, entry)
await router.async_setup() await router.async_setup()
undo_listener = config_entry.add_update_listener(update_listener) undo_listener = entry.add_update_listener(update_listener)
hass.data[DOMAIN][config_entry.entry_id] = { hass.data[DOMAIN][entry.entry_id] = {
ROUTER: router, ROUTER: router,
UNDO_UPDATE_LISTENER: undo_listener, UNDO_UPDATE_LISTENER: undo_listener,
} }
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True
@ -97,14 +97,14 @@ async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->
return unload_ok return unload_ok
async def update_listener(hass, config_entry): async def update_listener(hass, entry):
"""Handle options update.""" """Handle options update."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
def async_add_defaults(hass: HomeAssistant, config_entry: ConfigEntry): def async_add_defaults(hass: HomeAssistant, entry: ConfigEntry):
"""Populate default options.""" """Populate default options."""
host: str = config_entry.data[CONF_HOST] host: str = entry.data[CONF_HOST]
imported_options: dict = hass.data[DOMAIN].get(f"imported_options_{host}", {}) imported_options: dict = hass.data[DOMAIN].get(f"imported_options_{host}", {})
options = { options = {
CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL, CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL,
@ -114,8 +114,8 @@ def async_add_defaults(hass: HomeAssistant, config_entry: ConfigEntry):
CONF_INCLUDE_ARP: True, CONF_INCLUDE_ARP: True,
CONF_INCLUDE_ASSOCIATED: True, CONF_INCLUDE_ASSOCIATED: True,
**imported_options, **imported_options,
**config_entry.options, **entry.options,
} }
if options.keys() - config_entry.options.keys(): if options.keys() - entry.options.keys():
hass.config_entries.async_update_entry(config_entry, options=options) hass.config_entries.async_update_entry(entry, options=options)

View File

@ -30,15 +30,13 @@ PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up kraken from a config entry.""" """Set up kraken from a config entry."""
kraken_data = KrakenData(hass, config_entry) kraken_data = KrakenData(hass, entry)
await kraken_data.async_setup() await kraken_data.async_setup()
hass.data[DOMAIN] = kraken_data hass.data[DOMAIN] = kraken_data
config_entry.async_on_unload( entry.async_on_unload(entry.add_update_listener(async_options_updated))
config_entry.add_update_listener(async_options_updated) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
)
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS)
return True return True

View File

@ -5,7 +5,7 @@ from meteoclimatic import MeteoclimaticClient
from meteoclimatic.exceptions import MeteoclimaticError from meteoclimatic.exceptions import MeteoclimaticError
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_STATION_CODE, DOMAIN, PLATFORMS, SCAN_INTERVAL from .const import CONF_STATION_CODE, DOMAIN, PLATFORMS, SCAN_INTERVAL
@ -13,7 +13,7 @@ from .const import CONF_STATION_CODE, DOMAIN, PLATFORMS, SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a Meteoclimatic entry.""" """Set up a Meteoclimatic entry."""
station_code = entry.data[CONF_STATION_CODE] station_code = entry.data[CONF_STATION_CODE]
meteoclimatic_client = MeteoclimaticClient() meteoclimatic_client = MeteoclimaticClient()
@ -46,7 +46,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool
return True return True
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
return unload_ok return unload_ok

View File

@ -4,8 +4,8 @@ from meteoclimatic import Condition
from homeassistant.components.weather import WeatherEntity from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TEMP_CELSIUS from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
DataUpdateCoordinator, DataUpdateCoordinator,
@ -25,7 +25,7 @@ def format_condition(condition):
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
"""Set up the Meteoclimatic weather platform.""" """Set up the Meteoclimatic weather platform."""
coordinator = hass.data[DOMAIN][entry.entry_id] coordinator = hass.data[DOMAIN][entry.entry_id]

View File

@ -25,24 +25,24 @@ PLATFORMS = ["binary_sensor", "sensor"]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Minecraft Server from a config entry.""" """Set up Minecraft Server from a config entry."""
domain_data = hass.data.setdefault(DOMAIN, {}) domain_data = hass.data.setdefault(DOMAIN, {})
# Create and store server instance. # Create and store server instance.
unique_id = config_entry.unique_id unique_id = entry.unique_id
_LOGGER.debug( _LOGGER.debug(
"Creating server instance for '%s' (%s)", "Creating server instance for '%s' (%s)",
config_entry.data[CONF_NAME], entry.data[CONF_NAME],
config_entry.data[CONF_HOST], entry.data[CONF_HOST],
) )
server = MinecraftServer(hass, unique_id, config_entry.data) server = MinecraftServer(hass, unique_id, entry.data)
domain_data[unique_id] = server domain_data[unique_id] = server
await server.async_update() await server.async_update()
server.start_periodic_update() server.start_periodic_update()
# Set up platforms. # Set up platforms.
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True

View File

@ -13,17 +13,17 @@ from .onewirehub import CannotConnect, OneWireHub
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a 1-Wire proxy for a config entry.""" """Set up a 1-Wire proxy for a config entry."""
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
onewirehub = OneWireHub(hass) onewirehub = OneWireHub(hass)
try: try:
await onewirehub.initialize(config_entry) await onewirehub.initialize(entry)
except CannotConnect as exc: except CannotConnect as exc:
raise ConfigEntryNotReady() from exc raise ConfigEntryNotReady() from exc
hass.data[DOMAIN][config_entry.entry_id] = onewirehub hass.data[DOMAIN][entry.entry_id] = onewirehub
async def cleanup_registry() -> None: async def cleanup_registry() -> None:
# Get registries # Get registries
@ -35,7 +35,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
registry_devices = [ registry_devices = [
entry.id entry.id
for entry in dr.async_entries_for_config_entry( for entry in dr.async_entries_for_config_entry(
device_registry, config_entry.entry_id device_registry, entry.entry_id
) )
] ]
# Remove devices that don't belong to any entity # Remove devices that don't belong to any entity
@ -54,7 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
# wait until all required platforms are ready # wait until all required platforms are ready
await asyncio.gather( await asyncio.gather(
*[ *[
hass.config_entries.async_forward_entry_setup(config_entry, platform) hass.config_entries.async_forward_entry_setup(entry, platform)
for platform in PLATFORMS for platform in PLATFORMS
] ]
) )

View File

@ -30,14 +30,14 @@ from .weather_update_coordinator import WeatherUpdateCoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up OpenWeatherMap as config entry.""" """Set up OpenWeatherMap as config entry."""
name = config_entry.data[CONF_NAME] name = entry.data[CONF_NAME]
api_key = config_entry.data[CONF_API_KEY] api_key = entry.data[CONF_API_KEY]
latitude = config_entry.data.get(CONF_LATITUDE, hass.config.latitude) latitude = entry.data.get(CONF_LATITUDE, hass.config.latitude)
longitude = config_entry.data.get(CONF_LONGITUDE, hass.config.longitude) longitude = entry.data.get(CONF_LONGITUDE, hass.config.longitude)
forecast_mode = _get_config_value(config_entry, CONF_MODE) forecast_mode = _get_config_value(entry, CONF_MODE)
language = _get_config_value(config_entry, CONF_LANGUAGE) language = _get_config_value(entry, CONF_LANGUAGE)
config_dict = _get_owm_config(language) config_dict = _get_owm_config(language)
@ -49,15 +49,15 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
await weather_coordinator.async_config_entry_first_refresh() await weather_coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = { hass.data[DOMAIN][entry.entry_id] = {
ENTRY_NAME: name, ENTRY_NAME: name,
ENTRY_WEATHER_COORDINATOR: weather_coordinator, ENTRY_WEATHER_COORDINATOR: weather_coordinator,
} }
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
update_listener = config_entry.add_update_listener(async_update_options) update_listener = entry.add_update_listener(async_update_options)
hass.data[DOMAIN][config_entry.entry_id][UPDATE_LISTENER] = update_listener hass.data[DOMAIN][entry.entry_id][UPDATE_LISTENER] = update_listener
return True return True
@ -84,20 +84,18 @@ async def async_migrate_entry(hass, entry):
return True return True
async def async_update_options(hass: HomeAssistant, config_entry: ConfigEntry): async def async_update_options(hass: HomeAssistant, entry: ConfigEntry):
"""Update options.""" """Update options."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms( unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
config_entry, PLATFORMS
)
if unload_ok: if unload_ok:
update_listener = hass.data[DOMAIN][config_entry.entry_id][UPDATE_LISTENER] update_listener = hass.data[DOMAIN][entry.entry_id][UPDATE_LISTENER]
update_listener() update_listener()
hass.data[DOMAIN].pop(config_entry.entry_id) hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok return unload_ok

View File

@ -1,7 +1,7 @@
"""The pvpc_hourly_pricing integration to collect Spain official electric prices.""" """The pvpc_hourly_pricing integration to collect Spain official electric prices."""
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_NAME from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -36,19 +36,19 @@ async def async_setup(hass: HomeAssistant, config: dict):
for conf in config.get(DOMAIN, []): for conf in config.get(DOMAIN, []):
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(
DOMAIN, data=conf, context={"source": config_entries.SOURCE_IMPORT} DOMAIN, data=conf, context={"source": SOURCE_IMPORT}
) )
) )
return True return True
async def async_setup_entry(hass: HomeAssistant, entry: config_entries.ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up pvpc hourly pricing from a config entry.""" """Set up pvpc hourly pricing from a config entry."""
hass.config_entries.async_setup_platforms(entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True
async def async_unload_entry(hass: HomeAssistant, entry: config_entries.ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@ -35,9 +35,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
return True return True
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
# unload srp client # unload srp client
hass.data[SRP_ENERGY_DOMAIN] = None hass.data[SRP_ENERGY_DOMAIN] = None
# Remove config entry # Remove config entry
return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@ -19,9 +19,9 @@ from .const import (
) )
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the StarLine device from a config entry.""" """Set up the StarLine device from a config entry."""
account = StarlineAccount(hass, config_entry) account = StarlineAccount(hass, entry)
await account.update() await account.update()
await account.update_obd() await account.update_obd()
if not account.api.available: if not account.api.available:
@ -29,27 +29,27 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
if DOMAIN not in hass.data: if DOMAIN not in hass.data:
hass.data[DOMAIN] = {} hass.data[DOMAIN] = {}
hass.data[DOMAIN][config_entry.entry_id] = account hass.data[DOMAIN][entry.entry_id] = account
device_registry = await hass.helpers.device_registry.async_get_registry() device_registry = await hass.helpers.device_registry.async_get_registry()
for device in account.api.devices.values(): for device in account.api.devices.values():
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, **account.device_info(device) config_entry_id=entry.entry_id, **account.device_info(device)
) )
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
async def async_set_scan_interval(call): async def async_set_scan_interval(call):
"""Set scan interval.""" """Set scan interval."""
options = dict(config_entry.options) options = dict(entry.options)
options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL] options[CONF_SCAN_INTERVAL] = call.data[CONF_SCAN_INTERVAL]
hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.config_entries.async_update_entry(entry=entry, options=options)
async def async_set_scan_obd_interval(call): async def async_set_scan_obd_interval(call):
"""Set OBD info scan interval.""" """Set OBD info scan interval."""
options = dict(config_entry.options) options = dict(entry.options)
options[CONF_SCAN_OBD_INTERVAL] = call.data[CONF_SCAN_INTERVAL] options[CONF_SCAN_OBD_INTERVAL] = call.data[CONF_SCAN_INTERVAL]
hass.config_entries.async_update_entry(entry=config_entry, options=options) hass.config_entries.async_update_entry(entry=entry, options=options)
async def async_update(call=None): async def async_update(call=None):
"""Update all data.""" """Update all data."""
@ -82,10 +82,8 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
), ),
) )
config_entry.async_on_unload( entry.async_on_unload(entry.add_update_listener(async_options_updated))
config_entry.add_update_listener(async_options_updated) await async_options_updated(hass, entry)
)
await async_options_updated(hass, config_entry)
return True return True

View File

@ -72,7 +72,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up TPLink from a config entry.""" """Set up TPLink from a config entry."""
config_data = hass.data[DOMAIN].get(ATTR_CONFIG) config_data = hass.data[DOMAIN].get(ATTR_CONFIG)
@ -101,7 +101,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"Got %s lights: %s", len(lights), ", ".join(d.host for d in lights) "Got %s lights: %s", len(lights), ", ".join(d.host for d in lights)
) )
hass.async_create_task(forward_setup(config_entry, "light")) hass.async_create_task(forward_setup(entry, "light"))
if switches: if switches:
_LOGGER.debug( _LOGGER.debug(
@ -110,7 +110,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
", ".join(d.host for d in switches), ", ".join(d.host for d in switches),
) )
hass.async_create_task(forward_setup(config_entry, "switch")) hass.async_create_task(forward_setup(entry, "switch"))
return True return True

View File

@ -11,6 +11,7 @@ from homeassistant.components.device_tracker import (
SOURCE_TYPE_GPS, SOURCE_TYPE_GPS,
) )
from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
CONF_EVENT, CONF_EVENT,
CONF_HOST, CONF_HOST,
@ -116,7 +117,9 @@ PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
) )
async def async_setup_entry(hass: HomeAssistant, entry, async_add_entities): async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Configure a dispatcher connection based on a config entry.""" """Configure a dispatcher connection based on a config entry."""
@callback @callback

View File

@ -11,29 +11,29 @@ from .const import CONF_ENTRY_HOST, CONF_ENTRY_ID, DOMAIN
PLATFORMS = ["light"] PLATFORMS = ["light"]
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up entries from config flow.""" """Set up entries from config flow."""
# We setup the client here so if at some point we add any other entity for this device, # We setup the client here so if at some point we add any other entity for this device,
# we will be able to properly share the connection. # we will be able to properly share the connection.
uuid = config_entry.data[CONF_ENTRY_ID] uuid = entry.data[CONF_ENTRY_ID]
host = config_entry.data[CONF_ENTRY_HOST] host = entry.data[CONF_ENTRY_HOST]
hass.data.setdefault(DOMAIN, {})[uuid] = twinkly_client.TwinklyClient( hass.data.setdefault(DOMAIN, {})[uuid] = twinkly_client.TwinklyClient(
host, async_get_clientsession(hass) host, async_get_clientsession(hass)
) )
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Remove a twinkly entry.""" """Remove a twinkly entry."""
# For now light entries don't have unload method, so we don't have to async_forward_entry_unload # For now light entries don't have unload method, so we don't have to async_forward_entry_unload
# However we still have to cleanup the shared client! # However we still have to cleanup the shared client!
uuid = config_entry.data[CONF_ENTRY_ID] uuid = entry.data[CONF_ENTRY_ID]
hass.data[DOMAIN].pop(uuid) hass.data[DOMAIN].pop(uuid)
return True return True

View File

@ -162,11 +162,11 @@ async def _async_signal_options_update(
) )
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the UpCloud config entry.""" """Set up the UpCloud config entry."""
manager = upcloud_api.CloudManager( manager = upcloud_api.CloudManager(
config_entry.data[CONF_USERNAME], config_entry.data[CONF_PASSWORD] entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]
) )
try: try:
@ -182,20 +182,19 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
# Handle pre config entry (0.117) scan interval migration to options # Handle pre config entry (0.117) scan interval migration to options
migrated_scan_interval = upcloud_data.scan_interval_migrations.pop( migrated_scan_interval = upcloud_data.scan_interval_migrations.pop(
config_entry.data[CONF_USERNAME], None entry.data[CONF_USERNAME], None
) )
if migrated_scan_interval and ( if migrated_scan_interval and (
not config_entry.options.get(CONF_SCAN_INTERVAL) not entry.options.get(CONF_SCAN_INTERVAL)
or config_entry.options[CONF_SCAN_INTERVAL] or entry.options[CONF_SCAN_INTERVAL] == DEFAULT_SCAN_INTERVAL.total_seconds()
== DEFAULT_SCAN_INTERVAL.total_seconds()
): ):
update_interval = migrated_scan_interval update_interval = migrated_scan_interval
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
config_entry, entry,
options={CONF_SCAN_INTERVAL: update_interval.total_seconds()}, options={CONF_SCAN_INTERVAL: update_interval.total_seconds()},
) )
elif config_entry.options.get(CONF_SCAN_INTERVAL): elif entry.options.get(CONF_SCAN_INTERVAL):
update_interval = timedelta(seconds=config_entry.options[CONF_SCAN_INTERVAL]) update_interval = timedelta(seconds=entry.options[CONF_SCAN_INTERVAL])
else: else:
update_interval = DEFAULT_SCAN_INTERVAL update_interval = DEFAULT_SCAN_INTERVAL
@ -203,28 +202,26 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
hass, hass,
update_interval=update_interval, update_interval=update_interval,
cloud_manager=manager, cloud_manager=manager,
username=config_entry.data[CONF_USERNAME], username=entry.data[CONF_USERNAME],
) )
# Call the UpCloud API to refresh data # Call the UpCloud API to refresh data
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
# Listen to config entry updates # Listen to config entry updates
config_entry.async_on_unload( entry.async_on_unload(entry.add_update_listener(_async_signal_options_update))
config_entry.add_update_listener(_async_signal_options_update) entry.async_on_unload(
)
config_entry.async_on_unload(
async_dispatcher_connect( async_dispatcher_connect(
hass, hass,
_config_entry_update_signal_name(config_entry), _config_entry_update_signal_name(entry),
coordinator.async_update_config, coordinator.async_update_config,
) )
) )
upcloud_data.coordinators[config_entry.data[CONF_USERNAME]] = coordinator upcloud_data.coordinators[entry.data[CONF_USERNAME]] = coordinator
# Forward entry setup # Forward entry setup
hass.config_entries.async_setup_platforms(config_entry, CONFIG_ENTRY_DOMAINS) hass.config_entries.async_setup_platforms(entry, CONFIG_ENTRY_DOMAINS)
return True return True

View File

@ -92,13 +92,13 @@ async def async_setup(hass: HomeAssistant, config: ConfigType):
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up UPnP/IGD device from a config entry.""" """Set up UPnP/IGD device from a config entry."""
_LOGGER.debug("Setting up config entry: %s", config_entry.unique_id) _LOGGER.debug("Setting up config entry: %s", entry.unique_id)
# Discover and construct. # Discover and construct.
udn = config_entry.data[CONFIG_ENTRY_UDN] udn = entry.data[CONFIG_ENTRY_UDN]
st = config_entry.data[CONFIG_ENTRY_ST] # pylint: disable=invalid-name st = entry.data[CONFIG_ENTRY_ST] # pylint: disable=invalid-name
try: try:
device = await async_construct_device(hass, udn, st) device = await async_construct_device(hass, udn, st)
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
@ -112,31 +112,31 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
hass.data[DOMAIN][DOMAIN_DEVICES][device.udn] = device hass.data[DOMAIN][DOMAIN_DEVICES][device.udn] = device
# Ensure entry has a unique_id. # Ensure entry has a unique_id.
if not config_entry.unique_id: if not entry.unique_id:
_LOGGER.debug( _LOGGER.debug(
"Setting unique_id: %s, for config_entry: %s", "Setting unique_id: %s, for config_entry: %s",
device.unique_id, device.unique_id,
config_entry, entry,
) )
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
entry=config_entry, entry=entry,
unique_id=device.unique_id, unique_id=device.unique_id,
) )
# Ensure entry has a hostname, for older entries. # Ensure entry has a hostname, for older entries.
if ( if (
CONFIG_ENTRY_HOSTNAME not in config_entry.data CONFIG_ENTRY_HOSTNAME not in entry.data
or config_entry.data[CONFIG_ENTRY_HOSTNAME] != device.hostname or entry.data[CONFIG_ENTRY_HOSTNAME] != device.hostname
): ):
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
entry=config_entry, entry=entry,
data={CONFIG_ENTRY_HOSTNAME: device.hostname, **config_entry.data}, data={CONFIG_ENTRY_HOSTNAME: device.hostname, **entry.data},
) )
# Create device registry entry. # Create device registry entry.
device_registry = await dr.async_get_registry(hass) device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id, config_entry_id=entry.entry_id,
connections={(dr.CONNECTION_UPNP, device.udn)}, connections={(dr.CONNECTION_UPNP, device.udn)},
identifiers={(DOMAIN, device.udn)}, identifiers={(DOMAIN, device.udn)},
name=device.name, name=device.name,
@ -146,7 +146,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
# Create sensors. # Create sensors.
_LOGGER.debug("Enabling sensors") _LOGGER.debug("Enabling sensors")
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
# Start device updater. # Start device updater.
await device.async_start() await device.async_start()

View File

@ -83,30 +83,30 @@ async def async_setup(hass: HomeAssistant, base_config: dict) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Do setup of vera.""" """Do setup of vera."""
# Use options entered during initial config flow or provided from configuration.yml # Use options entered during initial config flow or provided from configuration.yml
if config_entry.data.get(CONF_LIGHTS) or config_entry.data.get(CONF_EXCLUDE): if entry.data.get(CONF_LIGHTS) or entry.data.get(CONF_EXCLUDE):
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
entry=config_entry, entry=entry,
data=config_entry.data, data=entry.data,
options=new_options( options=new_options(
config_entry.data.get(CONF_LIGHTS, []), entry.data.get(CONF_LIGHTS, []),
config_entry.data.get(CONF_EXCLUDE, []), entry.data.get(CONF_EXCLUDE, []),
), ),
) )
saved_light_ids = config_entry.options.get(CONF_LIGHTS, []) saved_light_ids = entry.options.get(CONF_LIGHTS, [])
saved_exclude_ids = config_entry.options.get(CONF_EXCLUDE, []) saved_exclude_ids = entry.options.get(CONF_EXCLUDE, [])
base_url = config_entry.data[CONF_CONTROLLER] base_url = entry.data[CONF_CONTROLLER]
light_ids = fix_device_id_list(saved_light_ids) light_ids = fix_device_id_list(saved_light_ids)
exclude_ids = fix_device_id_list(saved_exclude_ids) exclude_ids = fix_device_id_list(saved_exclude_ids)
# If the ids were corrected. Update the config entry. # If the ids were corrected. Update the config entry.
if light_ids != saved_light_ids or exclude_ids != saved_exclude_ids: if light_ids != saved_light_ids or exclude_ids != saved_exclude_ids:
hass.config_entries.async_update_entry( hass.config_entries.async_update_entry(
entry=config_entry, options=new_options(light_ids, exclude_ids) entry=entry, options=new_options(light_ids, exclude_ids)
) )
# Initialize the Vera controller. # Initialize the Vera controller.
@ -139,15 +139,15 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
controller=controller, controller=controller,
devices=vera_devices, devices=vera_devices,
scenes=vera_scenes, scenes=vera_scenes,
config_entry=config_entry, config_entry=entry,
) )
set_controller_data(hass, config_entry, controller_data) set_controller_data(hass, entry, controller_data)
# Forward the config data to the necessary platforms. # Forward the config data to the necessary platforms.
for platform in get_configured_platforms(controller_data): for platform in get_configured_platforms(controller_data):
hass.async_create_task( hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, platform) hass.config_entries.async_forward_entry_setup(entry, platform)
) )
def stop_subscription(event): def stop_subscription(event):
@ -155,13 +155,11 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
controller.stop() controller.stop()
await hass.async_add_executor_job(controller.start) await hass.async_add_executor_job(controller.start)
config_entry.async_on_unload( entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_subscription) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_subscription)
) )
config_entry.async_on_unload( entry.async_on_unload(entry.add_update_listener(_async_update_listener))
config_entry.add_update_listener(_async_update_listener)
)
return True return True

View File

@ -56,19 +56,19 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Load the saved entities.""" """Load the saved entities."""
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
if ( if (
CONF_APPS not in hass.data[DOMAIN] CONF_APPS not in hass.data[DOMAIN]
and config_entry.data[CONF_DEVICE_CLASS] == DEVICE_CLASS_TV and entry.data[CONF_DEVICE_CLASS] == DEVICE_CLASS_TV
): ):
coordinator = VizioAppsDataUpdateCoordinator(hass) coordinator = VizioAppsDataUpdateCoordinator(hass)
await coordinator.async_refresh() await coordinator.async_refresh()
hass.data[DOMAIN][CONF_APPS] = coordinator hass.data[DOMAIN][CONF_APPS] = coordinator
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True

View File

@ -12,18 +12,16 @@ PLATFORMS = ["sensor"]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Load the saved entities.""" """Load the saved entities."""
if config_entry.unique_id is not None: if entry.unique_id is not None:
hass.config_entries.async_update_entry(config_entry, unique_id=None) hass.config_entries.async_update_entry(entry, unique_id=None)
ent_reg = async_get(hass) ent_reg = async_get(hass)
for entity in async_entries_for_config_entry(ent_reg, config_entry.entry_id): for entity in async_entries_for_config_entry(ent_reg, entry.entry_id):
ent_reg.async_update_entity( ent_reg.async_update_entity(entity.entity_id, new_unique_id=entry.entry_id)
entity.entity_id, new_unique_id=config_entry.entry_id
)
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True

View File

@ -32,17 +32,17 @@ _LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor", "binary_sensor"] PLATFORMS = ["sensor", "binary_sensor"]
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up wiffi from a config entry, config_entry contains data from config entry database.""" """Set up wiffi from a config entry, config_entry contains data from config entry database."""
if not config_entry.update_listeners: if not entry.update_listeners:
config_entry.add_update_listener(async_update_options) entry.add_update_listener(async_update_options)
# create api object # create api object
api = WiffiIntegrationApi(hass) api = WiffiIntegrationApi(hass)
api.async_setup(config_entry) api.async_setup(entry)
# store api object # store api object
hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = api hass.data.setdefault(DOMAIN, {})[entry.entry_id] = api
try: try:
await api.server.start_server() await api.server.start_server()
@ -50,29 +50,27 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
if exc.errno != errno.EADDRINUSE: if exc.errno != errno.EADDRINUSE:
_LOGGER.error("Start_server failed, errno: %d", exc.errno) _LOGGER.error("Start_server failed, errno: %d", exc.errno)
return False return False
_LOGGER.error("Port %s already in use", config_entry.data[CONF_PORT]) _LOGGER.error("Port %s already in use", entry.data[CONF_PORT])
raise ConfigEntryNotReady from exc raise ConfigEntryNotReady from exc
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True return True
async def async_update_options(hass: HomeAssistant, config_entry: ConfigEntry): async def async_update_options(hass: HomeAssistant, entry: ConfigEntry):
"""Update options.""" """Update options."""
await hass.config_entries.async_reload(config_entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
api: WiffiIntegrationApi = hass.data[DOMAIN][config_entry.entry_id] api: WiffiIntegrationApi = hass.data[DOMAIN][entry.entry_id]
await api.server.close_server() await api.server.close_server()
unload_ok = await hass.config_entries.async_unload_platforms( unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
config_entry, PLATFORMS
)
if unload_ok: if unload_ok:
api = hass.data[DOMAIN].pop(config_entry.entry_id) api = hass.data[DOMAIN].pop(entry.entry_id)
api.shutdown() api.shutdown()
return unload_ok return unload_ok

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from functools import partial from functools import partial
from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_registry import ( from homeassistant.helpers.entity_registry import (
async_get_registry as async_get_entity_registry, async_get_registry as async_get_entity_registry,
@ -16,16 +17,18 @@ from .const import DOMAIN
PRESENCE_ATTRIBUTES = ["online", "in_party", "in_game", "in_multiplayer"] PRESENCE_ATTRIBUTES = ["online", "in_party", "in_game", "in_multiplayer"]
async def async_setup_entry(hass: HomeAssistant, config_entry, async_add_entities): async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Set up Xbox Live friends.""" """Set up Xbox Live friends."""
coordinator: XboxUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id][ coordinator: XboxUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][
"coordinator" "coordinator"
] ]
update_friends = partial(async_update_friends, coordinator, {}, async_add_entities) update_friends = partial(async_update_friends, coordinator, {}, async_add_entities)
unsub = coordinator.async_add_listener(update_friends) unsub = coordinator.async_add_listener(update_friends)
hass.data[DOMAIN][config_entry.entry_id]["binary_sensor_unsub"] = unsub hass.data[DOMAIN][entry.entry_id]["binary_sensor_unsub"] = unsub
update_friends() update_friends()

View File

@ -8,7 +8,7 @@ from voluptuous.schema_builder import raises
from homeassistant.components import wallbox from homeassistant.components import wallbox
from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -31,7 +31,7 @@ test_response_rounding_error = json.loads(
) )
async def test_wallbox_setup_entry(hass: HomeAssistantType): async def test_wallbox_setup_entry(hass: HomeAssistant):
"""Test Wallbox Setup.""" """Test Wallbox Setup."""
with requests_mock.Mocker() as m: with requests_mock.Mocker() as m:
m.get( m.get(
@ -55,7 +55,7 @@ async def test_wallbox_setup_entry(hass: HomeAssistantType):
assert await wallbox.async_setup_entry(hass, entry) is False assert await wallbox.async_setup_entry(hass, entry) is False
async def test_wallbox_unload_entry(hass: HomeAssistantType): async def test_wallbox_unload_entry(hass: HomeAssistant):
"""Test Wallbox Unload.""" """Test Wallbox Unload."""
hass.data[DOMAIN] = {"connections": {entry.entry_id: entry}} hass.data[DOMAIN] = {"connections": {entry.entry_id: entry}}
@ -67,7 +67,7 @@ async def test_wallbox_unload_entry(hass: HomeAssistantType):
await wallbox.async_unload_entry(hass, entry) await wallbox.async_unload_entry(hass, entry)
async def test_get_data(hass: HomeAssistantType): async def test_get_data(hass: HomeAssistant):
"""Test hub class, get_data.""" """Test hub class, get_data."""
station = ("12345",) station = ("12345",)
@ -90,7 +90,7 @@ async def test_get_data(hass: HomeAssistantType):
assert await hub.async_get_data() assert await hub.async_get_data()
async def test_get_data_rounding_error(hass: HomeAssistantType): async def test_get_data_rounding_error(hass: HomeAssistant):
"""Test hub class, get_data with rounding error.""" """Test hub class, get_data with rounding error."""
station = ("12345",) station = ("12345",)
@ -113,7 +113,7 @@ async def test_get_data_rounding_error(hass: HomeAssistantType):
assert await hub.async_get_data() assert await hub.async_get_data()
async def test_authentication_exception(hass: HomeAssistantType): async def test_authentication_exception(hass: HomeAssistant):
"""Test hub class, authentication raises exception.""" """Test hub class, authentication raises exception."""
station = ("12345",) station = ("12345",)
@ -142,7 +142,7 @@ async def test_authentication_exception(hass: HomeAssistantType):
assert await hub.async_get_data() assert await hub.async_get_data()
async def test_get_data_exception(hass: HomeAssistantType): async def test_get_data_exception(hass: HomeAssistant):
"""Test hub class, authentication raises exception.""" """Test hub class, authentication raises exception."""
station = ("12345",) station = ("12345",)