Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The iss component."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 from datetime import timedelta
7 import logging
8 
9 import pyiss
10 import requests
11 from requests.exceptions import HTTPError
12 
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.const import Platform
15 from homeassistant.core import HomeAssistant
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 @dataclass
26 class IssData:
27  """Dataclass representation of data returned from pyiss."""
28 
29  number_of_people_in_space: int
30  current_location: dict[str, str]
31 
32 
33 def update(iss: pyiss.ISS) -> IssData:
34  """Retrieve data from the pyiss API."""
35  return IssData(
36  number_of_people_in_space=iss.number_of_people_in_space(),
37  current_location=iss.current_location(),
38  )
39 
40 
41 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
42  """Set up this integration using UI."""
43  hass.data.setdefault(DOMAIN, {})
44 
45  iss = pyiss.ISS()
46 
47  async def async_update() -> IssData:
48  try:
49  return await hass.async_add_executor_job(update, iss)
50  except (HTTPError, requests.exceptions.ConnectionError) as ex:
51  raise UpdateFailed("Unable to retrieve data") from ex
52 
53  coordinator = DataUpdateCoordinator(
54  hass,
55  _LOGGER,
56  config_entry=entry,
57  name=DOMAIN,
58  update_method=async_update,
59  update_interval=timedelta(seconds=60),
60  )
61 
62  await coordinator.async_config_entry_first_refresh()
63 
64  hass.data[DOMAIN] = coordinator
65 
66  entry.async_on_unload(entry.add_update_listener(update_listener))
67 
68  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
69 
70  return True
71 
72 
73 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
74  """Handle removal of an entry."""
75  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
76  del hass.data[DOMAIN]
77  return unload_ok
78 
79 
80 async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
81  """Handle options update."""
82  await hass.config_entries.async_reload(entry.entry_id)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
None update_listener(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:80
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:73
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:41