Modify import of template and PEP257

This commit is contained in:
Fabian Affolter 2016-02-23 21:06:50 +01:00
parent 213cc920d0
commit 582394bc3b
25 changed files with 152 additions and 182 deletions

View File

@ -1,7 +1,5 @@
""" """
components.alexa Support for Alexa skill service end point.
~~~~~~~~~~~~~~~~
Component to offer a service end point for an Alexa skill.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/alexa/ https://home-assistant.io/components/alexa/
@ -11,7 +9,7 @@ import logging
from homeassistant.const import HTTP_OK, HTTP_UNPROCESSABLE_ENTITY from homeassistant.const import HTTP_OK, HTTP_UNPROCESSABLE_ENTITY
from homeassistant.helpers.service import call_from_config from homeassistant.helpers.service import call_from_config
from homeassistant.util import template from homeassistant.helpers import template
DOMAIN = 'alexa' DOMAIN = 'alexa'
DEPENDENCIES = ['http'] DEPENDENCIES = ['http']
@ -28,7 +26,7 @@ CONF_ACTION = 'action'
def setup(hass, config): def setup(hass, config):
""" Activate Alexa component. """ """Activate Alexa component."""
_CONFIG.update(config[DOMAIN].get(CONF_INTENTS, {})) _CONFIG.update(config[DOMAIN].get(CONF_INTENTS, {}))
hass.http.register_path('POST', API_ENDPOINT, _handle_alexa, True) 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): def _handle_alexa(handler, path_match, data):
""" Handle Alexa. """ """Handle Alexa."""
_LOGGER.debug('Received Alexa request: %s', data) _LOGGER.debug('Received Alexa request: %s', data)
req = data.get('request') req = data.get('request')
@ -99,19 +97,19 @@ def _handle_alexa(handler, path_match, data):
class SpeechType(enum.Enum): class SpeechType(enum.Enum):
""" Alexa speech types. """ """Alexa speech types."""
plaintext = "PlainText" plaintext = "PlainText"
ssml = "SSML" ssml = "SSML"
class CardType(enum.Enum): class CardType(enum.Enum):
""" Alexa card types. """ """Alexa card types."""
simple = "Simple" simple = "Simple"
link_account = "LinkAccount" link_account = "LinkAccount"
class AlexaResponse(object): class AlexaResponse(object):
""" Helps generating the response for Alexa. """ """Helps generating the response for Alexa."""
def __init__(self, hass, intent=None): def __init__(self, hass, intent=None):
self.hass = hass self.hass = hass
@ -154,7 +152,7 @@ class AlexaResponse(object):
} }
def add_reprompt(self, speech_type, text): 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 assert self.reprompt is None
key = 'ssml' if speech_type == SpeechType.ssml else 'text' key = 'ssml' if speech_type == SpeechType.ssml else 'text'
@ -165,7 +163,7 @@ class AlexaResponse(object):
} }
def as_dict(self): def as_dict(self):
""" Returns response in an Alexa valid dict. """ """Returns response in an Alexa valid dict."""
response = { response = {
'shouldEndSession': self.should_end_session 'shouldEndSession': self.should_end_session
} }
@ -188,5 +186,5 @@ class AlexaResponse(object):
} }
def _render(self, template_string): 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) return template.render(self.hass, template_string, self.variables)

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.api Rest API for Home Assistant.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides a Rest API for Home Assistant.
For more details about the RESTful API, please refer to the documentation at For more details about the RESTful API, please refer to the documentation at
https://home-assistant.io/developers/api/ https://home-assistant.io/developers/api/
@ -23,7 +21,7 @@ from homeassistant.const import (
URL_API_STREAM, URL_API_TEMPLATE) URL_API_STREAM, URL_API_TEMPLATE)
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers.state import TrackStates from homeassistant.helpers.state import TrackStates
from homeassistant.util import template from homeassistant.helpers import template
DOMAIN = 'api' DOMAIN = 'api'
DEPENDENCIES = ['http'] DEPENDENCIES = ['http']
@ -35,7 +33,7 @@ _LOGGER = logging.getLogger(__name__)
def setup(hass, config): def setup(hass, config):
""" Register the API with the HTTP interface. """ """Register the API with the HTTP interface."""
# /api - for validation purposes # /api - for validation purposes
hass.http.register_path('GET', URL_API, _handle_get_api) 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): def _handle_get_api(handler, path_match, data):
""" Renders the debug interface. """ """Renders the debug interface."""
handler.write_json_message("API running.") handler.write_json_message("API running.")
def _handle_get_api_stream(handler, path_match, data): 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 gracefully_closed = False
hass = handler.server.hass hass = handler.server.hass
wfile = handler.wfile wfile = handler.wfile
@ -116,7 +114,7 @@ def _handle_get_api_stream(handler, path_match, data):
restrict = restrict.split(',') restrict = restrict.split(',')
def write_message(payload): def write_message(payload):
""" Writes a message to the output. """ """Writes a message to the output."""
with write_lock: with write_lock:
msg = "data: {}\n\n".format(payload) msg = "data: {}\n\n".format(payload)
@ -129,7 +127,7 @@ def _handle_get_api_stream(handler, path_match, data):
block.set() block.set()
def forward_events(event): def forward_events(event):
""" Forwards events to the open request. """ """Forwards events to the open request."""
nonlocal gracefully_closed nonlocal gracefully_closed
if block.is_set() or event.event_type == EVENT_TIME_CHANGED: 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): 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()) handler.write_json(handler.server.hass.config.as_dict())
def _handle_get_api_states(handler, path_match, data): 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()) handler.write_json(handler.server.hass.states.all())
def _handle_get_api_states_entity(handler, path_match, data): 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') entity_id = path_match.group('entity_id')
state = handler.server.hass.states.get(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): 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: This handles the following paths:
/api/states/<entity_id> /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): 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)) handler.write_json(events_json(handler.server.hass))
def _handle_api_post_events_event(handler, path_match, event_data): 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: This handles the following paths:
/api/events/<event_type> /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): 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)) handler.write_json(services_json(handler.server.hass))
# pylint: disable=invalid-name # pylint: disable=invalid-name
def _handle_post_api_services_domain_service(handler, path_match, data): def _handle_post_api_services_domain_service(handler, path_match, data):
""" Handles calling a service. """Handles calling a service.
This handles the following paths: This handles the following paths:
/api/services/<domain>/<service> /api/services/<domain>/<service>
@ -300,8 +298,7 @@ def _handle_post_api_services_domain_service(handler, path_match, data):
# pylint: disable=invalid-name # pylint: disable=invalid-name
def _handle_post_api_event_forward(handler, path_match, data): def _handle_post_api_event_forward(handler, path_match, data):
""" Handles adding an event forwarding target. """ """Handles adding an event forwarding target."""
try: try:
host = data['host'] host = data['host']
api_password = data['api_password'] 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): def _handle_delete_api_event_forward(handler, path_match, data):
""" Handles deleting an event forwarding target. """ """Handles deleting an event forwarding target."""
try: try:
host = data['host'] host = data['host']
except KeyError: 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): 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) handler.write_json(handler.server.hass.config.components)
def _handle_get_api_error_log(handler, path_match, data): 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), handler.write_file(handler.server.hass.config.path(ERROR_LOG_FILENAME),
False) False)
def _handle_post_api_log_out(handler, path_match, data): def _handle_post_api_log_out(handler, path_match, data):
""" Log user out. """ """Log user out."""
handler.send_response(HTTP_OK) handler.send_response(HTTP_OK)
handler.destroy_session() handler.destroy_session()
handler.end_headers() handler.end_headers()
def _handle_post_api_template(handler, path_match, data): def _handle_post_api_template(handler, path_match, data):
""" Log user out. """ """Log user out."""
template_string = data.get('template', '') template_string = data.get('template', '')
try: try:
@ -393,12 +388,12 @@ def _handle_post_api_template(handler, path_match, data):
def services_json(hass): def services_json(hass):
""" Generate services data to JSONify. """ """Generate services data to JSONify."""
return [{"domain": key, "services": value} return [{"domain": key, "services": value}
for key, value in hass.services.services.items()] for key, value in hass.services.services.items()]
def events_json(hass): def events_json(hass):
""" Generate event data to JSONify. """ """Generate event data to JSONify."""
return [{"event": key, "listener_count": value} return [{"event": key, "listener_count": value}
for key, value in hass.bus.listeners.items()] 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.const import CONF_VALUE_TEMPLATE
from homeassistant.helpers.event import track_state_change from homeassistant.helpers.event import track_state_change
from homeassistant.util import template from homeassistant.helpers import template
CONF_ENTITY_ID = "entity_id" CONF_ENTITY_ID = "entity_id"
CONF_BELOW = "below" CONF_BELOW = "below"

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.light.mqtt Support for MQTT lights.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT light.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mqtt/ https://home-assistant.io/components/light.mqtt/
@ -12,7 +10,7 @@ from functools import partial
import homeassistant.components.mqtt as mqtt import homeassistant.components.mqtt as mqtt
from homeassistant.components.light import ( from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, Light) 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__) _LOGGER = logging.getLogger(__name__)
@ -26,7 +24,7 @@ DEPENDENCIES = ['mqtt']
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Light. """ """Add MQTT Light."""
if config.get('command_topic') is None: if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic") _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): class MqttLight(Light):
""" Provides a MQTT light. """ """Provides a MQTT light."""
# pylint: disable=too-many-arguments,too-many-instance-attributes # pylint: disable=too-many-arguments,too-many-instance-attributes
def __init__(self, hass, name, topic, templates, qos, payload, optimistic): def __init__(self, hass, name, topic, templates, qos, payload, optimistic):
@ -71,7 +69,7 @@ class MqttLight(Light):
for key, tpl in templates.items()} for key, tpl in templates.items()}
def state_received(topic, payload, qos): def state_received(topic, payload, qos):
""" A new MQTT message has been received. """ """A new MQTT message has been received."""
payload = templates['state'](payload) payload = templates['state'](payload)
if payload == self._payload["on"]: if payload == self._payload["on"]:
self._state = True self._state = True
@ -85,7 +83,7 @@ class MqttLight(Light):
state_received, self._qos) state_received, self._qos)
def brightness_received(topic, payload, 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._brightness = int(templates['brightness'](payload))
self.update_ha_state() self.update_ha_state()
@ -97,7 +95,7 @@ class MqttLight(Light):
self._brightness = None self._brightness = None
def rgb_received(topic, payload, qos): 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 self._rgb = [int(val) for val in
templates['rgb'](payload).split(',')] templates['rgb'](payload).split(',')]
self.update_ha_state() self.update_ha_state()
@ -111,27 +109,27 @@ class MqttLight(Light):
@property @property
def brightness(self): def brightness(self):
""" Brightness of this light between 0..255. """ """Brightness of this light between 0..255."""
return self._brightness return self._brightness
@property @property
def rgb_color(self): def rgb_color(self):
""" RGB color value. """ """RGB color value."""
return self._rgb return self._rgb
@property @property
def should_poll(self): def should_poll(self):
""" No polling needed for a MQTT light. """ """No polling needed for a MQTT light."""
return False return False
@property @property
def name(self): def name(self):
""" Returns the name of the device if any. """ """Returns the name of the device if any."""
return self._name return self._name
@property @property
def is_on(self): def is_on(self):
""" True if device is on. """ """True if device is on."""
return self._state return self._state
@property @property
@ -140,7 +138,7 @@ class MqttLight(Light):
return self._optimistic return self._optimistic
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
""" Turn the device on. """ """Turn the device on."""
should_update = False should_update = False
if ATTR_RGB_COLOR in kwargs and \ if ATTR_RGB_COLOR in kwargs and \
@ -166,7 +164,7 @@ class MqttLight(Light):
self._payload["on"], self._qos) self._payload["on"], self._qos)
if self._optimistic: if self._optimistic:
# optimistically assume that switch has changed state # Optimistically assume that switch has changed state.
self._state = True self._state = True
should_update = True should_update = True
@ -174,11 +172,11 @@ class MqttLight(Light):
self.update_ha_state() self.update_ha_state()
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
""" Turn the device off. """ """Turn the device off."""
mqtt.publish(self._hass, self._topic["command_topic"], mqtt.publish(self._hass, self._topic["command_topic"],
self._payload["off"], self._qos) self._payload["off"], self._qos)
if self._optimistic: if self._optimistic:
# optimistically assume that switch has changed state # Optimistically assume that switch has changed state.
self._state = False self._state = False
self.update_ha_state() self.update_ha_state()

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.logbook Event parser and human readable log generator.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Parses events and generates a human log.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logbook/ 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 DOMAIN as HA_DOMAIN
from homeassistant.core import State from homeassistant.core import State
from homeassistant.helpers.entity import split_entity_id from homeassistant.helpers.entity import split_entity_id
from homeassistant.util import template from homeassistant.helpers import template
DOMAIN = "logbook" DOMAIN = "logbook"
DEPENDENCIES = ['recorder', 'http'] DEPENDENCIES = ['recorder', 'http']
@ -43,7 +41,7 @@ ATTR_ENTITY_ID = 'entity_id'
def log_entry(hass, name, message, domain=None, entity_id=None): def log_entry(hass, name, message, domain=None, entity_id=None):
""" Adds an entry to the logbook. """ """Adds an entry to the logbook."""
data = { data = {
ATTR_NAME: name, ATTR_NAME: name,
ATTR_MESSAGE: message ATTR_MESSAGE: message
@ -57,10 +55,10 @@ def log_entry(hass, name, message, domain=None, entity_id=None):
def setup(hass, config): def setup(hass, config):
""" Listens for download events to download files. """ """Listens for download events to download files."""
# create service handler
def log_message(service): def log_message(service):
""" Handle sending notification message service calls. """ """Handle sending notification message service calls."""
message = service.data.get(ATTR_MESSAGE) message = service.data.get(ATTR_MESSAGE)
name = service.data.get(ATTR_NAME) name = service.data.get(ATTR_NAME)
domain = service.data.get(ATTR_DOMAIN, None) domain = service.data.get(ATTR_DOMAIN, None)
@ -78,7 +76,7 @@ def setup(hass, config):
def _handle_get_logbook(handler, path_match, data): def _handle_get_logbook(handler, path_match, data):
""" Return logbook entries. """ """Return logbook entries."""
date_str = path_match.group('date') date_str = path_match.group('date')
if date_str: if date_str:
@ -102,10 +100,9 @@ def _handle_get_logbook(handler, path_match, data):
class Entry(object): 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 # pylint: disable=too-many-arguments, too-few-public-methods
def __init__(self, when=None, name=None, message=None, domain=None, def __init__(self, when=None, name=None, message=None, domain=None,
entity_id=None): entity_id=None):
self.when = when self.when = when
@ -115,7 +112,7 @@ class Entry(object):
self.entity_id = entity_id self.entity_id = entity_id
def as_dict(self): 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 { return {
'when': dt_util.datetime_to_str(self.when), 'when': dt_util.datetime_to_str(self.when),
'name': self.name, 'name': self.name,
@ -134,7 +131,6 @@ def humanify(events):
- if home assistant stop and start happen in same minute call it restarted - if home assistant stop and start happen in same minute call it restarted
""" """
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
# Group events in batches of GROUP_BY_MINUTES # Group events in batches of GROUP_BY_MINUTES
for _, g_events in groupby( for _, g_events in groupby(
events, events,
@ -145,7 +141,7 @@ def humanify(events):
# Keep track of last sensor states # Keep track of last sensor states
last_sensor_event = {} last_sensor_event = {}
# group HA start/stop events # Group HA start/stop events
# Maps minute of event to 1: stop, 2: stop + start # Maps minute of event to 1: stop, 2: stop + start
start_stop_events = {} start_stop_events = {}
@ -182,7 +178,7 @@ def humanify(events):
to_state = State.from_dict(event.data.get('new_state')) 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. # we do not report on that yet. Also filter auto groups.
if not to_state or \ if not to_state or \
to_state.last_changed != to_state.last_updated or \ to_state.last_changed != to_state.last_updated or \
@ -238,7 +234,7 @@ def humanify(events):
def _entry_message_from_state(domain, state): 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 # We pass domain in so we don't have to split entity_id again
# pylint: disable=too-many-return-statements # pylint: disable=too-many-return-statements

View File

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

View File

@ -1,6 +1,4 @@
""" """
homeassistant.components.notify
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to notify people. Provides functionality to notify people.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
@ -13,7 +11,7 @@ import os
import homeassistant.bootstrap as bootstrap import homeassistant.bootstrap as bootstrap
from homeassistant.config import load_yaml_config_file from homeassistant.config import load_yaml_config_file
from homeassistant.helpers import config_per_platform from homeassistant.helpers import config_per_platform
from homeassistant.util import template from homeassistant.helpers import template
from homeassistant.const import CONF_NAME from homeassistant.const import CONF_NAME
@ -35,7 +33,7 @@ _LOGGER = logging.getLogger(__name__)
def send_message(hass, message, title=None): def send_message(hass, message, title=None):
""" Send a notification message. """ """Send a notification message."""
data = { data = {
ATTR_MESSAGE: message ATTR_MESSAGE: message
} }
@ -47,14 +45,13 @@ def send_message(hass, message, title=None):
def setup(hass, config): def setup(hass, config):
""" Sets up notify services. """ """Sets up notify services."""
success = False success = False
descriptions = load_yaml_config_file( descriptions = load_yaml_config_file(
os.path.join(os.path.dirname(__file__), 'services.yaml')) os.path.join(os.path.dirname(__file__), 'services.yaml'))
for platform, p_config in config_per_platform(config, DOMAIN, _LOGGER): for platform, p_config in config_per_platform(config, DOMAIN, _LOGGER):
# get platform
notify_implementation = bootstrap.prepare_setup_platform( notify_implementation = bootstrap.prepare_setup_platform(
hass, config, DOMAIN, platform) hass, config, DOMAIN, platform)
@ -62,7 +59,6 @@ def setup(hass, config):
_LOGGER.error("Unknown notification service specified.") _LOGGER.error("Unknown notification service specified.")
continue continue
# create platform service
notify_service = notify_implementation.get_service(hass, p_config) notify_service = notify_implementation.get_service(hass, p_config)
if notify_service is None: if notify_service is None:
@ -70,9 +66,8 @@ def setup(hass, config):
platform) platform)
continue continue
# create service handler
def notify_message(notify_service, call): def notify_message(notify_service, call):
""" Handle sending notification message service calls. """ """Handle sending notification message service calls."""
message = call.data.get(ATTR_MESSAGE) message = call.data.get(ATTR_MESSAGE)
if message is None: if message is None:
@ -85,7 +80,6 @@ def setup(hass, config):
notify_service.send_message(message, title=title, target=target) notify_service.send_message(message, title=title, target=target)
# register service
service_call_handler = partial(notify_message, notify_service) service_call_handler = partial(notify_message, notify_service)
service_notify = p_config.get(CONF_NAME, SERVICE_NOTIFY) service_notify = p_config.get(CONF_NAME, SERVICE_NOTIFY)
hass.services.register(DOMAIN, service_notify, service_call_handler, hass.services.register(DOMAIN, service_notify, service_call_handler,
@ -97,7 +91,7 @@ def setup(hass, config):
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class BaseNotificationService(object): class BaseNotificationService(object):
""" Provides an ABC for notification services. """ """Provides an ABC for notification services."""
def send_message(self, message, **kwargs): def send_message(self, message, **kwargs):
""" """

View File

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

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.rollershutter.mqtt Support for MQTT roller shutters.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT rollershutter.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/rollershutter.mqtt/ https://home-assistant.io/components/rollershutter.mqtt/
@ -11,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt import homeassistant.components.mqtt as mqtt
from homeassistant.components.rollershutter import RollershutterDevice from homeassistant.components.rollershutter import RollershutterDevice
from homeassistant.const import CONF_VALUE_TEMPLATE from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -25,7 +23,7 @@ DEFAULT_PAYLOAD_STOP = "STOP"
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Rollershutter """ """Add MQTT Rollershutter."""
if config.get('command_topic') is None: if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic") _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 # pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttRollershutter(RollershutterDevice): 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, def __init__(self, hass, name, state_topic, command_topic, qos,
payload_up, payload_down, payload_stop, value_template): payload_up, payload_down, payload_stop, value_template):
self._state = None self._state = None
@ -62,7 +60,7 @@ class MqttRollershutter(RollershutterDevice):
return return
def message_received(topic, payload, qos): 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: if value_template is not None:
payload = template.render_with_possible_json_value( payload = template.render_with_possible_json_value(
hass, value_template, payload) hass, value_template, payload)
@ -77,12 +75,12 @@ class MqttRollershutter(RollershutterDevice):
@property @property
def should_poll(self): def should_poll(self):
""" No polling needed """ """No polling needed."""
return False return False
@property @property
def name(self): def name(self):
""" The name of the rollershutter. """ """The name of the rollershutter."""
return self._name return self._name
@property @property
@ -94,16 +92,16 @@ class MqttRollershutter(RollershutterDevice):
return self._state return self._state
def move_up(self, **kwargs): def move_up(self, **kwargs):
""" Move the rollershutter up. """ """Move the rollershutter up."""
mqtt.publish(self.hass, self._command_topic, self._payload_up, mqtt.publish(self.hass, self._command_topic, self._payload_up,
self._qos) self._qos)
def move_down(self, **kwargs): def move_down(self, **kwargs):
""" Move the rollershutter down. """ """Move the rollershutter down."""
mqtt.publish(self.hass, self._command_topic, self._payload_down, mqtt.publish(self.hass, self._command_topic, self._payload_down,
self._qos) self._qos)
def stop(self, **kwargs): def stop(self, **kwargs):
""" Stop the device. """ """Stop the device."""
mqtt.publish(self.hass, self._command_topic, self._payload_stop, mqtt.publish(self.hass, self._command_topic, self._payload_stop,
self._qos) self._qos)

