core/homeassistant/components/logbook.py

259 lines
8.2 KiB
Python
Raw Normal View History

2015-03-29 21:43:16 +00:00
"""
2016-02-23 20:06:50 +00:00
Event parser and human readable log generator.
2015-10-25 14:10:51 +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/logbook/
2015-03-29 21:43:16 +00:00
"""
2016-01-27 17:03:37 +00:00
import logging
2016-02-19 05:27:50 +00:00
import re
from datetime import timedelta
from itertools import groupby
2015-03-29 21:43:16 +00:00
import homeassistant.util.dt as dt_util
2015-09-14 01:30:44 +00:00
from homeassistant.components import recorder, sun
2016-02-19 05:27:50 +00:00
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED,
HTTP_BAD_REQUEST, STATE_NOT_HOME, STATE_OFF, STATE_ON)
from homeassistant.core import DOMAIN as HA_DOMAIN
from homeassistant.core import State
2016-01-24 06:49:49 +00:00
from homeassistant.helpers.entity import split_entity_id
2016-02-23 20:06:50 +00:00
from homeassistant.helpers import template
2015-03-29 21:43:16 +00:00
DOMAIN = "logbook"
DEPENDENCIES = ['recorder', 'http']
URL_LOGBOOK = re.compile(r'/api/logbook(?:/(?P<date>\d{4}-\d{1,2}-\d{1,2})|)')
2015-03-29 21:43:16 +00:00
QUERY_EVENTS_BETWEEN = """
SELECT * FROM events WHERE time_fired > ? AND time_fired < ?
"""
2016-01-27 17:03:37 +00:00
_LOGGER = logging.getLogger(__name__)
EVENT_LOGBOOK_ENTRY = 'logbook_entry'
2015-09-14 01:30:44 +00:00
GROUP_BY_MINUTES = 15
2015-09-14 01:30:44 +00:00
ATTR_NAME = 'name'
ATTR_MESSAGE = 'message'
ATTR_DOMAIN = 'domain'
ATTR_ENTITY_ID = 'entity_id'
2016-01-27 16:27:55 +00:00
2015-09-14 01:30:44 +00:00
def log_entry(hass, name, message, domain=None, entity_id=None):
2016-03-08 16:55:57 +00:00
"""Add an entry to the logbook."""
2015-09-14 01:30:44 +00:00
data = {
ATTR_NAME: name,
ATTR_MESSAGE: message
}
if domain is not None:
data[ATTR_DOMAIN] = domain
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.bus.fire(EVENT_LOGBOOK_ENTRY, data)
2015-03-29 21:43:16 +00:00
def setup(hass, config):
2016-03-08 16:55:57 +00:00
"""Listen for download events to download files."""
2016-01-27 17:03:37 +00:00
def log_message(service):
2016-02-23 20:06:50 +00:00
"""Handle sending notification message service calls."""
2016-01-27 17:03:37 +00:00
message = service.data.get(ATTR_MESSAGE)
2016-01-29 07:13:46 +00:00
name = service.data.get(ATTR_NAME)
domain = service.data.get(ATTR_DOMAIN, None)
entity_id = service.data.get(ATTR_ENTITY_ID, None)
2016-01-27 16:27:55 +00:00
2016-01-29 07:13:46 +00:00
if not message or not name:
2016-01-27 16:27:55 +00:00
return
2016-01-29 07:13:46 +00:00
2016-01-27 16:37:15 +00:00
message = template.render(hass, message)
2016-01-29 07:13:46 +00:00
log_entry(hass, name, message, domain, entity_id)
2016-01-27 16:27:55 +00:00
hass.http.register_path('GET', URL_LOGBOOK, _handle_get_logbook)
2016-01-28 08:51:05 +00:00
hass.services.register(DOMAIN, 'log', log_message)
2015-03-29 21:43:16 +00:00
return True
def _handle_get_logbook(handler, path_match, data):
2016-02-23 20:06:50 +00:00
"""Return logbook entries."""
date_str = path_match.group('date')
2015-04-01 06:09:08 +00:00
if date_str:
start_date = dt_util.date_str_to_date(date_str)
if start_date is None:
handler.write_json_message("Error parsing JSON", HTTP_BAD_REQUEST)
return
start_day = dt_util.start_of_local_day(start_date)
else:
start_day = dt_util.start_of_local_day()
end_day = start_day + timedelta(days=1)
events = recorder.query_events(
QUERY_EVENTS_BETWEEN,
(dt_util.as_utc(start_day), dt_util.as_utc(end_day)))
handler.write_json(humanify(events))
2015-03-29 21:43:16 +00:00
class Entry(object):
2016-02-23 20:06:50 +00:00
"""A human readable version of the log."""
2016-03-08 16:55:57 +00:00
2015-03-30 07:19:56 +00:00
# pylint: disable=too-many-arguments, too-few-public-methods
2015-03-29 21:43:16 +00:00
def __init__(self, when=None, name=None, message=None, domain=None,
entity_id=None):
2016-03-08 16:55:57 +00:00
"""Initialize the entry."""
2015-03-29 21:43:16 +00:00
self.when = when
self.name = name
self.message = message
self.domain = domain
self.entity_id = entity_id
def as_dict(self):
2016-02-23 20:06:50 +00:00
"""Convert entry to a dict to be used within JSON."""
2015-03-29 21:43:16 +00:00
return {
'when': dt_util.datetime_to_str(self.when),
2015-03-29 21:43:16 +00:00
'name': self.name,
'message': self.message,
'domain': self.domain,
'entity_id': self.entity_id,
}
def humanify(events):
2016-03-08 16:55:57 +00:00
"""Generator that converts a list of events into Entry objects.
Will try to group events if possible:
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
2015-03-30 07:11:24 +00:00
- if home assistant stop and start happen in same minute call it restarted
"""
2015-03-30 07:19:56 +00:00
# pylint: disable=too-many-branches
# Group events in batches of GROUP_BY_MINUTES
for _, g_events in groupby(
events,
lambda event: event.time_fired.minute // GROUP_BY_MINUTES):
2015-03-29 21:43:16 +00:00
events_batch = list(g_events)
2015-03-29 21:43:16 +00:00
# Keep track of last sensor states
last_sensor_event = {}
2015-03-29 21:43:16 +00:00
2016-02-23 20:06:50 +00:00
# Group HA start/stop events
2015-03-30 07:11:24 +00:00
# Maps minute of event to 1: stop, 2: stop + start
start_stop_events = {}
# Process events
for event in events_batch:
if event.event_type == EVENT_STATE_CHANGED:
entity_id = event.data.get('entity_id')
2015-03-29 21:43:16 +00:00
2015-09-19 19:29:23 +00:00
if entity_id is None:
continue
if entity_id.startswith('sensor.'):
last_sensor_event[entity_id] = event
2015-03-29 21:43:16 +00:00
2015-03-30 07:11:24 +00:00
elif event.event_type == EVENT_HOMEASSISTANT_STOP:
if event.time_fired.minute in start_stop_events:
continue
start_stop_events[event.time_fired.minute] = 1
elif event.event_type == EVENT_HOMEASSISTANT_START:
if event.time_fired.minute not in start_stop_events:
continue
start_stop_events[event.time_fired.minute] = 2
# Yield entries
for event in events_batch:
if event.event_type == EVENT_STATE_CHANGED:
2015-03-29 21:43:16 +00:00
# Do not report on new entities
if 'old_state' not in event.data:
continue
to_state = State.from_dict(event.data.get('new_state'))
2016-02-23 20:06:50 +00:00
# If last_changed != last_updated only attributes have changed
2015-09-24 06:20:12 +00:00
# we do not report on that yet. Also filter auto groups.
2015-04-01 14:18:03 +00:00
if not to_state or \
2015-09-24 06:20:12 +00:00
to_state.last_changed != to_state.last_updated or \
to_state.domain == 'group' and \
to_state.attributes.get('auto', False):
continue
domain = to_state.domain
2015-03-29 21:43:16 +00:00
# Skip all but the last sensor state
if domain == 'sensor' and \
event != last_sensor_event[to_state.entity_id]:
continue
2015-03-29 21:43:16 +00:00
2015-03-30 07:19:56 +00:00
yield Entry(
event.time_fired,
name=to_state.name,
message=_entry_message_from_state(domain, to_state),
domain=domain,
entity_id=to_state.entity_id)
2015-03-29 21:43:16 +00:00
elif event.event_type == EVENT_HOMEASSISTANT_START:
2015-03-30 07:11:24 +00:00
if start_stop_events.get(event.time_fired.minute) == 2:
continue
yield Entry(
event.time_fired, "Home Assistant", "started",
domain=HA_DOMAIN)
2015-03-29 21:43:16 +00:00
elif event.event_type == EVENT_HOMEASSISTANT_STOP:
2015-03-30 07:11:24 +00:00
if start_stop_events.get(event.time_fired.minute) == 2:
action = "restarted"
else:
action = "stopped"
yield Entry(
2015-03-30 07:11:24 +00:00
event.time_fired, "Home Assistant", action,
domain=HA_DOMAIN)
2015-03-30 07:19:56 +00:00
elif event.event_type.lower() == EVENT_LOGBOOK_ENTRY:
2015-09-14 01:30:44 +00:00
domain = event.data.get(ATTR_DOMAIN)
entity_id = event.data.get(ATTR_ENTITY_ID)
if domain is None and entity_id is not None:
try:
2016-01-24 06:49:49 +00:00
domain = split_entity_id(str(entity_id))[0]
2015-09-14 01:30:44 +00:00
except IndexError:
pass
yield Entry(
event.time_fired, event.data.get(ATTR_NAME),
event.data.get(ATTR_MESSAGE), domain,
entity_id)
2015-03-30 07:19:56 +00:00
def _entry_message_from_state(domain, state):
2016-02-23 20:06:50 +00:00
"""Convert a state to a message for the logbook."""
2015-03-30 07:19:56 +00:00
# We pass domain in so we don't have to split entity_id again
2015-10-03 18:26:57 +00:00
# pylint: disable=too-many-return-statements
2015-03-30 07:19:56 +00:00
if domain == 'device_tracker':
if state.state == STATE_NOT_HOME:
return 'is away'
else:
return 'is at {}'.format(state.state)
2015-03-30 07:19:56 +00:00
elif domain == 'sun':
if state.state == sun.STATE_ABOVE_HORIZON:
return 'has risen'
else:
return 'has set'
elif state.state == STATE_ON:
# Future: combine groups and its entity entries ?
return "turned on"
elif state.state == STATE_OFF:
return "turned off"
return "changed to {}".format(state.state)