List entity_ids in config and only react to them (#2144)
* List entity_ids in config and only react to them This allows us to define a list of entity_ids in the config to make the template sensor, binary sensor and switch only react to state changes of these entities instead of listening to all state changes. * Forgot to import the track_state_change function * Changed test for added entity_ids to config * Use default MATCH_ALL and remove event_listener
This commit is contained in:
1 parent
19522b1f39
commit
65fbba0e79
4 files changed
+38
-21
No files matched your search
@@ -8,12 +8,14 @@ import logging
|
||||
|
||||
from homeassistant.components.switch import ENTITY_ID_FORMAT, SwitchDevice
|
||||
from homeassistant.const import (
|
||||
ATTR_FRIENDLY_NAME, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON)
|
||||
ATTR_FRIENDLY_NAME, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON,
|
||||
ATTR_ENTITY_ID, MATCH_ALL)
|
||||
from homeassistant.core import EVENT_STATE_CHANGED
|
||||
from homeassistant.exceptions import TemplateError
|
||||
from homeassistant.helpers.entity import generate_entity_id
|
||||
from homeassistant.helpers.service import call_from_config
|
||||
from homeassistant.helpers import template
|
||||
from homeassistant.helpers.event import track_state_change
|
||||
from homeassistant.util import slugify
|
||||
|
||||
CONF_SWITCHES = 'switches'
|
||||
@@ -58,6 +60,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"Missing action for switch %s", device)
|
||||
continue
|
||||
|
||||
entity_ids = device_config.get(ATTR_ENTITY_ID, MATCH_ALL)
|
||||
|
||||
switches.append(
|
||||
SwitchTemplate(
|
||||
hass,
|
||||
@@ -65,7 +69,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
friendly_name,
|
||||
state_template,
|
||||
on_action,
|
||||
off_action)
|
||||
off_action,
|
||||
entity_ids)
|
||||
)
|
||||
if not switches:
|
||||
_LOGGER.error("No switches added")
|
||||
@@ -79,7 +84,7 @@ class SwitchTemplate(SwitchDevice):
|
||||
|
||||
# pylint: disable=too-many-arguments
|
||||
def __init__(self, hass, device_id, friendly_name, state_template,
|
||||
on_action, off_action):
|
||||
on_action, off_action, entity_ids):
|
||||
"""Initialize the Template switch."""
|
||||
self.hass = hass
|
||||
self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, device_id,
|
||||
@@ -92,12 +97,12 @@ class SwitchTemplate(SwitchDevice):
|
||||
|
||||
self.update()
|
||||
|
||||
def template_switch_event_listener(event):
|
||||
def template_switch_state_listener(self, entity, old_state, new_state):
|
||||
"""Called when the target device changes state."""
|
||||
self.update_ha_state(True)
|
||||
|
||||
hass.bus.listen(EVENT_STATE_CHANGED,
|
||||
template_switch_event_listener)
|
||||
track_state_change(hass, entity_ids,
|
||||
template_switch_state_listener)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
|
||||
Reference in new issue
Block a user