Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Snooz component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from pysnooz.device import SnoozDevice
8 
9 from homeassistant.components.bluetooth import async_ble_device_from_address
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_ADDRESS, CONF_TOKEN
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryNotReady
14 
15 from .const import DOMAIN, PLATFORMS
16 from .models import SnoozConfigurationData
17 
18 
19 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
20  """Set up Snooz device from a config entry."""
21  address: str = entry.data[CONF_ADDRESS]
22  token: str = entry.data[CONF_TOKEN]
23 
24  # transitions info logs are verbose. Only enable warnings
25  logging.getLogger("transitions.core").setLevel(logging.WARNING)
26 
27  if not (ble_device := async_ble_device_from_address(hass, address)):
28  raise ConfigEntryNotReady(
29  f"Could not find Snooz with address {address}. Try power cycling the device"
30  )
31 
32  device = SnoozDevice(ble_device, token)
33 
34  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = SnoozConfigurationData(
35  ble_device, device, entry.title
36  )
37 
38  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
39  entry.async_on_unload(entry.add_update_listener(_async_update_listener))
40  return True
41 
42 
43 async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
44  """Handle options update."""
45  data: SnoozConfigurationData = hass.data[DOMAIN][entry.entry_id]
46  if entry.title != data.title:
47  await hass.config_entries.async_reload(entry.entry_id)
48 
49 
50 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
51  """Unload a config entry."""
52  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
53  data: SnoozConfigurationData = hass.data[DOMAIN][entry.entry_id]
54 
55  # also called by fan entities, but do it here too for good measure
56  await data.device.async_disconnect()
57 
58  hass.data[DOMAIN].pop(entry.entry_id)
59 
60  if not hass.config_entries.async_entries(DOMAIN):
61  hass.data.pop(DOMAIN)
62 
63  return unload_ok
BLEDevice|None async_ble_device_from_address(HomeAssistant hass, str address, bool connectable=True)
Definition: api.py:88
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:50
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:19
None _async_update_listener(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:43