Skip to content

Commit

Permalink
Add Zeroconf singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Mar 7, 2020
1 parent 1750f28 commit a23d9a6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
14 changes: 11 additions & 3 deletions custom_components/sonoff/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import voluptuous as vol
from aiohttp import ClientSession
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_DEVICES, \
CONF_NAME, CONF_DEVICE_CLASS
CONF_NAME, CONF_DEVICE_CLASS, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import ServiceCall
from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.helpers.aiohttp_client import async_get_clientsession
Expand Down Expand Up @@ -44,6 +44,8 @@


async def async_setup(hass: HomeAssistantType, hass_config: dict):
utils.init_zeroconf_singleton(hass)

config = hass_config[DOMAIN]

# load devices from file in config dir
Expand Down Expand Up @@ -137,6 +139,8 @@ def add_device(devicecfg: dict, state: dict):
listener = EWeLinkListener(devices, session)
listener.listen(add_device)

hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, listener.stop)

async def send_command(call: ServiceCall):
data = dict(call.data)

Expand Down Expand Up @@ -164,17 +168,21 @@ def __init__(self, devices: dict, session: ClientSession):
self.session = session

self._add_device = None
self._zeroconf = None

def listen(self, add_device: Callable):
"""Начать поиск всех устройств Sonoff в сети.
:param add_device: функция, которая будет вызываться при обнаружении
нового устройства
"""
from homeassistant.components.zeroconf import Zeroconf
self._add_device = add_device
self._zeroconf = Zeroconf()
ServiceBrowser(self._zeroconf, '_ewelink._tcp.local.', listener=self)

zeroconf = Zeroconf()
ServiceBrowser(zeroconf, '_ewelink._tcp.local.', listener=self)
def stop(self, *args):
self._zeroconf.close()

def add_service(self, zeroconf: Zeroconf, type_: str, name: str):
"""Стандартная функция ServiceBrowser."""
Expand Down
17 changes: 17 additions & 0 deletions custom_components/sonoff/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,23 @@
_LOGGER = logging.getLogger(__name__)


def init_zeroconf_singleton(hass):
"""Generate only one Zeroconf. Component must be loaded before Zeroconf."""
from homeassistant.components import zeroconf
if isinstance(zeroconf.Zeroconf, type):
def zeroconf_singleton():
if 'zeroconf' not in hass.data:
from zeroconf import Zeroconf
_LOGGER.debug("Generate zeroconf singleton")
hass.data['zeroconf'] = Zeroconf()
else:
_LOGGER.debug("Use zeroconf singleton")
return hass.data['zeroconf']

_LOGGER.debug("Init zeroconf singleton")
zeroconf.Zeroconf = zeroconf_singleton


def _params(**kwargs):
"""Generate params for sonoff API. Pretend mobile application."""
return {
Expand Down

0 comments on commit a23d9a6

Please sign in to comment.