2020-08-12 14:08:33 +00:00
|
|
|
"""Zeroconf usage utility to warn about multiple instances."""
|
|
|
|
|
2021-03-23 13:36:43 +00:00
|
|
|
from contextlib import suppress
|
2020-08-12 14:08:33 +00:00
|
|
|
import logging
|
2021-03-30 16:48:04 +00:00
|
|
|
from typing import Any
|
2020-08-12 14:08:33 +00:00
|
|
|
|
|
|
|
import zeroconf
|
|
|
|
|
|
|
|
from homeassistant.helpers.frame import (
|
|
|
|
MissingIntegrationFrame,
|
|
|
|
get_integration_frame,
|
|
|
|
report_integration,
|
|
|
|
)
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
from .models import HaZeroconf
|
|
|
|
|
2020-08-12 14:08:33 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def install_multiple_zeroconf_catcher(hass_zc: HaZeroconf) -> None:
|
2020-08-12 14:08:33 +00:00
|
|
|
"""Wrap the Zeroconf class to return the shared instance if multiple instances are detected."""
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def new_zeroconf_new(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> HaZeroconf:
|
2020-08-12 14:08:33 +00:00
|
|
|
_report(
|
|
|
|
"attempted to create another Zeroconf instance. Please use the shared Zeroconf via await homeassistant.components.zeroconf.async_get_instance(hass)",
|
|
|
|
)
|
|
|
|
return hass_zc
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
def new_zeroconf_init(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> None:
|
2020-08-12 14:08:33 +00:00
|
|
|
return
|
|
|
|
|
2021-03-30 16:48:04 +00:00
|
|
|
zeroconf.Zeroconf.__new__ = new_zeroconf_new # type: ignore
|
|
|
|
zeroconf.Zeroconf.__init__ = new_zeroconf_init # type: ignore
|
2020-08-12 14:08:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _report(what: str) -> None:
|
|
|
|
"""Report incorrect usage.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
|
|
|
integration_frame = None
|
|
|
|
|
2021-03-23 13:36:43 +00:00
|
|
|
with suppress(MissingIntegrationFrame):
|
2020-08-12 14:08:33 +00:00
|
|
|
integration_frame = get_integration_frame(exclude_integrations={"zeroconf"})
|
|
|
|
|
|
|
|
if not integration_frame:
|
|
|
|
_LOGGER.warning(
|
2021-03-19 14:26:36 +00:00
|
|
|
"Detected code that %s; Please report this issue", what, stack_info=True
|
2020-08-12 14:08:33 +00:00
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
report_integration(what, integration_frame)
|