Merge pull request #1381 from fabaff/template-helpers

Template helpers
pull/1384/head
Paulus Schoutsen 2016-02-23 13:38:19 -08:00
commit 49e588deb3
25 changed files with 154 additions and 184 deletions

View File

@ -1,7 +1,5 @@
"""
components.alexa
~~~~~~~~~~~~~~~~
Component to offer a service end point for an Alexa skill.
Support for Alexa skill service end point.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/alexa/
@ -11,7 +9,7 @@ import logging
from homeassistant.const import HTTP_OK, HTTP_UNPROCESSABLE_ENTITY
from homeassistant.helpers.service import call_from_config
from homeassistant.util import template
from homeassistant.helpers import template
DOMAIN = 'alexa'
DEPENDENCIES = ['http']
@ -154,7 +152,7 @@ class AlexaResponse(object):
}
def add_reprompt(self, speech_type, text):
""" Add repromopt if user does not answer. """
"""Add reprompt if user does not answer."""
assert self.reprompt is None
key = 'ssml' if speech_type == SpeechType.ssml else 'text'

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.api
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides a Rest API for Home Assistant.
Rest API for Home Assistant.
For more details about the RESTful API, please refer to the documentation at
https://home-assistant.io/developers/api/
@ -23,7 +21,7 @@ from homeassistant.const import (
URL_API_STREAM, URL_API_TEMPLATE)
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.state import TrackStates
from homeassistant.util import template
from homeassistant.helpers import template
DOMAIN = 'api'
DEPENDENCIES = ['http']
@ -173,7 +171,7 @@ def _handle_get_api_stream(handler, path_match, data):
def _handle_get_api_config(handler, path_match, data):
""" Returns the Home Assistant config. """
"""Returns the Home Assistant configuration."""
handler.write_json(handler.server.hass.config.as_dict())
@ -301,7 +299,6 @@ def _handle_post_api_services_domain_service(handler, path_match, data):
# pylint: disable=invalid-name
def _handle_post_api_event_forward(handler, path_match, data):
"""Handles adding an event forwarding target."""
try:
host = data['host']
api_password = data['api_password']
@ -335,7 +332,6 @@ def _handle_post_api_event_forward(handler, path_match, data):
def _handle_delete_api_event_forward(handler, path_match, data):
"""Handles deleting an event forwarding target."""
try:
host = data['host']
except KeyError:
@ -359,7 +355,6 @@ def _handle_delete_api_event_forward(handler, path_match, data):
def _handle_get_api_components(handler, path_match, data):
"""Returns all the loaded components."""
handler.write_json(handler.server.hass.config.components)

View File

@ -11,7 +11,7 @@ from functools import partial
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.helpers.event import track_state_change
from homeassistant.util import template
from homeassistant.helpers import template
CONF_ENTITY_ID = "entity_id"
CONF_BELOW = "below"

View File

@ -10,7 +10,7 @@ import logging
from homeassistant.const import CONF_VALUE_TEMPLATE, EVENT_STATE_CHANGED
from homeassistant.exceptions import TemplateError
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)

View File

@ -11,7 +11,7 @@ from datetime import timedelta
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.sensor.command_sensor import CommandSensorData
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)

View File

@ -9,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)

View File

@ -9,7 +9,7 @@ import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.sensor.rest import RestData
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.light.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT light.
Support for MQTT lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mqtt/
@ -12,7 +10,7 @@ from functools import partial
import homeassistant.components.mqtt as mqtt
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, Light)
from homeassistant.util.template import render_with_possible_json_value
from homeassistant.helpers.template import render_with_possible_json_value
_LOGGER = logging.getLogger(__name__)
@ -166,7 +164,7 @@ class MqttLight(Light):
self._payload["on"], self._qos)
if self._optimistic:
# optimistically assume that switch has changed state
# Optimistically assume that switch has changed state.
self._state = True
should_update = True
@ -179,6 +177,6 @@ class MqttLight(Light):
self._payload["off"], self._qos)
if self._optimistic:
# optimistically assume that switch has changed state
# Optimistically assume that switch has changed state.
self._state = False
self.update_ha_state()

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.logbook
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Parses events and generates a human log.
Event parser and human readable log generator.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logbook/
@ -19,7 +17,7 @@ from homeassistant.const import (
from homeassistant.core import DOMAIN as HA_DOMAIN
from homeassistant.core import State
from homeassistant.helpers.entity import split_entity_id
from homeassistant.util import template
from homeassistant.helpers import template
DOMAIN = "logbook"
DEPENDENCIES = ['recorder', 'http']
@ -58,7 +56,7 @@ def log_entry(hass, name, message, domain=None, entity_id=None):
def setup(hass, config):
"""Listens for download events to download files."""
# create service handler
def log_message(service):
"""Handle sending notification message service calls."""
message = service.data.get(ATTR_MESSAGE)
@ -105,7 +103,6 @@ class Entry(object):
"""A human readable version of the log."""
# pylint: disable=too-many-arguments, too-few-public-methods
def __init__(self, when=None, name=None, message=None, domain=None,
entity_id=None):
self.when = when
@ -115,7 +112,7 @@ class Entry(object):
self.entity_id = entity_id
def as_dict(self):
""" Convert Entry to a dict to be used within JSON. """
"""Convert entry to a dict to be used within JSON."""
return {
'when': dt_util.datetime_to_str(self.when),
'name': self.name,
@ -134,7 +131,6 @@ def humanify(events):
- if home assistant stop and start happen in same minute call it restarted
"""
# pylint: disable=too-many-branches
# Group events in batches of GROUP_BY_MINUTES
for _, g_events in groupby(
events,
@ -145,7 +141,7 @@ def humanify(events):
# Keep track of last sensor states
last_sensor_event = {}
# group HA start/stop events
# Group HA start/stop events
# Maps minute of event to 1: stop, 2: stop + start
start_stop_events = {}
@ -182,7 +178,7 @@ def humanify(events):
to_state = State.from_dict(event.data.get('new_state'))
# if last_changed != last_updated only attributes have changed
# If last_changed != last_updated only attributes have changed
# we do not report on that yet. Also filter auto groups.
if not to_state or \
to_state.last_changed != to_state.last_updated or \

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT component, using paho-mqtt.
Support for MQTT message handling..
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/
@ -15,7 +13,7 @@ import time
from homeassistant.config import load_yaml_config_file
from homeassistant.exceptions import HomeAssistantError
import homeassistant.util as util
from homeassistant.util import template
from homeassistant.helpers import template
from homeassistant.helpers import validate_config
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)

