2019-02-13 20:21:14 +00:00
|
|
|
"""Support for exposing Home Assistant via Zeroconf."""
|
2021-03-18 21:58:19 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
import asyncio
|
2021-05-26 16:06:30 +00:00
|
|
|
from collections.abc import Coroutine
|
2021-03-23 13:36:43 +00:00
|
|
|
from contextlib import suppress
|
2020-09-11 10:19:21 +00:00
|
|
|
import fnmatch
|
2021-08-18 17:33:26 +00:00
|
|
|
from ipaddress import IPv6Address, ip_address
|
2016-04-10 22:34:04 +00:00
|
|
|
import logging
|
2019-06-05 15:13:40 +00:00
|
|
|
import socket
|
2021-04-25 00:39:24 +00:00
|
|
|
from typing import Any, TypedDict, cast
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2016-09-30 02:02:22 +00:00
|
|
|
import voluptuous as vol
|
2021-07-26 07:27:49 +00:00
|
|
|
from zeroconf import InterfaceChoice, IPVersion, ServiceStateChange
|
2021-06-30 03:13:31 +00:00
|
|
|
from zeroconf.asyncio import AsyncServiceInfo
|
2019-05-21 22:36:26 +00:00
|
|
|
|
2021-07-22 18:12:33 +00:00
|
|
|
from homeassistant import config_entries
|
2021-05-26 16:06:30 +00:00
|
|
|
from homeassistant.components import network
|
2021-07-22 18:12:33 +00:00
|
|
|
from homeassistant.components.network import async_get_source_ip
|
2021-05-26 16:06:30 +00:00
|
|
|
from homeassistant.components.network.models import Adapter
|
2019-10-13 21:16:27 +00:00
|
|
|
from homeassistant.const import (
|
|
|
|
EVENT_HOMEASSISTANT_START,
|
2020-07-22 00:18:43 +00:00
|
|
|
EVENT_HOMEASSISTANT_STARTED,
|
2019-12-09 17:54:54 +00:00
|
|
|
EVENT_HOMEASSISTANT_STOP,
|
2019-10-13 21:16:27 +00:00
|
|
|
__version__,
|
|
|
|
)
|
2021-05-18 03:51:05 +00:00
|
|
|
from homeassistant.core import Event, HomeAssistant, callback
|
|
|
|
from homeassistant.data_entry_flow import FlowResult
|
2020-05-06 14:16:59 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2020-05-08 19:53:28 +00:00
|
|
|
from homeassistant.helpers.network import NoURLAvailableError, get_url
|
2021-08-18 11:22:05 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType
|
2021-05-11 16:03:36 +00:00
|
|
|
from homeassistant.loader import async_get_homekit, async_get_zeroconf, bind_hass
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
from .models import HaAsyncServiceBrowser, HaAsyncZeroconf, HaZeroconf
|
2020-08-12 14:08:33 +00:00
|
|
|
from .usage import install_multiple_zeroconf_catcher
|
|
|
|
|
2016-09-30 02:02:22 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
DOMAIN = "zeroconf"
|
2016-04-10 23:09:52 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
ZEROCONF_TYPE = "_home-assistant._tcp.local."
|
2021-01-07 18:44:34 +00:00
|
|
|
HOMEKIT_TYPES = [
|
|
|
|
"_hap._tcp.local.",
|
|
|
|
# Thread based devices
|
|
|
|
"_hap._udp.local.",
|
|
|
|
]
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2020-05-06 14:16:59 +00:00
|
|
|
CONF_DEFAULT_INTERFACE = "default_interface"
|
2020-07-15 18:26:40 +00:00
|
|
|
CONF_IPV6 = "ipv6"
|
2021-03-25 01:04:55 +00:00
|
|
|
DEFAULT_DEFAULT_INTERFACE = True
|
2020-07-15 18:26:40 +00:00
|
|
|
DEFAULT_IPV6 = True
|
2020-05-06 14:16:59 +00:00
|
|
|
|
2020-05-12 19:59:29 +00:00
|
|
|
HOMEKIT_PAIRED_STATUS_FLAG = "sf"
|
|
|
|
HOMEKIT_MODEL = "md"
|
|
|
|
|
2021-04-22 05:10:34 +00:00
|
|
|
MDNS_TARGET_IP = "224.0.0.251"
|
|
|
|
|
2020-08-21 12:31:17 +00:00
|
|
|
# Property key=value has a max length of 255
|
|
|
|
# so we use 230 to leave space for key=
|
|
|
|
MAX_PROPERTY_VALUE_LEN = 230
|
|
|
|
|
|
|
|
# Dns label max length
|
|
|
|
MAX_NAME_LEN = 63
|
|
|
|
|
2020-05-06 14:16:59 +00:00
|
|
|
CONFIG_SCHEMA = vol.Schema(
|
|
|
|
{
|
2021-05-26 16:06:30 +00:00
|
|
|
DOMAIN: vol.All(
|
|
|
|
cv.deprecated(CONF_DEFAULT_INTERFACE),
|
2021-06-30 03:13:31 +00:00
|
|
|
cv.deprecated(CONF_IPV6),
|
2021-05-26 16:06:30 +00:00
|
|
|
vol.Schema(
|
|
|
|
{
|
|
|
|
vol.Optional(CONF_DEFAULT_INTERFACE): cv.boolean,
|
|
|
|
vol.Optional(CONF_IPV6, default=DEFAULT_IPV6): cv.boolean,
|
|
|
|
}
|
|
|
|
),
|
2020-05-06 14:16:59 +00:00
|
|
|
)
|
|
|
|
},
|
|
|
|
extra=vol.ALLOW_EXTRA,
|
|
|
|
)
|
2016-04-10 22:34:04 +00:00
|
|
|
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
class HaServiceInfo(TypedDict):
|
|
|
|
"""Prepared info from mDNS entries."""
|
|
|
|
|
|
|
|
host: str
|
|
|
|
port: int | None
|
|
|
|
hostname: str
|
|
|
|
type: str
|
|
|
|
name: str
|
|
|
|
properties: dict[str, Any]
|
|
|
|
|
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
class ZeroconfFlow(TypedDict):
|
|
|
|
"""A queued zeroconf discovery flow."""
|
|
|
|
|
|
|
|
domain: str
|
|
|
|
context: dict[str, Any]
|
|
|
|
data: HaServiceInfo
|
|
|
|
|
|
|
|
|
2021-05-11 16:03:36 +00:00
|
|
|
@bind_hass
|
2021-03-30 16:48:04 +00:00
|
|
|
async def async_get_instance(hass: HomeAssistant) -> HaZeroconf:
|
2021-05-11 16:03:36 +00:00
|
|
|
"""Zeroconf instance to be shared with other integrations that use it."""
|
|
|
|
return cast(HaZeroconf, (await _async_get_instance(hass)).zeroconf)
|
|
|
|
|
|
|
|
|
|
|
|
@bind_hass
|
|
|
|
async def async_get_async_instance(hass: HomeAssistant) -> HaAsyncZeroconf:
|
2020-05-11 05:51:23 +00:00
|
|
|
"""Zeroconf instance to be shared with other integrations that use it."""
|
2020-09-13 23:06:19 +00:00
|
|
|
return await _async_get_instance(hass)
|
2020-05-11 05:51:23 +00:00
|
|
|
|
|
|
|
|
2021-05-11 16:03:36 +00:00
|
|
|
async def _async_get_instance(hass: HomeAssistant, **zcargs: Any) -> HaAsyncZeroconf:
|
|
|
|
if DOMAIN in hass.data:
|
|
|
|
return cast(HaAsyncZeroconf, hass.data[DOMAIN])
|
|
|
|
|
2020-07-13 17:20:18 +00:00
|
|
|
logging.getLogger("zeroconf").setLevel(logging.NOTSET)
|
2020-07-15 18:26:40 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
zeroconf = HaZeroconf(**zcargs)
|
|
|
|
aio_zc = HaAsyncZeroconf(zc=zeroconf)
|
2020-07-15 18:26:40 +00:00
|
|
|
|
2020-09-13 23:06:19 +00:00
|
|
|
install_multiple_zeroconf_catcher(zeroconf)
|
2020-05-11 05:51:23 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
async def _async_stop_zeroconf(_event: Event) -> None:
|
2020-05-11 05:51:23 +00:00
|
|
|
"""Stop Zeroconf."""
|
2021-06-30 03:13:31 +00:00
|
|
|
await aio_zc.ha_async_close()
|
2020-05-11 05:51:23 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_zeroconf)
|
2021-05-11 16:03:36 +00:00
|
|
|
hass.data[DOMAIN] = aio_zc
|
2020-05-11 05:51:23 +00:00
|
|
|
|
2021-05-11 16:03:36 +00:00
|
|
|
return aio_zc
|
2020-05-11 05:51:23 +00:00
|
|
|
|
|
|
|
|
2021-08-18 11:22:05 +00:00
|
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
2016-04-10 23:02:07 +00:00
|
|
|
"""Set up Zeroconf and make Home Assistant discoverable."""
|
2021-03-30 16:48:04 +00:00
|
|
|
zc_args: dict = {}
|
2021-04-22 05:10:34 +00:00
|
|
|
|
2021-05-26 16:06:30 +00:00
|
|
|
adapters = await network.async_get_adapters(hass)
|
2021-08-09 19:13:55 +00:00
|
|
|
|
|
|
|
ipv6 = True
|
|
|
|
if not any(adapter["enabled"] and adapter["ipv6"] for adapter in adapters):
|
|
|
|
ipv6 = False
|
|
|
|
zc_args["ip_version"] = IPVersion.V4Only
|
|
|
|
else:
|
|
|
|
zc_args["ip_version"] = IPVersion.All
|
|
|
|
|
2021-08-18 17:33:26 +00:00
|
|
|
if not ipv6 and network.async_only_default_interface_enabled(adapters):
|
2020-09-13 23:06:19 +00:00
|
|
|
zc_args["interfaces"] = InterfaceChoice.Default
|
2021-05-26 16:06:30 +00:00
|
|
|
else:
|
2021-08-18 17:33:26 +00:00
|
|
|
zc_args["interfaces"] = [
|
|
|
|
str(source_ip)
|
|
|
|
for source_ip in await network.async_get_enabled_source_ips(hass)
|
|
|
|
if not source_ip.is_loopback
|
|
|
|
and not (isinstance(source_ip, IPv6Address) and source_ip.is_global)
|
|
|
|
]
|
2021-06-30 03:13:31 +00:00
|
|
|
|
2021-05-11 16:03:36 +00:00
|
|
|
aio_zc = await _async_get_instance(hass, **zc_args)
|
2021-06-30 03:13:31 +00:00
|
|
|
zeroconf = cast(HaZeroconf, aio_zc.zeroconf)
|
2021-05-18 03:51:05 +00:00
|
|
|
zeroconf_types, homekit_models = await asyncio.gather(
|
|
|
|
async_get_zeroconf(hass), async_get_homekit(hass)
|
|
|
|
)
|
2021-06-30 03:13:31 +00:00
|
|
|
discovery = ZeroconfDiscovery(hass, zeroconf, zeroconf_types, homekit_models, ipv6)
|
2021-05-18 03:51:05 +00:00
|
|
|
await discovery.async_setup()
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
async def _async_zeroconf_hass_start(_event: Event) -> None:
|
2020-09-13 23:06:19 +00:00
|
|
|
"""Expose Home Assistant on zeroconf when it starts.
|
|
|
|
|
|
|
|
Wait till started or otherwise HTTP is not up and running.
|
|
|
|
"""
|
|
|
|
uuid = await hass.helpers.instance_id.async_get()
|
2021-05-11 16:03:36 +00:00
|
|
|
await _async_register_hass_zc_service(hass, aio_zc, uuid)
|
2020-09-13 23:06:19 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
@callback
|
|
|
|
def _async_start_discovery(_event: Event) -> None:
|
|
|
|
"""Start processing flows."""
|
|
|
|
discovery.async_start()
|
2020-09-13 23:06:19 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
async def _async_zeroconf_hass_stop(_event: Event) -> None:
|
|
|
|
await discovery.async_stop()
|
2020-09-13 23:06:19 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_zeroconf_hass_stop)
|
2020-09-13 23:06:19 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_zeroconf_hass_start)
|
2021-05-18 03:51:05 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, _async_start_discovery)
|
2020-05-20 06:37:32 +00:00
|
|
|
|
2020-09-13 23:06:19 +00:00
|
|
|
return True
|
2020-08-12 14:08:33 +00:00
|
|
|
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2021-07-27 17:31:51 +00:00
|
|
|
def _get_announced_addresses(
|
|
|
|
adapters: list[Adapter],
|
|
|
|
first_ip: bytes | None = None,
|
|
|
|
) -> list[bytes]:
|
|
|
|
"""Return a list of IP addresses to announce via zeroconf.
|
|
|
|
|
|
|
|
If first_ip is not None, it will be the first address in the list.
|
|
|
|
"""
|
|
|
|
addresses = {
|
|
|
|
addr.packed
|
|
|
|
for addr in [
|
2021-08-18 17:33:26 +00:00
|
|
|
ip_address(ip["address"])
|
2021-07-27 17:31:51 +00:00
|
|
|
for adapter in adapters
|
|
|
|
if adapter["enabled"]
|
|
|
|
for ip in cast(list, adapter["ipv6"]) + cast(list, adapter["ipv4"])
|
|
|
|
]
|
|
|
|
if not (addr.is_unspecified or addr.is_loopback)
|
|
|
|
}
|
|
|
|
if first_ip:
|
|
|
|
address_list = [first_ip]
|
|
|
|
address_list.extend(addresses - set({first_ip}))
|
|
|
|
else:
|
|
|
|
address_list = list(addresses)
|
|
|
|
return address_list
|
|
|
|
|
|
|
|
|
2021-05-11 16:03:36 +00:00
|
|
|
async def _async_register_hass_zc_service(
|
|
|
|
hass: HomeAssistant, aio_zc: HaAsyncZeroconf, uuid: str
|
2021-03-30 16:48:04 +00:00
|
|
|
) -> None:
|
2020-09-13 23:06:19 +00:00
|
|
|
# Get instance UUID
|
2021-08-20 21:33:23 +00:00
|
|
|
valid_location_name = _truncate_location_name_to_valid(
|
|
|
|
hass.config.location_name or "Home"
|
|
|
|
)
|
2020-08-21 12:31:17 +00:00
|
|
|
|
2016-09-30 02:02:22 +00:00
|
|
|
params = {
|
2020-08-21 12:31:17 +00:00
|
|
|
"location_name": valid_location_name,
|
2020-05-20 06:37:32 +00:00
|
|
|
"uuid": uuid,
|
2019-07-31 19:25:30 +00:00
|
|
|
"version": __version__,
|
2020-06-05 19:43:58 +00:00
|
|
|
"external_url": "",
|
|
|
|
"internal_url": "",
|
2020-05-08 00:29:47 +00:00
|
|
|
# Old base URL, for backward compatibility
|
2020-06-05 19:43:58 +00:00
|
|
|
"base_url": "",
|
2019-11-23 15:46:06 +00:00
|
|
|
# Always needs authentication
|
2019-07-31 19:25:30 +00:00
|
|
|
"requires_api_password": True,
|
2016-09-30 02:02:22 +00:00
|
|
|
}
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2020-05-20 06:37:32 +00:00
|
|
|
# Get instance URL's
|
2021-03-23 13:36:43 +00:00
|
|
|
with suppress(NoURLAvailableError):
|
2020-05-08 19:53:28 +00:00
|
|
|
params["external_url"] = get_url(hass, allow_internal=False)
|
2020-05-08 00:29:47 +00:00
|
|
|
|
2021-03-23 13:36:43 +00:00
|
|
|
with suppress(NoURLAvailableError):
|
2020-05-08 19:53:28 +00:00
|
|
|
params["internal_url"] = get_url(hass, allow_external=False)
|
2020-05-08 00:29:47 +00:00
|
|
|
|
|
|
|
# Set old base URL based on external or internal
|
|
|
|
params["base_url"] = params["external_url"] or params["internal_url"]
|
|
|
|
|
2021-07-27 17:31:51 +00:00
|
|
|
adapters = await network.async_get_adapters(hass)
|
2019-06-05 15:13:40 +00:00
|
|
|
|
2021-07-27 17:31:51 +00:00
|
|
|
# Puts the default IPv4 address first in the list to preserve compatibility,
|
|
|
|
# because some mDNS implementations ignores anything but the first announced address.
|
|
|
|
host_ip = await async_get_source_ip(hass, target_ip=MDNS_TARGET_IP)
|
|
|
|
host_ip_pton = None
|
|
|
|
if host_ip:
|
2019-06-05 15:13:40 +00:00
|
|
|
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
|
2021-07-27 17:31:51 +00:00
|
|
|
address_list = _get_announced_addresses(adapters, host_ip_pton)
|
2019-06-05 15:13:40 +00:00
|
|
|
|
2020-08-21 12:31:17 +00:00
|
|
|
_suppress_invalid_properties(params)
|
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
info = AsyncServiceInfo(
|
2019-07-31 19:25:30 +00:00
|
|
|
ZEROCONF_TYPE,
|
2020-08-21 12:31:17 +00:00
|
|
|
name=f"{valid_location_name}.{ZEROCONF_TYPE}",
|
2020-05-20 06:37:32 +00:00
|
|
|
server=f"{uuid}.local.",
|
2021-07-27 17:31:51 +00:00
|
|
|
addresses=address_list,
|
2019-07-31 19:25:30 +00:00
|
|
|
port=hass.http.server_port,
|
|
|
|
properties=params,
|
|
|
|
)
|
2019-05-16 19:04:20 +00:00
|
|
|
|
2020-09-13 23:06:19 +00:00
|
|
|
_LOGGER.info("Starting Zeroconf broadcast")
|
2021-07-26 07:27:49 +00:00
|
|
|
await aio_zc.async_register_service(info, allow_name_change=True)
|
2019-10-13 21:16:27 +00:00
|
|
|
|
2017-01-03 20:39:42 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
class FlowDispatcher:
|
|
|
|
"""Dispatch discovery flows."""
|
2020-09-13 23:06:19 +00:00
|
|
|
|
2021-05-19 03:49:10 +00:00
|
|
|
def __init__(self, hass: HomeAssistant) -> None:
|
2021-05-18 03:51:05 +00:00
|
|
|
"""Init the discovery dispatcher."""
|
|
|
|
self.hass = hass
|
|
|
|
self.pending_flows: list[ZeroconfFlow] = []
|
|
|
|
self.started = False
|
2020-09-13 23:06:19 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
@callback
|
|
|
|
def async_start(self) -> None:
|
|
|
|
"""Start processing pending flows."""
|
|
|
|
self.started = True
|
|
|
|
self.hass.loop.call_soon(self._async_process_pending_flows)
|
2016-04-10 22:34:04 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
def _async_process_pending_flows(self) -> None:
|
|
|
|
for flow in self.pending_flows:
|
|
|
|
self.hass.async_create_task(self._init_flow(flow))
|
|
|
|
self.pending_flows = []
|
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
def async_create(self, flow: ZeroconfFlow) -> None:
|
2021-05-18 03:51:05 +00:00
|
|
|
"""Create and add or queue a flow."""
|
|
|
|
if self.started:
|
2021-06-30 03:13:31 +00:00
|
|
|
self.hass.async_create_task(self._init_flow(flow))
|
2021-05-18 03:51:05 +00:00
|
|
|
else:
|
|
|
|
self.pending_flows.append(flow)
|
|
|
|
|
|
|
|
def _init_flow(self, flow: ZeroconfFlow) -> Coroutine[None, None, FlowResult]:
|
|
|
|
"""Create a flow."""
|
|
|
|
return self.hass.config_entries.flow.async_init(
|
|
|
|
flow["domain"], context=flow["context"], data=flow["data"]
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class ZeroconfDiscovery:
|
|
|
|
"""Discovery via zeroconf."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
hass: HomeAssistant,
|
2021-06-30 03:13:31 +00:00
|
|
|
zeroconf: HaZeroconf,
|
2021-05-18 03:51:05 +00:00
|
|
|
zeroconf_types: dict[str, list[dict[str, str]]],
|
|
|
|
homekit_models: dict[str, str],
|
2021-06-30 03:13:31 +00:00
|
|
|
ipv6: bool,
|
2021-05-18 03:51:05 +00:00
|
|
|
) -> None:
|
|
|
|
"""Init discovery."""
|
|
|
|
self.hass = hass
|
|
|
|
self.zeroconf = zeroconf
|
|
|
|
self.zeroconf_types = zeroconf_types
|
|
|
|
self.homekit_models = homekit_models
|
2021-06-30 03:13:31 +00:00
|
|
|
self.ipv6 = ipv6
|
2021-05-18 03:51:05 +00:00
|
|
|
|
|
|
|
self.flow_dispatcher: FlowDispatcher | None = None
|
2021-06-30 03:13:31 +00:00
|
|
|
self.async_service_browser: HaAsyncServiceBrowser | None = None
|
2021-05-18 03:51:05 +00:00
|
|
|
|
|
|
|
async def async_setup(self) -> None:
|
|
|
|
"""Start discovery."""
|
|
|
|
self.flow_dispatcher = FlowDispatcher(self.hass)
|
|
|
|
types = list(self.zeroconf_types)
|
|
|
|
# We want to make sure we know about other HomeAssistant
|
|
|
|
# instances as soon as possible to avoid name conflicts
|
|
|
|
# so we always browse for ZEROCONF_TYPE
|
|
|
|
for hk_type in (ZEROCONF_TYPE, *HOMEKIT_TYPES):
|
|
|
|
if hk_type not in self.zeroconf_types:
|
|
|
|
types.append(hk_type)
|
2021-06-30 03:13:31 +00:00
|
|
|
_LOGGER.debug("Starting Zeroconf browser for: %s", types)
|
|
|
|
self.async_service_browser = HaAsyncServiceBrowser(
|
|
|
|
self.ipv6, self.zeroconf, types, handlers=[self.async_service_update]
|
2021-05-18 03:51:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def async_stop(self) -> None:
|
|
|
|
"""Cancel the service browser and stop processing the queue."""
|
2021-06-30 03:13:31 +00:00
|
|
|
if self.async_service_browser:
|
|
|
|
await self.async_service_browser.async_cancel()
|
2021-05-18 03:51:05 +00:00
|
|
|
|
|
|
|
@callback
|
|
|
|
def async_start(self) -> None:
|
|
|
|
"""Start processing discovery flows."""
|
|
|
|
assert self.flow_dispatcher is not None
|
|
|
|
self.flow_dispatcher.async_start()
|
2020-08-05 13:50:56 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
@callback
|
|
|
|
def async_service_update(
|
2021-05-18 03:51:05 +00:00
|
|
|
self,
|
2021-06-30 03:13:31 +00:00
|
|
|
zeroconf: HaZeroconf,
|
2021-03-30 16:48:04 +00:00
|
|
|
service_type: str,
|
|
|
|
name: str,
|
|
|
|
state_change: ServiceStateChange,
|
|
|
|
) -> None:
|
2019-05-21 22:36:26 +00:00
|
|
|
"""Service state changed."""
|
2021-06-30 03:13:31 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"service_update: type=%s name=%s state_change=%s",
|
|
|
|
service_type,
|
|
|
|
name,
|
|
|
|
state_change,
|
|
|
|
)
|
|
|
|
|
2021-03-09 20:14:00 +00:00
|
|
|
if state_change == ServiceStateChange.Removed:
|
2019-05-31 18:58:48 +00:00
|
|
|
return
|
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
asyncio.create_task(self._process_service_update(zeroconf, service_type, name))
|
|
|
|
|
|
|
|
async def _process_service_update(
|
|
|
|
self, zeroconf: HaZeroconf, service_type: str, name: str
|
|
|
|
) -> None:
|
|
|
|
"""Process a zeroconf update."""
|
|
|
|
async_service_info = AsyncServiceInfo(service_type, name)
|
|
|
|
await async_service_info.async_request(zeroconf, 3000)
|
2020-05-14 16:58:40 +00:00
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
info = info_from_service(async_service_info)
|
2020-07-23 06:21:57 +00:00
|
|
|
if not info:
|
|
|
|
# Prevent the browser thread from collapsing
|
|
|
|
_LOGGER.debug("Failed to get addresses for device %s", name)
|
|
|
|
return
|
|
|
|
|
2019-05-31 18:58:48 +00:00
|
|
|
_LOGGER.debug("Discovered new device %s %s", name, info)
|
2021-05-18 03:51:05 +00:00
|
|
|
assert self.flow_dispatcher is not None
|
2019-05-31 18:58:48 +00:00
|
|
|
|
|
|
|
# If we can handle it as a HomeKit discovery, we do that here.
|
2021-01-07 18:44:34 +00:00
|
|
|
if service_type in HOMEKIT_TYPES:
|
2021-05-18 03:51:05 +00:00
|
|
|
if pending_flow := handle_homekit(self.hass, self.homekit_models, info):
|
2021-06-30 03:13:31 +00:00
|
|
|
self.flow_dispatcher.async_create(pending_flow)
|
2020-05-12 19:59:29 +00:00
|
|
|
# Continue on here as homekit_controller
|
|
|
|
# still needs to get updates on devices
|
|
|
|
# so it can see when the 'c#' field is updated.
|
|
|
|
#
|
|
|
|
# We only send updates to homekit_controller
|
|
|
|
# if the device is already paired in order to avoid
|
|
|
|
# offering a second discovery for the same device
|
2021-05-18 03:51:05 +00:00
|
|
|
if pending_flow and HOMEKIT_PAIRED_STATUS_FLAG in info["properties"]:
|
2020-05-12 19:59:29 +00:00
|
|
|
try:
|
2020-05-14 16:58:40 +00:00
|
|
|
# 0 means paired and not discoverable by iOS clients)
|
2021-03-30 16:48:04 +00:00
|
|
|
if int(info["properties"][HOMEKIT_PAIRED_STATUS_FLAG]):
|
2020-05-12 19:59:29 +00:00
|
|
|
return
|
|
|
|
except ValueError:
|
|
|
|
# HomeKit pairing status unknown
|
|
|
|
# likely bad homekit data
|
|
|
|
return
|
2019-05-31 18:58:48 +00:00
|
|
|
|
2020-12-31 00:06:26 +00:00
|
|
|
if "name" in info:
|
2021-03-30 16:48:04 +00:00
|
|
|
lowercase_name: str | None = info["name"].lower()
|
2020-12-31 00:06:26 +00:00
|
|
|
else:
|
|
|
|
lowercase_name = None
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
if "macaddress" in info["properties"]:
|
|
|
|
uppercase_mac: str | None = info["properties"]["macaddress"].upper()
|
2020-12-31 00:06:26 +00:00
|
|
|
else:
|
|
|
|
uppercase_mac = None
|
|
|
|
|
2021-04-08 19:03:10 +00:00
|
|
|
if "manufacturer" in info["properties"]:
|
|
|
|
lowercase_manufacturer: str | None = info["properties"][
|
|
|
|
"manufacturer"
|
|
|
|
].lower()
|
|
|
|
else:
|
|
|
|
lowercase_manufacturer = None
|
|
|
|
|
2021-01-07 18:44:34 +00:00
|
|
|
# Not all homekit types are currently used for discovery
|
|
|
|
# so not all service type exist in zeroconf_types
|
2021-05-18 03:51:05 +00:00
|
|
|
for matcher in self.zeroconf_types.get(service_type, []):
|
2021-05-12 04:24:42 +00:00
|
|
|
if len(matcher) > 1:
|
|
|
|
if "macaddress" in matcher and (
|
|
|
|
uppercase_mac is None
|
|
|
|
or not fnmatch.fnmatch(uppercase_mac, matcher["macaddress"])
|
2020-12-31 00:06:26 +00:00
|
|
|
):
|
|
|
|
continue
|
2021-05-12 04:24:42 +00:00
|
|
|
if "name" in matcher and (
|
|
|
|
lowercase_name is None
|
|
|
|
or not fnmatch.fnmatch(lowercase_name, matcher["name"])
|
2020-12-31 00:06:26 +00:00
|
|
|
):
|
|
|
|
continue
|
2021-05-12 04:24:42 +00:00
|
|
|
if "manufacturer" in matcher and (
|
|
|
|
lowercase_manufacturer is None
|
|
|
|
or not fnmatch.fnmatch(
|
|
|
|
lowercase_manufacturer, matcher["manufacturer"]
|
2021-04-08 19:03:10 +00:00
|
|
|
)
|
|
|
|
):
|
|
|
|
continue
|
2020-09-11 10:19:21 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
flow: ZeroconfFlow = {
|
|
|
|
"domain": matcher["domain"],
|
|
|
|
"context": {"source": config_entries.SOURCE_ZEROCONF},
|
|
|
|
"data": info,
|
|
|
|
}
|
2021-06-30 03:13:31 +00:00
|
|
|
self.flow_dispatcher.async_create(flow)
|
2019-05-21 22:36:26 +00:00
|
|
|
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def handle_homekit(
|
|
|
|
hass: HomeAssistant, homekit_models: dict[str, str], info: HaServiceInfo
|
2021-05-18 03:51:05 +00:00
|
|
|
) -> ZeroconfFlow | None:
|
2019-05-31 18:58:48 +00:00
|
|
|
"""Handle a HomeKit discovery.
|
|
|
|
|
|
|
|
Return if discovery was forwarded.
|
|
|
|
"""
|
|
|
|
model = None
|
2021-03-30 16:48:04 +00:00
|
|
|
props = info["properties"]
|
2019-05-31 18:58:48 +00:00
|
|
|
|
|
|
|
for key in props:
|
2020-05-12 19:59:29 +00:00
|
|
|
if key.lower() == HOMEKIT_MODEL:
|
2019-05-31 18:58:48 +00:00
|
|
|
model = props[key]
|
|
|
|
break
|
|
|
|
|
|
|
|
if model is None:
|
2021-05-18 03:51:05 +00:00
|
|
|
return None
|
2019-05-31 18:58:48 +00:00
|
|
|
|
2020-08-05 13:50:56 +00:00
|
|
|
for test_model in homekit_models:
|
2020-03-26 22:15:35 +00:00
|
|
|
if (
|
|
|
|
model != test_model
|
2021-05-19 05:20:56 +00:00
|
|
|
and not model.startswith((f"{test_model} ", f"{test_model}-"))
|
|
|
|
and not fnmatch.fnmatch(model, test_model)
|
2020-03-26 22:15:35 +00:00
|
|
|
):
|
2019-05-31 18:58:48 +00:00
|
|
|
continue
|
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
return {
|
|
|
|
"domain": homekit_models[test_model],
|
|
|
|
"context": {"source": config_entries.SOURCE_HOMEKIT},
|
|
|
|
"data": info,
|
|
|
|
}
|
2019-05-31 18:58:48 +00:00
|
|
|
|
2021-05-18 03:51:05 +00:00
|
|
|
return None
|
2019-05-31 18:58:48 +00:00
|
|
|
|
|
|
|
|
2021-06-30 03:13:31 +00:00
|
|
|
def info_from_service(service: AsyncServiceInfo) -> HaServiceInfo | None:
|
2019-05-21 22:36:26 +00:00
|
|
|
"""Return prepared info from mDNS entries."""
|
2021-03-30 16:48:04 +00:00
|
|
|
properties: dict[str, Any] = {"_raw": {}}
|
2019-05-21 22:36:26 +00:00
|
|
|
|
|
|
|
for key, value in service.properties.items():
|
2020-01-22 05:24:59 +00:00
|
|
|
# See https://ietf.org/rfc/rfc6763.html#section-6.4 and
|
|
|
|
# https://ietf.org/rfc/rfc6763.html#section-6.5 for expected encodings
|
|
|
|
# for property keys and values
|
2020-04-18 00:36:46 +00:00
|
|
|
try:
|
|
|
|
key = key.decode("ascii")
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Ignoring invalid key provided by [%s]: %s", service.name, key
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
|
2020-01-22 05:24:59 +00:00
|
|
|
properties["_raw"][key] = value
|
|
|
|
|
2021-03-23 13:36:43 +00:00
|
|
|
with suppress(UnicodeDecodeError):
|
2019-05-21 22:36:26 +00:00
|
|
|
if isinstance(value, bytes):
|
2020-01-22 05:24:59 +00:00
|
|
|
properties[key] = value.decode("utf-8")
|
2019-05-21 22:36:26 +00:00
|
|
|
|
2020-07-23 06:21:57 +00:00
|
|
|
if not service.addresses:
|
|
|
|
return None
|
|
|
|
|
2019-06-04 21:14:51 +00:00
|
|
|
address = service.addresses[0]
|
2019-05-21 22:36:26 +00:00
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
return {
|
2021-08-18 17:33:26 +00:00
|
|
|
"host": str(ip_address(address)),
|
2021-03-30 16:48:04 +00:00
|
|
|
"port": service.port,
|
|
|
|
"hostname": service.server,
|
|
|
|
"type": service.type,
|
|
|
|
"name": service.name,
|
|
|
|
"properties": properties,
|
2019-05-21 22:36:26 +00:00
|
|
|
}
|
|
|
|
|
2020-08-21 12:31:17 +00:00
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def _suppress_invalid_properties(properties: dict) -> None:
|
2020-08-21 12:31:17 +00:00
|
|
|
"""Suppress any properties that will cause zeroconf to fail to startup."""
|
|
|
|
|
|
|
|
for prop, prop_value in properties.items():
|
|
|
|
if not isinstance(prop_value, str):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if len(prop_value.encode("utf-8")) > MAX_PROPERTY_VALUE_LEN:
|
|
|
|
_LOGGER.error(
|
|
|
|
"The property '%s' was suppressed because it is longer than the maximum length of %d bytes: %s",
|
|
|
|
prop,
|
|
|
|
MAX_PROPERTY_VALUE_LEN,
|
|
|
|
prop_value,
|
|
|
|
)
|
|
|
|
properties[prop] = ""
|
|
|
|
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def _truncate_location_name_to_valid(location_name: str) -> str:
|
2020-08-21 12:31:17 +00:00
|
|
|
"""Truncate or return the location name usable for zeroconf."""
|
|
|
|
if len(location_name.encode("utf-8")) < MAX_NAME_LEN:
|
|
|
|
return location_name
|
|
|
|
|
|
|
|
_LOGGER.warning(
|
|
|
|
"The location name was truncated because it is longer than the maximum length of %d bytes: %s",
|
|
|
|
MAX_NAME_LEN,
|
|
|
|
location_name,
|
|
|
|
)
|
|
|
|
return location_name.encode("utf-8")[:MAX_NAME_LEN].decode("utf-8", "ignore")
|