Deprecate calling async_listen and async_listen_once with run_immediately (#115169)

This commit is contained in:
J. Nick Koston 2024-04-08 10:07:54 -10:00 committed by GitHub
parent 5ef42078a3
commit ca5ed274cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
67 changed files with 126 additions and 243 deletions

View file

@ -342,7 +342,6 @@ async def async_enable_proactive_mode(
EVENT_STATE_CHANGED,
_async_entity_state_listener,
event_filter=_async_entity_state_filter,
run_immediately=True,
)

View file

@ -398,7 +398,6 @@ class APIDomainServicesView(HomeAssistantView):
cancel_listen = hass.bus.async_listen(
EVENT_STATE_CHANGED,
_async_save_changed_entities,
run_immediately=True,
)
try:

View file

@ -102,9 +102,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await manager.disconnect()
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, on_hass_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

View file

@ -71,7 +71,6 @@ class AugustSubscriberMixin:
self._stop_interval = self._hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP,
self._async_cancel_update_interval,
run_immediately=True,
)
@callback

View file

@ -782,7 +782,6 @@ class AutomationEntity(BaseAutomationEntity, RestoreEntity):
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED,
self._async_enable_automation,
run_immediately=True,
)
self.async_write_ha_state()

View file

@ -158,7 +158,7 @@ class AzureEventHub:
"""
logging.getLogger("azure.eventhub").setLevel(logging.WARNING)
self._listener_remover = self.hass.bus.async_listen(
MATCH_ALL, self.async_listen, run_immediately=True
MATCH_ALL, self.async_listen
)
self._schedule_next_send()

View file

@ -166,9 +166,7 @@ async def _async_start_adapter_discovery(
"""Shutdown debouncer."""
discovery_debouncer.async_shutdown()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_shutdown_debouncer, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_shutdown_debouncer)
async def _async_call_debouncer(now: datetime.datetime) -> None:
"""Call the debouncer at a later time."""
@ -201,7 +199,6 @@ async def _async_start_adapter_discovery(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
hass_callback(lambda event: cancel()),
run_immediately=True,
)

View file

@ -135,11 +135,9 @@ class HomeAssistantBluetoothManager(BluetoothManager):
self._bluetooth_adapters, self.storage
)
self._cancel_logging_listener = self.hass.bus.async_listen(
EVENT_LOGGING_CHANGED, self._async_logging_changed, run_immediately=True
)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.async_stop, run_immediately=True
EVENT_LOGGING_CHANGED, self._async_logging_changed
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.async_stop)
seen: set[str] = set()
for address, service_info in itertools.chain(
self._connectable_history.items(), self._all_history.items()

View file

@ -274,7 +274,6 @@ async def async_setup(hass: HomeAssistant) -> None:
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
_async_save_processor_data_at_stop,
run_immediately=True,
)

View file

@ -68,9 +68,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
entry.async_on_unload(_async_stop_event)
entry.async_on_unload(
hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, _async_stop_event, run_immediately=True
)
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, _async_stop_event)
)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = BondData(hub, bpup_subs)

View file

@ -412,9 +412,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
stream.add_provider("hls")
await stream.start()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, preload_stream, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, preload_stream)
@callback
def update_tokens(t: datetime) -> None:
@ -432,9 +430,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Unsubscribe track time interval timer."""
unsub()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, unsub_track_time_interval, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, unsub_track_time_interval)
component.async_register_entity_service(
SERVICE_ENABLE_MOTION, {}, "async_enable_motion_detection"

View file

@ -262,9 +262,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Shutdown event."""
await cloud.stop()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _shutdown, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown)
_remote_handle_prefs_updated(cloud)

View file

@ -197,24 +197,20 @@ class DefaultAgent(ConversationEntity):
self.hass.bus.async_listen(
ar.EVENT_AREA_REGISTRY_UPDATED,
self._async_clear_slot_list,
run_immediately=True,
),
self.hass.bus.async_listen(
fr.EVENT_FLOOR_REGISTRY_UPDATED,
self._async_clear_slot_list,
run_immediately=True,
),
self.hass.bus.async_listen(
er.EVENT_ENTITY_REGISTRY_UPDATED,
self._async_clear_slot_list,
event_filter=self._filter_entity_registry_changes,
run_immediately=True,
),
self.hass.bus.async_listen(
EVENT_STATE_CHANGED,
self._async_clear_slot_list,
event_filter=self._filter_state_changes,
run_immediately=True,
),
async_listen_entity_updates(self.hass, DOMAIN, self._async_clear_slot_list),
]

View file

@ -159,9 +159,7 @@ def _async_register_mac(
# Enable entity
ent_reg.async_update_entity(entity_id, disabled_by=None)
hass.bus.async_listen(
dr.EVENT_DEVICE_REGISTRY_UPDATED, handle_device_event, run_immediately=True
)
hass.bus.async_listen(dr.EVENT_DEVICE_REGISTRY_UPDATED, handle_device_event)
class BaseTrackerEntity(Entity):

View file

@ -281,9 +281,7 @@ async def _async_setup_integration(
"""
cancel_update_stale()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _on_hass_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_hass_stop)
@attr.s

