Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The melnor integration."""
2 
3 from __future__ import annotations
4 
5 from melnor_bluetooth.device import Device
6 
7 from homeassistant.components import bluetooth
8 from homeassistant.components.bluetooth.match import BluetoothCallbackMatcher
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_ADDRESS, Platform
11 from homeassistant.core import HomeAssistant, callback
12 from homeassistant.exceptions import ConfigEntryNotReady
13 
14 from .const import DOMAIN
15 from .coordinator import MelnorDataUpdateCoordinator
16 
17 PLATFORMS: list[Platform] = [
18  Platform.NUMBER,
19  Platform.SENSOR,
20  Platform.SWITCH,
21  Platform.TIME,
22 ]
23 
24 
25 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
26  """Set up melnor from a config entry."""
27 
28  hass.data.setdefault(DOMAIN, {}).setdefault(entry.entry_id, {})
29 
30  ble_device = bluetooth.async_ble_device_from_address(hass, entry.data[CONF_ADDRESS])
31 
32  if not ble_device:
33  raise ConfigEntryNotReady(
34  f"Couldn't find a nearby device for address: {entry.data[CONF_ADDRESS]}"
35  )
36 
37  # Create the device and connect immediately so we can pull down
38  # required attributes before building out our entities
39  device = Device(ble_device)
40  await device.connect(retry_attempts=4)
41 
42  if not device.is_connected:
43  raise ConfigEntryNotReady(f"Failed to connect to: {device.mac}")
44 
45  @callback
46  def _async_update_ble(
47  service_info: bluetooth.BluetoothServiceInfoBleak,
48  change: bluetooth.BluetoothChange,
49  ) -> None:
50  """Update from a ble callback."""
51  device.update_ble_device(service_info.device)
52 
53  bluetooth.async_register_callback(
54  hass,
55  _async_update_ble,
56  BluetoothCallbackMatcher(address=device.mac),
57  bluetooth.BluetoothScanningMode.PASSIVE,
58  )
59 
60  coordinator = MelnorDataUpdateCoordinator(hass, device)
61  await coordinator.async_config_entry_first_refresh()
62 
63  hass.data[DOMAIN][entry.entry_id] = coordinator
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  """Unload a config entry."""
71 
72  device: Device = hass.data[DOMAIN][entry.entry_id].data
73 
74  await device.disconnect()
75 
76  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
77  hass.data[DOMAIN].pop(entry.entry_id)
78 
79  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:25