|
1 | 1 | """🤖 Auto Areas. A custom component for Home Assistant which automates your areas.""" |
2 | 2 | from __future__ import annotations |
| 3 | +import asyncio |
3 | 4 |
|
4 | 5 | from homeassistant.helpers import issue_registry |
5 | 6 | from homeassistant.config_entries import ConfigEntry, ConfigType |
6 | 7 | from homeassistant.const import Platform |
7 | 8 | from homeassistant.core import HomeAssistant |
| 9 | +from homeassistant.const import EVENT_HOMEASSISTANT_STARTED |
| 10 | + |
8 | 11 |
|
9 | 12 | from .auto_area import ( |
10 | 13 | AutoArea, |
|
18 | 21 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
19 | 22 | """Initialize AutoArea for this config entry.""" |
20 | 23 | hass.data.setdefault(DOMAIN, {}) |
21 | | - hass.data[DOMAIN][entry.entry_id] = AutoArea(hass=hass, entry=entry) |
22 | 24 |
|
| 25 | + auto_area = AutoArea(hass=hass, entry=entry) |
| 26 | + hass.data[DOMAIN][entry.entry_id] = auto_area |
| 27 | + |
| 28 | + # Initialize AutoArea once HA is started |
| 29 | + if hass.is_running: |
| 30 | + initialize(hass, entry, auto_area) |
| 31 | + else: |
| 32 | + hass.bus.async_listen_once( |
| 33 | + EVENT_HOMEASSISTANT_STARTED, |
| 34 | + lambda init: initialize(hass, entry, auto_area) |
| 35 | + ) |
| 36 | + |
| 37 | + return True |
| 38 | + |
| 39 | +async def async_init(hass: HomeAssistant, entry: ConfigEntry, auto_area: AutoArea): |
| 40 | + await auto_area.initialize() |
| 41 | + entry.async_on_unload(entry.add_update_listener(async_reload_entry)) |
23 | 42 | hass.async_create_task( |
24 | 43 | hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) |
25 | 44 | ) |
26 | | - entry.async_on_unload(entry.add_update_listener(async_reload_entry)) |
27 | | - |
28 | | - return True |
29 | 45 |
|
| 46 | +def initialize(hass: HomeAssistant, entry: ConfigEntry, auto_area: AutoArea): |
| 47 | + """Initialize area after HA has started.""" |
| 48 | + return asyncio.run_coroutine_threadsafe( |
| 49 | + async_init(hass, entry, auto_area), hass.loop |
| 50 | + ).result() |
30 | 51 |
|
31 | 52 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
32 | 53 | """Handle removal of an entry.""" |
|
0 commit comments