View file

@ -162,13 +162,9 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
for watcher in watchers:
watcher.async_stop()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, _async_initialize, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, _async_initialize)
return True

View file

@ -103,7 +103,7 @@ class ESPHomeDashboardManager:
await dashboard.async_shutdown()
self._cancel_shutdown = hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, on_hass_stop, run_immediately=True
EVENT_HOMEASSISTANT_STOP, on_hass_stop
)
new_data = {"info": {"addon_slug": addon_slug, "host": host, "port": port}}

View file

@ -550,15 +550,12 @@ class ESPHomeManager:
# when the CLOSE event is fired so anything using a Bluetooth
# proxy has a chance to shut down properly.
entry_data.cleanup_callbacks.append(
hass.bus.async_listen(
EVENT_HOMEASSISTANT_CLOSE, self.on_stop, run_immediately=True
)
hass.bus.async_listen(EVENT_HOMEASSISTANT_CLOSE, self.on_stop)
)
entry_data.cleanup_callbacks.append(
hass.bus.async_listen(
EVENT_LOGGING_CHANGED,
self._async_handle_logging_changed,
run_immediately=True,
)
)

View file

@ -190,7 +190,6 @@ def async_enable_report_state(
EVENT_STATE_CHANGED,
_async_entity_state_listener,
event_filter=_async_entity_state_filter,
run_immediately=True,
)
unsub = async_call_later(

View file

@ -386,7 +386,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa:
last_timezone = new_timezone
await hassio.update_hass_timezone(new_timezone)
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, push_config, run_immediately=True)
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, push_config)
push_config_task = hass.async_create_task(push_config(None), eager_start=True)
# Start listening for problems with supervisor and making issues

View file

@ -171,9 +171,7 @@ async def async_attach_trigger(
event_filter = filter_event if event_data_items or event_data_schema else None
removes = [
hass.bus.async_listen(
event_type, handle_event, event_filter=event_filter, run_immediately=True
)
hass.bus.async_listen(event_type, handle_event, event_filter=event_filter)
for event_type in event_types
]

View file

@ -104,9 +104,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
refresh_debouncer.async_schedule_call()
await coordinator.async_refresh()
hass.bus.async_listen(
EVENT_COMPONENT_LOADED, _component_loaded, run_immediately=True
)
hass.bus.async_listen(EVENT_COMPONENT_LOADED, _component_loaded)
async_at_start(hass, initial_refresh)

View file

@ -351,9 +351,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, homekit.async_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, homekit.async_stop)
)
entry_data = HomeKitEntryData(

View file

@ -86,9 +86,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
)
)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_stop_homekit_controller, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_homekit_controller)
return True

View file

@ -286,7 +286,6 @@ class HKDevice:
self.hass.bus.async_listen(
EVENT_HOMEASSISTANT_STARTED,
self._async_populate_ble_accessory_state,
run_immediately=True,
)
)
else:

View file

@ -77,9 +77,7 @@ async def async_get_controller(hass: HomeAssistant) -> Controller:
# Right now _async_stop_homekit_controller is only called on HA exiting
# So we don't have to worry about leaking a callback here.
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_stop_homekit_controller, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_homekit_controller)
await controller.async_start()

View file

@ -166,9 +166,7 @@ async def async_setup_entry(
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_stop_auto_update, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_auto_update)
)
# Register Integration-wide Services:

View file

