core/homeassistant/components/group.py

359 lines
10 KiB
Python
Raw Normal View History

"""
2016-03-06 03:55:05 +00:00
Provides functionality to group entities.
2015-10-25 14:09:01 +00:00
For more details about this component, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/group/
2015-10-25 14:09:01 +00:00
"""
import logging
import os
2016-03-06 03:55:05 +00:00
import threading
2016-03-28 01:48:51 +00:00
import voluptuous as vol
from homeassistant import config as conf_util, core as ha
from homeassistant.const import (
2016-02-19 05:27:50 +00:00
ATTR_ENTITY_ID, CONF_ICON, CONF_NAME, STATE_CLOSED, STATE_HOME,
STATE_NOT_HOME, STATE_OFF, STATE_ON, STATE_OPEN, STATE_LOCKED,
STATE_UNLOCKED, STATE_UNKNOWN, ATTR_ASSUMED_STATE)
2016-08-09 03:21:40 +00:00
from homeassistant.helpers.entity import Entity, generate_entity_id
from homeassistant.helpers.entity_component import EntityComponent
2016-02-19 05:27:50 +00:00
from homeassistant.helpers.event import track_state_change
2016-03-28 01:48:51 +00:00
import homeassistant.helpers.config_validation as cv
2016-01-24 22:13:39 +00:00
DOMAIN = 'group'
2016-01-24 22:13:39 +00:00
ENTITY_ID_FORMAT = DOMAIN + '.{}'
2016-01-24 22:13:39 +00:00
CONF_ENTITIES = 'entities'
CONF_VIEW = 'view'
ATTR_AUTO = 'auto'
ATTR_ORDER = 'order'
ATTR_VIEW = 'view'
2014-10-29 07:47:55 +00:00
SERVICE_RELOAD = 'reload'
RELOAD_SERVICE_SCHEMA = vol.Schema({})
_LOGGER = logging.getLogger(__name__)
2016-03-28 01:48:51 +00:00
def _conf_preprocess(value):
"""Preprocess alternative configuration formats."""
if not isinstance(value, dict):
2016-03-28 01:48:51 +00:00
value = {CONF_ENTITIES: value}
return value
CONFIG_SCHEMA = vol.Schema({
DOMAIN: cv.ordered_dict(vol.All(_conf_preprocess, {
vol.Optional(CONF_ENTITIES): vol.Any(cv.entity_ids, None),
CONF_VIEW: cv.boolean,
CONF_NAME: cv.string,
CONF_ICON: cv.icon,
}, cv.match_all))
}, extra=vol.ALLOW_EXTRA)
2016-03-28 01:48:51 +00:00
# List of ON/OFF state tuples for groupable states
_GROUP_TYPES = [(STATE_ON, STATE_OFF), (STATE_HOME, STATE_NOT_HOME),
(STATE_OPEN, STATE_CLOSED), (STATE_LOCKED, STATE_UNLOCKED)]
def _get_group_on_off(state):
2016-03-06 03:55:05 +00:00
"""Determine the group on/off states based on a state."""
for states in _GROUP_TYPES:
if state in states:
return states
return None, None
def is_on(hass, entity_id):
2016-03-06 03:55:05 +00:00
"""Test if the group state is in its ON-state."""
state = hass.states.get(entity_id)
if state:
group_on, _ = _get_group_on_off(state.state)
2014-04-15 06:48:00 +00:00
# If we found a group_type, compare to ON-state
return group_on is not None and state.state == group_on
2014-04-15 06:48:00 +00:00
return False
def reload(hass):
"""Reload the automation from config."""
hass.services.call(DOMAIN, SERVICE_RELOAD)
def expand_entity_ids(hass, entity_ids):
2016-03-06 03:55:05 +00:00
"""Return entity_ids with group entity ids replaced by their members."""
2014-04-13 19:59:45 +00:00
found_ids = []
for entity_id in entity_ids:
if not isinstance(entity_id, str):
continue
entity_id = entity_id.lower()
2014-04-13 19:59:45 +00:00
try:
# If entity_id points at a group, expand it
2016-08-09 03:21:40 +00:00
domain, _ = ha.split_entity_id(entity_id)
2014-04-13 19:59:45 +00:00
if domain == DOMAIN:
found_ids.extend(
ent_id for ent_id
2016-02-10 06:43:07 +00:00
in expand_entity_ids(hass, get_entity_ids(hass, entity_id))
2014-04-13 19:59:45 +00:00
if ent_id not in found_ids)
else:
if entity_id not in found_ids:
found_ids.append(entity_id)
except AttributeError:
2016-01-24 06:49:49 +00:00
# Raised by split_entity_id if entity_id is not a string
2014-04-13 19:59:45 +00:00
pass
return found_ids
def get_entity_ids(hass, entity_id, domain_filter=None):
2016-03-06 03:55:05 +00:00
"""Get members of this group."""
group = hass.states.get(entity_id)
if not group or ATTR_ENTITY_ID not in group.attributes:
return []
entity_ids = group.attributes[ATTR_ENTITY_ID]
if not domain_filter:
return entity_ids
domain_filter = domain_filter.lower() + '.'
return [ent_id for ent_id in entity_ids
if ent_id.startswith(domain_filter)]
def setup(hass, config):
2016-03-08 16:55:57 +00:00
"""Setup all groups found definded in the configuration."""
component = EntityComponent(_LOGGER, DOMAIN, hass)
success = _process_config(hass, config, component)
if not success:
return False
descriptions = conf_util.load_yaml_config_file(
os.path.join(os.path.dirname(__file__), 'services.yaml'))
def reload_service_handler(service_call):
"""Remove all groups and load new ones from config."""
conf = component.prepare_reload()
if conf is None:
return
_process_config(hass, conf, component)
hass.services.register(DOMAIN, SERVICE_RELOAD, reload_service_handler,
descriptions[DOMAIN][SERVICE_RELOAD],
schema=RELOAD_SERVICE_SCHEMA)
return True
def _process_config(hass, config, component):
"""Process group configuration."""
2016-01-24 22:13:39 +00:00
for object_id, conf in config.get(DOMAIN, {}).items():
name = conf.get(CONF_NAME, object_id)
entity_ids = conf.get(CONF_ENTITIES) or []
2016-01-24 22:13:39 +00:00
icon = conf.get(CONF_ICON)
view = conf.get(CONF_VIEW)
group = Group(hass, name, entity_ids, icon=icon, view=view,
object_id=object_id)
component.add_entities((group,))
return True
2014-10-22 07:38:22 +00:00
2015-04-23 05:19:21 +00:00
class Group(Entity):
2016-03-06 03:55:05 +00:00
"""Track a group of entity ids."""
2016-01-24 22:13:39 +00:00
# pylint: disable=too-many-instance-attributes, too-many-arguments
def __init__(self, hass, name, entity_ids=None, user_defined=True,
icon=None, view=False, object_id=None):
2016-03-06 03:55:05 +00:00
"""Initialize a group."""
2015-01-09 04:02:34 +00:00
self.hass = hass
2015-04-23 05:19:21 +00:00
self._name = name
self._state = STATE_UNKNOWN
2016-01-24 22:13:39 +00:00
self._order = len(hass.states.entity_ids(DOMAIN))
self._user_defined = user_defined
self._icon = icon
self._view = view
self.entity_id = generate_entity_id(
ENTITY_ID_FORMAT, object_id or name, hass=hass)
2015-01-09 04:02:34 +00:00
self.tracking = []
2015-04-23 05:19:21 +00:00
self.group_on = None
self.group_off = None
2016-02-21 03:11:02 +00:00
self._assumed_state = False
2016-03-06 03:55:05 +00:00
self._lock = threading.Lock()
2016-08-26 06:25:35 +00:00
self._unsub_state_changed = None
2015-01-09 04:02:34 +00:00
if entity_ids is not None:
self.update_tracked_entity_ids(entity_ids)
else:
2015-04-23 05:19:21 +00:00
self.update_ha_state(True)
@property
def should_poll(self):
2016-03-06 03:55:05 +00:00
"""No need to poll because groups will update themselves."""
2015-04-23 05:19:21 +00:00
return False
@property
def name(self):
2016-03-08 16:55:57 +00:00
"""Return the name of the group."""
2015-04-23 05:19:21 +00:00
return self._name
2015-01-09 04:02:34 +00:00
@property
def state(self):
2016-03-08 16:55:57 +00:00
"""Return the state of the group."""
2015-04-23 05:19:21 +00:00
return self._state
2016-01-24 22:13:39 +00:00
@property
def icon(self):
2016-03-08 16:55:57 +00:00
"""Return the icon of the group."""
2016-01-24 22:13:39 +00:00
return self._icon
@property
def hidden(self):
2016-03-08 16:55:57 +00:00
"""If group should be hidden or not."""
return not self._user_defined or self._view
2015-01-09 04:02:34 +00:00
@property
2015-04-23 05:19:21 +00:00
def state_attributes(self):
2016-03-08 16:55:57 +00:00
"""Return the state attributes for the group."""
2016-01-24 22:13:39 +00:00
data = {
2015-01-09 04:02:34 +00:00
ATTR_ENTITY_ID: self.tracking,
2016-01-24 22:13:39 +00:00
ATTR_ORDER: self._order,
2015-01-09 04:02:34 +00:00
}
2016-01-24 22:13:39 +00:00
if not self._user_defined:
data[ATTR_AUTO] = True
if self._view:
data[ATTR_VIEW] = True
return data
2016-02-21 03:11:02 +00:00
@property
def assumed_state(self):
2016-03-06 03:55:05 +00:00
"""Test if any member has an assumed state."""
2016-02-21 03:11:02 +00:00
return self._assumed_state
2015-01-09 04:02:34 +00:00
def update_tracked_entity_ids(self, entity_ids):
2016-03-06 03:55:05 +00:00
"""Update the member entity IDs."""
2015-01-09 04:02:34 +00:00
self.stop()
self.tracking = tuple(ent_id.lower() for ent_id in entity_ids)
2015-01-09 04:02:34 +00:00
self.group_on, self.group_off = None, None
2015-04-23 05:19:21 +00:00
self.update_ha_state(True)
2015-01-09 04:02:34 +00:00
self.start()
2015-01-09 04:02:34 +00:00
def start(self):
2016-03-06 03:55:05 +00:00
"""Start tracking members."""
2016-08-26 06:25:35 +00:00
self._unsub_state_changed = track_state_change(
2015-08-04 16:13:35 +00:00
self.hass, self.tracking, self._state_changed_listener)
2015-01-09 04:02:34 +00:00
def stop(self):
2016-03-08 16:55:57 +00:00
"""Unregister the group from Home Assistant."""
self.remove()
2015-04-23 05:19:21 +00:00
def update(self):
2016-03-06 03:55:05 +00:00
"""Query all members and determine current group state."""
2015-04-23 05:19:21 +00:00
self._state = STATE_UNKNOWN
2016-02-21 03:11:02 +00:00
self._update_group_state()
def remove(self):
"""Remove group from HASS."""
super().remove()
if self._unsub_state_changed:
self._unsub_state_changed()
self._unsub_state_changed = None
2016-02-21 03:11:02 +00:00
def _state_changed_listener(self, entity_id, old_state, new_state):
2016-03-06 03:55:05 +00:00
"""Respond to a member state changing."""
2016-02-21 03:11:02 +00:00
self._update_group_state(new_state)
self.update_ha_state()
@property
def _tracking_states(self):
2016-03-08 16:55:57 +00:00
"""The states that the group is tracking."""
2016-02-21 03:11:02 +00:00
states = []
2015-04-23 05:19:21 +00:00
for entity_id in self.tracking:
state = self.hass.states.get(entity_id)
if state is not None:
2016-02-21 03:11:02 +00:00
states.append(state)
2015-04-23 05:19:21 +00:00
2016-02-21 03:11:02 +00:00
return states
def _update_group_state(self, tr_state=None):
"""Update group state.
2015-04-23 05:19:21 +00:00
2016-02-21 03:11:02 +00:00
Optionally you can provide the only state changed since last update
allowing this method to take shortcuts.
"""
# pylint: disable=too-many-branches
# To store current states of group entities. Might not be needed.
2016-03-06 03:55:05 +00:00
with self._lock:
states = None
gr_state = self._state
gr_on = self.group_on
gr_off = self.group_off
# We have not determined type of group yet
if gr_on is None:
if tr_state is None:
states = self._tracking_states
for state in states:
gr_on, gr_off = \
_get_group_on_off(state.state)
if gr_on is not None:
break
else:
gr_on, gr_off = _get_group_on_off(tr_state.state)
if gr_on is not None:
self.group_on, self.group_off = gr_on, gr_off
# We cannot determine state of the group
if gr_on is None:
return
if tr_state is None or ((gr_state == gr_on and
tr_state.state == gr_off) or
tr_state.state not in (gr_on, gr_off)):
2016-03-06 03:55:05 +00:00
if states is None:
states = self._tracking_states
if any(state.state == gr_on for state in states):
self._state = gr_on
else:
self._state = gr_off
elif tr_state.state in (gr_on, gr_off):
self._state = tr_state.state
if tr_state is None or self._assumed_state and \
not tr_state.attributes.get(ATTR_ASSUMED_STATE):
if states is None:
states = self._tracking_states
self._assumed_state = any(
state.attributes.get(ATTR_ASSUMED_STATE) for state
in states)
elif tr_state.attributes.get(ATTR_ASSUMED_STATE):
self._assumed_state = True