View File

@ -13,11 +13,12 @@ from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, DEVICE_DEFAULT_NAME) ATTR_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, DEVICE_DEFAULT_NAME)
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity 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__) _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) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
CONF_RESOURCE = 'resource' CONF_RESOURCE = 'resource'

View File

@ -10,7 +10,8 @@ from datetime import timedelta
from homeassistant.const import CONF_VALUE_TEMPLATE from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.helpers.entity import Entity 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__) _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.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity 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__) _LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['dweepy==0.2.0'] REQUIREMENTS = ['dweepy==0.2.0']

View File

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

View File

@ -11,7 +11,8 @@ import requests
from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN from homeassistant.const import CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.helpers.entity import Entity 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__) _LOGGER = logging.getLogger(__name__)

View File

@ -9,7 +9,7 @@ import socket
import select import select
from homeassistant.const import CONF_NAME, CONF_HOST 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.exceptions import TemplateError
from homeassistant.helpers.entity import Entity 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.core import EVENT_STATE_CHANGED
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity import Entity, generate_entity_id 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 + '.{}' ENTITY_ID_FORMAT = DOMAIN + '.{}'

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.switch.command_switch Support for custom shell commands to turn a switch on/off.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure custom shell commands to turn a switch on/off.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.command_switch/ https://home-assistant.io/components/switch.command_switch/
@ -11,15 +9,14 @@ import subprocess
from homeassistant.components.switch import SwitchDevice from homeassistant.components.switch import SwitchDevice
from homeassistant.const import CONF_VALUE_TEMPLATE from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): 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', {}) switches = config.get('switches', {})
devices = [] devices = []
@ -37,7 +34,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class CommandSwitch(SwitchDevice): 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 # pylint: disable=too-many-arguments
def __init__(self, hass, name, command_on, command_off, def __init__(self, hass, name, command_on, command_off,
@ -53,7 +50,7 @@ class CommandSwitch(SwitchDevice):
@staticmethod @staticmethod
def _switch(command): def _switch(command):
""" Execute the actual commands. """ """Execute the actual commands."""
_LOGGER.info('Running command: %s', command) _LOGGER.info('Running command: %s', command)
success = (subprocess.call(command, shell=True) == 0) success = (subprocess.call(command, shell=True) == 0)
@ -65,7 +62,7 @@ class CommandSwitch(SwitchDevice):
@staticmethod @staticmethod
def _query_state_value(command): def _query_state_value(command):
""" Execute state command for return value. """ """Execute state command for return value."""
_LOGGER.info('Running state command: %s', command) _LOGGER.info('Running state command: %s', command)
try: try:
@ -76,27 +73,27 @@ class CommandSwitch(SwitchDevice):
@staticmethod @staticmethod
def _query_state_code(command): def _query_state_code(command):
""" Execute state command for return code. """ """Execute state command for return code."""
_LOGGER.info('Running state command: %s', command) _LOGGER.info('Running state command: %s', command)
return subprocess.call(command, shell=True) == 0 return subprocess.call(command, shell=True) == 0
@property @property
def should_poll(self): def should_poll(self):
""" Only poll if we have statecmd. """ """Only poll if we have state command."""
return self._command_state is not None return self._command_state is not None
@property @property
def name(self): def name(self):
""" The name of the switch. """ """The name of the switch."""
return self._name return self._name
@property @property
def is_on(self): def is_on(self):
""" True if device is on. """ """True if device is on."""
return self._state return self._state
def _query_state(self): def _query_state(self):
""" Query for state. """ """Query for state."""
if not self._command_state: if not self._command_state:
_LOGGER.error('No state command specified') _LOGGER.error('No state command specified')
return return
@ -105,7 +102,7 @@ class CommandSwitch(SwitchDevice):
return CommandSwitch._query_state_code(self._command_state) return CommandSwitch._query_state_code(self._command_state)
def update(self): def update(self):
""" Update device state. """ """Update device state."""
if self._command_state: if self._command_state:
payload = str(self._query_state()) payload = str(self._query_state())
if self._value_template: if self._value_template:
@ -114,14 +111,14 @@ class CommandSwitch(SwitchDevice):
self._state = (payload.lower() == "true") self._state = (payload.lower() == "true")
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
""" Turn the device on. """ """Turn the device on."""
if (CommandSwitch._switch(self._command_on) and if (CommandSwitch._switch(self._command_on) and
not self._command_state): not self._command_state):
self._state = True self._state = True
self.update_ha_state() self.update_ha_state()
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
""" Turn the device off. """ """Turn the device off."""
if (CommandSwitch._switch(self._command_off) and if (CommandSwitch._switch(self._command_off) and
not self._command_state): not self._command_state):
self._state = False self._state = False

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.switch.mqtt Support for MQTT switches.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT switch.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.mqtt/ https://home-assistant.io/components/switch.mqtt/
@ -11,7 +9,7 @@ import logging
import homeassistant.components.mqtt as mqtt import homeassistant.components.mqtt as mqtt
from homeassistant.components.switch import SwitchDevice from homeassistant.components.switch import SwitchDevice
from homeassistant.const import CONF_VALUE_TEMPLATE from homeassistant.const import CONF_VALUE_TEMPLATE
from homeassistant.util import template from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -27,7 +25,7 @@ DEPENDENCIES = ['mqtt']
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Switch. """ """Add MQTT switch."""
if config.get('command_topic') is None: if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic") _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 # pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttSwitch(SwitchDevice): 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, def __init__(self, hass, name, state_topic, command_topic, qos, retain,
payload_on, payload_off, optimistic, value_template): payload_on, payload_off, optimistic, value_template):
self._state = False self._state = False
@ -63,7 +61,7 @@ class MqttSwitch(SwitchDevice):
self._optimistic = optimistic self._optimistic = optimistic
def message_received(topic, payload, qos): 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: if value_template is not None:
payload = template.render_with_possible_json_value( payload = template.render_with_possible_json_value(
hass, value_template, payload) hass, value_template, payload)
@ -75,26 +73,25 @@ class MqttSwitch(SwitchDevice):
self.update_ha_state() self.update_ha_state()
if self._state_topic is None: if self._state_topic is None:
# force optimistic mode # Force into optimistic mode.
self._optimistic = True self._optimistic = True
else: else:
# subscribe the state_topic
mqtt.subscribe(hass, self._state_topic, message_received, mqtt.subscribe(hass, self._state_topic, message_received,
self._qos) self._qos)
@property @property
def should_poll(self): def should_poll(self):
""" No polling needed. """ """No polling needed."""
return False return False
@property @property
def name(self): def name(self):
""" The name of the switch. """ """The name of the switch."""
return self._name return self._name
@property @property
def is_on(self): def is_on(self):
""" True if device is on. """ """True if device is on."""
return self._state return self._state
@property @property
@ -103,19 +100,19 @@ class MqttSwitch(SwitchDevice):
return self._optimistic return self._optimistic
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
""" Turn the device on. """ """Turn the device on."""
mqtt.publish(self.hass, self._command_topic, self._payload_on, mqtt.publish(self.hass, self._command_topic, self._payload_on,
self._qos, self._retain) self._qos, self._retain)
if self._optimistic: if self._optimistic:
# optimistically assume that switch has changed state # Optimistically assume that switch has changed state.
self._state = True self._state = True
self.update_ha_state() self.update_ha_state()
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
""" Turn the device off. """ """Turn the device off."""
mqtt.publish(self.hass, self._command_topic, self._payload_off, mqtt.publish(self.hass, self._command_topic, self._payload_off,
self._qos, self._retain) self._qos, self._retain)
if self._optimistic: if self._optimistic:
# optimistically assume that switch has changed state # Optimistically assume that switch has changed state.
self._state = False self._state = False
self.update_ha_state() self.update_ha_state()

View File

@ -1,7 +1,5 @@
""" """
homeassistant.components.switch.template Support for switches which integrates with other components.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows the creation of a switch that integrates other components together
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.template/ 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.exceptions import TemplateError
from homeassistant.helpers.entity import generate_entity_id from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.service import call_from_config 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 + '.{}' ENTITY_ID_FORMAT = DOMAIN + '.{}'
@ -31,7 +30,7 @@ OFF_ACTION = 'turn_off'
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the switches. """ """Sets up the Template switch."""
switches = [] switches = []
if config.get(CONF_SWITCHES) is None: if config.get(CONF_SWITCHES) is None:
@ -80,7 +79,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SwitchTemplate(SwitchDevice): class SwitchTemplate(SwitchDevice):
""" Represents a Template Switch. """ """Represents a Template switch."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, def __init__(self,
@ -103,37 +102,37 @@ class SwitchTemplate(SwitchDevice):
self.update() self.update()
def _update_callback(_event): def _update_callback(_event):
""" Called when the target device changes state. """ """Called when the target device changes state."""
self.update_ha_state(True) self.update_ha_state(True)
self.hass.bus.listen(EVENT_STATE_CHANGED, _update_callback) self.hass.bus.listen(EVENT_STATE_CHANGED, _update_callback)
@property @property
def name(self): def name(self):
""" Returns the name of the device. """ """Returns the name of the switch."""
return self._name return self._name
@property @property
def should_poll(self): def should_poll(self):
""" Tells Home Assistant not to poll this entity. """ """No polling needed."""
return False return False
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
""" Fires the on action. """ """Fires the on action."""
call_from_config(self.hass, self._on_action, True) call_from_config(self.hass, self._on_action, True)
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
""" Fires the off action. """ """Fires the off action."""
call_from_config(self.hass, self._off_action, True) call_from_config(self.hass, self._off_action, True)
@property @property
def is_on(self): def is_on(self):
""" True if device is on. """ """True if device is on."""
return self._value.lower() == 'true' or self._value == STATE_ON return self._value.lower() == 'true' or self._value == STATE_ON
@property @property
def is_off(self): def is_off(self):
""" True if device is off. """ """True if device is off."""
return self._value.lower() == 'false' or self._value == STATE_OFF return self._value.lower() == 'false' or self._value == STATE_OFF
@property @property
@ -142,7 +141,7 @@ class SwitchTemplate(SwitchDevice):
return self.is_on or self.is_off return self.is_on or self.is_off
def update(self): def update(self):
""" Updates the state from the template. """ """Updates the state from the template."""
try: try:
self._value = template.render(self.hass, self._template) self._value = template.render(self.hass, self._template)
if not self.available: if not self.available:

View File

@ -1,7 +1,5 @@
""" """
homeassistant.util.template Template helper methods for rendering strings with HA data.
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Template utility methods for rendering strings with HA data.
""" """
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
import json import json
@ -23,8 +21,10 @@ _SENTINEL = object()
def render_with_possible_json_value(hass, template, value, def render_with_possible_json_value(hass, template, value,
error_value=_SENTINEL): 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 = { variables = {
'value': value 'value': value
} }
@ -41,7 +41,7 @@ def render_with_possible_json_value(hass, template, value,
def render(hass, template, variables=None, **kwargs): def render(hass, template, variables=None, **kwargs):
""" Render given template. """ """Render given template."""
if variables is not None: if variables is not None:
kwargs.update(variables) kwargs.update(variables)
@ -63,7 +63,7 @@ def render(hass, template, variables=None, **kwargs):
class AllStates(object): class AllStates(object):
""" Class to expose all HA states as attributes. """ """Class to expose all HA states as attributes."""
def __init__(self, hass): def __init__(self, hass):
self._hass = hass self._hass = hass
@ -80,7 +80,7 @@ class AllStates(object):
class DomainStates(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): def __init__(self, hass, domain):
self._hass = hass self._hass = hass

View File

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