@ -176,8 +176,7 @@ def async_subscribe_events(
target, entities_filter, entity_ids, device_ids
)
subscriptions.extend(
hass.bus.async_listen(event_type, event_forwarder, run_immediately=True)
for event_type in event_types
hass.bus.async_listen(event_type, event_forwarder) for event_type in event_types
)
if device_ids and not entity_ids:
@ -211,7 +210,6 @@ def async_subscribe_events(
hass.bus.async_listen(
EVENT_STATE_CHANGED,
_forward_state_events_filtered,
run_immediately=True,
)
)

View file

@ -219,9 +219,7 @@ class MatrixBot:
loop_sleep_time=1_000,
) # milliseconds.
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, handle_startup, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, handle_startup)
def _load_commands(self, commands: list[ConfigCommand]) -> None:
for command in commands:

View file

@ -241,7 +241,6 @@ class PersonStorageCollection(collection.DictStorageCollection):
er.EVENT_ENTITY_REGISTRY_UPDATED,
self._entity_registry_updated,
event_filter=self._entity_registry_filter,
run_immediately=True,
)
@callback

View file

@ -333,7 +333,6 @@ class Recorder(threading.Thread):
self._event_listener = self.hass.bus.async_listen(
MATCH_ALL,
_event_listener,
run_immediately=True,
)
self._queue_watcher = async_track_time_interval(
self.hass,
@ -478,12 +477,8 @@ class Recorder(threading.Thread):
def async_register(self) -> None:
"""Post connection initialize."""
bus = self.hass.bus
bus.async_listen_once(
EVENT_HOMEASSISTANT_CLOSE, self._async_close, run_immediately=True
)
bus.async_listen_once(
EVENT_HOMEASSISTANT_FINAL_WRITE, self._async_shutdown, run_immediately=True
)
bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, self._async_close)
bus.async_listen_once(EVENT_HOMEASSISTANT_FINAL_WRITE, self._async_shutdown)
async_at_started(self.hass, self._async_hass_started)
@callback

View file

@ -47,7 +47,6 @@ def async_setup(hass: HomeAssistant) -> None:
er.EVENT_ENTITY_REGISTRY_UPDATED,
_async_entity_id_changed,
event_filter=entity_registry_changed_filter,
run_immediately=True,
)
async_at_start(hass, _setup_entity_registry_event_handler)

View file

@ -280,9 +280,7 @@ async def async_setup_internal(hass: HomeAssistant, entry: ConfigEntry) -> None:
hass.data[DOMAIN][DATA_RFXOBJECT] = rfx_object
entry.async_on_unload(
hass.bus.async_listen(
dr.EVENT_DEVICE_REGISTRY_UPDATED, _updated_device, run_immediately=True
)
hass.bus.async_listen(dr.EVENT_DEVICE_REGISTRY_UPDATED, _updated_device)
)
def _shutdown_rfxtrx(event: Event) -> None:

View file

@ -149,9 +149,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await bridge.async_close_remote()
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, stop_bridge, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_bridge)
)
await _async_update_ssdp_locations(hass, entry)

View file

@ -189,9 +189,7 @@ class ShellyBlockCoordinator(ShellyCoordinatorBase[BlockDevice]):
self.async_add_listener(self._async_device_updates_handler)
)
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop)
)
@callback
@ -420,9 +418,7 @@ class ShellyRpcCoordinator(ShellyCoordinatorBase[RpcDevice]):
self._input_event_listeners: list[Callable[[dict[str, Any]], None]] = []
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop)
)
entry.async_on_unload(entry.add_update_listener(self._async_update_listener))

View file

@ -577,7 +577,6 @@ class SonosDiscoveryManager:
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
self._async_stop_event_listener,
run_immediately=True,
)
)
_LOGGER.debug("Adding discovery job")
@ -586,7 +585,6 @@ class SonosDiscoveryManager:
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
self._stop_manual_heartbeat,
run_immediately=True,
)
)
await self.async_poll_manual_hosts()

View file

@ -392,9 +392,7 @@ class Scanner:
await self._async_start_ssdp_listeners()
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.async_stop, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.async_stop)
self._cancel_scan = async_track_time_interval(
self.hass, self.async_scan, SCAN_INTERVAL, name="SSDP scanner"
)
@ -755,13 +753,10 @@ class Server:
async def async_start(self) -> None:
"""Start the server."""
bus = self.hass.bus
bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.async_stop, run_immediately=True
)
bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.async_stop)
bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED,
self._async_start_upnp_servers,
run_immediately=True,
)
async def _async_get_instance_udn(self) -> str:

