Streamline setup of deCONZ button platform (#70593)

* Streamline setup of deCONZ button platform

* Update homeassistant/components/deconz/button.py

Co-authored-by: J. Nick Koston <nick@koston.org>

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Robert Svensson 2022-04-24 22:58:36 +02:00 committed by GitHub
parent bab9f4ba76
commit 0726bc2cab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from pydeconz.models.event import EventType
from pydeconz.models.scene import Scene as PydeconzScene from pydeconz.models.scene import Scene as PydeconzScene
from homeassistant.components.button import ( from homeassistant.components.button import (
@ -13,7 +14,6 @@ from homeassistant.components.button import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
@ -57,34 +57,23 @@ async def async_setup_entry(
gateway.entities[DOMAIN] = set() gateway.entities[DOMAIN] = set()
@callback @callback
def async_add_scene(scenes: list[PydeconzScene] | None = None) -> None: def async_add_scene(_: EventType, scene_id: str) -> None:
"""Add scene button from deCONZ.""" """Add scene button from deCONZ."""
entities = [] scene = gateway.api.scenes[scene_id]
async_add_entities(
if scenes is None: DeconzButton(scene, gateway, description)
scenes = list(gateway.api.scenes.values()) for description in ENTITY_DESCRIPTIONS.get(PydeconzScene, [])
)
for scene in scenes:
known_entities = set(gateway.entities[DOMAIN])
for description in ENTITY_DESCRIPTIONS.get(PydeconzScene, []):
new_entity = DeconzButton(scene, gateway, description)
if new_entity.unique_id not in known_entities:
entities.append(new_entity)
if entities:
async_add_entities(entities)
config_entry.async_on_unload( config_entry.async_on_unload(
async_dispatcher_connect( gateway.api.scenes.subscribe(
hass,
gateway.signal_new_scene,
async_add_scene, async_add_scene,
EventType.ADDED,
) )
) )
async_add_scene() for scene_id in gateway.api.scenes:
async_add_scene(EventType.ADDED, scene_id)
class DeconzButton(DeconzSceneMixin, ButtonEntity): class DeconzButton(DeconzSceneMixin, ButtonEntity):