Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Vogel's MotionMount integration."""
2 
3 from __future__ import annotations
4 
5 import socket
6 
7 import motionmount
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_HOST, CONF_PORT, Platform
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryNotReady
13 from homeassistant.helpers.device_registry import format_mac
14 
15 from .const import DOMAIN, EMPTY_MAC
16 
17 PLATFORMS: list[Platform] = [
18  Platform.BINARY_SENSOR,
19  Platform.NUMBER,
20  Platform.SELECT,
21  Platform.SENSOR,
22 ]
23 
24 
25 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
26  """Set up Vogel's MotionMount from a config entry."""
27 
28  host = entry.data[CONF_HOST]
29 
30  # Create API instance
31  mm = motionmount.MotionMount(host, entry.data[CONF_PORT])
32 
33  # Validate the API connection
34  try:
35  await mm.connect()
36  except (ConnectionError, TimeoutError, socket.gaierror) as ex:
37  raise ConfigEntryNotReady(f"Failed to connect to {host}") from ex
38 
39  found_mac = format_mac(mm.mac.hex())
40  if found_mac not in (EMPTY_MAC, entry.unique_id):
41  # If the mac address of the device does not match the unique_id
42  # of the config entry, it likely means the DHCP lease has expired
43  # and the device has been assigned a new IP address. We need to
44  # wait for the next discovery to find the device at its new address
45  # and update the config entry so we do not mix up devices.
46  await mm.disconnect()
47  raise ConfigEntryNotReady(
48  f"Unexpected device found at {host}; expected {entry.unique_id}, found {found_mac}"
49  )
50 
51  # Store an API object for your platforms to access
52  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = mm
53 
54  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
55 
56  return True
57 
58 
59 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
60  """Unload a config entry."""
61  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
62  mm: motionmount.MotionMount = hass.data[DOMAIN].pop(entry.entry_id)
63  await mm.disconnect()
64 
65  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:25
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:59