Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The EufyLife integration."""
2 
3 from __future__ import annotations
4 
5 from eufylife_ble_client import EufyLifeBLEDevice
6 
7 from homeassistant.components import bluetooth
8 from homeassistant.components.bluetooth.match import ADDRESS, BluetoothCallbackMatcher
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_MODEL, EVENT_HOMEASSISTANT_STOP, Platform
11 from homeassistant.core import Event, HomeAssistant, callback
12 
13 from .const import DOMAIN
14 from .models import EufyLifeData
15 
16 PLATFORMS: list[Platform] = [Platform.SENSOR]
17 
18 
19 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
20  """Set up EufyLife device from a config entry."""
21  address = entry.unique_id
22  assert address is not None
23 
24  model = entry.data[CONF_MODEL]
25  client = EufyLifeBLEDevice(model=model)
26 
27  @callback
28  def _async_update_ble(
29  service_info: bluetooth.BluetoothServiceInfoBleak,
30  change: bluetooth.BluetoothChange,
31  ) -> None:
32  """Update from a ble callback."""
33  client.set_ble_device_and_advertisement_data(
34  service_info.device, service_info.advertisement
35  )
36  if not client.advertisement_data_contains_state:
37  hass.async_create_task(client.connect())
38 
39  entry.async_on_unload(
40  bluetooth.async_register_callback(
41  hass,
42  _async_update_ble,
43  BluetoothCallbackMatcher({ADDRESS: address}),
44  bluetooth.BluetoothScanningMode.ACTIVE,
45  )
46  )
47 
48  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = EufyLifeData(
49  address,
50  model,
51  client,
52  )
53 
54  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
55 
56  async def _async_stop(event: Event) -> None:
57  """Close the connection."""
58  await client.stop()
59 
60  entry.async_on_unload(
61  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop)
62  )
63  return True
64 
65 
66 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
67  """Unload a config entry."""
68  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
69  hass.data[DOMAIN].pop(entry.entry_id)
70 
71  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:19
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:66
None _async_stop(HomeAssistant hass, bool restart)
Definition: __init__.py:392