View file

@ -214,7 +214,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
# Only pass through PyAV log messages if stream logging is above DEBUG
cancel_logging_listener = hass.bus.async_listen(
EVENT_LOGGING_CHANGED, update_pyav_logging, run_immediately=True
EVENT_LOGGING_CHANGED, update_pyav_logging
)
# libav.mp4 and libav.swscaler have a few unimportant messages that are logged
# at logging.WARNING. Set those Logger levels to logging.ERROR
@ -266,7 +266,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.debug("Stopped stream workers")
cancel_logging_listener()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown, run_immediately=True)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown)
return True

View file

@ -47,7 +47,7 @@ class TriggerUpdateCoordinator(DataUpdateCoordinator):
await self._attach_triggers()
else:
self._unsub_start = self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, self._attach_triggers, run_immediately=True
EVENT_HOMEASSISTANT_START, self._attach_triggers
)
for platform_domain in PLATFORMS:

View file

@ -68,9 +68,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.error("Error storing traces", exc_info=exc)
# Store traces when stopping hass
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_store_traces_at_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_store_traces_at_stop)
return True

View file

@ -110,9 +110,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = data_service
entry.async_on_unload(entry.add_update_listener(_async_options_updated))
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, data_service.async_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, data_service.async_stop)
)
if not entry.options.get(CONF_ALLOW_EA, False) and (

View file

@ -207,12 +207,8 @@ class USBDiscovery:
async def async_setup(self) -> None:
"""Set up USB Discovery."""
await self._async_start_monitor()
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, self.async_start, run_immediately=True
)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.async_stop, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, self.async_start)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.async_stop)
async def async_start(self, event: Event) -> None:
"""Start USB Discovery and run a manual scan."""
@ -242,9 +238,7 @@ class USBDiscovery:
def _stop_observer(event: Event) -> None:
observer.stop()
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _stop_observer, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_observer)
self.observer_active = True
def _get_monitor_observer(self) -> MonitorObserver | None:

View file

@ -165,7 +165,7 @@ def handle_subscribe_events(
)
connection.subscriptions[msg["id"]] = hass.bus.async_listen(
event_type, forward_events, run_immediately=True
event_type, forward_events
)
connection.send_result(msg["id"])
@ -410,7 +410,6 @@ def handle_subscribe_entities(
connection.user,
msg["id"],
),
run_immediately=True,
)
connection.send_result(msg["id"])

View file

@ -292,7 +292,7 @@ class WebSocketHandler:
self._handle_task = asyncio.current_task()
unsub_stop = hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, self._async_handle_hass_stop, run_immediately=True
EVENT_HOMEASSISTANT_STOP, self._async_handle_hass_stop
)
writer = wsock._writer # pylint: disable=protected-access

View file

@ -96,9 +96,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
discovery_responder.stop()
registry.stop()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _on_hass_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_hass_stop)
yaml_config = config.get(DOMAIN, {})
hass.data[DOMAIN] = WemoData(

View file

@ -127,9 +127,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
entry.async_on_unload(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_shutdown, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_shutdown)
)
return True

View file

@ -169,9 +169,7 @@ async def _async_get_instance(hass: HomeAssistant, **zcargs: Any) -> HaAsyncZero
# Wait to the close event to shutdown zeroconf to give
# integrations time to send a good bye message
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_CLOSE, _async_stop_zeroconf, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, _async_stop_zeroconf)
hass.data[DOMAIN] = aio_zc
return aio_zc
@ -248,9 +246,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
async def _async_zeroconf_hass_stop(_event: Event) -> None:
await discovery.async_stop()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_zeroconf_hass_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_zeroconf_hass_stop)
async_when_setup_or_start(hass, "frontend", _async_zeroconf_hass_start)
return True

View file

