Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Husqvarna Autoconnect Bluetooth integration."""
2 
3 from __future__ import annotations
4 
5 from automower_ble.mower import Mower
6 from bleak import BleakError
7 from bleak_retry_connector import close_stale_connections_by_address, get_device
8 
9 from homeassistant.components import bluetooth
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_ADDRESS, CONF_CLIENT_ID, Platform
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryNotReady
14 
15 from .const import LOGGER
16 from .coordinator import HusqvarnaCoordinator
17 
18 PLATFORMS = [
19  Platform.LAWN_MOWER,
20 ]
21 
22 
23 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
24  """Set up Husqvarna Autoconnect Bluetooth from a config entry."""
25  address = entry.data[CONF_ADDRESS]
26  channel_id = entry.data[CONF_CLIENT_ID]
27 
28  mower = Mower(channel_id, address)
29 
30  await close_stale_connections_by_address(address)
31 
32  LOGGER.debug("connecting to %s with channel ID %s", address, str(channel_id))
33  try:
34  device = bluetooth.async_ble_device_from_address(
35  hass, address, connectable=True
36  ) or await get_device(address)
37  if not await mower.connect(device):
38  raise ConfigEntryNotReady
39  except (TimeoutError, BleakError) as exception:
40  raise ConfigEntryNotReady(
41  f"Unable to connect to device {address} due to {exception}"
42  ) from exception
43  LOGGER.debug("connected and paired")
44 
45  model = await mower.get_model()
46  LOGGER.debug("Connected to Automower: %s", model)
47 
48  coordinator = HusqvarnaCoordinator(hass, mower, address, channel_id, model)
49 
50  await coordinator.async_config_entry_first_refresh()
51  entry.runtime_data = coordinator
52  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
53 
54  return True
55 
56 
57 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
58  """Unload a config entry."""
59  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
60  coordinator: HusqvarnaCoordinator = entry.runtime_data
61  await coordinator.async_shutdown()
62 
63  return unload_ok
DeviceEntry get_device(HomeAssistant hass, str unique_id)
Definition: util.py:12
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:57
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:23