Merge pull request #840 from balloob/reproduce-group

Reproduce state upgrades
This commit is contained in:
Paulus Schoutsen committed 2016-01-03 11:36:45 -08:00
commit 2478623ebc
2 files changed
+173 -13

No files matched your search

+25 -13
View File
@@ -1,9 +1,6 @@
"""
homeassistant.helpers.state
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Helpers that help with state related things.
"""
"""Helpers that help with state related things."""
from collections import defaultdict
import json
import logging
from homeassistant.core import State
@@ -25,32 +22,36 @@ class TrackStates(object):
that have changed since the start time to the return list when with-block
is exited.
"""
def __init__(self, hass):
"""Initialize a TrackStates block."""
self.hass = hass
self.states = []
def __enter__(self):
"""Record time from which to track changes."""
self.now = dt_util.utcnow()
return self.states
def __exit__(self, exc_type, exc_value, traceback):
"""Add changes states to changes list."""
self.states.extend(get_changed_since(self.hass.states.all(), self.now))
def get_changed_since(states, utc_point_in_time):
"""
Returns all states that have been changed since utc_point_in_time.
"""
"""List of states that have been changed since utc_point_in_time."""
point_in_time = dt_util.strip_microseconds(utc_point_in_time)
return [state for state in states if state.last_updated >= point_in_time]
def reproduce_state(hass, states, blocking=False):
""" Takes in a state and will try to have the entity reproduce it. """
"""Reproduce given state."""
if isinstance(states, State):
states = [states]
to_call = defaultdict(list)
for state in states:
current_state = hass.states.get(state.entity_id)
@@ -76,7 +77,18 @@ def reproduce_state(hass, states, blocking=False):
state)
continue
service_data = dict(state.attributes)
service_data[ATTR_ENTITY_ID] = state.entity_id
if state.domain == 'group':
service_domain = 'homeassistant'
else:
service_domain = state.domain
hass.services.call(state.domain, service, service_data, blocking)
# We group service calls for entities by service call
# json used to create a hashable version of dict with maybe lists in it
key = (service_domain, service,
json.dumps(state.attributes, sort_keys=True))
to_call[key].append(state.entity_id)
for (service_domain, service, service_data), entity_ids in to_call.items():
data = json.loads(service_data)
data[ATTR_ENTITY_ID] = entity_ids
hass.services.call(service_domain, service, data, blocking)