Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The launch_library component."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import TypedDict
8 
9 from pylaunches import PyLaunches, PyLaunchesError
10 from pylaunches.types import Launch, StarshipResponse
11 
12 from homeassistant.config_entries import ConfigEntry
13 from homeassistant.const import Platform
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
17 
18 from .const import DOMAIN
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 PLATFORMS = [Platform.SENSOR]
23 
24 
25 class LaunchLibraryData(TypedDict):
26  """Typed dict representation of data returned from pylaunches."""
27 
28  upcoming_launches: list[Launch]
29  starship_events: StarshipResponse
30 
31 
32 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
33  """Set up this integration using UI."""
34 
35  hass.data.setdefault(DOMAIN, {})
36 
37  session = async_get_clientsession(hass)
38  launches = PyLaunches(session)
39 
40  async def async_update() -> LaunchLibraryData:
41  try:
42  return LaunchLibraryData(
43  upcoming_launches=await launches.launch_upcoming(
44  filters={"limit": 1, "hide_recent_previous": "True"},
45  ),
46  starship_events=await launches.dashboard_starship(),
47  )
48  except PyLaunchesError as ex:
49  raise UpdateFailed(ex) from ex
50 
51  coordinator = DataUpdateCoordinator(
52  hass,
53  _LOGGER,
54  config_entry=entry,
55  name=DOMAIN,
56  update_method=async_update,
57  update_interval=timedelta(hours=1),
58  )
59 
60  await coordinator.async_config_entry_first_refresh()
61 
62  hass.data[DOMAIN] = coordinator
63 
64  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
65 
66  return True
67 
68 
69 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
70  """Handle removal of an entry."""
71  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
72  del hass.data[DOMAIN]
73  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:69
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:32
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)