Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Component for the Portuguese weather service - IPMA."""
2 
3 import asyncio
4 import logging
5 
6 from pyipma import IPMAException
7 from pyipma.api import IPMA_API
8 from pyipma.location import Location
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, Platform
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryNotReady
14 from homeassistant.helpers.aiohttp_client import async_get_clientsession
15 
16 from .config_flow import IpmaFlowHandler # noqa: F401
17 from .const import DATA_API, DATA_LOCATION, DOMAIN
18 
19 DEFAULT_NAME = "ipma"
20 
21 PLATFORMS = [Platform.SENSOR, Platform.WEATHER]
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
27  """Set up IPMA station as config entry."""
28 
29  latitude = config_entry.data[CONF_LATITUDE]
30  longitude = config_entry.data[CONF_LONGITUDE]
31 
32  api = IPMA_API(async_get_clientsession(hass))
33 
34  try:
35  async with asyncio.timeout(30):
36  location = await Location.get(api, float(latitude), float(longitude))
37  except (IPMAException, TimeoutError) as err:
38  raise ConfigEntryNotReady(
39  f"Could not get location for ({latitude},{longitude})"
40  ) from err
41 
42  _LOGGER.debug(
43  "Initializing for coordinates %s, %s -> station %s (%d, %d)",
44  latitude,
45  longitude,
46  location.station,
47  location.id_station,
48  location.global_id_local,
49  )
50 
51  hass.data.setdefault(DOMAIN, {})
52  hass.data[DOMAIN][config_entry.entry_id] = {DATA_API: api, DATA_LOCATION: location}
53 
54  await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
55  return True
56 
57 
58 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
59  """Unload a config entry."""
60 
61  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
62  hass.data[DOMAIN].pop(entry.entry_id)
63 
64  if not hass.data[DOMAIN]:
65  hass.data.pop(DOMAIN)
66 
67  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:26
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:58
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)