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']
@ -28,7 +26,7 @@ CONF_ACTION = 'action'
def setup(hass, config):
""" Activate Alexa component. """
"""Activate Alexa component."""
_CONFIG.update(config[DOMAIN].get(CONF_INTENTS, {}))
hass.http.register_path('POST', API_ENDPOINT, _handle_alexa, True)
@ -37,7 +35,7 @@ def setup(hass, config):
def _handle_alexa(handler, path_match, data):
""" Handle Alexa. """
"""Handle Alexa."""
_LOGGER.debug('Received Alexa request: %s', data)
req = data.get('request')
@ -99,19 +97,19 @@ def _handle_alexa(handler, path_match, data):
class SpeechType(enum.Enum):
""" Alexa speech types. """
"""Alexa speech types."""
plaintext = "PlainText"
ssml = "SSML"
class CardType(enum.Enum):
""" Alexa card types. """
"""Alexa card types."""
simple = "Simple"
link_account = "LinkAccount"
class AlexaResponse(object):
""" Helps generating the response for Alexa. """
"""Helps generating the response for Alexa."""
def __init__(self, hass, intent=None):
self.hass = hass
@ -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'
@ -165,7 +163,7 @@ class AlexaResponse(object):
}
def as_dict(self):
""" Returns response in an Alexa valid dict. """
"""Returns response in an Alexa valid dict."""
response = {
'shouldEndSession': self.should_end_session
}
@ -188,5 +186,5 @@ class AlexaResponse(object):
}
def _render(self, template_string):
""" Render a response, adding data from intent if available. """
"""Render a response, adding data from intent if available."""
return template.render(self.hass, template_string, self.variables)

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']
@ -35,7 +33,7 @@ _LOGGER = logging.getLogger(__name__)
def setup(hass, config):
""" Register the API with the HTTP interface. """
"""Register the API with the HTTP interface."""
# /api - for validation purposes
hass.http.register_path('GET', URL_API, _handle_get_api)
@ -98,12 +96,12 @@ def setup(hass, config):
def _handle_get_api(handler, path_match, data):
""" Renders the debug interface. """
"""Renders the debug interface."""
handler.write_json_message("API running.")
def _handle_get_api_stream(handler, path_match, data):
""" Provide a streaming interface for the event bus. """
"""Provide a streaming interface for the event bus."""
gracefully_closed = False
hass = handler.server.hass
wfile = handler.wfile
@ -116,7 +114,7 @@ def _handle_get_api_stream(handler, path_match, data):
restrict = restrict.split(',')
def write_message(payload):
""" Writes a message to the output. """
"""Writes a message to the output."""
with write_lock:
msg = "data: {}\n\n".format(payload)
@ -129,7 +127,7 @@ def _handle_get_api_stream(handler, path_match, data):
block.set()
def forward_events(event):
""" Forwards events to the open request. """
"""Forwards events to the open request."""
nonlocal gracefully_closed
if block.is_set() or event.event_type == EVENT_TIME_CHANGED:
@ -173,17 +171,17 @@ 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())
def _handle_get_api_states(handler, path_match, data):
""" Returns a dict containing all entity ids and their state. """
"""Returns a dict containing all entity ids and their state."""
handler.write_json(handler.server.hass.states.all())
def _handle_get_api_states_entity(handler, path_match, data):
""" Returns the state of a specific entity. """
"""Returns the state of a specific entity."""
entity_id = path_match.group('entity_id')
state = handler.server.hass.states.get(entity_id)
@ -195,7 +193,7 @@ def _handle_get_api_states_entity(handler, path_match, data):
def _handle_post_state_entity(handler, path_match, data):
""" Handles updating the state of an entity.
"""Handles updating the state of an entity.
This handles the following paths:
/api/states/<entity_id>
@ -242,12 +240,12 @@ def _handle_delete_state_entity(handler, path_match, data):
def _handle_get_api_events(handler, path_match, data):
""" Handles getting overview of event listeners. """
"""Handles getting overview of event listeners."""
handler.write_json(events_json(handler.server.hass))
def _handle_api_post_events_event(handler, path_match, event_data):
""" Handles firing of an event.
"""Handles firing of an event.
This handles the following paths:
/api/events/<event_type>
@ -278,13 +276,13 @@ def _handle_api_post_events_event(handler, path_match, event_data):
def _handle_get_api_services(handler, path_match, data):
""" Handles getting overview of services. """
"""Handles getting overview of services."""
handler.write_json(services_json(handler.server.hass))
# pylint: disable=invalid-name
def _handle_post_api_services_domain_service(handler, path_match, data):
""" Handles calling a service.
"""Handles calling a service.
This handles the following paths:
/api/services/<domain>/<service>
@ -300,8 +298,7 @@ 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. """
"""Handles adding an event forwarding target."""
try:
host = data['host']
api_password = data['api_password']
@ -334,8 +331,7 @@ 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. """
"""Handles deleting an event forwarding target."""
try:
host = data['host']
except KeyError:
@ -358,26 +354,25 @@ def _handle_delete_api_event_forward(handler, path_match, data):
def _handle_get_api_components(handler, path_match, data):
""" Returns all the loaded components. """
"""Returns all the loaded components."""
handler.write_json(handler.server.hass.config.components)
def _handle_get_api_error_log(handler, path_match, data):
""" Returns the logged errors for this session. """
"""Returns the logged errors for this session."""
handler.write_file(handler.server.hass.config.path(ERROR_LOG_FILENAME),
False)
def _handle_post_api_log_out(handler, path_match, data):
""" Log user out. """
"""Log user out."""
handler.send_response(HTTP_OK)
handler.destroy_session()
handler.end_headers()
def _handle_post_api_template(handler, path_match, data):
""" Log user out. """
"""Log user out."""
template_string = data.get('template', '')
try:
@ -393,12 +388,12 @@ def _handle_post_api_template(handler, path_match, data):
def services_json(hass):
""" Generate services data to JSONify. """
"""Generate services data to JSONify."""
return [{"domain": key, "services": value}
for key, value in hass.services.services.items()]
def events_json(hass):
""" Generate event data to JSONify. """
"""Generate event data to JSONify."""
return [{"event": key, "listener_count": value}
for key, value in hass.bus.listeners.items()]

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__)
@ -26,7 +24,7 @@ DEPENDENCIES = ['mqtt']
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Light. """
"""Add MQTT Light."""
if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic")
@ -50,7 +48,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class MqttLight(Light):
""" Provides a MQTT light. """
"""Provides a MQTT light."""
# pylint: disable=too-many-arguments,too-many-instance-attributes
def __init__(self, hass, name, topic, templates, qos, payload, optimistic):
@ -71,7 +69,7 @@ class MqttLight(Light):
for key, tpl in templates.items()}
def state_received(topic, payload, qos):
""" A new MQTT message has been received. """
"""A new MQTT message has been received."""
payload = templates['state'](payload)
if payload == self._payload["on"]:
self._state = True
@ -85,7 +83,7 @@ class MqttLight(Light):
state_received, self._qos)
def brightness_received(topic, payload, qos):
""" A new MQTT message for the brightness has been received. """
"""A new MQTT message for the brightness has been received."""
self._brightness = int(templates['brightness'](payload))
self.update_ha_state()
@ -97,7 +95,7 @@ class MqttLight(Light):
self._brightness = None
def rgb_received(topic, payload, qos):
""" A new MQTT message has been received. """
"""A new MQTT message has been received."""
self._rgb = [int(val) for val in
templates['rgb'](payload).split(',')]
self.update_ha_state()
@ -111,27 +109,27 @@ class MqttLight(Light):
@property
def brightness(self):
""" Brightness of this light between 0..255. """
"""Brightness of this light between 0..255."""
return self._brightness
@property
def rgb_color(self):
""" RGB color value. """
"""RGB color value."""
return self._rgb
@property
def should_poll(self):
""" No polling needed for a MQTT light. """
"""No polling needed for a MQTT light."""
return False
@property
def name(self):
""" Returns the name of the device if any. """
"""Returns the name of the device if any."""
return self._name
@property
def is_on(self):
""" True if device is on. """
"""True if device is on."""
return self._state
@property
@ -140,7 +138,7 @@ class MqttLight(Light):
return self._optimistic
def turn_on(self, **kwargs):
""" Turn the device on. """
"""Turn the device on."""
should_update = False
if ATTR_RGB_COLOR in kwargs and \
@ -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
@ -174,11 +172,11 @@ class MqttLight(Light):
self.update_ha_state()
def turn_off(self, **kwargs):
""" Turn the device off. """
"""Turn the device off."""
mqtt.publish(self._hass, self._topic["command_topic"],
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']
@ -43,7 +41,7 @@ ATTR_ENTITY_ID = 'entity_id'
def log_entry(hass, name, message, domain=None, entity_id=None):
""" Adds an entry to the logbook. """
"""Adds an entry to the logbook."""
data = {
ATTR_NAME: name,
ATTR_MESSAGE: message
@ -57,10 +55,10 @@ 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
"""Listens for download events to download files."""
def log_message(service):
""" Handle sending notification message service calls. """
"""Handle sending notification message service calls."""
message = service.data.get(ATTR_MESSAGE)
name = service.data.get(ATTR_NAME)
domain = service.data.get(ATTR_DOMAIN, None)
@ -78,7 +76,7 @@ def setup(hass, config):
def _handle_get_logbook(handler, path_match, data):
""" Return logbook entries. """
"""Return logbook entries."""
date_str = path_match.group('date')
if date_str:
@ -102,10 +100,9 @@ def _handle_get_logbook(handler, path_match, data):
class Entry(object):
""" A human readable version of the log. """
"""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 \
@ -238,7 +234,7 @@ def humanify(events):
def _entry_message_from_state(domain, state):
""" Convert a state to a message for the logbook. """
"""Convert a state to a message for the logbook."""
# We pass domain in so we don't have to split entity_id again
# pylint: disable=too-many-return-statements

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
@ -35,7 +33,7 @@ _LOGGER = logging.getLogger(__name__)
def send_message(hass, message, title=None):
""" Send a notification message. """
"""Send a notification message."""
data = {
ATTR_MESSAGE: message
}
@ -47,14 +45,13 @@ def send_message(hass, message, title=None):
def setup(hass, config):
""" Sets up notify services. """
"""Sets up notify services."""
success = False
descriptions = load_yaml_config_file(
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,9 +66,8 @@ def setup(hass, config):
platform)
continue
# create service handler
def notify_message(notify_service, call):
""" Handle sending notification message service calls. """
"""Handle sending notification message service calls."""
message = call.data.get(ATTR_MESSAGE)
if message is None:
@ -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,
@ -97,7 +91,7 @@ def setup(hass, config):
# pylint: disable=too-few-public-methods
class BaseNotificationService(object):
""" Provides an ABC for notification services. """
"""Provides an ABC for notification services."""
def send_message(self, message, **kwargs):
"""

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")
@ -45,7 +43,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttRollershutter(RollershutterDevice):
""" Represents a rollershutter that can be controlled using MQTT. """
"""Represents a rollershutter that can be controlled using MQTT."""
def __init__(self, hass, name, state_topic, command_topic, qos,
payload_up, payload_down, payload_stop, value_template):
self._state = None
@ -62,7 +60,7 @@ class MqttRollershutter(RollershutterDevice):
return
def message_received(topic, payload, qos):
""" A new MQTT message has been received. """
"""A new MQTT message has been received."""
if value_template is not None:
payload = template.render_with_possible_json_value(
hass, value_template, payload)
@ -77,12 +75,12 @@ class MqttRollershutter(RollershutterDevice):
@property
def should_poll(self):
""" No polling needed """
"""No polling needed."""
return False
@property
def name(self):
""" The name of the rollershutter. """
"""The name of the rollershutter."""
return self._name
@property
@ -94,16 +92,16 @@ class MqttRollershutter(RollershutterDevice):
return self._state
def move_up(self, **kwargs):
""" Move the rollershutter up. """
"""Move the rollershutter up."""
mqtt.publish(self.hass, self._command_topic, self._payload_up,
self._qos)
def move_down(self, **kwargs):
""" Move the rollershutter down. """
"""Move the rollershutter down."""
mqtt.publish(self.hass, self._command_topic, self._payload_down,
self._qos)
def stop(self, **kwargs):
""" Stop the device. """
"""Stop the device."""
mqtt.publish(self.hass, self._command_topic, self._payload_stop,
self._qos)

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,15 +9,14 @@ 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__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return switches controlled by shell commands. """
"""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,
@ -53,7 +50,7 @@ class CommandSwitch(SwitchDevice):
@staticmethod
def _switch(command):
""" Execute the actual commands. """
"""Execute the actual commands."""
_LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0)
@ -65,7 +62,7 @@ class CommandSwitch(SwitchDevice):
@staticmethod
def _query_state_value(command):
""" Execute state command for return value. """
"""Execute state command for return value."""
_LOGGER.info('Running state command: %s', command)
try:
@ -76,27 +73,27 @@ class CommandSwitch(SwitchDevice):
@staticmethod
def _query_state_code(command):
""" Execute state command for return code. """
"""Execute state command for return code."""
_LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0
@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
def name(self):
""" The name of the switch. """
"""The name of the switch."""
return self._name
@property
def is_on(self):
""" True if device is on. """
"""True if device is on."""
return self._state
def _query_state(self):
""" Query for state. """
"""Query for state."""
if not self._command_state:
_LOGGER.error('No state command specified')
return
@ -105,7 +102,7 @@ class CommandSwitch(SwitchDevice):
return CommandSwitch._query_state_code(self._command_state)
def update(self):
""" Update device state. """
"""Update device state."""
if self._command_state:
payload = str(self._query_state())
if self._value_template:
@ -114,14 +111,14 @@ class CommandSwitch(SwitchDevice):
self._state = (payload.lower() == "true")
def turn_on(self, **kwargs):
""" Turn the device on. """
"""Turn the device on."""
if (CommandSwitch._switch(self._command_on) and
not self._command_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
""" Turn the device off. """
"""Turn the device off."""
if (CommandSwitch._switch(self._command_off) and
not self._command_state):
self._state = False

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")
@ -48,7 +46,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttSwitch(SwitchDevice):
""" Represents a switch that can be toggled using MQTT. """
"""Represents a switch that can be toggled using MQTT."""
def __init__(self, hass, name, state_topic, command_topic, qos, retain,
payload_on, payload_off, optimistic, value_template):
self._state = False
@ -63,7 +61,7 @@ class MqttSwitch(SwitchDevice):
self._optimistic = optimistic
def message_received(topic, payload, qos):
""" A new MQTT message has been received. """
"""A new MQTT message has been received."""
if value_template is not None:
payload = template.render_with_possible_json_value(
hass, value_template, payload)
@ -75,26 +73,25 @@ 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)
@property
def should_poll(self):
""" No polling needed. """
"""No polling needed."""
return False
@property
def name(self):
""" The name of the switch. """
"""The name of the switch."""
return self._name
@property
def is_on(self):
""" True if device is on. """
"""True if device is on."""
return self._state
@property
@ -103,19 +100,19 @@ class MqttSwitch(SwitchDevice):
return self._optimistic
def turn_on(self, **kwargs):
""" Turn the device on. """
"""Turn the device on."""
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()
def turn_off(self, **kwargs):
""" Turn the device off. """
"""Turn the device off."""
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,
@ -103,37 +102,37 @@ class SwitchTemplate(SwitchDevice):
self.update()
def _update_callback(_event):
""" Called when the target device changes state. """
"""Called when the target device changes state."""
self.update_ha_state(True)
self.hass.bus.listen(EVENT_STATE_CHANGED, _update_callback)
@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):
""" Fires the on action. """
"""Fires the on action."""
call_from_config(self.hass, self._on_action, True)
def turn_off(self, **kwargs):
""" Fires the off action. """
"""Fires the off action."""
call_from_config(self.hass, self._off_action, True)
@property
def is_on(self):
""" True if device is on. """
"""True if device is on."""
return self._value.lower() == 'true' or self._value == STATE_ON
@property
def is_off(self):
""" True if device is off. """
"""True if device is off."""
return self._value.lower() == 'false' or self._value == STATE_OFF
@property
@ -142,7 +141,7 @@ class SwitchTemplate(SwitchDevice):
return self.is_on or self.is_off
def update(self):
""" Updates the state from the template. """
"""Updates the state from the template."""
try:
self._value = template.render(self.hass, self._template)
if not self.available:

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
}
@ -41,7 +41,7 @@ def render_with_possible_json_value(hass, template, value,
def render(hass, template, variables=None, **kwargs):
""" Render given template. """
"""Render given template."""
if variables is not None:
kwargs.update(variables)
@ -63,7 +63,7 @@ def render(hass, template, variables=None, **kwargs):
class AllStates(object):
""" Class to expose all HA states as attributes. """
"""Class to expose all HA states as attributes."""
def __init__(self, hass):
self._hass = hass
@ -80,7 +80,7 @@ class AllStates(object):
class DomainStates(object):
""" Class to expose a specific HA domain as attributes. """
"""Class to expose a specific HA domain as attributes."""
def __init__(self, hass, domain):
self._hass = hass

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
@ -22,7 +19,7 @@ class TestUtilTemplate(unittest.TestCase):
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
""" Stop down stuff we started. """
"""Stop down stuff we started."""
self.hass.stop()
def test_referring_states_by_entity_id(self):
@ -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(),