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']
@ -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'

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']
@ -173,7 +171,7 @@ 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())
@ -301,7 +299,6 @@ 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']
@ -335,7 +332,6 @@ 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:
@ -359,7 +355,6 @@ 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)

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__)
@ -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
@ -179,6 +177,6 @@ class MqttLight(Light):
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']
@ -58,7 +56,7 @@ 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)
@ -105,7 +103,6 @@ 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 \

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
@ -54,7 +52,6 @@ def setup(hass, config):
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,7 +66,6 @@ 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)
@ -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,

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")
@ -77,7 +75,7 @@ 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

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,7 +9,7 @@ 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__)
@ -19,7 +17,6 @@ _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,
@ -82,7 +79,7 @@ class CommandSwitch(SwitchDevice):
@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

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")
@ -75,10 +73,9 @@ 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)
@ -107,7 +104,7 @@ class MqttSwitch(SwitchDevice):
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()
@ -116,6 +113,6 @@ class MqttSwitch(SwitchDevice):
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,
@ -110,12 +109,12 @@ class SwitchTemplate(SwitchDevice):
@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):

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
} }

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
@ -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(