2021-05-31 23:35:31 +00:00
|
|
|
"""Helpers to help during startup."""
|
2021-09-29 14:32:11 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-08-09 20:12:33 +00:00
|
|
|
from collections.abc import Callable, Coroutine
|
|
|
|
from typing import Any
|
2021-05-31 23:35:31 +00:00
|
|
|
|
|
|
|
from homeassistant.const import EVENT_HOMEASSISTANT_START
|
2022-04-01 21:34:36 +00:00
|
|
|
from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant, callback
|
2021-05-31 23:35:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def async_at_start(
|
2022-08-09 20:12:33 +00:00
|
|
|
hass: HomeAssistant,
|
|
|
|
at_start_cb: Callable[[HomeAssistant], Coroutine[Any, Any, None] | None],
|
2022-04-01 21:34:36 +00:00
|
|
|
) -> CALLBACK_TYPE:
|
2021-05-31 23:35:31 +00:00
|
|
|
"""Execute something when Home Assistant is started.
|
|
|
|
|
|
|
|
Will execute it now if Home Assistant is already started.
|
|
|
|
"""
|
2022-01-05 17:04:09 +00:00
|
|
|
at_start_job = HassJob(at_start_cb)
|
2021-05-31 23:35:31 +00:00
|
|
|
if hass.is_running:
|
2022-01-05 17:04:09 +00:00
|
|
|
hass.async_run_hass_job(at_start_job, hass)
|
2022-04-01 21:34:36 +00:00
|
|
|
return lambda: None
|
2021-05-31 23:35:31 +00:00
|
|
|
|
2022-05-02 14:41:14 +00:00
|
|
|
unsub: None | CALLBACK_TYPE = None
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def _matched_event(event: Event) -> None:
|
2021-05-31 23:35:31 +00:00
|
|
|
"""Call the callback when Home Assistant started."""
|
2022-01-05 17:04:09 +00:00
|
|
|
hass.async_run_hass_job(at_start_job, hass)
|
2022-05-02 14:41:14 +00:00
|
|
|
nonlocal unsub
|
|
|
|
unsub = None
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def cancel() -> None:
|
|
|
|
if unsub:
|
|
|
|
unsub()
|
2021-05-31 23:35:31 +00:00
|
|
|
|
2022-05-02 14:41:14 +00:00
|
|
|
unsub = hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _matched_event)
|
|
|
|
return cancel
|