Deduplicate MQTT entity discovery code (#44970)

This commit is contained in:
Erik Montnemery 2021-01-09 14:37:33 +01:00 committed by GitHub
parent 2d9eb25142
commit 6dd6d9b368
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 145 additions and 413 deletions

View file

@ -1,4 +1,5 @@
"""Support for MQTT fans."""
import functools
import logging
import voluptuous as vol
@ -25,10 +26,6 @@ from homeassistant.const import (
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
@ -42,9 +39,7 @@ from . import (
subscription,
)
from .. import mqtt
from .const import ATTR_DISCOVERY_HASH
from .debug_info import log_messages
from .discovery import MQTT_DISCOVERY_DONE, MQTT_DISCOVERY_NEW, clear_discovery_hash
from .mixins import (
MQTT_AVAILABILITY_SCHEMA,
MQTT_ENTITY_DEVICE_INFO_SCHEMA,
@ -53,6 +48,7 @@ from .mixins import (
MqttAvailability,
MqttDiscoveryUpdate,
MqttEntityDeviceInfo,
async_setup_entry_helper,
)
_LOGGER = logging.getLogger(__name__)
@ -124,35 +120,20 @@ async def async_setup_platform(
):
"""Set up MQTT fan through configuration.yaml."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
await _async_setup_entity(hass, config, async_add_entities)
await _async_setup_entity(hass, async_add_entities, config)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up MQTT fan dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT fan."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(
hass, config, async_add_entities, config_entry, discovery_data
)
except Exception:
discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
clear_discovery_hash(hass, discovery_hash)
async_dispatcher_send(
hass, MQTT_DISCOVERY_DONE.format(discovery_hash), None
)
raise
async_dispatcher_connect(
hass, MQTT_DISCOVERY_NEW.format(fan.DOMAIN, "mqtt"), async_discover
setup = functools.partial(
_async_setup_entity, hass, async_add_entities, config_entry=config_entry
)
await async_setup_entry_helper(hass, fan.DOMAIN, setup, PLATFORM_SCHEMA)
async def _async_setup_entity(
hass, config, async_add_entities, config_entry=None, discovery_data=None
hass, async_add_entities, config, config_entry=None, discovery_data=None
):
"""Set up the MQTT fan."""
async_add_entities([MqttFan(hass, config, config_entry, discovery_data)])