Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """NextBus platform."""
2 
3 from homeassistant.config_entries import ConfigEntry
4 from homeassistant.const import CONF_STOP, Platform
5 from homeassistant.core import HomeAssistant
6 from homeassistant.exceptions import ConfigEntryNotReady
7 
8 from .const import CONF_AGENCY, CONF_ROUTE, DOMAIN
9 from .coordinator import NextBusDataUpdateCoordinator
10 
11 PLATFORMS = [Platform.SENSOR]
12 
13 
14 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
15  """Set up platforms for NextBus."""
16  entry_agency = entry.data[CONF_AGENCY]
17  entry_stop = entry.data[CONF_STOP]
18  coordinator_key = f"{entry_agency}-{entry_stop}"
19 
20  coordinator: NextBusDataUpdateCoordinator | None = hass.data.setdefault(
21  DOMAIN, {}
22  ).get(
23  coordinator_key,
24  )
25  if coordinator is None:
26  coordinator = NextBusDataUpdateCoordinator(hass, entry_agency)
27  hass.data[DOMAIN][coordinator_key] = coordinator
28 
29  coordinator.add_stop_route(entry_stop, entry.data[CONF_ROUTE])
30 
31  await coordinator.async_refresh()
32  if not coordinator.last_update_success:
33  raise ConfigEntryNotReady from coordinator.last_exception
34 
35  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
36 
37  return True
38 
39 
40 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
41  """Unload a config entry."""
42  if await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
43  entry_agency = entry.data[CONF_AGENCY]
44  entry_stop = entry.data[CONF_STOP]
45  coordinator_key = f"{entry_agency}-{entry_stop}"
46 
47  coordinator: NextBusDataUpdateCoordinator = hass.data[DOMAIN][coordinator_key]
48  coordinator.remove_stop_route(entry_stop, entry.data[CONF_ROUTE])
49 
50  if not coordinator.has_routes():
51  await coordinator.async_shutdown()
52  hass.data[DOMAIN].pop(coordinator_key)
53 
54  return True
55 
56  return False
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:40
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:14