View File

@ -1,6 +1,4 @@
"""
homeassistant.components.notify
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to notify people.
For more details about this component, please refer to the documentation at
@ -13,7 +11,7 @@ import os
import homeassistant.bootstrap as bootstrap
from homeassistant.config import load_yaml_config_file
from homeassistant.helpers import config_per_platform
from homeassistant.util import template
from homeassistant.helpers import template
from homeassistant.const import CONF_NAME
@ -54,7 +52,6 @@ def setup(hass, config):
os.path.join(os.path.dirname(__file__), 'services.yaml'))
for platform, p_config in config_per_platform(config, DOMAIN, _LOGGER):
# get platform
notify_implementation = bootstrap.prepare_setup_platform(
hass, config, DOMAIN, platform)
@ -62,7 +59,6 @@ def setup(hass, config):
_LOGGER.error("Unknown notification service specified.")
continue
# create platform service
notify_service = notify_implementation.get_service(hass, p_config)
if notify_service is None:
@ -70,7 +66,6 @@ def setup(hass, config):
platform)
continue
# create service handler
def notify_message(notify_service, call):
"""Handle sending notification message service calls."""
message = call.data.get(ATTR_MESSAGE)
@ -85,7 +80,6 @@ def setup(hass, config):
notify_service.send_message(message, title=title, target=target)
# register service
service_call_handler = partial(notify_message, notify_service)
service_notify = p_config.get(CONF_NAME, SERVICE_NOTIFY)
hass.services.register(DOMAIN, service_notify, service_call_handler,

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.rollershutter.command_rollershutter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a command rollershutter.
Support for command roller shutters.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/rollershutter.command_rollershutter/
@ -11,13 +9,13 @@ import subprocess
from homeassistant.components.rollershutter import RollershutterDevice
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return rollershutter controlled by shell commands. """
"""Setup rollershutter controlled by shell commands."""
rollershutters = config.get('rollershutters', {})
devices = []

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.rollershutter.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT rollershutter.
Support for MQTT roller shutters.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/rollershutter.mqtt/
@ -11,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt
from homeassistant.components.rollershutter import RollershutterDevice
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)
@ -25,7 +23,7 @@ DEFAULT_PAYLOAD_STOP = "STOP"
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Rollershutter """
"""Add MQTT Rollershutter."""
if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic")
@ -77,7 +75,7 @@ class MqttRollershutter(RollershutterDevice):
@property
def should_poll(self):
""" No polling needed """
"""No polling needed."""
return False
@property

View File

@ -13,11 +13,12 @@ from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, DEVICE_DEFAULT_NAME)
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, template
from homeassistant.helpers import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
CONF_RESOURCE = 'resource'

View File

@ -10,7 +10,8 @@ from datetime import timedelta
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, template
from homeassistant.helpers import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)

View File

@ -10,7 +10,8 @@ from datetime import timedelta
from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, template
from homeassistant.helpers import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['dweepy==0.2.0']

View File

@ -9,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt
from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)

View File

@ -11,7 +11,8 @@ import requests
from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, template
from homeassistant.helpers import template
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)

View File

@ -9,7 +9,7 @@ import socket
import select
from homeassistant.const import CONF_NAME, CONF_HOST
from homeassistant.util import template
from homeassistant.helpers import template
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity

View File

@ -13,7 +13,8 @@ from homeassistant.const import (
from homeassistant.core import EVENT_STATE_CHANGED
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity, generate_entity_id
from homeassistant.util import slugify, template
from homeassistant.helpers import template
from homeassistant.util import slugify
ENTITY_ID_FORMAT = DOMAIN + '.{}'

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.switch.command_switch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure custom shell commands to turn a switch on/off.
Support for custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_switch/
@ -11,7 +9,7 @@ import subprocess
from homeassistant.components.switch import SwitchDevice
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)
@ -19,7 +17,6 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Find and return switches controlled by shell commands."""
switches = config.get('switches', {})
devices = []
@ -37,7 +34,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class CommandSwitch(SwitchDevice):
""" Represents a switch that can be togggled using shell commands. """
"""Represents a switch that can be toggled using shell commands."""
# pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off,
@ -82,7 +79,7 @@ class CommandSwitch(SwitchDevice):
@property
def should_poll(self):
""" Only poll if we have statecmd. """
"""Only poll if we have state command."""
return self._command_state is not None
@property

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.switch.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT switch.
Support for MQTT switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.mqtt/
@ -11,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt
from homeassistant.components.switch import SwitchDevice
from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)
@ -27,7 +25,7 @@ DEPENDENCIES = ['mqtt']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Switch. """
"""Add MQTT switch."""
if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic")
@ -75,10 +73,9 @@ class MqttSwitch(SwitchDevice):
self.update_ha_state()
if self._state_topic is None:
# force optimistic mode
# Force into optimistic mode.
self._optimistic = True
else:
# subscribe the state_topic
mqtt.subscribe(hass, self._state_topic, message_received,
self._qos)
@ -107,7 +104,7 @@ class MqttSwitch(SwitchDevice):
mqtt.publish(self.hass, self._command_topic, self._payload_on,
self._qos, self._retain)
if self._optimistic:
# optimistically assume that switch has changed state
# Optimistically assume that switch has changed state.
self._state = True
self.update_ha_state()
@ -116,6 +113,6 @@ class MqttSwitch(SwitchDevice):
mqtt.publish(self.hass, self._command_topic, self._payload_off,
self._qos, self._retain)
if self._optimistic:
# optimistically assume that switch has changed state
# Optimistically assume that switch has changed state.
self._state = False
self.update_ha_state()

View File

@ -1,7 +1,5 @@
"""
homeassistant.components.switch.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows the creation of a switch that integrates other components together
Support for switches which integrates with other components.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.template/
@ -15,7 +13,8 @@ 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.util import slugify, template
from homeassistant.helpers import template
from homeassistant.util import slugify
ENTITY_ID_FORMAT = DOMAIN + '.{}'
@ -31,7 +30,7 @@ OFF_ACTION = 'turn_off'
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the switches. """
"""Sets up the Template switch."""
switches = []
if config.get(CONF_SWITCHES) is None:
@ -80,7 +79,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SwitchTemplate(SwitchDevice):
""" Represents a Template Switch. """
"""Represents a Template switch."""
# pylint: disable=too-many-arguments
def __init__(self,
@ -110,12 +109,12 @@ class SwitchTemplate(SwitchDevice):
@property
def name(self):
""" Returns the name of the device. """
"""Returns the name of the switch."""
return self._name
@property
def should_poll(self):
""" Tells Home Assistant not to poll this entity. """
"""No polling needed."""
return False
def turn_on(self, **kwargs):

View File

@ -1,7 +1,5 @@
"""
homeassistant.util.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Template utility methods for rendering strings with HA data.
Template helper methods for rendering strings with HA data.
"""
# pylint: disable=too-few-public-methods
import json
@ -23,8 +21,10 @@ _SENTINEL = object()
def render_with_possible_json_value(hass, template, value,
error_value=_SENTINEL):
""" Renders template with value exposed.
If valid JSON will expose value_json too. """
"""
Renders template with value exposed.
If valid JSON will expose value_json too.
"""
variables = {
'value': value
}

View File

@ -1,8 +1,5 @@
"""
tests.util.test_template
~~~~~~~~~~~~~~~~~~~~~~~~
Tests Home Assistant template util methods.
Tests Home Assistant template helper methods.
"""
# pylint: disable=too-many-public-methods
import unittest
@ -10,7 +7,7 @@ from unittest.mock import patch
from homeassistant.components import group
from homeassistant.exceptions import TemplateError
from homeassistant.util import template
from homeassistant.helpers import template
import homeassistant.util.dt as dt_util
from tests.common import get_test_home_assistant
@ -174,16 +171,16 @@ class TestUtilTemplate(unittest.TestCase):
template.render(self.hass, '{{ states("test.object2") }}'))
@patch('homeassistant.core.dt_util.utcnow', return_value=dt_util.utcnow())
@patch('homeassistant.util.template.TemplateEnvironment.is_safe_callable',
return_value=True)
@patch('homeassistant.helpers.template.TemplateEnvironment.'
'is_safe_callable', return_value=True)
def test_now(self, mock_is_safe, mock_utcnow):
self.assertEqual(
dt_util.utcnow().isoformat(),
template.render(self.hass, '{{ now.isoformat() }}'))
@patch('homeassistant.core.dt_util.utcnow', return_value=dt_util.utcnow())
@patch('homeassistant.util.template.TemplateEnvironment.is_safe_callable',
return_value=True)
@patch('homeassistant.helpers.template.TemplateEnvironment.'
'is_safe_callable', return_value=True)
def test_utcnow(self, mock_is_safe, mock_utcnow):
self.assertEqual(
dt_util.utcnow().isoformat(),