2013-09-25 01:39:58 +00:00
|
|
|
"""
|
|
|
|
homeassistant
|
|
|
|
~~~~~~~~~~~~~
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
Home Assistant is a Home Automation framework for observing the state
|
2014-01-20 07:37:40 +00:00
|
|
|
of entities and react to changes.
|
2013-09-25 01:39:58 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
import time
|
2013-09-30 07:20:27 +00:00
|
|
|
import logging
|
|
|
|
import threading
|
2014-01-20 07:37:40 +00:00
|
|
|
from collections import namedtuple
|
2014-01-20 03:10:40 +00:00
|
|
|
import datetime as dt
|
|
|
|
|
|
|
|
import homeassistant.util as util
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
MATCH_ALL = '*'
|
2013-11-20 07:48:08 +00:00
|
|
|
|
2014-01-05 01:55:05 +00:00
|
|
|
DOMAIN = "homeassistant"
|
|
|
|
|
|
|
|
STATE_ON = "on"
|
|
|
|
STATE_OFF = "off"
|
|
|
|
STATE_NOT_HOME = 'device_not_home'
|
|
|
|
STATE_HOME = 'device_home'
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
SERVICE_TURN_ON = "turn_on"
|
|
|
|
SERVICE_TURN_OFF = "turn_off"
|
2013-11-20 07:48:08 +00:00
|
|
|
SERVICE_HOMEASSISTANT_STOP = "stop"
|
|
|
|
|
2013-11-11 22:58:57 +00:00
|
|
|
EVENT_HOMEASSISTANT_START = "homeassistant.start"
|
2013-09-30 07:20:27 +00:00
|
|
|
EVENT_STATE_CHANGED = "state_changed"
|
|
|
|
EVENT_TIME_CHANGED = "time_changed"
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
TIMER_INTERVAL = 10 # seconds
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
# We want to be able to fire every time a minute starts (seconds=0).
|
|
|
|
# We want this so other modules can use that to make sure they fire
|
|
|
|
# every minute.
|
|
|
|
assert 60 % TIMER_INTERVAL == 0, "60 % TIMER_INTERVAL should be 0!"
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def start_home_assistant(bus):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Start home assistant. """
|
2013-11-11 22:58:57 +00:00
|
|
|
request_shutdown = threading.Event()
|
|
|
|
|
2014-01-05 01:55:05 +00:00
|
|
|
bus.register_service(DOMAIN, SERVICE_HOMEASSISTANT_STOP,
|
2013-11-20 07:48:08 +00:00
|
|
|
lambda service: request_shutdown.set())
|
2013-11-11 22:58:57 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
Timer(bus)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
bus.fire_event(EVENT_HOMEASSISTANT_START)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-04 21:48:17 +00:00
|
|
|
while not request_shutdown.isSet():
|
2013-09-30 07:20:27 +00:00
|
|
|
try:
|
|
|
|
time.sleep(1)
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
break
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
def _process_match_param(parameter):
|
|
|
|
""" Wraps parameter in a list if it is not one and returns it. """
|
2014-01-23 03:40:19 +00:00
|
|
|
if not parameter:
|
2014-01-20 03:10:40 +00:00
|
|
|
return MATCH_ALL
|
|
|
|
elif isinstance(parameter, list):
|
|
|
|
return parameter
|
|
|
|
else:
|
|
|
|
return [parameter]
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def _matcher(subject, pattern):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Returns True if subject matches the pattern.
|
2013-10-08 06:55:19 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
Pattern is either a list of allowed subjects or a `MATCH_ALL`.
|
2013-10-08 06:55:19 +00:00
|
|
|
"""
|
2014-01-20 03:10:40 +00:00
|
|
|
return MATCH_ALL == pattern or subject in pattern
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def split_entity_id(entity_id):
|
|
|
|
""" Splits a state entity_id into domain, object_id. """
|
|
|
|
return entity_id.split(".", 1)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def filter_entity_ids(entity_ids, domain_filter=None, strip_domain=False):
|
|
|
|
""" Filter a list of entities based on domain. Setting strip_domain
|
2014-01-05 01:55:05 +00:00
|
|
|
will only return the object_ids. """
|
|
|
|
return [
|
2014-01-20 07:37:40 +00:00
|
|
|
split_entity_id(entity_id)[1] if strip_domain else entity_id
|
|
|
|
for entity_id in entity_ids if
|
|
|
|
not domain_filter or entity_id.startswith(domain_filter)
|
2014-01-05 01:55:05 +00:00
|
|
|
]
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def track_state_change(bus, entity_id, action, from_state=None, to_state=None):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Helper method to track specific state changes. """
|
2014-01-20 03:10:40 +00:00
|
|
|
from_state = _process_match_param(from_state)
|
|
|
|
to_state = _process_match_param(to_state)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
def listener(event):
|
|
|
|
""" State change listener that listens for specific state changes. """
|
2014-01-20 07:37:40 +00:00
|
|
|
if entity_id == event.data['entity_id'] and \
|
2014-01-20 03:10:40 +00:00
|
|
|
_matcher(event.data['old_state'].state, from_state) and \
|
|
|
|
_matcher(event.data['new_state'].state, to_state):
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
action(event.data['entity_id'],
|
2013-10-08 06:55:19 +00:00
|
|
|
event.data['old_state'],
|
|
|
|
event.data['new_state'])
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
bus.listen_event(EVENT_STATE_CHANGED, listener)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
2013-11-20 07:48:08 +00:00
|
|
|
def track_time_change(bus, action,
|
2014-01-20 03:10:40 +00:00
|
|
|
year=None, month=None, day=None,
|
|
|
|
hour=None, minute=None, second=None,
|
2013-10-08 06:55:19 +00:00
|
|
|
point_in_time=None, listen_once=False):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Adds a listener that will listen for a specified or matching time. """
|
2014-01-20 05:39:13 +00:00
|
|
|
pmp = _process_match_param
|
|
|
|
year, month, day = pmp(year), pmp(month), pmp(day)
|
|
|
|
hour, minute, second = pmp(hour), pmp(minute), pmp(second)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def listener(event):
|
|
|
|
""" Listens for matching time_changed events. """
|
2014-01-20 03:10:40 +00:00
|
|
|
now = event.data['now']
|
2013-10-28 00:39:54 +00:00
|
|
|
|
2014-01-20 05:39:13 +00:00
|
|
|
mat = _matcher
|
|
|
|
|
2013-11-10 17:31:34 +00:00
|
|
|
if (point_in_time and now > point_in_time) or \
|
2013-11-11 00:46:48 +00:00
|
|
|
(not point_in_time and
|
2014-01-20 05:39:13 +00:00
|
|
|
mat(now.year, year) and
|
|
|
|
mat(now.month, month) and
|
|
|
|
mat(now.day, day) and
|
|
|
|
mat(now.hour, hour) and
|
|
|
|
mat(now.minute, minute) and
|
|
|
|
mat(now.second, second)):
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
# point_in_time are exact points in time
|
|
|
|
# so we always remove it after fire
|
2013-10-09 01:50:30 +00:00
|
|
|
if listen_once or point_in_time:
|
2013-11-20 07:48:08 +00:00
|
|
|
event.bus.remove_event_listener(EVENT_TIME_CHANGED, listener)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-28 00:39:54 +00:00
|
|
|
action(now)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
bus.listen_event(EVENT_TIME_CHANGED, listener)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
ServiceCall = namedtuple("ServiceCall", ["bus", "domain", "service", "data"])
|
|
|
|
Event = namedtuple("Event", ["bus", "event_type", "data"])
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
class Bus(object):
|
|
|
|
""" Class that allows different components to communicate via services
|
|
|
|
and events.
|
|
|
|
"""
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
2014-01-20 03:10:40 +00:00
|
|
|
self._event_listeners = {}
|
2013-11-20 07:48:08 +00:00
|
|
|
self._services = {}
|
2013-09-25 01:39:58 +00:00
|
|
|
self.logger = logging.getLogger(__name__)
|
2014-01-20 05:39:57 +00:00
|
|
|
self.event_lock = threading.Lock()
|
|
|
|
self.service_lock = threading.Lock()
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-01 19:28:18 +00:00
|
|
|
@property
|
2013-11-20 07:48:08 +00:00
|
|
|
def services(self):
|
|
|
|
""" Dict with per domain a list of available services. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.service_lock:
|
|
|
|
return {domain: self._services[domain].keys()
|
|
|
|
for domain in self._services}
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def event_listeners(self):
|
|
|
|
""" Dict with events that is being listened for and the number
|
|
|
|
of listeners.
|
|
|
|
"""
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.event_lock:
|
|
|
|
return {key: len(self._event_listeners[key])
|
|
|
|
for key in self._event_listeners}
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
def call_service(self, domain, service, service_data=None):
|
|
|
|
""" Calls a service. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.service_lock:
|
|
|
|
try:
|
|
|
|
self._services[domain][service]
|
|
|
|
except KeyError:
|
|
|
|
# Domain or Service does not exist
|
|
|
|
raise ServiceDoesNotExistException(
|
|
|
|
"Service does not exist: {}/{}".format(domain, service))
|
2013-11-20 07:48:08 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
service_data = service_data or {}
|
2013-11-20 07:48:08 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
def run():
|
|
|
|
""" Executes a service. """
|
|
|
|
service_call = ServiceCall(self, domain, service, service_data)
|
2013-11-20 07:48:08 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
try:
|
|
|
|
self._services[domain][service](service_call)
|
|
|
|
except Exception: # pylint: disable=broad-except
|
|
|
|
self.logger.exception(
|
|
|
|
"Bus:Exception in service {}/{}".format(
|
|
|
|
domain, service))
|
2013-11-20 07:48:08 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
# We dont want the bus to be blocking - run in a thread.
|
|
|
|
threading.Thread(target=run).start()
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
def register_service(self, domain, service, service_callback):
|
|
|
|
""" Register a service. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.service_lock:
|
|
|
|
try:
|
|
|
|
self._services[domain][service] = service_callback
|
|
|
|
except KeyError:
|
|
|
|
# Domain does not exist yet
|
|
|
|
self._services[domain] = {service: service_callback}
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
def fire_event(self, event_type, event_data=None):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Fire an event. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.event_lock:
|
|
|
|
# Copy the list of the current listeners because some listeners
|
|
|
|
# choose to remove themselves as a listener while being executed
|
|
|
|
# which causes the iterator to be confused.
|
|
|
|
get = self._event_listeners.get
|
|
|
|
listeners = get(MATCH_ALL, []) + get(event_type, [])
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
if not listeners:
|
|
|
|
return
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
event_data = event_data or {}
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
self.logger.info("Bus:Event {}: {}".format(
|
|
|
|
event_type, event_data))
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
def run():
|
|
|
|
""" Fire listeners for event. """
|
|
|
|
event = Event(self, event_type, event_data)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
for listener in listeners:
|
|
|
|
try:
|
|
|
|
listener(event)
|
|
|
|
except Exception: # pylint: disable=broad-except
|
|
|
|
self.logger.exception(
|
|
|
|
"Bus:Exception in event listener")
|
2013-10-09 01:50:30 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
# We dont want the bus to be blocking - run in a thread.
|
|
|
|
threading.Thread(target=run).start()
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def listen_event(self, event_type, listener):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Listen for all events or events of a specific type.
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
2013-10-08 06:55:19 +00:00
|
|
|
as event_type.
|
|
|
|
"""
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.event_lock:
|
|
|
|
try:
|
|
|
|
self._event_listeners[event_type].append(listener)
|
|
|
|
except KeyError: # event_type did not exist
|
|
|
|
self._event_listeners[event_type] = [listener]
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def listen_once_event(self, event_type, listener):
|
2013-10-23 23:29:33 +00:00
|
|
|
""" Listen once for event of a specific type.
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
2013-10-23 23:29:33 +00:00
|
|
|
as event_type.
|
2013-10-25 10:05:34 +00:00
|
|
|
|
|
|
|
Note: at the moment it is impossible to remove a one time listener.
|
2013-10-23 23:29:33 +00:00
|
|
|
"""
|
|
|
|
def onetime_listener(event):
|
|
|
|
""" Removes listener from eventbus and then fires listener. """
|
2013-11-20 07:48:08 +00:00
|
|
|
self.remove_event_listener(event_type, onetime_listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
|
|
|
listener(event)
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
self.listen_event(event_type, onetime_listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def remove_event_listener(self, event_type, listener):
|
2013-10-09 01:50:30 +00:00
|
|
|
""" Removes a listener of a specific event_type. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.event_lock:
|
|
|
|
try:
|
|
|
|
self._event_listeners[event_type].remove(listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
# delete event_type list if empty
|
|
|
|
if not self._event_listeners[event_type]:
|
|
|
|
del self._event_listeners[event_type]
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
except (KeyError, ValueError):
|
|
|
|
# KeyError is key event_type did not exist
|
|
|
|
# ValueError if the list [event_type] did not contain listener
|
|
|
|
pass
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
class State(object):
|
|
|
|
""" Object to represent a state within the state machine. """
|
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
__slots__ = ['entity_id','state','attributes','last_changed']
|
|
|
|
|
|
|
|
def __init__(self, entity_id, state, attributes=None, last_changed=None):
|
|
|
|
self.entity_id = entity_id
|
2014-01-20 03:10:40 +00:00
|
|
|
self.state = state
|
|
|
|
self.attributes = attributes or {}
|
|
|
|
last_changed = last_changed or dt.datetime.now()
|
|
|
|
|
|
|
|
# Strip microsecond from last_changed else we cannot guarantee
|
2014-01-23 03:40:19 +00:00
|
|
|
# state == State.from_dict(state.as_dict())
|
|
|
|
# This behavior occurs because to_dict uses datetime_to_str
|
|
|
|
# which strips microseconds
|
2014-01-20 03:10:40 +00:00
|
|
|
if last_changed.microsecond:
|
|
|
|
self.last_changed = last_changed - dt.timedelta(
|
|
|
|
microseconds=last_changed.microsecond)
|
|
|
|
else:
|
|
|
|
self.last_changed = last_changed
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def copy(self):
|
|
|
|
""" Creates a copy of itself. """
|
2014-01-23 03:40:19 +00:00
|
|
|
return State(self.entity_id, self.state,
|
|
|
|
dict(self.attributes), self.last_changed)
|
2014-01-20 07:37:40 +00:00
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
def as_dict(self):
|
2014-01-20 03:10:40 +00:00
|
|
|
""" Converts State to a dict to be used within JSON.
|
2014-01-23 03:40:19 +00:00
|
|
|
Ensures: state == State.from_dict(state.as_dict()) """
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
return {'entity_id': self.entity_id,
|
|
|
|
'state': self.state,
|
|
|
|
'attributes': self.attributes,
|
|
|
|
'last_changed': util.datetime_to_str(self.last_changed)}
|
2014-01-20 03:10:40 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2014-01-23 03:40:19 +00:00
|
|
|
def from_dict(json_dict):
|
2014-01-20 03:10:40 +00:00
|
|
|
""" Static method to create a state from a dict.
|
|
|
|
Ensures: state == State.from_json_dict(state.to_json_dict()) """
|
|
|
|
|
|
|
|
try:
|
|
|
|
last_changed = json_dict.get('last_changed')
|
|
|
|
|
|
|
|
if last_changed:
|
|
|
|
last_changed = util.str_to_datetime(last_changed)
|
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
return State(json_dict['entity_id'],
|
|
|
|
json_dict['state'],
|
2014-01-20 03:10:40 +00:00
|
|
|
json_dict.get('attributes'),
|
|
|
|
last_changed)
|
|
|
|
except KeyError: # if key 'state' did not exist
|
|
|
|
return None
|
|
|
|
|
|
|
|
def __repr__(self):
|
2014-01-23 03:40:19 +00:00
|
|
|
return "<state {}:{}, {}>".format(
|
2014-01-20 03:10:40 +00:00
|
|
|
self.state, self.attributes,
|
|
|
|
util.datetime_to_str(self.last_changed))
|
|
|
|
|
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class StateMachine(object):
|
2014-01-20 07:37:40 +00:00
|
|
|
""" Helper class that tracks the state of different entities. """
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def __init__(self, bus):
|
2014-01-20 07:37:40 +00:00
|
|
|
self.states = {}
|
2013-11-20 07:48:08 +00:00
|
|
|
self.bus = bus
|
2013-10-09 01:50:30 +00:00
|
|
|
self.lock = threading.Lock()
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-23 23:08:28 +00:00
|
|
|
@property
|
2014-01-20 07:37:40 +00:00
|
|
|
def entity_ids(self):
|
|
|
|
""" List of entitie ids that are being tracked. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.lock:
|
|
|
|
return self.states.keys()
|
2013-10-23 23:08:28 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def remove_entity(self, entity_id):
|
|
|
|
""" Removes a entity from the state machine.
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
Returns boolean to indicate if a entity was removed. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.lock:
|
|
|
|
try:
|
2014-01-20 07:37:40 +00:00
|
|
|
del self.states[entity_id]
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
return True
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
except KeyError:
|
2014-01-20 07:37:40 +00:00
|
|
|
# if entity does not exist
|
2014-01-20 05:39:57 +00:00
|
|
|
return False
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def set_state(self, entity_id, new_state, attributes=None):
|
|
|
|
""" Set the state of an entity, add entity if it does not exist.
|
2013-10-24 06:57:08 +00:00
|
|
|
|
|
|
|
Attributes is an optional dict to specify attributes of this state. """
|
|
|
|
|
|
|
|
attributes = attributes or {}
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-21 06:58:23 +00:00
|
|
|
with self.lock:
|
2014-01-20 05:39:57 +00:00
|
|
|
# Change state and fire listeners
|
2014-01-21 06:58:23 +00:00
|
|
|
try:
|
2014-01-20 07:37:40 +00:00
|
|
|
old_state = self.states[entity_id]
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-21 06:58:23 +00:00
|
|
|
except KeyError:
|
|
|
|
# If state did not exist yet
|
2014-01-23 03:40:19 +00:00
|
|
|
self.states[entity_id] = State(entity_id, new_state,
|
|
|
|
attributes)
|
2014-01-21 06:58:23 +00:00
|
|
|
|
|
|
|
else:
|
2014-01-20 05:39:57 +00:00
|
|
|
if old_state.state != new_state or \
|
|
|
|
old_state.attributes != attributes:
|
2013-10-24 06:57:08 +00:00
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
state = self.states[entity_id] = \
|
|
|
|
State(entity_id, new_state, attributes)
|
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
self.bus.fire_event(EVENT_STATE_CHANGED,
|
2014-01-20 07:37:40 +00:00
|
|
|
{'entity_id': entity_id,
|
2014-01-20 05:39:57 +00:00
|
|
|
'old_state': old_state,
|
2014-01-21 06:58:23 +00:00
|
|
|
'new_state': state})
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def get_state(self, entity_id):
|
2014-01-23 03:40:19 +00:00
|
|
|
""" Returns the state of the specified entity. """
|
2014-01-20 05:39:57 +00:00
|
|
|
with self.lock:
|
|
|
|
try:
|
|
|
|
# Make a copy so people won't mutate the state
|
2014-01-20 07:37:40 +00:00
|
|
|
return self.states[entity_id].copy()
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
except KeyError:
|
2014-01-20 07:37:40 +00:00
|
|
|
# If entity does not exist
|
2014-01-20 05:39:57 +00:00
|
|
|
return None
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def is_state(self, entity_id, state):
|
|
|
|
""" Returns True if entity exists and is specified state. """
|
2014-01-20 05:39:57 +00:00
|
|
|
try:
|
2014-01-20 07:37:40 +00:00
|
|
|
return self.get_state(entity_id).state == state
|
2014-01-20 05:39:57 +00:00
|
|
|
except AttributeError:
|
|
|
|
# get_state returned None
|
|
|
|
return False
|
2013-10-26 21:26:58 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class Timer(threading.Thread):
|
|
|
|
""" Timer will sent out an event every TIMER_INTERVAL seconds. """
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def __init__(self, bus):
|
2013-09-30 07:20:27 +00:00
|
|
|
threading.Thread.__init__(self)
|
|
|
|
|
2013-10-09 02:00:10 +00:00
|
|
|
self.daemon = True
|
2013-11-20 07:48:08 +00:00
|
|
|
self.bus = bus
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
bus.listen_once_event(EVENT_HOMEASSISTANT_START,
|
|
|
|
lambda event: self.start())
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
""" Start the timer. """
|
|
|
|
|
|
|
|
logging.getLogger(__name__).info("Timer:starting")
|
|
|
|
|
2013-10-24 00:42:16 +00:00
|
|
|
last_fired_on_second = -1
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
calc_now = dt.datetime.now
|
|
|
|
|
2013-09-25 01:39:58 +00:00
|
|
|
while True:
|
2014-01-20 07:37:40 +00:00
|
|
|
now = calc_now()
|
2013-10-24 00:42:16 +00:00
|
|
|
|
2014-01-04 21:48:17 +00:00
|
|
|
# First check checks if we are not on a second matching the
|
|
|
|
# timer interval. Second check checks if we did not already fire
|
|
|
|
# this interval.
|
|
|
|
if now.second % TIMER_INTERVAL or \
|
2013-11-11 00:46:48 +00:00
|
|
|
now.second == last_fired_on_second:
|
2013-10-24 00:42:16 +00:00
|
|
|
|
2014-01-04 21:48:17 +00:00
|
|
|
# Sleep till it is the next time that we have to fire an event.
|
|
|
|
# Aim for halfway through the second that fits TIMER_INTERVAL.
|
|
|
|
# If TIMER_INTERVAL is 10 fire at .5, 10.5, 20.5, etc seconds.
|
|
|
|
# This will yield the best results because time.sleep() is not
|
|
|
|
# 100% accurate because of non-realtime OS's
|
2013-10-24 00:42:16 +00:00
|
|
|
slp_seconds = TIMER_INTERVAL - now.second % TIMER_INTERVAL + \
|
2013-11-11 00:46:48 +00:00
|
|
|
.5 - now.microsecond/1000000.0
|
2013-10-24 00:42:16 +00:00
|
|
|
|
|
|
|
time.sleep(slp_seconds)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
now = calc_now()
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-24 00:42:16 +00:00
|
|
|
last_fired_on_second = now.second
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
self.bus.fire_event(EVENT_TIME_CHANGED,
|
2014-01-20 03:10:40 +00:00
|
|
|
{'now': now})
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
class HomeAssistantException(Exception):
|
|
|
|
""" General Home Assistant exception occured. """
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ServiceDoesNotExistException(HomeAssistantException):
|
|
|
|
""" A service has been referenced that deos not exist. """
|