@ -288,9 +288,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Handle core config updated."""
await home_zone.async_update_config(_home_conf(hass))
hass.bus.async_listen(
EVENT_CORE_CONFIG_UPDATE, core_config_updated, run_immediately=True
)
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, core_config_updated)
hass.data[DOMAIN] = storage_collection

View file

@ -636,7 +636,6 @@ class ConfigEntry:
self._async_cancel_retry_setup = hass.bus.async_listen(
EVENT_HOMEASSISTANT_STARTED,
functools.partial(self._async_setup_again, hass),
run_immediately=True,
)
await self._async_process_on_unload(hass)
@ -1646,9 +1645,7 @@ class ConfigEntries:
old_conf_migrate_func=_old_conf_migrator,
)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self._async_shutdown, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_shutdown)
if config is None:
self._entries = ConfigEntryItems(self.hass)

View file

@ -136,6 +136,7 @@ _P = ParamSpec("_P")
_Ts = TypeVarTuple("_Ts")
# Internal; not helpers.typing.UNDEFINED due to circular dependency
_UNDEF: dict[Any, Any] = {}
_SENTINEL = object()
_CallableT = TypeVar("_CallableT", bound=Callable[..., Any])
_DataT = TypeVar("_DataT", bound=Mapping[str, Any], default=Mapping[str, Any])
CALLBACK_TYPE = Callable[[], None]
@ -1355,7 +1356,6 @@ def _event_repr(
_FilterableJobType = tuple[
HassJob[[Event[_DataT]], Coroutine[Any, Any, None] | None], # job
Callable[[_DataT], bool] | None, # event_filter
bool, # run_immediately
]
@ -1399,9 +1399,7 @@ class EventBus:
self._listeners[MATCH_ALL] = self._match_all_listeners
self._hass = hass
self._async_logging_changed()
self.async_listen(
EVENT_LOGGING_CHANGED, self._async_logging_changed, run_immediately=True
)
self.async_listen(EVENT_LOGGING_CHANGED, self._async_logging_changed)
@callback
def _async_logging_changed(self, event: Event | None = None) -> None:
@ -1486,7 +1484,7 @@ class EventBus:
event: Event[_DataT] | None = None
for job, event_filter, run_immediately in listeners:
for job, event_filter in listeners:
if event_filter is not None:
try:
if event_data is None or not event_filter(event_data):
@ -1504,14 +1502,10 @@ class EventBus:
context,
)
if run_immediately:
try:
self._hass.async_run_hass_job(job, event)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error running job: %s", job)
else:
# pylint: disable-next=protected-access
self._hass._async_add_hass_job(job, event)
try:
self._hass.async_run_hass_job(job, event)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error running job: %s", job)
def listen(
self,
@ -1539,7 +1533,7 @@ class EventBus:
event_type: EventType[_DataT] | str,
listener: Callable[[Event[_DataT]], Coroutine[Any, Any, None] | None],
event_filter: Callable[[_DataT], bool] | None = None,
run_immediately: bool = True,
run_immediately: bool | object = _SENTINEL,
) -> CALLBACK_TYPE:
"""Listen for all events or events of a specific type.
@ -1556,6 +1550,16 @@ class EventBus:
This method must be run in the event loop.
"""
if run_immediately in (True, False):
# late import to avoid circular imports
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report(
"calls `async_listen` with run_immediately, which is"
" deprecated and will be removed in Assistant 2025.5",
error_if_core=False,
)
if event_filter is not None and not is_callback_check_partial(event_filter):
raise HomeAssistantError(f"Event filter {event_filter} is not a callback")
if event_type == EVENT_STATE_REPORTED:
@ -1563,16 +1567,11 @@ class EventBus:
raise HomeAssistantError(
f"Event filter is required for event {event_type}"
)
if not run_immediately:
raise HomeAssistantError(
f"Run immediately must be set to True for event {event_type}"
)
return self._async_listen_filterable_job(
event_type,
(
HassJob(listener, f"listen {event_type}"),
event_filter,
run_immediately,
),
)
@ -1614,7 +1613,7 @@ class EventBus:
self,
event_type: EventType[_DataT] | str,
listener: Callable[[Event[_DataT]], Coroutine[Any, Any, None] | None],
run_immediately: bool = True,
run_immediately: bool | object = _SENTINEL,
) -> CALLBACK_TYPE:
"""Listen once for event of a specific type.
@ -1625,6 +1624,16 @@ class EventBus:
This method must be run in the event loop.
"""
if run_immediately in (True, False):
# late import to avoid circular imports
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report(
"calls `async_listen_once` with run_immediately, which is "
"deprecated and will be removed in Assistant 2025.5",
error_if_core=False,
)
one_time_listener: _OneTimeListener[_DataT] = _OneTimeListener(
self._hass, HassJob(listener)
)
@ -1637,7 +1646,6 @@ class EventBus:
job_type=HassJobType.Callback,
),
None,
run_immediately,
),
)
one_time_listener.remove = remove

View file

@ -393,7 +393,6 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]):
event_type=fr.EVENT_FLOOR_REGISTRY_UPDATED,
event_filter=_removed_from_registry_filter,
listener=_handle_floor_registry_update,
run_immediately=True,
)
@callback
@ -410,7 +409,6 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]):
event_type=lr.EVENT_LABEL_REGISTRY_UPDATED,
event_filter=_removed_from_registry_filter,
listener=_handle_label_registry_update,
run_immediately=True,
)

View file

@ -1207,7 +1207,6 @@ def async_setup_cleanup(hass: HomeAssistant, dev_reg: DeviceRegistry) -> None:
event_type=lr.EVENT_LABEL_REGISTRY_UPDATED,
event_filter=_label_removed_from_registry_filter,
listener=_handle_label_registry_update,
run_immediately=True,
)
@callback
@ -1245,7 +1244,6 @@ def async_setup_cleanup(hass: HomeAssistant, dev_reg: DeviceRegistry) -> None:
entity_registry.EVENT_ENTITY_REGISTRY_UPDATED,
_async_entity_registry_changed,
event_filter=entity_registry_changed_filter,
run_immediately=True,
)
return
@ -1255,22 +1253,17 @@ def async_setup_cleanup(hass: HomeAssistant, dev_reg: DeviceRegistry) -> None:
entity_registry.EVENT_ENTITY_REGISTRY_UPDATED,
_async_entity_registry_changed,
event_filter=entity_registry_changed_filter,
run_immediately=True,
)
await debounced_cleanup.async_call()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, startup_clean, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, startup_clean)
@callback
def _on_homeassistant_stop(event: Event) -> None:
"""Cancel debounced cleanup."""
debounced_cleanup.async_cancel()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _on_homeassistant_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_homeassistant_stop)
def _normalize_connections(connections: set[tuple[str, str]]) -> set[tuple[str, str]]:

View file

@ -82,9 +82,7 @@ class FlowDispatcher:
@callback
def async_setup(self) -> None:
"""Set up the flow disptcher."""
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, self._async_start, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, self._async_start)
async def _async_start(self, event: Event) -> None:
"""Start processing pending flows."""

View file

@ -120,9 +120,7 @@ class EntityComponent(Generic[_EntityT]):
Note: this is only required if the integration never calls
`setup` or `async_setup`.
"""
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self._async_shutdown, run_immediately=True
)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_shutdown)
def setup(self, config: ConfigType) -> None:
"""Set up a full entity component.

View file

@ -683,7 +683,6 @@ class EntityRegistry(BaseRegistry):
self.hass.bus.async_listen(
EVENT_DEVICE_REGISTRY_UPDATED,
self.async_device_modified,
run_immediately=True,
)
@callback
@ -1492,7 +1491,6 @@ def _async_setup_cleanup(hass: HomeAssistant, registry: EntityRegistry) -> None:
event_type=lr.EVENT_LABEL_REGISTRY_UPDATED,
event_filter=_removed_from_registry_filter,
listener=_handle_label_registry_update,
run_immediately=True,
)
@callback
@ -1506,7 +1504,6 @@ def _async_setup_cleanup(hass: HomeAssistant, registry: EntityRegistry) -> None:
event_type=cr.EVENT_CATEGORY_REGISTRY_UPDATED,
event_filter=_removed_from_registry_filter,
listener=_handle_category_registry_update,
run_immediately=True,
)
@callback
@ -1525,9 +1522,7 @@ def _async_setup_cleanup(hass: HomeAssistant, registry: EntityRegistry) -> None:
"""Cancel cleanup."""
cancel()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _on_homeassistant_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_homeassistant_stop)
@callback
@ -1553,7 +1548,6 @@ def _async_setup_entity_restore(hass: HomeAssistant, registry: EntityRegistry) -
EVENT_ENTITY_REGISTRY_UPDATED,
cleanup_restored_states,
event_filter=cleanup_restored_states_filter,
run_immediately=True,
)
if hass.is_running:
@ -1570,9 +1564,7 @@ def _async_setup_entity_restore(hass: HomeAssistant, registry: EntityRegistry) -
entry.write_unavailable_state(hass)
hass.bus.async_listen(
EVENT_HOMEASSISTANT_START, _write_unavailable_states, run_immediately=True
)
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _write_unavailable_states)
async def async_migrate_entries(

View file

@ -276,7 +276,6 @@ def async_track_state_change(
EVENT_STATE_CHANGED,
state_change_dispatcher,
event_filter=state_change_filter,
run_immediately=True,
)
@ -419,7 +418,6 @@ def _async_track_event(
tracker.event_type,
ft.partial(tracker.dispatcher_callable, hass, callbacks),
event_filter=ft.partial(tracker.filter_callable, hass, callbacks),
run_immediately=True,
)
job = HassJob(action, f"track {tracker.event_type} event {keys}", job_type=job_type)

View file

@ -169,7 +169,6 @@ async def async_process_integration_platforms(
hass,
integration_platforms,
),
run_immediately=True,
)
else:
integration_platforms = hass.data[DATA_INTEGRATION_PLATFORMS]

View file

@ -252,7 +252,7 @@ class RestoreStateData:
# Dump states when stopping hass
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_dump_states_at_stop, run_immediately=True
EVENT_HOMEASSISTANT_STOP, _async_dump_states_at_stop
)
@callback

View file

@ -50,7 +50,7 @@ def _async_at_core_state(
if unsub:
unsub()
unsub = hass.bus.async_listen_once(event_type, _matched_event, run_immediately=True)
unsub = hass.bus.async_listen_once(event_type, _matched_event)
return cancel

View file

@ -125,7 +125,6 @@ class _StoreManager:
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED,
self._async_schedule_cleanup,
run_immediately=True,
)
@callback
@ -185,7 +184,6 @@ class _StoreManager:
self._hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
self._async_cancel_and_cleanup,
run_immediately=True,
)
@callback
@ -481,7 +479,6 @@ class Store(Generic[_T]):
self._unsub_final_write_listener = self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_FINAL_WRITE,
self._async_callback_final_write,
run_immediately=True,
)
@callback

View file

@ -212,12 +212,8 @@ def async_setup(hass: HomeAssistant) -> bool:
cancel = async_track_time_interval(
hass, _async_adjust_lru_sizes, timedelta(minutes=10)
)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, _async_adjust_lru_sizes, run_immediately=True
)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, callback(lambda _: cancel()), run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_adjust_lru_sizes)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, callback(lambda _: cancel()))
return True

View file

@ -136,7 +136,7 @@ class DataUpdateCoordinator(BaseDataUpdateCoordinatorProtocol, Generic[_DataT]):
await self.async_shutdown()
self._unsub_shutdown = self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _on_hass_stop, run_immediately=True
EVENT_HOMEASSISTANT_STOP, _on_hass_stop
)
@callback

View file

@ -615,14 +615,11 @@ def _async_when_setup(
EVENT_COMPONENT_LOADED,
_matched_event,
event_filter=_async_is_component_filter,
run_immediately=True,
)
)
if start_event:
listeners.append(
hass.bus.async_listen(
EVENT_HOMEASSISTANT_START, _matched_event, run_immediately=True
)
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event)
)

View file

@ -299,7 +299,6 @@ async def async_test_home_assistant(
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP,
hass.config_entries._async_shutdown,
run_immediately=True,
)
# Load the registries
@ -358,9 +357,7 @@ async def async_test_home_assistant(
await asyncio.sleep(0) # Give aiohttp one loop iteration to close
INSTANCES.remove(hass)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_CLOSE, clear_instance, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, clear_instance)
yield hass
@ -918,9 +915,7 @@ class MockEntityPlatform(entity_platform.EntityPlatform):
def _async_on_stop(_: Event) -> None:
self.async_shutdown()
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _async_on_stop, run_immediately=True
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_on_stop)
class MockToggleEntity(entity.ToggleEntity):
@ -1493,7 +1488,7 @@ def async_capture_events(hass: HomeAssistant, event_name: str) -> list[Event]:
def capture_events(event: Event) -> None:
events.append(event)
hass.bus.async_listen(event_name, capture_events, run_immediately=True)
hass.bus.async_listen(event_name, capture_events)
return events

View file

@ -2513,9 +2513,7 @@ async def test_recursive_automation_starting_script(
hass.services.async_register(
"test", "automation_started", async_service_handler
)
hass.bus.async_listen(
"automation_triggered", async_automation_triggered, run_immediately=True
)
hass.bus.async_listen("automation_triggered", async_automation_triggered)
hass.bus.async_fire("trigger_automation")
await asyncio.wait_for(script_done_event.wait(), 10)

View file

@ -1174,7 +1174,7 @@ async def test_eventbus_run_immediately_callback(hass: HomeAssistant) -> None:
"""Mock listener."""
calls.append(event)
unsub = hass.bus.async_listen("test", listener, run_immediately=True)
unsub = hass.bus.async_listen("test", listener)
hass.bus.async_fire("test", {"event": True})
# No async_block_till_done here
@ -1191,7 +1191,7 @@ async def test_eventbus_run_immediately_coro(hass: HomeAssistant) -> None:
"""Mock listener."""
calls.append(event)
unsub = hass.bus.async_listen("test", listener, run_immediately=True)
unsub = hass.bus.async_listen("test", listener)
hass.bus.async_fire("test", {"event": True})
# No async_block_till_done here
@ -1208,7 +1208,7 @@ async def test_eventbus_listen_once_run_immediately_coro(hass: HomeAssistant) ->
"""Mock listener."""
calls.append(event)
hass.bus.async_listen_once("test", listener, run_immediately=True)
hass.bus.async_listen_once("test", listener)
hass.bus.async_fire("test", {"event": True})
# No async_block_till_done here
@ -3343,9 +3343,7 @@ async def test_statemachine_report_state(hass: HomeAssistant) -> None:
hass.states.async_set("light.bowl", "on", {})
state_changed_events = async_capture_events(hass, EVENT_STATE_CHANGED)
state_reported_events = []
hass.bus.async_listen(
EVENT_STATE_REPORTED, listener, event_filter=filter, run_immediately=True
)
hass.bus.async_listen(EVENT_STATE_REPORTED, listener, event_filter=filter)
hass.states.async_set("light.bowl", "on")
await hass.async_block_till_done()
@ -3380,17 +3378,36 @@ async def test_report_state_listener_restrictions(hass: HomeAssistant) -> None:
"""Mock filter."""
return False
# run_immediately set to False
with pytest.raises(HomeAssistantError):
hass.bus.async_listen(
EVENT_STATE_REPORTED, listener, event_filter=filter, run_immediately=False
)
# no filter
with pytest.raises(HomeAssistantError):
hass.bus.async_listen(EVENT_STATE_REPORTED, listener, run_immediately=True)
hass.bus.async_listen(EVENT_STATE_REPORTED, listener)
# Both filter and run_immediately
hass.bus.async_listen(
EVENT_STATE_REPORTED, listener, event_filter=filter, run_immediately=True
)
hass.bus.async_listen(EVENT_STATE_REPORTED, listener, event_filter=filter)
@pytest.mark.parametrize(
"run_immediately",
[True, False],
)
@pytest.mark.parametrize(
"method",
["async_listen", "async_listen_once"],
)
async def test_async_listen_with_run_immediately_deprecated(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
run_immediately: bool,
method: str,
) -> None:
"""Test async_add_job warns about its deprecation."""
async def _test(event: ha.Event):
pass
func = getattr(hass.bus, method)
func(EVENT_HOMEASSISTANT_START, _test, run_immediately=run_immediately)
assert (
f"Detected code that calls `{method}` with run_immediately, which is "
"deprecated and will be removed in Assistant 2025.5."
) in caplog.text

View file

@ -399,7 +399,6 @@ async def test_show_progress(hass: HomeAssistant, manager) -> None:
hass.bus.async_listen(
data_entry_flow.EVENT_DATA_ENTRY_FLOW_PROGRESSED,
capture_events,
run_immediately=True,
)
result = await manager.async_init("test")
@ -479,7 +478,6 @@ async def test_show_progress_error(hass: HomeAssistant, manager) -> None:
hass.bus.async_listen(
data_entry_flow.EVENT_DATA_ENTRY_FLOW_PROGRESSED,
capture_events,
run_immediately=True,
)
result = await manager.async_init("test")