Update docstrings (#7374)

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstrings

* Update docstring

* Update docstrings

* Update docstrings

* Fix lint issues

* Update docstrings

* Revert changes in dict
This commit is contained in:
Fabian Affolter 2017-05-02 18:18:47 +02:00 committed by Paulus Schoutsen
parent 0e08925259
commit a4f1f6e724
340 changed files with 1533 additions and 1708 deletions

View File

@ -26,7 +26,7 @@ STATES = [STATE_OFF, STATE_ON, 'true', 'false']
# pylint: disable=unused-argument
def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None):
"""Setup the ISY994 binary sensor platform."""
"""Set up the ISY994 binary sensor platform."""
if isy.ISY is None or not isy.ISY.connected:
_LOGGER.error("A connection has not been made to the ISY controller")
return False

View File

@ -34,8 +34,8 @@ PRESENCE_SENSOR_TYPES = {
"Outdoor vehicle": "motion"
}
TAG_SENSOR_TYPES = {
"Tag Vibration": 'vibration',
"Tag Open": 'opening'
"Tag Vibration": "vibration",
"Tag Open": "opening"
}
CONF_HOME = 'home'
@ -117,7 +117,7 @@ class NetatmoBinarySensor(BinarySensorDevice):
def __init__(self, data, camera_name, module_name, home,
timeout, offset, camera_type, sensor):
"""Setup for access to the Netatmo camera events."""
"""Set up for access to the Netatmo camera events."""
self._data = data
self._camera_name = camera_name
self._module_name = module_name

View File

@ -54,7 +54,7 @@ class GoogleCalendarData(object):
"""Class to utilize calendar service object to get next event."""
def __init__(self, calendar_service, calendar_id, search=None):
"""Setup how we are going to search the google calendar."""
"""Set up how we are going to search the google calendar."""
self.calendar_service = calendar_service
self.calendar_id = calendar_id
self.search = search

View File

@ -55,7 +55,7 @@ class NetatmoCamera(Camera):
"""Representation of the images published from a Netatmo camera."""
def __init__(self, data, camera_name, home, camera_type, verify_ssl):
"""Set up access to the Netatmo camera images."""
"""Set up for access to the Netatmo camera images."""
super(NetatmoCamera, self).__init__()
self._data = data
self._camera_name = camera_name

View File

@ -208,7 +208,7 @@ def set_swing_mode(hass, swing_mode, entity_id=None):
@asyncio.coroutine
def async_setup(hass, config):
"""Setup climate devices."""
"""Set up climate devices."""
component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL)
yield from component.async_setup(config)

View File

@ -63,10 +63,10 @@ class MikrotikScanner(DeviceScanner):
self.success_init = self.connect_to_device()
if self.success_init:
_LOGGER.info('Start polling Mikrotik router...')
_LOGGER.info("Start polling Mikrotik router...")
self._update_info()
else:
_LOGGER.error('Connection to Mikrotik failed.')
_LOGGER.error("Connection to Mikrotik failed")
def connect_to_device(self):
"""Connect to Mikrotik method."""
@ -83,14 +83,14 @@ class MikrotikScanner(DeviceScanner):
routerboard_info = self.client(cmd='/system/routerboard/getall')
if routerboard_info:
_LOGGER.info('Connected to Mikrotik %s with ip %s.',
_LOGGER.info("Connected to Mikrotik %s with IP %s",
routerboard_info[0].get('model', 'Router'),
self.host)
self.connected = True
except (librouteros.exceptions.TrapError,
librouteros.exceptions.ConnectionError) as api_error:
_LOGGER.error('Connection error: %s', api_error)
_LOGGER.error("Connection error: %s", api_error)
return self.connected
@ -108,7 +108,7 @@ class MikrotikScanner(DeviceScanner):
def _update_info(self):
"""Retrieve latest information from the Mikrotik box."""
with self.lock:
_LOGGER.info('Loading wireless device from Mikrotik...')
_LOGGER.info("Loading wireless device from Mikrotik...")
wireless_clients = self.client(
cmd='/interface/wireless/registration-table/getall'

View File

@ -35,7 +35,7 @@ STATES = [SPEED_OFF, SPEED_LOW, 'med', SPEED_HIGH]
# pylint: disable=unused-argument
def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None):
"""Setup the ISY994 fan platform."""
"""Set up the ISY994 fan platform."""
if isy.ISY is None or not isy.ISY.connected:
_LOGGER.error("A connection has not been made to the ISY controller")
return False

View File

@ -19,7 +19,7 @@ SPEED_AUTO = 'auto'
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink platform."""
"""Set up the Wink platform."""
import pywink
for fan in pywink.get_fans():

View File

@ -27,7 +27,7 @@ SUPPORT_DEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT |
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Setup the demo light platform."""
"""Set up the demo light platform."""
add_devices_callback([
DemoLight("Bed Light", False, True, effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0]),

View File

@ -56,12 +56,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the LIFX platform."""
"""Set up the LIFX platform."""
import aiolifx
if sys.platform == 'win32':
_LOGGER.warning('The lifx platform is known to not work on Windows. '
'Consider using the lifx_legacy platform instead.')
_LOGGER.warning("The lifx platform is known to not work on Windows. "
"Consider using the lifx_legacy platform instead")
server_addr = config.get(CONF_SERVER)
@ -420,9 +420,8 @@ class LIFXLight(Light):
self._bri = bri
self._kel = kel
red, green, blue = colorsys.hsv_to_rgb(hue / SHORT_MAX,
sat / SHORT_MAX,
bri / SHORT_MAX)
red, green, blue = colorsys.hsv_to_rgb(
hue / SHORT_MAX, sat / SHORT_MAX, bri / SHORT_MAX)
red = int(red * BYTE_MAX)
green = int(green * BYTE_MAX)

View File

@ -40,22 +40,22 @@ LIFX_EFFECT_BREATHE_SCHEMA = LIFX_EFFECT_SCHEMA.extend({
ATTR_COLOR_NAME: cv.string,
ATTR_RGB_COLOR: vol.All(vol.ExactSequence((cv.byte, cv.byte, cv.byte)),
vol.Coerce(tuple)),
vol.Optional(ATTR_PERIOD, default=1.0): vol.All(vol.Coerce(float),
vol.Range(min=0.05)),
vol.Optional(ATTR_CYCLES, default=1.0): vol.All(vol.Coerce(float),
vol.Range(min=1)),
vol.Optional(ATTR_PERIOD, default=1.0):
vol.All(vol.Coerce(float), vol.Range(min=0.05)),
vol.Optional(ATTR_CYCLES, default=1.0):
vol.All(vol.Coerce(float), vol.Range(min=1)),
})
LIFX_EFFECT_PULSE_SCHEMA = LIFX_EFFECT_BREATHE_SCHEMA
LIFX_EFFECT_COLORLOOP_SCHEMA = LIFX_EFFECT_SCHEMA.extend({
ATTR_BRIGHTNESS: vol.All(vol.Coerce(int), vol.Clamp(min=0, max=255)),
vol.Optional(ATTR_PERIOD, default=60): vol.All(vol.Coerce(float),
vol.Clamp(min=1)),
vol.Optional(ATTR_CHANGE, default=20): vol.All(vol.Coerce(float),
vol.Clamp(min=0, max=360)),
vol.Optional(ATTR_SPREAD, default=30): vol.All(vol.Coerce(float),
vol.Clamp(min=0, max=360)),
vol.Optional(ATTR_PERIOD, default=60):
vol.All(vol.Coerce(float), vol.Clamp(min=1)),
vol.Optional(ATTR_CHANGE, default=20):
vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)),
vol.Optional(ATTR_SPREAD, default=30):
vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)),
})
LIFX_EFFECT_STOP_SCHEMA = vol.Schema({

View File

@ -1,4 +1,9 @@
"""Support for Lutron lights."""
"""
Support for Lutron lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.lutron/
"""
import logging
from homeassistant.components.light import (

View File

@ -1,4 +1,9 @@
"""Support for Lutron Caseta lights."""
"""
Support for Lutron Caseta lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.lutron_caseta/
"""
import logging
from homeassistant.components.light import (
@ -8,7 +13,6 @@ from homeassistant.components.light.lutron import (
from homeassistant.components.lutron_caseta import (
LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron_caseta']
@ -16,7 +20,7 @@ DEPENDENCIES = ['lutron_caseta']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Lutron Caseta lights."""
"""Set up the Lutron Caseta lights."""
devs = []
bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE]
light_devices = bridge.get_devices_by_types(["WallDimmer", "PlugInDimmer"])

View File

@ -92,7 +92,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Add MQTT Light."""
"""Set up a MQTT Light."""
if discovery_info is not None:
config = PLATFORM_SCHEMA(discovery_info)
@ -142,7 +142,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class MqttLight(Light):
"""MQTT light."""
"""Representation of a MQTT light."""
def __init__(self, name, effect_list, topic, templates, qos,
retain, payload, optimistic, brightness_scale,
@ -197,7 +197,7 @@ class MqttLight(Light):
@asyncio.coroutine
def async_added_to_hass(self):
"""Subscribe mqtt events.
"""Subscribe to MQTT events.
This method is a coroutine.
"""
@ -211,7 +211,7 @@ class MqttLight(Light):
@callback
def state_received(topic, payload, qos):
"""A new MQTT message has been received."""
"""Handle new MQTT messages."""
payload = templates[CONF_STATE](payload)
if payload == self._payload['on']:
self._state = True
@ -226,7 +226,7 @@ class MqttLight(Light):
@callback
def brightness_received(topic, payload, qos):
"""A new MQTT message for the brightness has been received."""
"""Handle new MQTT messages for the brightness."""
device_value = float(templates[CONF_BRIGHTNESS](payload))
percent_bright = device_value / self._brightness_scale
self._brightness = int(percent_bright * 255)
@ -244,7 +244,7 @@ class MqttLight(Light):
@callback
def rgb_received(topic, payload, qos):
"""A new MQTT message has been received."""
"""Handle new MQTT messages for RGB."""
self._rgb = [int(val) for val in
templates[CONF_RGB](payload).split(',')]
self.hass.async_add_job(self.async_update_ha_state())
@ -261,7 +261,7 @@ class MqttLight(Light):
@callback
def color_temp_received(topic, payload, qos):
"""A new MQTT message for color temp has been received."""
"""Handle new MQTT messages for color temperature."""
self._color_temp = int(templates[CONF_COLOR_TEMP](payload))
self.hass.async_add_job(self.async_update_ha_state())
@ -277,7 +277,7 @@ class MqttLight(Light):
@callback
def effect_received(topic, payload, qos):
"""A new MQTT message for effect has been received."""
"""Handle new MQTT messages for effect."""
self._effect = templates[CONF_EFFECT](payload)
self.hass.async_add_job(self.async_update_ha_state())
@ -293,7 +293,7 @@ class MqttLight(Light):
@callback
def white_value_received(topic, payload, qos):
"""A new MQTT message for the white value has been received."""
"""Handle new MQTT messages for white value."""
device_value = float(templates[CONF_WHITE_VALUE](payload))
percent_white = device_value / self._white_value_scale
self._white_value = int(percent_white * 255)
@ -311,7 +311,7 @@ class MqttLight(Light):
@callback
def xy_received(topic, payload, qos):
"""A new MQTT message has been received."""
"""Handle new MQTT messages for color."""
self._xy = [float(val) for val in
templates[CONF_XY](payload).split(',')]
self.hass.async_add_job(self.async_update_ha_state())

View File

@ -157,13 +157,13 @@ class MqttJson(Light):
@asyncio.coroutine
def async_added_to_hass(self):
"""Subscribe mqtt events.
"""Subscribe to MQTT events.
This method is a coroutine.
"""
@callback
def state_received(topic, payload, qos):
"""A new MQTT message has been received."""
"""Handle new MQTT messages."""
values = json.loads(payload)
if values['state'] == 'ON':
@ -189,7 +189,7 @@ class MqttJson(Light):
except KeyError:
pass
except ValueError:
_LOGGER.warning('Invalid brightness value received')
_LOGGER.warning("Invalid brightness value received")
if self._color_temp is not None:
try:
@ -197,7 +197,7 @@ class MqttJson(Light):
except KeyError:
pass
except ValueError:
_LOGGER.warning('Invalid color temp value received')
_LOGGER.warning("Invalid color temp value received")
if self._effect is not None:
try:
@ -205,7 +205,7 @@ class MqttJson(Light):
except KeyError:
pass
except ValueError:
_LOGGER.warning('Invalid effect value received')
_LOGGER.warning("Invalid effect value received")
if self._white_value is not None:
try:
@ -213,7 +213,7 @@ class MqttJson(Light):
except KeyError:
pass
except ValueError:
_LOGGER.warning('Invalid white value value received')
_LOGGER.warning("Invalid white value value received")
if self._xy is not None:
try:

View File

@ -104,7 +104,7 @@ class MqttTemplate(Light):
def __init__(self, hass, name, effect_list, topics, templates, optimistic,
qos, retain):
"""Initialize MQTT Template light."""
"""Initialize a MQTT Template light."""
self._name = name
self._effect_list = effect_list
self._topics = topics
@ -139,21 +139,19 @@ class MqttTemplate(Light):
self._rgb = None
self._effect = None
# init hass to template
for tpl in self._templates.values():
if tpl is not None:
tpl.hass = hass
@asyncio.coroutine
def async_added_to_hass(self):
"""Subscribe mqtt events.
"""Subscribe to MQTT events.
This method is a coroutine.
"""
@callback
def state_received(topic, payload, qos):
"""A new MQTT message has been received."""
# read state
"""Handle new MQTT messages."""
state = self._templates[CONF_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if state == STATE_ON:
@ -161,9 +159,8 @@ class MqttTemplate(Light):
elif state == STATE_OFF:
self._state = False
else:
_LOGGER.warning('Invalid state value received')
_LOGGER.warning("Invalid state value received")
# read brightness
if self._brightness is not None:
try:
self._brightness = int(
@ -171,9 +168,8 @@ class MqttTemplate(Light):
async_render_with_possible_json_value(payload)
)
except ValueError:
_LOGGER.warning('Invalid brightness value received')
_LOGGER.warning("Invalid brightness value received")
# read color temperature
if self._color_temp is not None:
try:
self._color_temp = int(
@ -181,9 +177,8 @@ class MqttTemplate(Light):
async_render_with_possible_json_value(payload)
)
except ValueError:
_LOGGER.warning('Invalid color temperature value received')
_LOGGER.warning("Invalid color temperature value received")
# read color
if self._rgb is not None:
try:
self._rgb[0] = int(
@ -196,9 +191,8 @@ class MqttTemplate(Light):
self._templates[CONF_BLUE_TEMPLATE].
async_render_with_possible_json_value(payload))
except ValueError:
_LOGGER.warning('Invalid color value received')
_LOGGER.warning("Invalid color value received")
# read white value
if self._white_value is not None:
try:
self._white_value = int(
@ -208,16 +202,14 @@ class MqttTemplate(Light):
except ValueError:
_LOGGER.warning('Invalid white value received')
# read effect
if self._templates[CONF_EFFECT_TEMPLATE] is not None:
effect = self._templates[CONF_EFFECT_TEMPLATE].\
async_render_with_possible_json_value(payload)
# validate effect value
if effect in self._effect_list:
self._effect = effect
else:
_LOGGER.warning('Unsupported effect value received')
_LOGGER.warning("Unsupported effect value received")
self.hass.async_add_job(self.async_update_ha_state())
@ -285,26 +277,22 @@ class MqttTemplate(Light):
This method is a coroutine.
"""
# state
values = {'state': True}
if self._optimistic:
self._state = True
# brightness
if ATTR_BRIGHTNESS in kwargs:
values['brightness'] = int(kwargs[ATTR_BRIGHTNESS])
if self._optimistic:
self._brightness = kwargs[ATTR_BRIGHTNESS]
# color_temp
if ATTR_COLOR_TEMP in kwargs:
values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])
if self._optimistic:
self._color_temp = kwargs[ATTR_COLOR_TEMP]
# color
if ATTR_RGB_COLOR in kwargs:
values['red'] = kwargs[ATTR_RGB_COLOR][0]
values['green'] = kwargs[ATTR_RGB_COLOR][1]
@ -313,22 +301,18 @@ class MqttTemplate(Light):
if self._optimistic:
self._rgb = kwargs[ATTR_RGB_COLOR]
# white value
if ATTR_WHITE_VALUE in kwargs:
values['white_value'] = int(kwargs[ATTR_WHITE_VALUE])
if self._optimistic:
self._white_value = kwargs[ATTR_WHITE_VALUE]
# effect
if ATTR_EFFECT in kwargs:
values['effect'] = kwargs.get(ATTR_EFFECT)
# flash
if ATTR_FLASH in kwargs:
values['flash'] = kwargs.get(ATTR_FLASH)
# transition
if ATTR_TRANSITION in kwargs:
values['transition'] = int(kwargs[ATTR_TRANSITION])
@ -347,12 +331,10 @@ class MqttTemplate(Light):
This method is a coroutine.
"""
# state
values = {'state': False}
if self._optimistic:
self._state = False
# transition
if ATTR_TRANSITION in kwargs:
values['transition'] = int(kwargs[ATTR_TRANSITION])

View File

@ -4,15 +4,12 @@ Support for MySensors lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mysensors/
"""
import logging
from homeassistant.components import mysensors
from homeassistant.components.light import (ATTR_BRIGHTNESS, ATTR_RGB_COLOR,
ATTR_WHITE_VALUE,
SUPPORT_BRIGHTNESS,
SUPPORT_RGB_COLOR,
SUPPORT_WHITE_VALUE, Light)
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_WHITE_VALUE,
SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, SUPPORT_WHITE_VALUE, Light)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.util.color import rgb_hex_to_rgb_list
@ -25,9 +22,7 @@ SUPPORT_MYSENSORS = (SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the mysensors platform for sensors."""
# Only act if loaded via mysensors by discovery event.
# Otherwise gateway is not setup.
"""Set up the MySensors platform for lights."""
if discovery_info is None:
return
@ -62,10 +57,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
"""Represent the value of a MySensors Light child node."""
"""Representation of a MySensors Light child node."""
def __init__(self, *args):
"""Set up instance attributes."""
"""Initialize a MySensors Light."""
mysensors.MySensorsDeviceEntity.__init__(self, *args)
self._state = None
self._brightness = None
@ -157,7 +152,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
elif white is not None:
rgb.append(white)
else:
_LOGGER.error('White value is not updated for RGBW light')
_LOGGER.error("White value is not updated for RGBW light")
return
hex_color = hex_template % tuple(rgb)
if len(rgb) > 3:
@ -206,9 +201,8 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
set_req = self.gateway.const.SetReq
if value_type is None or value is None:
_LOGGER.warning(
'%s: value_type %s, value = %s, '
'None is not valid argument when setting child value'
'', self._name, value_type, value)
"%s: value_type %s, value = %s, None is not valid argument "
"when setting child value", self._name, value_type, value)
return
self.gateway.set_child_value(
self.node_id, self.child_id, value_type, value)
@ -244,7 +238,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
value = self._values[self.value_type]
if len(value) != 6 and len(value) != 8:
_LOGGER.error(
'Wrong value %s for %s', value, set_req(self.value_type).name)
"Wrong value %s for %s", value, set_req(self.value_type).name)
return
color_list = rgb_hex_to_rgb_list(value)
if set_req.V_LIGHT not in self._values and \
@ -253,7 +247,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
if len(color_list) > 3:
if set_req.V_RGBW != self.value_type:
_LOGGER.error(
'Wrong value %s for %s',
"Wrong value %s for %s",
value, set_req(self.value_type).name)
return
self._white = color_list.pop()
@ -265,7 +259,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
child = node.children[self.child_id]
for value_type, value in child.values.items():
_LOGGER.debug(
'%s: value_type %s, value = %s', self._name, value_type, value)
"%s: value_type %s, value = %s", self._name, value_type, value)
self._values[value_type] = value

View File

@ -72,7 +72,7 @@ class MyStromLight(Light):
@property
def brightness(self):
"""Brightness of the light."""
"""Return the brightness of the light."""
return self._brightness
@property

View File

@ -46,13 +46,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
try:
bridge = lightify.Lightify(host)
except socket.error as err:
msg = 'Error connecting to bridge: {} due to: {}'.format(host,
str(err))
msg = "Error connecting to bridge: {} due to: {}".format(
host, str(err))
_LOGGER.exception(msg)
return False
setup_bridge(bridge, add_devices)
else:
_LOGGER.error('No host found in configuration')
_LOGGER.error("No host found in configuration")
return False
@ -105,8 +105,8 @@ class OsramLightifyLight(Light):
@property
def rgb_color(self):
"""Last RGB color value set."""
_LOGGER.debug("rgb_color light state for light: %s is: %s %s %s ",
"""Return the last RGB color value set."""
_LOGGER.debug("rgb_color light state for light: %s is: %s %s %s",
self._name, self._rgb[0], self._rgb[1], self._rgb[2])
return self._rgb
@ -117,16 +117,16 @@ class OsramLightifyLight(Light):
@property
def brightness(self):
"""Brightness of this light between 0..255."""
_LOGGER.debug("brightness for light %s is: %s",
self._name, self._brightness)
"""Return the brightness of this light between 0..255."""
_LOGGER.debug(
"Brightness for light %s is: %s", self._name, self._brightness)
return self._brightness
@property
def is_on(self):
"""Update Status to True if device is on."""
_LOGGER.debug("is_on light state for light: %s is: %s",
self._name, self._state)
_LOGGER.debug(
"is_on light state for light: %s is: %s", self._name, self._state)
return self._state
@property
@ -136,35 +136,31 @@ class OsramLightifyLight(Light):
def turn_on(self, **kwargs):
"""Turn the device on."""
_LOGGER.debug("turn_on Attempting to turn on light: %s ",
self._name)
_LOGGER.debug("turn_on Attempting to turn on light: %s ", self._name)
self._light.set_onoff(1)
self._state = self._light.on()
if ATTR_TRANSITION in kwargs:
transition = int(kwargs[ATTR_TRANSITION] * 10)
_LOGGER.debug("turn_on requested transition time for light:"
" %s is: %s ",
self._name, transition)
_LOGGER.debug("turn_on requested transition time for light: "
"%s is: %s", self._name, transition)
else:
transition = 0
_LOGGER.debug("turn_on requested transition time for light:"
" %s is: %s ",
self._name, transition)
_LOGGER.debug("turn_on requested transition time for light: "
"%s is: %s", self._name, transition)
if ATTR_RGB_COLOR in kwargs:
red, green, blue = kwargs[ATTR_RGB_COLOR]
_LOGGER.debug("turn_on requested ATTR_RGB_COLOR for light:"
" %s is: %s %s %s ",
self._name, red, green, blue)
_LOGGER.debug("turn_on requested ATTR_RGB_COLOR for light: "
"%s is: %s %s %s", self._name, red, green, blue)
self._light.set_rgb(red, green, blue, transition)
if ATTR_COLOR_TEMP in kwargs:
color_t = kwargs[ATTR_COLOR_TEMP]
kelvin = int(color_temperature_mired_to_kelvin(color_t))
_LOGGER.debug("turn_on requested set_temperature for light:"
" %s: %s ", self._name, kelvin)
_LOGGER.debug("turn_on requested set_temperature for light: "
"%s: %s", self._name, kelvin)
self._light.set_temperature(kelvin, transition)
if ATTR_BRIGHTNESS in kwargs:
@ -182,9 +178,8 @@ class OsramLightifyLight(Light):
random.randrange(0, 255),
random.randrange(0, 255),
transition)
_LOGGER.debug("turn_on requested random effect for light:"
" %s with transition %s ",
self._name, transition)
_LOGGER.debug("turn_on requested random effect for light: "
"%s with transition %s", self._name, transition)
self.schedule_update_ha_state()
@ -194,15 +189,13 @@ class OsramLightifyLight(Light):
self._name)
if ATTR_TRANSITION in kwargs:
transition = int(kwargs[ATTR_TRANSITION] * 10)
_LOGGER.debug("turn_off requested transition time for light:"
" %s is: %s ",
self._name, transition)
_LOGGER.debug("turn_off requested transition time for light: "
"%s is: %s", self._name, transition)
self._light.set_luminance(0, transition)
else:
transition = 0
_LOGGER.debug("turn_off requested transition time for light:"
" %s is: %s ",
self._name, transition)
_LOGGER.debug("turn_off requested transition time for light: "
"%s is: %s ", self._name, transition)
self._light.set_onoff(0)
self._state = self._light.on()

View File

@ -59,7 +59,7 @@ class PiglowLight(Light):
@property
def brightness(self):
"""Brightness of the light (an integer in the range 1-255)."""
"""Return the brightness of the light."""
return self._brightness
@property

View File

@ -15,7 +15,7 @@ DEPENDENCIES = ['qwikswitch']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Add lights from the main Qwikswitch component."""
"""Set up the lights from the main Qwikswitch component."""
if discovery_info is None:
_LOGGER.error("Configure Qwikswitch component failed")
return False

View File

@ -119,7 +119,7 @@ def devices_from_config(domain_config, hass=None):
# Register entity (and aliasses) to listen to incoming rflink events
# device id and normal aliasses respond to normal and group command
# Device id and normal aliasses respond to normal and group command
hass.data[DATA_ENTITY_LOOKUP][
EVENT_KEY_COMMAND][device_id].append(device)
if config[CONF_GROUP]:
@ -188,7 +188,7 @@ class DimmableRflinkLight(SwitchableRflinkDevice, Light):
# rflink only support 16 brightness levels
self._brightness = int(kwargs[ATTR_BRIGHTNESS] / 17) * 17
# turn on light at the requested dim level
# Turn on light at the requested dim level
yield from self._async_handle_command('dim', self._brightness)
@property

View File

@ -27,7 +27,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices(lights)
def light_update(event):
"""Define callback for light updates from the RFXtrx gateway."""
"""Handle light updates from the RFXtrx gateway."""
if not isinstance(event.device, rfxtrxmod.LightingDevice) or \
not event.device.known_to_be_dimmable:
return
@ -38,13 +38,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
rfxtrx.apply_received_command(event)
# Subscribe to main rfxtrx events
# Subscribe to main RFXtrx events
if light_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS:
rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(light_update)
class RfxtrxLight(rfxtrx.RfxtrxDevice, Light):
"""Represenation of a RFXtrx light."""
"""Representation of a RFXtrx light."""
@property
def brightness(self):
@ -61,8 +61,8 @@ class RfxtrxLight(rfxtrx.RfxtrxDevice, Light):
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness is None:
self._brightness = 255
self._send_command("turn_on")
self._send_command('turn_on')
else:
self._brightness = brightness
_brightness = (brightness * 100 // 255)
self._send_command("dim", _brightness)
self._send_command('dim', _brightness)

View File

@ -4,7 +4,6 @@ Support for LED lights that can be controlled using PWM.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.pwm/
"""
import logging
import voluptuous as vol
@ -55,7 +54,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the pwm lights."""
"""Set up the PWM LED lights."""
from pwmled.led import SimpleLed
from pwmled.led.rgb import RgbLed
from pwmled.led.rgbw import RgbwLed
@ -76,7 +75,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
opt_args['address'] = led_conf[CONF_ADDRESS]
driver = Pca9685Driver(pins, **opt_args)
else:
_LOGGER.error("Invalid driver type.")
_LOGGER.error("Invalid driver type")
return
name = led_conf[CONF_NAME]
@ -88,7 +87,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
elif led_type == CONF_LED_TYPE_RGBW:
led = PwmRgbLed(RgbwLed(driver), name)
else:
_LOGGER.error("Invalid led type.")
_LOGGER.error("Invalid led type")
return
leds.append(led)
@ -96,10 +95,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class PwmSimpleLed(Light):
"""Representation of a simple on-color pwm led."""
"""Representation of a simple one-color PWM LED."""
def __init__(self, led, name):
"""Initialize led."""
"""Initialize one-color PWM LED."""
self._led = led
self._name = name
self._is_on = False
@ -149,7 +148,7 @@ class PwmSimpleLed(Light):
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn off a led."""
"""Turn off a LED."""
if self.is_on:
if ATTR_TRANSITION in kwargs:
transition_time = kwargs[ATTR_TRANSITION]
@ -162,10 +161,10 @@ class PwmSimpleLed(Light):
class PwmRgbLed(PwmSimpleLed):
"""Representation of a rgb(w) pwm led."""
"""Representation of a RGB(W) PWM LED."""
def __init__(self, led, name):
"""Initialize led."""
"""Initialize a RGB(W) PWM LED."""
super().__init__(led, name)
self._color = DEFAULT_COLOR
@ -180,7 +179,7 @@ class PwmRgbLed(PwmSimpleLed):
return SUPPORT_RGB_LED
def turn_on(self, **kwargs):
"""Turn on a led."""
"""Turn on a LED."""
if ATTR_RGB_COLOR in kwargs:
self._color = kwargs[ATTR_RGB_COLOR]
if ATTR_BRIGHTNESS in kwargs:

View File

@ -47,7 +47,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class SCSGateLight(Light):
"""representation of a SCSGate light."""
"""Representation of a SCSGate light."""
def __init__(self, scs_id, name, logger):
"""Initialize the light."""

View File

@ -58,10 +58,7 @@ class SenseHatLight(Light):
@property
def brightness(self):
"""Read back the brightness of the light.
Returns integer in the range of 1-255.
"""
"""Read back the brightness of the light."""
return self._brightness
@property

View File

@ -5,7 +5,6 @@ This platform uses the Telldus Live online service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.tellduslive/
"""
import logging
@ -17,17 +16,17 @@ _LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up lights."""
"""Set up the Tellstick Net lights."""
if discovery_info is None:
return
add_devices(TelldusLiveLight(hass, light) for light in discovery_info)
class TelldusLiveLight(TelldusLiveEntity, Light):
"""Representation of a light."""
"""Representation of a Tellstick Net light."""
def __init__(self, hass, device_id):
"""Initialize the light."""
"""Initialize the Tellstick Net light."""
super().__init__(hass, device_id)
self._last_brightness = self.brightness

View File

@ -6,12 +6,11 @@ https://home-assistant.io/components/light.tellstick/
"""
import voluptuous as vol
from homeassistant.components.light import (ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS, Light)
from homeassistant.components.tellstick import (DEFAULT_SIGNAL_REPETITIONS,
ATTR_DISCOVER_DEVICES,
ATTR_DISCOVER_CONFIG,
DOMAIN, TellstickDevice)
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light)
from homeassistant.components.tellstick import (
DEFAULT_SIGNAL_REPETITIONS, ATTR_DISCOVER_DEVICES, ATTR_DISCOVER_CONFIG,
DOMAIN, TellstickDevice)
PLATFORM_SCHEMA = vol.Schema({vol.Required("platform"): DOMAIN})
@ -20,14 +19,13 @@ SUPPORT_TELLSTICK = SUPPORT_BRIGHTNESS
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Tellstick lights."""
"""Set up the Tellstick lights."""
if (discovery_info is None or
discovery_info[ATTR_DISCOVER_DEVICES] is None):
return
# Allow platform level override, fallback to module config
signal_repetitions = discovery_info.get(ATTR_DISCOVER_CONFIG,
DEFAULT_SIGNAL_REPETITIONS)
signal_repetitions = discovery_info.get(
ATTR_DISCOVER_CONFIG, DEFAULT_SIGNAL_REPETITIONS)
add_devices(TellstickLight(tellcore_id, hass.data['tellcore_registry'],
signal_repetitions)
@ -38,7 +36,7 @@ class TellstickLight(TellstickDevice, Light):
"""Representation of a Tellstick light."""
def __init__(self, tellcore_id, tellcore_registry, signal_repetitions):
"""Initialize the light."""
"""Initialize the Tellstick light."""
super().__init__(tellcore_id, tellcore_registry, signal_repetitions)
self._brightness = 255

View File

@ -60,8 +60,8 @@ class TikteckLight(Light):
self._rgb = [255, 255, 255]
self._state = False
self.is_valid = True
self._bulb = tikteck.tikteck(self._address, "Smart Light",
self._password)
self._bulb = tikteck.tikteck(
self._address, "Smart Light", self._password)
if self._bulb.connect() is False:
self.is_valid = False
_LOGGER.error(
@ -99,12 +99,12 @@ class TikteckLight(Light):
@property
def should_poll(self):
"""Don't poll."""
"""Return the polling state."""
return False
@property
def assumed_state(self):
"""We can't read the actual state, so assume it matches."""
"""Return the assumed state."""
return True
def set_state(self, red, green, blue, brightness):

View File

@ -59,7 +59,7 @@ class TradfriGroup(Light):
@property
def brightness(self):
"""Brightness of the group lights (an integer in the range 1-255)."""
"""Return the brightness of the group lights."""
return self._group.dimmer
def turn_off(self, **kwargs):
@ -79,7 +79,7 @@ class TradfriGroup(Light):
class Tradfri(Light):
"""The platform class required by hass."""
"""The platform class required by Home Asisstant."""
def __init__(self, light):
"""Initialize a Light."""
@ -118,7 +118,7 @@ class Tradfri(Light):
@property
def brightness(self):
"""Brightness of the light (an integer in the range 1-255)."""
"""Return the brightness of the light."""
return self._light_data.dimmer
@property
@ -134,7 +134,7 @@ class Tradfri(Light):
if hex_color == self._light_data.hex_color), None)
if kelvin is None:
_LOGGER.error(
'unexpected color temperature found for %s: %s',
"Unexpected color temperature found for %s: %s",
self.name, self._light_data.hex_color)
return
return color_util.color_temperature_kelvin_to_mired(kelvin)

View File

@ -20,7 +20,7 @@ SUPPORT_VERA = SUPPORT_BRIGHTNESS
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Vera lights."""
"""Set up the Vera lights."""
add_devices(
VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light'])

View File

@ -26,7 +26,7 @@ SUPPORT_WEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_RGB_COLOR |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up WeMo bridges and register connected lights."""
"""Set up the WeMo bridges and register connected lights."""
import pywemo.discovery as discovery
if discovery_info is not None:
@ -64,7 +64,7 @@ class WemoLight(Light):
"""Representation of a WeMo light."""
def __init__(self, device, update_lights):
"""Initialize the light."""
"""Initialize the WeMo light."""
self.light_id = device.name
self.device = device
self.update_lights = update_lights
@ -97,7 +97,7 @@ class WemoLight(Light):
@property
def is_on(self):
"""Set True if device is on."""
"""Return true if device is on."""
return self.device.state['onoff'] != 0
@property

View File

@ -105,8 +105,8 @@ class WinkLight(WinkDevice, Light):
state_kwargs['color_xy'] = xyb[0], xyb[1]
state_kwargs['brightness'] = xyb[2]
elif self.wink.supports_hue_saturation():
hsv = colorsys.rgb_to_hsv(rgb_color[0],
rgb_color[1], rgb_color[2])
hsv = colorsys.rgb_to_hsv(
rgb_color[0], rgb_color[1], rgb_color[2])
state_kwargs['color_hue_saturation'] = hsv[0], hsv[1]
if color_temp_mired:

View File

@ -67,7 +67,7 @@ class X10Light(Light):
@property
def brightness(self):
"""Brightness of the light (an integer in the range 1-255)."""
"""Return the brightness of the light."""
return self._brightness
@property

View File

@ -26,11 +26,11 @@ REQUIREMENTS = ['yeelight==0.2.2']
_LOGGER = logging.getLogger(__name__)
CONF_TRANSITION = "transition"
CONF_TRANSITION = 'transition'
DEFAULT_TRANSITION = 350
CONF_SAVE_ON_CHANGE = "save_on_change"
CONF_MODE_MUSIC = "use_music_mode"
CONF_SAVE_ON_CHANGE = 'save_on_change'
CONF_MODE_MUSIC = 'use_music_mode'
DOMAIN = 'yeelight'
@ -67,14 +67,14 @@ def _cmd(func):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Yeelight bulbs."""
"""Set up the Yeelight bulbs."""
lights = []
if discovery_info is not None:
_LOGGER.debug("Adding autodetected %s", discovery_info['hostname'])
# not using hostname, as it seems to vary.
name = "yeelight_%s_%s" % (discovery_info["device_type"],
discovery_info["properties"]["mac"])
# Not using hostname, as it seems to vary.
name = "yeelight_%s_%s" % (discovery_info['device_type'],
discovery_info['properties']['mac'])
device = {'name': name, 'ipaddr': discovery_info['host']}
lights.append(YeelightLight(device, DEVICE_SCHEMA({})))
@ -85,14 +85,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
device = {'name': device_config[CONF_NAME], 'ipaddr': ipaddr}
lights.append(YeelightLight(device, device_config))
add_devices(lights, True) # true to request an update before adding.
add_devices(lights, True)
class YeelightLight(Light):
"""Representation of a Yeelight light."""
def __init__(self, device, config):
"""Initialize the light."""
"""Initialize the Yeelight light."""
self.config = config
self._name = device['name']
self._ipaddr = device['ipaddr']
@ -142,8 +142,8 @@ class YeelightLight(Light):
return self._brightness
def _get_rgb_from_properties(self):
rgb = self._properties.get("rgb", None)
color_mode = self._properties.get("color_mode", None)
rgb = self._properties.get('rgb', None)
color_mode = self._properties.get('color_mode', None)
if not rgb or not color_mode:
return rgb
@ -151,9 +151,9 @@ class YeelightLight(Light):
if color_mode == 2: # color temperature
return color_temperature_to_rgb(self.color_temp)
if color_mode == 3: # hsv
hue = self._properties.get("hue")
sat = self._properties.get("sat")
val = self._properties.get("bright")
hue = self._properties.get('hue')
sat = self._properties.get('sat')
val = self._properties.get('bright')
return colorsys.hsv_to_rgb(hue, sat, val)
rgb = int(rgb)
@ -204,13 +204,13 @@ class YeelightLight(Light):
if self._bulb_device.bulb_type == yeelight.BulbType.Color:
self._supported_features = SUPPORT_YEELIGHT_RGB
self._is_on = self._properties.get("power") == "on"
self._is_on = self._properties.get('power') == 'on'
bright = self._properties.get("bright", None)
bright = self._properties.get('bright', None)
if bright:
self._brightness = 255 * (int(bright) / 100)
temp_in_k = self._properties.get("ct", None)
temp_in_k = self._properties.get('ct', None)
if temp_in_k:
self._color_temp = kelvin_to_mired(int(temp_in_k))

View File

@ -67,7 +67,7 @@ class SunflowerBulb(Light):
@property
def brightness(self):
"""HA brightness is 0-255; Yeelight Sunflower's brightness is 0-100."""
"""Return the brightness is 0-255; Yeelight's brightness is 0-100."""
return int(self._brightness / 100 * 255)
@property

View File

@ -17,7 +17,7 @@ DEPENDENCIES = ['zha']
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up Zigbee Home Automation lights."""
"""Set up the Zigbee Home Automation lights."""
discovery_info = zha.get_discovery_info(hass, discovery_info)
if discovery_info is None:
return
@ -33,12 +33,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class Light(zha.Entity, light.Light):
"""ZHA or ZLL light."""
"""Representation of a ZHA or ZLL light."""
_domain = light.DOMAIN
def __init__(self, **kwargs):
"""Initialize ZHA light."""
"""Initialize the ZHA light."""
super().__init__(**kwargs)
self._supported_features = 0
self._color_temp = None
@ -61,7 +61,7 @@ class Light(zha.Entity, light.Light):
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
"""Return true if entity is on."""
if self._state == 'unknown':
return False
return bool(self._state)

View File

@ -46,13 +46,12 @@ TEMP_COLD_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 + TEMP_COLOR_MIN
def get_device(node, values, node_config, **kwargs):
"""Create zwave entity device."""
"""Create Z-Wave entity device."""
name = '{}.{}'.format(DOMAIN, zwave.object_id(values.primary))
refresh = node_config.get(zwave.CONF_REFRESH_VALUE)
delay = node_config.get(zwave.CONF_REFRESH_DELAY)
_LOGGER.debug('name=%s node_config=%s CONF_REFRESH_VALUE=%s'
' CONF_REFRESH_DELAY=%s', name, node_config,
refresh, delay)
_LOGGER.debug("name=%s node_config=%s CONF_REFRESH_VALUE=%s"
" CONF_REFRESH_DELAY=%s", name, node_config, refresh, delay)
if node.has_command_class(zwave.const.COMMAND_CLASS_SWITCH_COLOR):
return ZwaveColorLight(values, refresh, delay)

View File

@ -22,17 +22,19 @@ from homeassistant.const import (
STATE_UNKNOWN, SERVICE_LOCK, SERVICE_UNLOCK)
from homeassistant.components import group
DOMAIN = 'lock'
SCAN_INTERVAL = timedelta(seconds=30)
ATTR_CHANGED_BY = 'changed_by'
GROUP_NAME_ALL_LOCKS = 'all locks'
ENTITY_ID_ALL_LOCKS = group.ENTITY_ID_FORMAT.format('all_locks')
DOMAIN = 'lock'
ENTITY_ID_ALL_LOCKS = group.ENTITY_ID_FORMAT.format('all_locks')
ENTITY_ID_FORMAT = DOMAIN + '.{}'
GROUP_NAME_ALL_LOCKS = 'all locks'
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
SCAN_INTERVAL = timedelta(seconds=30)
LOCK_SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(ATTR_CODE): cv.string,

View File

@ -10,7 +10,7 @@ from homeassistant.const import (STATE_LOCKED, STATE_UNLOCKED)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo lock platform."""
"""Set up the Demo lock platform."""
add_devices([
DemoLock('Front Door', STATE_LOCKED),
DemoLock('Kitchen Door', STATE_UNLOCKED)

View File

@ -28,7 +28,7 @@ def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None):
"""Set up the ISY994 lock platform."""
if isy.ISY is None or not isy.ISY.connected:
_LOGGER.error('A connection has not been made to the ISY controller.')
_LOGGER.error("A connection has not been made to the ISY controller")
return False
devices = []
@ -115,9 +115,9 @@ class ISYLockProgram(ISYLockDevice):
def lock(self, **kwargs) -> None:
"""Lock the device."""
if not self._actions.runThen():
_LOGGER.error('Unable to lock device')
_LOGGER.error("Unable to lock device")
def unlock(self, **kwargs) -> None:
"""Unlock the device."""
if not self._actions.runElse():
_LOGGER.error('Unable to unlock device')
_LOGGER.error("Unable to unlock device")

View File

@ -28,16 +28,17 @@ API_ACTION_URL = BASE_URL + '/v2/locks/{}?access_token={}&state={}'
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Lockitron platform."""
"""Set up the Lockitron platform."""
access_token = config.get(CONF_ACCESS_TOKEN)
device_id = config.get(CONF_ID)
response = requests.get(API_STATE_URL.format(device_id, access_token))
response = requests.get(
API_STATE_URL.format(device_id, access_token), timeout=5)
if response.status_code == 200:
add_devices([Lockitron(response.json()['state'], access_token,
device_id)])
else:
_LOGGER.error('Error retrieving lock status during init: %s',
response.text)
_LOGGER.error(
"Error retrieving lock status during init: %s", response.text)
class Lockitron(LockDevice):
@ -72,21 +73,20 @@ class Lockitron(LockDevice):
def update(self):
"""Update the internal state of the device."""
response = requests \
.get(API_STATE_URL.format(self.device_id, self.access_token))
response = requests.get(API_STATE_URL.format(
self.device_id, self.access_token), timeout=5)
if response.status_code == 200:
self._state = response.json()['state']
else:
_LOGGER.error('Error retrieving lock status: %s', response.text)
_LOGGER.error("Error retrieving lock status: %s", response.text)
def do_change_request(self, requested_state):
"""Execute the change request and pull out the new state."""
response = requests.put(
API_ACTION_URL.format(self.device_id, self.access_token,
requested_state))
response = requests.put(API_ACTION_URL.format(
self.device_id, self.access_token, requested_state), timeout=5)
if response.status_code == 200:
return response.json()['state']
else:
_LOGGER.error('Error setting lock state: %s\n%s',
_LOGGER.error("Error setting lock state: %s\n%s",
requested_state, response.text)
return self._state

View File

@ -20,7 +20,6 @@ import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_PAYLOAD_LOCK = 'payload_lock'
CONF_PAYLOAD_UNLOCK = 'payload_unlock'
@ -42,7 +41,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the MQTT lock."""
"""Set up the MQTT lock."""
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
@ -61,7 +60,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class MqttLock(LockDevice):
"""Represents a lock that can be toggled using MQTT."""
"""Representation of a lock that can be toggled using MQTT."""
def __init__(self, name, state_topic, command_topic, qos, retain,
payload_lock, payload_unlock, optimistic, value_template):
@ -79,13 +78,13 @@ class MqttLock(LockDevice):
@asyncio.coroutine
def async_added_to_hass(self):
"""Subscribe mqtt events.
"""Subscribe to MQTT events.
This method is a coroutine.
"""
@callback
def message_received(topic, payload, qos):
"""A new MQTT message has been received."""
"""Handle new MQTT messages."""
if self._template is not None:
payload = self._template.async_render_with_possible_json_value(
payload)
@ -110,7 +109,7 @@ class MqttLock(LockDevice):
@property
def name(self):
"""The name of the lock."""
"""Return the name of the lock."""
return self._name
@property

View File

@ -6,13 +6,13 @@ https://home-assistant.io/components/lock.nuki/
"""
from datetime import timedelta
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.lock import (LockDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_HOST, CONF_PORT, CONF_TOKEN)
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pynuki==1.2.2']
@ -33,7 +33,7 @@ MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo lock platform."""
"""Set up the Nuki lock platform."""
from pynuki import NukiBridge
bridge = NukiBridge(config.get(CONF_HOST), config.get(CONF_TOKEN))
add_devices([NukiLock(lock) for lock in bridge.locks])

View File

@ -48,6 +48,6 @@ class VeraLock(VeraDevice, LockDevice):
return self._state == STATE_LOCKED
def update(self):
"""Called by the Vera device callback to update state."""
"""Update state by the Vera device callback."""
self._state = (STATE_LOCKED if self.vera_device.is_locked(True)
else STATE_UNLOCKED)

View File

@ -1,5 +1,5 @@
"""
Support for Volvo locks.
Support for Volvo On Call locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.volvooncall/
@ -14,9 +14,10 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the lock."""
"""Set up the Volvo On Call lock."""
if discovery_info is None:
return
add_devices([VolvoLock(hass, *discovery_info)])

View File

@ -4,7 +4,6 @@ Support for Wink locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.wink/
"""
from homeassistant.components.lock import LockDevice
from homeassistant.components.wink import WinkDevice, DOMAIN
@ -12,7 +11,7 @@ DEPENDENCIES = ['wink']
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink platform."""
"""Set up the Wink platform."""
import pywink
for lock in pywink.get_locks():

View File

@ -1,5 +1,5 @@
"""
Zwave platform that handles simple door locks.
Z-Wave platform that handles simple door locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.zwave/
@ -122,7 +122,7 @@ CLEAR_USERCODE_SCHEMA = vol.Schema({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Generic Z-Wave platform setup."""
"""Set up the Z-Wave Lock platform."""
yield from zwave.async_setup_platform(
hass, config, async_add_devices, discovery_info)
@ -142,8 +142,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
if value.index != code_slot:
continue
if len(str(usercode)) > 4:
_LOGGER.error('Invalid code provided: (%s)'
' usercode must %s or less digits',
_LOGGER.error("Invalid code provided: (%s) "
"usercode must %s or less digits",
usercode, len(value.data))
break
value.data = str(usercode)
@ -159,7 +159,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class_id=zwave.const.COMMAND_CLASS_USER_CODE).values():
if value.index != code_slot:
continue
_LOGGER.info('Usercode at slot %s is: %s', value.index, value.data)
_LOGGER.info("Usercode at slot %s is: %s", value.index, value.data)
break
def clear_usercode(service):
@ -178,28 +178,22 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
i += 1
_LOGGER.debug('Data to clear lock: %s', data)
value.data = data
_LOGGER.info('Usercode at slot %s is cleared', value.index)
_LOGGER.info("Usercode at slot %s is cleared", value.index)
break
hass.services.async_register(DOMAIN,
SERVICE_SET_USERCODE,
set_usercode,
descriptions.get(SERVICE_SET_USERCODE),
schema=SET_USERCODE_SCHEMA)
hass.services.async_register(DOMAIN,
SERVICE_GET_USERCODE,
get_usercode,
descriptions.get(SERVICE_GET_USERCODE),
schema=GET_USERCODE_SCHEMA)
hass.services.async_register(DOMAIN,
SERVICE_CLEAR_USERCODE,
clear_usercode,
descriptions.get(SERVICE_CLEAR_USERCODE),
schema=CLEAR_USERCODE_SCHEMA)
hass.services.async_register(
DOMAIN, SERVICE_SET_USERCODE, set_usercode,
descriptions.get(SERVICE_SET_USERCODE), schema=SET_USERCODE_SCHEMA)
hass.services.async_register(
DOMAIN, SERVICE_GET_USERCODE, get_usercode,
descriptions.get(SERVICE_GET_USERCODE), schema=GET_USERCODE_SCHEMA)
hass.services.async_register(
DOMAIN, SERVICE_CLEAR_USERCODE, clear_usercode,
descriptions.get(SERVICE_CLEAR_USERCODE), schema=CLEAR_USERCODE_SCHEMA)
def get_device(node, values, **kwargs):
"""Create zwave entity device."""
"""Create Z-Wave entity device."""
return ZwaveLock(values)
@ -230,8 +224,7 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
def update_properties(self):
"""Callback on data changes for node values."""
self._state = self.values.primary.data
_LOGGER.debug('Lock state set from Bool value and'
' is %s', self._state)
_LOGGER.debug("Lock state set from Bool value and is %s", self._state)
if self.values.access_control:
notification_data = self.values.access_control.data
self._notification = LOCK_NOTIFICATION.get(str(notification_data))
@ -240,21 +233,20 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
if self.values.v2btze_advanced and \
self.values.v2btze_advanced.data == CONFIG_ADVANCED:
self._state = LOCK_STATUS.get(str(notification_data))
_LOGGER.debug('Lock state set from Access Control '
'value and is %s, get=%s',
str(notification_data),
self.state)
_LOGGER.debug(
"Lock state set from Access Control value and is %s, "
"get=%s", str(notification_data), self.state)
if not self.values.alarm_type:
return
alarm_type = self.values.alarm_type.data
_LOGGER.debug('Lock alarm_type is %s', str(alarm_type))
_LOGGER.debug("Lock alarm_type is %s", str(alarm_type))
if self.values.alarm_level:
alarm_level = self.values.alarm_level.data
else:
alarm_level = None
_LOGGER.debug('Lock alarm_level is %s', str(alarm_level))
_LOGGER.debug("Lock alarm_level is %s", str(alarm_level))
if not alarm_type:
return

View File

@ -897,7 +897,7 @@ class MediaPlayerDevice(Entity):
@asyncio.coroutine
def _async_fetch_image(hass, url):
"""Helper method to fetch image.
"""Fetch image.
Images are cached in memory (the images are typically 10-100kB in size).
"""
@ -942,8 +942,8 @@ class MediaPlayerImageView(HomeAssistantView):
"""Media player view to serve an image."""
requires_auth = False
url = "/api/media_player_proxy/{entity_id}"
name = "api:media_player:image"
url = '/api/media_player_proxy/{entity_id}'
name = 'api:media_player:image'
def __init__(self, entities):
"""Initialize a media player view."""

View File

@ -45,11 +45,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
name = config.get(CONF_NAME)
device = None
_LOGGER.info('Provisioning Anthem AVR device at %s:%d', host, port)
_LOGGER.info("Provisioning Anthem AVR device at %s:%d", host, port)
def async_anthemav_update_callback(message):
"""Receive notification from transport that new data exists."""
_LOGGER.info('Received update calback from AVR: %s', message)
_LOGGER.info("Received update calback from AVR: %s", message)
hass.async_add_job(device.async_update_ha_state())
avr = yield from anthemav.Connection.create(
@ -58,9 +58,9 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
device = AnthemAVR(avr, name)
_LOGGER.debug('dump_devicedata: '+device.dump_avrdata)
_LOGGER.debug('dump_conndata: '+avr.dump_conndata)
_LOGGER.debug('dump_rawdata: '+avr.protocol.dump_rawdata)
_LOGGER.debug("dump_devicedata: %s", device.dump_avrdata)
_LOGGER.debug("dump_conndata: %s", avr.dump_conndata)
_LOGGER.debug("dump_rawdata: %s", avr.protocol.dump_rawdata)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.avr.close)
async_add_devices([device])
@ -70,7 +70,7 @@ class AnthemAVR(MediaPlayerDevice):
"""Entity reading values from Anthem AVR protocol."""
def __init__(self, avr, name):
""""Initialize entity with transport."""
"""Initialize entity with transport."""
super().__init__()
self.avr = avr
self._name = name
@ -163,7 +163,8 @@ class AnthemAVR(MediaPlayerDevice):
def _update_avr(self, propname, value):
"""Update a property in the AVR."""
_LOGGER.info('Sending command to AVR: set '+propname+' to '+str(value))
_LOGGER.info(
"Sending command to AVR: set %s to %s", propname, str(value))
setattr(self.avr.protocol, propname, value)
@property

View File

@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the Apple TV platform."""
"""Set up the Apple TV platform."""
import pyatv
if discovery_info is not None:
@ -95,12 +95,13 @@ class AppleTvDevice(MediaPlayerDevice):
@asyncio.coroutine
def async_added_to_hass(self):
"""Called when entity is about to be added to HASS."""
"""Handle when an entity is about to be added to Home Assistant."""
if not self._is_off:
self._atv.push_updater.start()
@callback
def _set_power_off(self, is_off):
"""Set the power to off."""
self._playing = None
self._artwork_hash = None
self._is_off = is_off

View File

@ -61,7 +61,7 @@ SOURCES = {0: 'TV / Antenna',
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Sharp Aquos TV platform."""
"""Set up the Sharp Aquos TV platform."""
import sharp_aquos_rc
name = config.get(CONF_NAME)
@ -77,30 +77,21 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
port = vals[1]
host = vals[0]
remote = sharp_aquos_rc.TV(host,
port,
username,
password,
timeout=20)
remote = sharp_aquos_rc.TV(host, port, username, password, timeout=20)
add_devices([SharpAquosTVDevice(name, remote, power_on_enabled)])
return True
host = config.get(CONF_HOST)
remote = sharp_aquos_rc.TV(host,
port,
username,
password,
15,
1)
remote = sharp_aquos_rc.TV(host, port, username, password, 15, 1)
add_devices([SharpAquosTVDevice(name, remote, power_on_enabled)])
return True
def _retry(func):
"""Decorator to handle query retries."""
"""Handle query retries."""
def wrapper(obj, *args, **kwargs):
"""Wrapper for all query functions."""
"""Wrap all query functions."""
update_retries = 5
while update_retries > 0:
try:

View File

@ -76,7 +76,7 @@ def _config_from_file(filename, config=None):
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(new_config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
_LOGGER.error("Saving config file failed: %s", error)
return False
return True
else:
@ -88,7 +88,7 @@ def _config_from_file(filename, config=None):
except ValueError as error:
return {}
except IOError as error:
_LOGGER.error('Reading config file failed: %s', error)
_LOGGER.error("Reading config file failed: %s", error)
# This won't work yet
return False
else:
@ -135,13 +135,13 @@ def setup_bravia(config, pin, hass, add_devices):
request_id = _CONFIGURING.pop(host)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info('Discovery configuration done!')
_LOGGER.info("Discovery configuration done")
# Save config
if not _config_from_file(
hass.config.path(BRAVIA_CONFIG_FILE),
{host: {'pin': pin, 'host': host, 'mac': mac}}):
_LOGGER.error('failed to save config file')
_LOGGER.error("Failed to save configuration file")
add_devices([BraviaTVDevice(host, mac, name, pin)])
@ -160,7 +160,7 @@ def request_configuration(config, hass, add_devices):
return
def bravia_configuration_callback(data):
"""Callback after user enter PIN."""
"""Handle the entry of user PIN."""
from braviarc import braviarc
pin = data.get('pin')

View File

@ -43,10 +43,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the cast platform."""
"""Set up the cast platform."""
import pychromecast
# import CEC IGNORE attributes
# Import CEC IGNORE attributes
pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, [])
hosts = []
@ -68,8 +68,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
casts = []
# get_chromecasts() returns Chromecast objects
# with the correct friendly name for grouped devices
# get_chromecasts() returns Chromecast objects with the correct friendly
# name for grouped devices
all_chromecasts = pychromecast.get_chromecasts()
for host in hosts:
@ -204,7 +204,7 @@ class CastDevice(MediaPlayerDevice):
@property
def media_series_title(self):
"""The title of the series of current playing media (TV Show only)."""
"""Return the title of the series of current playing media."""
return self.media_status.series_title if self.media_status else None
@property
@ -310,12 +310,12 @@ class CastDevice(MediaPlayerDevice):
# Implementation of chromecast status_listener methods
def new_cast_status(self, status):
"""Called when a new cast status is received."""
"""Handle updates of the cast status."""
self.cast_status = status
self.schedule_update_ha_state()
def new_media_status(self, status):
"""Called when a new media status is received."""
"""Handle updates of the media status."""
self.media_status = status
self.media_status_received = dt_util.utcnow()
self.schedule_update_ha_state()

View File

@ -28,6 +28,7 @@ SCAN_INTERVAL = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Clementine Remote'
DEFAULT_PORT = 5500
SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
SUPPORT_PREVIOUS_TRACK | SUPPORT_VOLUME_SET | \
@ -35,19 +36,22 @@ SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
SUPPORT_SELECT_SOURCE | SUPPORT_PLAY
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=5500): cv.positive_int,
vol.Optional(CONF_ACCESS_TOKEN, default=None): cv.positive_int,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
})
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Clementine platform."""
"""Set up the Clementine platform."""
from clementineremote import ClementineRemote
client = ClementineRemote(config.get(CONF_HOST), config.get(CONF_PORT),
config.get(CONF_ACCESS_TOKEN), reconnect=True)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
token = config.get(CONF_ACCESS_TOKEN)
client = ClementineRemote(host, port, token, reconnect=True)
add_devices([ClementineDevice(client, config[CONF_NAME])])

View File

@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discover_info=None):
"""Setup the CMUS platform."""
"""Set up the CMUS platform."""
from pycmus import exceptions
host = config.get(CONF_HOST)
@ -166,7 +166,7 @@ class CmusDevice(MediaPlayerDevice):
self.cmus.set_volume(int(volume * 100))
def volume_up(self):
"""Function to send CMUS the command for volume up."""
"""Set the volume up."""
left = self.status['set'].get('vol_left')
right = self.status['set'].get('vol_right')
if left != right:
@ -178,7 +178,7 @@ class CmusDevice(MediaPlayerDevice):
self.cmus.set_volume(int(current_volume) + 5)
def volume_down(self):
"""Function to send CMUS the command for volume down."""
"""Set the volume down."""
left = self.status['set'].get('vol_left')
right = self.status['set'].get('vol_right')
if left != right:

View File

@ -16,7 +16,7 @@ import homeassistant.util.dt as dt_util
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the media player demo platform."""
"""Set up the media player demo platform."""
add_devices([
DemoYoutubePlayer(
'Living Room', 'eyU3bRy2x44',

View File

@ -50,7 +50,7 @@ MEDIA_MODES = {'Tuner': 'TUNER', 'Media server': 'SERVER',
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Denon platform."""
"""Set up the Denon platform."""
denon = DenonDevice(config.get(CONF_NAME), config.get(CONF_HOST))
if denon.update():
@ -101,7 +101,7 @@ class DenonDevice(MediaPlayerDevice):
@classmethod
def telnet_request(cls, telnet, command, all_lines=False):
"""Execute `command` and return the response."""
_LOGGER.debug('Sending: "%s"', command)
_LOGGER.debug("Sending: %s", command)
telnet.write(command.encode('ASCII') + b'\r')
lines = []
while True:
@ -109,7 +109,7 @@ class DenonDevice(MediaPlayerDevice):
if not line:
break
lines.append(line.decode('ASCII').strip())
_LOGGER.debug('Recived: "%s"', line)
_LOGGER.debug("Recived: %s", line)
if all_lines:
return lines
@ -118,7 +118,7 @@ class DenonDevice(MediaPlayerDevice):
def telnet_command(self, command):
"""Establish a telnet connection and sends `command`."""
telnet = telnetlib.Telnet(self._host)
_LOGGER.debug('Sending: "%s"', command)
_LOGGER.debug("Sending: %s", command)
telnet.write(command.encode('ASCII') + b'\r')
telnet.read_very_eager() # skip response
telnet.close()
@ -179,17 +179,17 @@ class DenonDevice(MediaPlayerDevice):
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
"""Return boolean if volume is currently muted."""
return self._muted
@property
def source_list(self):
"""List of available input sources."""
"""Return the list of available input sources."""
return sorted(list(self._source_list.keys()))
@property
def media_title(self):
"""Current media info."""
"""Return the current media info."""
return self._mediainfo
@property

View File

@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Denon platform."""
"""Set up the Denon platform."""
import denonavr
# Initialize list with receivers to be started
@ -116,9 +116,7 @@ class DenonDevice(MediaPlayerDevice):
def update(self):
"""Get the latest status information from device."""
# Update denonavr
self._receiver.update()
# Refresh own data
self._name = self._receiver.name
self._muted = self._receiver.muted
self._volume = self._receiver.volume
@ -146,7 +144,7 @@ class DenonDevice(MediaPlayerDevice):
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
"""Return boolean if volume is currently muted."""
return self._muted
@property
@ -163,7 +161,7 @@ class DenonDevice(MediaPlayerDevice):
@property
def source_list(self):
"""List of available input sources."""
"""Return a list of available input sources."""
return self._source_list
@property

View File

@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the DirecTV platform."""
"""Set up the DirecTV platform."""
hosts = []
if discovery_info:
@ -94,13 +94,13 @@ class DirecTvDevice(MediaPlayerDevice):
"""Return the state of the device."""
if self._is_standby:
return STATE_OFF
# haven't determined a way to see if the content is paused
# Haven't determined a way to see if the content is paused
else:
return STATE_PLAYING
@property
def media_content_id(self):
"""Content ID of current playing media."""
"""Return the content ID of current playing media."""
if self._is_standby:
return None
else:
@ -108,7 +108,7 @@ class DirecTvDevice(MediaPlayerDevice):
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
"""Return the duration of current playing media in seconds."""
if self._is_standby:
return None
else:
@ -116,7 +116,7 @@ class DirecTvDevice(MediaPlayerDevice):
@property
def media_title(self):
"""Title of current playing media."""
"""Return the title of current playing media."""
if self._is_standby:
return None
else:
@ -124,7 +124,7 @@ class DirecTvDevice(MediaPlayerDevice):
@property
def media_series_title(self):
"""Title of current episode of TV show."""
"""Return the title of current episode of TV show."""
if self._is_standby:
return None
else:
@ -140,7 +140,7 @@ class DirecTvDevice(MediaPlayerDevice):
@property
def media_content_type(self):
"""Content type of current playing media."""
"""Return the content type of current playing media."""
if 'episodeTitle' in self._current:
return MEDIA_TYPE_TVSHOW
else:
@ -148,38 +148,38 @@ class DirecTvDevice(MediaPlayerDevice):
@property
def media_channel(self):
"""Channel current playing media."""
"""Return the channel current playing media."""
if self._is_standby:
return None
else:
chan = "{} ({})".format(self._current['callsign'],
self._current['major'])
chan = "{} ({})".format(
self._current['callsign'], self._current['major'])
return chan
def turn_on(self):
"""Turn on the reciever."""
"""Turn on the receiver."""
self.dtv.key_press('poweron')
def turn_off(self):
"""Turn off the reciever."""
"""Turn off the receiver."""
self.dtv.key_press('poweroff')
def media_play(self):
"""Send play commmand."""
"""Send play command."""
self.dtv.key_press('play')
def media_pause(self):
"""Send pause commmand."""
"""Send pause command."""
self.dtv.key_press('pause')
def media_stop(self):
"""Send stop commmand."""
"""Send stop command."""
self.dtv.key_press('stop')
def media_previous_track(self):
"""Send rewind commmand."""
"""Send rewind command."""
self.dtv.key_press('rew')
def media_next_track(self):
"""Send fast forward commmand."""
"""Send fast forward command."""
self.dtv.key_press('ffwd')

View File

@ -48,7 +48,7 @@ class DuneHDPlayerEntity(MediaPlayerDevice):
"""Implementation of the Dune HD player."""
def __init__(self, player, name, sources):
"""Setup entity to control Dune HD."""
"""Initialize entity to control Dune HD."""
self._player = player
self._name = name
self._sources = sources
@ -83,17 +83,17 @@ class DuneHDPlayerEntity(MediaPlayerDevice):
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
"""Return the volume level of the media player (0..1)."""
return int(self._state.get('playback_volume', 0)) / 100
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
"""Return a boolean if volume is currently muted."""
return int(self._state.get('playback_mute', 0)) == 1
@property
def source_list(self):
"""List of available input sources."""
"""Return a list of available input sources."""
return list(self._sources.keys())
@property

View File

@ -52,7 +52,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the Emby platform."""
"""Set up the Emby platform."""
from pyemby import EmbyServer
host = config.get(CONF_HOST)
@ -64,7 +64,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
if port is None:
port = DEFAULT_SSL_PORT if ssl else DEFAULT_PORT
_LOGGER.debug('Setting up Emby server at: %s:%s', host, port)
_LOGGER.debug("Setting up Emby server at: %s:%s", host, port)
emby = EmbyServer(host, key, port, ssl, hass.loop)
@ -93,12 +93,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
add.set_hidden(False)
if new_devices:
_LOGGER.debug("Adding new devices to HASS: %s", new_devices)
_LOGGER.debug("Adding new devices: %s", new_devices)
async_add_devices(new_devices, update_before_add=True)
@callback
def device_removal_callback(data):
"""Callback for when devices are removed from emby."""
"""Handle the removal of devices from Emby."""
if data in active_emby_devices:
rem = active_emby_devices.pop(data)
inactive_emby_devices[data] = rem
@ -109,12 +109,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
@callback
def start_emby(event):
"""Start emby connection."""
"""Start Emby connection."""
emby.start()
@asyncio.coroutine
def stop_emby(event):
"""Stop emby connection."""
"""Stop Emby connection."""
yield from emby.stop()
emby.add_new_devices_callback(device_update_callback)
@ -129,7 +129,7 @@ class EmbyDevice(MediaPlayerDevice):
def __init__(self, emby, device_id):
"""Initialize the Emby device."""
_LOGGER.debug('New Emby Device initialized with ID: %s', device_id)
_LOGGER.debug("New Emby Device initialized with ID: %s", device_id)
self.emby = emby
self.device_id = device_id
self.device = self.emby.devices[self.device_id]
@ -143,12 +143,12 @@ class EmbyDevice(MediaPlayerDevice):
@asyncio.coroutine
def async_added_to_hass(self):
"""Register callback."""
self.emby.add_update_callback(self.async_update_callback,
self.device_id)
self.emby.add_update_callback(
self.async_update_callback, self.device_id)
@callback
def async_update_callback(self, msg):
"""Callback for device updates."""
"""Handle device updates."""
# Check if we should update progress
if self.device.media_position:
if self.device.media_position != self.media_status_last_position:

View File

@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the FireTV platform."""
"""Set up the FireTV platform."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
@ -52,13 +52,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
response = requests.get(DEVICE_LIST_URL.format(host, port)).json()
if device_id in response[CONF_DEVICES].keys():
add_devices([FireTVDevice(host, port, device_id, name)])
_LOGGER.info('Device %s accessible and ready for control',
_LOGGER.info("Device %s accessible and ready for control",
device_id)
else:
_LOGGER.warning('Device %s is not registered with firetv-server',
_LOGGER.warning("Device %s is not registered with firetv-server",
device_id)
except requests.exceptions.RequestException:
_LOGGER.error('Could not connect to firetv-server at %s', host)
_LOGGER.error("Could not connect to firetv-server at %s", host)
class FireTV(object):
@ -88,7 +88,7 @@ class FireTV(object):
return response.get('state', STATE_UNKNOWN)
except requests.exceptions.RequestException:
_LOGGER.error(
'Could not retrieve device state for %s', self.device_id)
"Could not retrieve device state for %s", self.device_id)
return STATE_UNKNOWN
def action(self, action_id):
@ -98,7 +98,7 @@ class FireTV(object):
self.host, self.port, self.device_id, action_id), timeout=10)
except requests.exceptions.RequestException:
_LOGGER.error(
'Action request for %s was not accepted for device %s',
"Action request for %s was not accepted for device %s",
action_id, self.device_id)

View File

@ -79,8 +79,8 @@ def request_configuration(hass, config, url, add_devices_callback):
'arguments': ['Home Assistant', pin]}))
tmpmsg = json.loads(websocket.recv())
if tmpmsg['channel'] == 'time':
_LOGGER.error('Error setting up GPMDP. Please pause'
' the desktop player and try again.')
_LOGGER.error("Error setting up GPMDP. Please pause "
"the desktop player and try again")
break
code = tmpmsg['payload']
if code == 'CODE_REQUIRED':
@ -106,7 +106,7 @@ def request_configuration(hass, config, url, add_devices_callback):
def setup_gpmdp(hass, config, code, add_devices):
"""Setup gpmdp."""
"""Set up gpmdp."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)

View File

@ -36,7 +36,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Gstreamer platform."""
"""Set up the Gstreamer platform."""
from gsp import GstreamerPlayer
name = config.get(CONF_NAME)
pipeline = config.get(CONF_PIPELINE)

View File

@ -134,7 +134,7 @@ class CecPlayerDevice(CecDevice, MediaPlayerDevice):
@property
def state(self) -> str:
"""Cached state of device."""
"""Cache state of device."""
return self._state
def _update(self, device=None):

View File

@ -154,7 +154,7 @@ class Itunes(object):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the iTunes platform."""
"""Set up the iTunes platform."""
add_devices([
ItunesDevice(
config.get(CONF_NAME),

View File

@ -47,17 +47,17 @@ TURN_OFF_ACTION = [None, 'quit', 'hibernate', 'suspend', 'reboot', 'shutdown']
# https://github.com/xbmc/xbmc/blob/master/xbmc/media/MediaType.h
MEDIA_TYPES = {
"music": MEDIA_TYPE_MUSIC,
"artist": MEDIA_TYPE_MUSIC,
"album": MEDIA_TYPE_MUSIC,
"song": MEDIA_TYPE_MUSIC,
"video": MEDIA_TYPE_VIDEO,
"set": MEDIA_TYPE_PLAYLIST,
"musicvideo": MEDIA_TYPE_VIDEO,
"movie": MEDIA_TYPE_VIDEO,
"tvshow": MEDIA_TYPE_TVSHOW,
"season": MEDIA_TYPE_TVSHOW,
"episode": MEDIA_TYPE_TVSHOW,
'music': MEDIA_TYPE_MUSIC,
'artist': MEDIA_TYPE_MUSIC,
'album': MEDIA_TYPE_MUSIC,
'song': MEDIA_TYPE_MUSIC,
'video': MEDIA_TYPE_VIDEO,
'set': MEDIA_TYPE_PLAYLIST,
'musicvideo': MEDIA_TYPE_VIDEO,
'movie': MEDIA_TYPE_VIDEO,
'tvshow': MEDIA_TYPE_TVSHOW,
'season': MEDIA_TYPE_TVSHOW,
'episode': MEDIA_TYPE_TVSHOW,
}
SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
@ -161,11 +161,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
def cmd(func):
"""Decorator to catch command exceptions."""
"""Catch command exceptions."""
@wraps(func)
@asyncio.coroutine
def wrapper(obj, *args, **kwargs):
"""Wrapper for all command methods."""
"""Wrap all command methods."""
import jsonrpc_base
try:
yield from func(obj, *args, **kwargs)
@ -245,7 +245,7 @@ class KodiDevice(MediaPlayerDevice):
@callback
def async_on_speed_event(self, sender, data):
"""Called when player changes between playing and paused."""
"""Handle player changes between playing and paused."""
self._properties['speed'] = data['player']['speed']
if not hasattr(data['item'], 'id'):
@ -259,7 +259,7 @@ class KodiDevice(MediaPlayerDevice):
@callback
def async_on_stop(self, sender, data):
"""Called when the player stops playback."""
"""Handle the stop of the player playback."""
# Prevent stop notifications which are sent after quit notification
if self._players is None:
return
@ -271,14 +271,14 @@ class KodiDevice(MediaPlayerDevice):
@callback
def async_on_volume_changed(self, sender, data):
"""Called when the volume is changed."""
"""Handle the volume changes."""
self._app_properties['volume'] = data['volume']
self._app_properties['muted'] = data['muted']
self.hass.async_add_job(self.async_update_ha_state())
@callback
def async_on_quit(self, sender, data):
"""Called when the volume is changed."""
"""Handle the muted volume."""
self._players = None
self._properties = {}
self._item = {}
@ -293,8 +293,8 @@ class KodiDevice(MediaPlayerDevice):
return (yield from self.server.Player.GetActivePlayers())
except jsonrpc_base.jsonrpc.TransportError:
if self._players is not None:
_LOGGER.info('Unable to fetch kodi data')
_LOGGER.debug('Unable to fetch kodi data', exc_info=True)
_LOGGER.info("Unable to fetch kodi data")
_LOGGER.debug("Unable to fetch kodi data", exc_info=True)
return None
@property
@ -548,7 +548,7 @@ class KodiDevice(MediaPlayerDevice):
@asyncio.coroutine
def async_set_play_state(self, state):
"""Helper method for play/pause/toggle."""
"""Handle play/pause/toggle."""
players = yield from self._get_players()
if players is not None and players:
@ -590,7 +590,7 @@ class KodiDevice(MediaPlayerDevice):
@asyncio.coroutine
def _goto(self, direction):
"""Helper method used for previous/next track."""
"""Handle for previous/next track."""
players = yield from self._get_players()
if players:

View File

@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the LG TV platform."""
"""Set up the LG TV platform."""
from pylgnetcast import LgNetCastClient
client = LgNetCastClient(
config.get(CONF_HOST), config.get(CONF_ACCESS_TOKEN))

View File

@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Orange Livebox Play TV platform."""
"""Set up the Orange Livebox Play TV platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
@ -56,8 +56,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
device = LiveboxPlayTvDevice(host, port, name)
livebox_devices.append(device)
except IOError:
_LOGGER.error('Failed to connect to Livebox Play TV at %s:%s. '
'Please check your configuration.', host, port)
_LOGGER.error("Failed to connect to Livebox Play TV at %s:%s. "
"Please check your configuration", host, port)
add_devices(livebox_devices, True)

View File

@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the MPC-HC platform."""
"""Set up the MPC-HC platform."""
name = config.get(CONF_NAME)
url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT))
@ -59,8 +59,8 @@ class MpcHcDevice(MediaPlayerDevice):
self._player_variables = dict()
try:
response = requests.get('{}/variables.html'.format(self._url),
data=None, timeout=3)
response = requests.get(
'{}/variables.html'.format(self._url), data=None, timeout=3)
mpchc_variables = re.findall(r'<p id="(.+?)">(.+?)</p>',
response.text)
@ -102,24 +102,24 @@ class MpcHcDevice(MediaPlayerDevice):
@property
def media_title(self):
"""Title of current playing media."""
"""Return the title of current playing media."""
return self._player_variables.get('file', None)
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
"""Return the volume level of the media player (0..1)."""
return int(self._player_variables.get('volumelevel', 0)) / 100.0
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
"""Return boolean if volume is currently muted."""
return self._player_variables.get('muted', '0') == '1'
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
duration = self._player_variables.get('durationstring',
"00:00:00").split(':')
"""Return the duration of the current playing media in seconds."""
duration = self._player_variables.get(
'durationstring', "00:00:00").split(':')
return \
int(duration[0]) * 3600 + \
int(duration[1]) * 60 + \

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the MPD platform."""
"""Set up the MPD platform."""
daemon = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
@ -136,23 +136,23 @@ class MpdDevice(MediaPlayerDevice):
@property
def media_content_id(self):
"""Content ID of current playing media."""
"""Return the content ID of current playing media."""
return self.currentsong.get('file')
@property
def media_content_type(self):
"""Content type of current playing media."""
"""Return the content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
"""Return the duration of current playing media in seconds."""
# Time does not exist for streams
return self.currentsong.get('time')
@property
def media_title(self):
"""Title of current playing media."""
"""Return the title of current playing media."""
name = self.currentsong.get('name', None)
title = self.currentsong.get('title', None)
@ -167,12 +167,12 @@ class MpdDevice(MediaPlayerDevice):
@property
def media_artist(self):
"""Artist of current playing media (Music track only)."""
"""Return the artist of current playing media (Music track only)."""
return self.currentsong.get('artist')
@property
def media_album_name(self):
"""Album of current playing media (Music track only)."""
"""Return the album of current playing media (Music track only)."""
return self.currentsong.get('album')
@property
@ -192,7 +192,7 @@ class MpdDevice(MediaPlayerDevice):
@property
def source_list(self):
"""List of available input sources."""
"""Return the list of available input sources."""
return self.playlists
def select_source(self, source):

View File

@ -49,7 +49,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the NAD platform."""
"""Set up the NAD platform."""
from nad_receiver import NADReceiver
add_devices([NAD(
config.get(CONF_NAME),

View File

@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Onkyo platform."""
"""Set up the Onkyo platform."""
import eiscp
from eiscp import eISCP
@ -52,12 +52,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if CONF_HOST in config and host not in KNOWN_HOSTS:
try:
hosts.append(OnkyoDevice(eiscp.eISCP(host),
config.get(CONF_SOURCES),
name=config.get(CONF_NAME)))
hosts.append(OnkyoDevice(
eiscp.eISCP(host), config.get(CONF_SOURCES),
name=config.get(CONF_NAME)))
KNOWN_HOSTS.append(host)
except OSError:
_LOGGER.error('Unable to connect to receiver at %s.', host)
_LOGGER.error("Unable to connect to receiver at %s", host)
else:
for receiver in eISCP.discover():
if receiver.host not in KNOWN_HOSTS:
@ -90,9 +90,9 @@ class OnkyoDevice(MediaPlayerDevice):
except (ValueError, OSError, AttributeError, AssertionError):
if self._receiver.command_socket:
self._receiver.command_socket = None
_LOGGER.info('Resetting connection to %s.', self._name)
_LOGGER.info("Resetting connection to %s", self._name)
else:
_LOGGER.info('%s is disconnected. Attempting to reconnect.',
_LOGGER.info("%s is disconnected. Attempting to reconnect",
self._name)
return False
return result
@ -142,7 +142,7 @@ class OnkyoDevice(MediaPlayerDevice):
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
"""Return the volume level of the media player (0..1)."""
return self._volume
@property
@ -157,7 +157,7 @@ class OnkyoDevice(MediaPlayerDevice):
@property
def source(self):
""""Return the current input source of the device."""
"""Return the current input source of the device."""
return self._current_source
@property

View File

@ -22,13 +22,12 @@ SUPPORT_OPENHOME = SUPPORT_SELECT_SOURCE | \
_LOGGER = logging.getLogger(__name__)
# List of devices that have been registered
DEVICES = []
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup Openhome Platform."""
"""Set up the Openhome platform."""
from openhomedevice.Device import Device
if not discovery_info:
@ -36,7 +35,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
name = discovery_info.get('name')
description = discovery_info.get('ssdp_description')
_LOGGER.info('Openhome device found, (%s)', name)
_LOGGER.info('Openhome device found: %s', name)
device = Device(description)
# if device has already been discovered

View File

@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Panasonic Viera TV platform."""
"""Set up the Panasonic Viera TV platform."""
from panasonic_viera import RemoteControl
mac = config.get(CONF_MAC)

View File

@ -46,12 +46,12 @@ STATION_PATTERN = re.compile(r'Station\s"(.+?)"', re.MULTILINE)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the media player pandora platform."""
"""Set up the Pandora media player platform."""
if not _pianobar_exists():
return False
pandora = PandoraMediaPlayer('Pandora')
# make sure we end the pandora subprocess on exit in case user doesn't
# Make sure we end the pandora subprocess on exit in case user doesn't
# power it down.
def _stop_pianobar(_event):
pandora.turn_off()
@ -98,7 +98,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
if self._player_state != STATE_OFF:
return
self._pianobar = pexpect.spawn('pianobar')
_LOGGER.info('Started pianobar subprocess')
_LOGGER.info("Started pianobar subprocess")
mode = self._pianobar.expect(['Receiving new playlist',
'Select station:',
'Email:'])
@ -106,10 +106,10 @@ class PandoraMediaPlayer(MediaPlayerDevice):
# station list was presented. dismiss it.
self._pianobar.sendcontrol('m')
elif mode == 2:
_LOGGER.warning('The pianobar client is not configured to log in. '
'Please create a config file for it as described '
'at https://home-assistant.io'
'/components/media_player.pandora/')
_LOGGER.warning(
"The pianobar client is not configured to log in. "
"Please create a config file for it as described at "
"https://home-assistant.io/components/media_player.pandora/")
# pass through the email/password prompts to quit cleanly
self._pianobar.sendcontrol('m')
self._pianobar.sendcontrol('m')
@ -126,16 +126,16 @@ class PandoraMediaPlayer(MediaPlayerDevice):
"""Turn the media player off."""
import pexpect
if self._pianobar is None:
_LOGGER.info('Pianobar subprocess already stopped')
_LOGGER.info("Pianobar subprocess already stopped")
return
self._pianobar.send('q')
try:
_LOGGER.info('Stopped Pianobar subprocess')
_LOGGER.debug("Stopped Pianobar subprocess")
self._pianobar.terminate()
except pexpect.exceptions.TIMEOUT:
# kill the process group
os.killpg(os.getpgid(self._pianobar.pid), signal.SIGTERM)
_LOGGER.info('Killed Pianobar subprocess')
_LOGGER.debug("Killed Pianobar subprocess")
self._pianobar = None
self._player_state = STATE_OFF
self.schedule_update_ha_state()
@ -203,9 +203,9 @@ class PandoraMediaPlayer(MediaPlayerDevice):
try:
station_index = self._stations.index(source)
except ValueError:
_LOGGER.warning('Station `%s` is not in list', source)
_LOGGER.warning("Station %s is not in list", source)
return
_LOGGER.info('Setting station %s, %d', source, station_index)
_LOGGER.debug("Setting station %s, %d", source, station_index)
self._send_station_list_command()
self._pianobar.sendline('{}'.format(station_index))
self._pianobar.expect('\r\n')
@ -243,7 +243,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
'Select station',
'Receiving new playlist'])
except pexpect.exceptions.EOF:
_LOGGER.info('Pianobar process already exited.')
_LOGGER.info("Pianobar process already exited")
return None
self._log_match()
@ -252,12 +252,12 @@ class PandoraMediaPlayer(MediaPlayerDevice):
response = None
elif match_idx == 2:
# stuck on a station selection dialog. Clear it.
_LOGGER.warning('On unexpected station list page.')
_LOGGER.warning("On unexpected station list page")
self._pianobar.sendcontrol('m') # press enter
self._pianobar.sendcontrol('m') # do it again b/c an 'i' got in
response = self.update_playing_status()
elif match_idx == 3:
_LOGGER.debug('Received new playlist list.')
_LOGGER.debug("Received new playlist list")
response = self.update_playing_status()
else:
response = self._pianobar.before.decode('utf-8')
@ -268,9 +268,9 @@ class PandoraMediaPlayer(MediaPlayerDevice):
station_match = re.search(STATION_PATTERN, response)
if station_match:
self._station = station_match.group(1)
_LOGGER.debug('Got station as: %s', self._station)
_LOGGER.debug("Got station as: %s", self._station)
else:
_LOGGER.warning('No station match. ')
_LOGGER.warning("No station match")
def _update_current_song(self, response):
"""Update info about current song."""
@ -278,9 +278,9 @@ class PandoraMediaPlayer(MediaPlayerDevice):
if song_match:
(self._media_title, self._media_artist,
self._media_album) = song_match.groups()
_LOGGER.debug('Got song as: %s', self._media_title)
_LOGGER.debug("Got song as: %s", self._media_title)
else:
_LOGGER.warning('No song match.')
_LOGGER.warning("No song match")
@util.Throttle(MIN_TIME_BETWEEN_UPDATES)
def _update_song_position(self):
@ -305,7 +305,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
def _log_match(self):
"""Log grabbed values from console."""
_LOGGER.debug('Before: %s\nMatch: %s\nAfter: %s',
_LOGGER.debug("Before: %s\nMatch: %s\nAfter: %s",
repr(self._pianobar.before),
repr(self._pianobar.match),
repr(self._pianobar.after))
@ -313,10 +313,10 @@ class PandoraMediaPlayer(MediaPlayerDevice):
def _send_pianobar_command(self, service_cmd):
"""Send a command to Pianobar."""
command = CMD_MAP.get(service_cmd)
_LOGGER.debug('Sending pinaobar command %s for %s',
command, service_cmd)
_LOGGER.debug(
"Sending pinaobar command %s for %s", command, service_cmd)
if command is None:
_LOGGER.info('Command %s not supported yet', service_cmd)
_LOGGER.info("Command %s not supported yet", service_cmd)
self._clear_buffer()
self._pianobar.sendline(command)
@ -324,16 +324,16 @@ class PandoraMediaPlayer(MediaPlayerDevice):
"""List defined Pandora stations."""
self._send_station_list_command()
station_lines = self._pianobar.before.decode('utf-8')
_LOGGER.debug('Getting stations: %s', station_lines)
_LOGGER.debug("Getting stations: %s", station_lines)
self._stations = []
for line in station_lines.split('\r\n'):
match = re.search(r'\d+\).....(.+)', line)
if match:
station = match.group(1).strip()
_LOGGER.debug('Found station %s', station)
_LOGGER.debug("Found station %s", station)
self._stations.append(station)
else:
_LOGGER.debug('No station match on `%s`', line)
_LOGGER.debug("No station match on %s", line)
self._pianobar.sendcontrol('m') # press enter with blank line
self._pianobar.sendcontrol('m') # do it twice in case an 'i' got in
@ -360,9 +360,8 @@ def _pianobar_exists():
if pianobar_exe:
return True
else:
_LOGGER.warning('The Pandora component depends on the Pianobar '
'client, which cannot be found. Please install '
'using instructions at'
'https://home-assistant.io'
'/components/media_player.pandora/')
_LOGGER.warning(
"The Pandora component depends on the Pianobar client, which "
"cannot be found. Please install using instructions at "
"https://home-assistant.io/components/media_player.pandora/")
return False

View File

@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Philips TV platform."""
"""Set up the Philips TV platform."""
import haphilipsjs
name = config.get(CONF_NAME)

View File

@ -40,11 +40,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Pioneer platform."""
pioneer = PioneerDevice(config.get(CONF_NAME),
config.get(CONF_HOST),
config.get(CONF_PORT),
config.get(CONF_TIMEOUT))
"""Set up the Pioneer platform."""
pioneer = PioneerDevice(
config.get(CONF_NAME), config.get(CONF_HOST), config.get(CONF_PORT),
config.get(CONF_TIMEOUT))
if pioneer.update():
add_devices([pioneer])
@ -126,9 +125,8 @@ class PioneerDevice(MediaPlayerDevice):
# Build the source name dictionaries if necessary
if not self._source_name_to_number:
for i in range(MAX_SOURCE_NUMBERS):
result = self.telnet_request(telnet,
"?RGB" + str(i).zfill(2),
"RGB")
result = self.telnet_request(
telnet, "?RGB" + str(i).zfill(2), "RGB")
if not result:
continue

View File

@ -76,7 +76,7 @@ def config_from_file(filename, config=None):
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Setup the Plex platform."""
"""Set up the Plex platform."""
# get config from plex.conf
file_config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
@ -100,7 +100,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
def setup_plexserver(host, token, hass, config, add_devices_callback):
"""Setup a plexserver based on host parameter."""
"""Set up a plexserver based on host parameter."""
import plexapi.server
import plexapi.exceptions
@ -110,8 +110,7 @@ def setup_plexserver(host, token, hass, config, add_devices_callback):
plexapi.exceptions.NotFound) as error:
_LOGGER.info(error)
# No token or wrong token
request_configuration(host, hass, config,
add_devices_callback)
request_configuration(host, hass, config, add_devices_callback)
return
# If we came here and configuring this host, mark as done
@ -141,7 +140,7 @@ def setup_plexserver(host, token, hass, config, add_devices_callback):
try:
devices = plexserver.clients()
except plexapi.exceptions.BadRequest:
_LOGGER.exception('Error listing plex devices')
_LOGGER.exception("Error listing plex devices")
return
except OSError:
_LOGGER.error("Could not connect to plex server at http://%s",
@ -214,10 +213,9 @@ def request_configuration(host, hass, config, add_devices_callback):
return
def plex_configuration_callback(data):
"""The actions to do when our configuration callback is called."""
setup_plexserver(host,
data.get('token'), hass, config,
add_devices_callback)
"""Handle configuration changes."""
setup_plexserver(
host, data.get('token'), hass, config, add_devices_callback)
_CONFIGURING[host] = configurator.request_config(
hass,
@ -547,12 +545,12 @@ class PlexClient(MediaPlayerDevice):
@property
def media_content_id(self):
"""Content ID of current playing media."""
"""Return the content ID of current playing media."""
return self._media_content_id
@property
def media_content_type(self):
"""Content type of current playing media."""
"""Return the content type of current playing media."""
if self._session_type == 'clip':
_LOGGER.debug("Clip content type detected, "
"compatibility may vary: %s", self.entity_id)
@ -568,57 +566,57 @@ class PlexClient(MediaPlayerDevice):
@property
def media_artist(self):
"""Artist of current playing media, music track only."""
"""Return the artist of current playing media, music track only."""
return self._media_artist
@property
def media_album_name(self):
"""Album name of current playing media, music track only."""
"""Return the album name of current playing media, music track only."""
return self._media_album_name
@property
def media_album_artist(self):
"""Album artist of current playing media, music track only."""
"""Return the album artist of current playing media, music only."""
return self._media_album_artist
@property
def media_track(self):
"""Track number of current playing media, music track only."""
"""Return the track number of current playing media, music only."""
return self._media_track
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
"""Return the duration of current playing media in seconds."""
return self._media_duration
@property
def media_image_url(self):
"""Image url of current playing media."""
"""Return the image URL of current playing media."""
return self._media_image_url
@property
def media_title(self):
"""Title of current playing media."""
"""Return the title of current playing media."""
return self._media_title
@property
def media_season(self):
"""Season of curent playing media (TV Show only)."""
"""Return the season of current playing media (TV Show only)."""
return self._media_season
@property
def media_series_title(self):
"""The title of the series of current playing media (TV Show only)."""
"""Return the title of the series of current playing media."""
return self._media_series_title
@property
def media_episode(self):
"""Episode of current playing media (TV Show only)."""
"""Return the episode of current playing media (TV Show only)."""
return self._media_episode
@property
def make(self):
"""The make of the device (ex. SHIELD Android TV)."""
"""Return the make of the device (ex. SHIELD Android TV)."""
return self._make
@property

View File

@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Roku platform."""
"""Set up the Roku platform."""
hosts = []
if discovery_info:
@ -48,7 +48,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if host in KNOWN_HOSTS:
return
_LOGGER.debug('Discovered Roku: %s', host)
_LOGGER.debug("Discovered Roku: %s", host)
hosts.append(discovery_info.get("host"))
elif CONF_HOST in config:
@ -175,9 +175,8 @@ class RokuDevice(MediaPlayerDevice):
elif self.current_app.id is None:
return None
return 'http://{0}:{1}/query/icon/{2}'.format(self.ip_address,
DEFAULT_PORT,
self.current_app.id)
return 'http://{0}:{1}/query/icon/{2}'.format(
self.ip_address, DEFAULT_PORT, self.current_app.id)
@property
def app_name(self):

View File

@ -4,8 +4,8 @@ Support for interfacing with Russound via RNET Protocol.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.russound_rnet/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Russound RNET platform."""
"""Set up the Russound RNET platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
@ -163,5 +163,5 @@ class RussoundRNETDevice(MediaPlayerDevice):
@property
def source_list(self):
"""List of available input sources."""
"""Return a list of available input sources."""
return self._sources

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Samsung TV platform."""
"""Set up the Samsung TV platform."""
known_devices = hass.data.get(KNOWN_DEVICES_KEY)
if known_devices is None:
known_devices = set()
@ -66,8 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
timeout = DEFAULT_TIMEOUT
mac = None
else:
_LOGGER.warning(
'Internal error on samsungtv component. Cannot determine device')
_LOGGER.warning("Cannot determine device")
return
# Only add a device once, so discovered devices do not override manual

View File

@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Snapcast platform."""
"""Set up the Snapcast platform."""
import snapcast.control
host = config.get(CONF_HOST)
port = config.get(CONF_PORT, snapcast.control.CONTROL_PORT)
@ -42,8 +42,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
try:
server = snapcast.control.Snapserver(host, port)
except socket.gaierror:
_LOGGER.error('Could not connect to Snapcast server at %s:%d',
host, port)
_LOGGER.error(
"Could not connect to Snapcast server at %s:%d", host, port)
return False
add_devices([SnapcastDevice(client) for client in server.clients])

View File

@ -92,7 +92,7 @@ SONOS_SET_TIMER_SCHEMA = SONOS_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Sonos platform."""
"""Set up the Sonos platform."""
import soco
if DATA_SONOS not in hass.data:
@ -105,7 +105,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if discovery_info:
player = soco.SoCo(discovery_info.get('host'))
# if device allready exists by config
# if device already exists by config
if player.uid in [x.unique_id for x in hass.data[DATA_SONOS]]:
return
@ -132,18 +132,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
interface_addr=config.get(CONF_INTERFACE_ADDR))
if not players:
_LOGGER.warning('No Sonos speakers found.')
_LOGGER.warning("No Sonos speakers found")
return
hass.data[DATA_SONOS] = [SonosDevice(p) for p in players]
add_devices(hass.data[DATA_SONOS], True)
_LOGGER.info('Added %s Sonos speakers', len(players))
_LOGGER.info("Added %s Sonos speakers", len(players))
descriptions = load_yaml_config_file(
path.join(path.dirname(__file__), 'services.yaml'))
def service_handle(service):
"""Internal func for applying a service."""
"""Handle for services."""
entity_ids = service.data.get('entity_id')
if entity_ids:
@ -221,28 +221,28 @@ def _get_entity_from_soco(hass, soco):
for device in hass.data[DATA_SONOS]:
if soco == device.soco:
return device
raise ValueError("No entity for SoCo device!")
raise ValueError("No entity for SoCo device")
def soco_error(funct):
"""Decorator to catch soco exceptions."""
"""Catch soco exceptions."""
@ft.wraps(funct)
def wrapper(*args, **kwargs):
"""Wrapper for all soco exception."""
"""Wrap for all soco exception."""
from soco.exceptions import SoCoException
try:
return funct(*args, **kwargs)
except SoCoException as err:
_LOGGER.error("Error on %s with %s.", funct.__name__, err)
_LOGGER.error("Error on %s with %s", funct.__name__, err)
return wrapper
def soco_coordinator(funct):
"""Decorator to call funct on coordinator."""
"""Call function on coordinator."""
@ft.wraps(funct)
def wrapper(device, *args, **kwargs):
"""Wrapper for call to coordinator."""
"""Wrap for call to coordinator."""
if device.is_coordinator:
return funct(device, *args, **kwargs)
return funct(device.coordinator, *args, **kwargs)
@ -296,7 +296,7 @@ class SonosDevice(MediaPlayerDevice):
@property
def should_poll(self):
"""Polling needed."""
"""Return the polling state."""
return True
@property
@ -340,8 +340,7 @@ class SonosDevice(MediaPlayerDevice):
def _is_available(self):
try:
sock = socket.create_connection(
address=(self._player.ip_address, 1443),
timeout=3)
address=(self._player.ip_address, 1443), timeout=3)
sock.close()
return True
except socket.error:

View File

@ -1,4 +1,9 @@
"""Support for interface with a Bose Soundtouch."""
"""
Support for interface with a Bose Soundtouch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.soundtouch/
"""
import logging
from os import path
@ -69,14 +74,14 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Bose Soundtouch platform."""
"""Set up the Bose Soundtouch platform."""
if DATA_SOUNDTOUCH not in hass.data:
hass.data[DATA_SOUNDTOUCH] = []
if discovery_info:
# Discovery
host = discovery_info["host"]
port = int(discovery_info["port"])
host = discovery_info['host']
port = int(discovery_info['port'])
# if device already exists by config
if host in [device.config['host'] for device in
@ -119,8 +124,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
device.entity_id == master_device_id].__iter__(), None)
if master is None:
_LOGGER.warning("Unable to find master with entity_id:" + str(
master_device_id))
_LOGGER.warning("Unable to find master with entity_id: %s",
str(master_device_id))
return
if service.service == SERVICE_PLAY_EVERYWHERE:

View File

@ -4,7 +4,6 @@ Support for interacting with Spotify Connect.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.spotify/
"""
import logging
from datetime import timedelta
@ -22,7 +21,6 @@ from homeassistant.const import (
CONF_NAME, STATE_PLAYING, STATE_PAUSED, STATE_IDLE, STATE_UNKNOWN)
import homeassistant.helpers.config_validation as cv
COMMIT = '544614f4b1d508201d363e84e871f86c90aa26b2'
REQUIREMENTS = ['https://github.com/happyleavesaoc/spotipy/'
'archive/%s.zip#spotipy==2.4.4' % COMMIT]
@ -72,7 +70,7 @@ def request_configuration(hass, config, add_devices, oauth):
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Spotify platform."""
"""Set up the Spotify platform."""
import spotipy.oauth2
callback_url = '{}{}'.format(hass.config.api.base_url, AUTH_CALLBACK_PATH)
cache = config.get(CONF_CACHE_PATH, hass.config.path(DEFAULT_CACHE_PATH))
@ -82,7 +80,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
cache_path=cache)
token_info = oauth.get_cached_token()
if not token_info:
_LOGGER.info('no token; requesting authorization')
_LOGGER.info("no token; requesting authorization")
hass.http.register_view(SpotifyAuthCallbackView(
config, add_devices, oauth))
request_configuration(hass, config, add_devices, oauth)
@ -225,31 +223,31 @@ class SpotifyMediaPlayer(MediaPlayerDevice):
elif media_type == MEDIA_TYPE_PLAYLIST:
kwargs['context_uri'] = media_id
else:
_LOGGER.error('media type %s is not supported', media_type)
_LOGGER.error("media type %s is not supported", media_type)
return
if not media_id.startswith('spotify:'):
_LOGGER.error('media id must be spotify uri')
_LOGGER.error("media id must be spotify uri")
return
self._player.start_playback(**kwargs)
@property
def name(self):
"""Name."""
"""Return the name."""
return self._name
@property
def icon(self):
"""Icon."""
"""Return the icon."""
return ICON
@property
def state(self):
"""Playback state."""
"""Return the playback state."""
return self._state
@property
def volume_level(self):
"""Device volume."""
"""Return the device volume."""
return self._volume
@property
@ -259,40 +257,40 @@ class SpotifyMediaPlayer(MediaPlayerDevice):
@property
def source_list(self):
"""Playback devices."""
"""Return a list of source devices."""
return list(self._devices.keys())
@property
def source(self):
"""Current playback device."""
"""Return the current playback device."""
return self._current_device
@property
def media_content_id(self):
"""Media URL."""
"""Return the media URL."""
return self._uri
@property
def media_image_url(self):
"""Media image url."""
"""Return the media image URL."""
return self._image_url
@property
def media_artist(self):
"""Media artist."""
"""Return the media artist."""
return self._artist
@property
def media_album_name(self):
"""Media album."""
"""Return the media album."""
return self._album
@property
def media_title(self):
"""Media title."""
"""Return the media title."""
return self._title
@property
def supported_features(self):
"""Media player features that are supported."""
"""Return the media player features that are supported."""
return SUPPORT_SPOTIFY

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the squeezebox platform."""
"""Set up the squeezebox platform."""
import socket
username = config.get(CONF_USERNAME)
@ -65,8 +65,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
try:
ipaddr = socket.gethostbyname(host)
except (OSError) as error:
_LOGGER.error("Could not communicate with %s:%d: %s",
host, port, error)
_LOGGER.error(
"Could not communicate with %s:%d: %s", host, port, error)
return False
_LOGGER.debug("Creating LMS object for %s", ipaddr)

View File

@ -51,7 +51,7 @@ _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the universal media players."""
"""Set up the universal media players."""
if not validate_config(config):
return
@ -72,7 +72,7 @@ def validate_config(config):
# Validate name
if CONF_NAME not in config:
_LOGGER.error('Universal Media Player configuration requires name')
_LOGGER.error("Universal Media Player configuration requires name")
return False
validate_children(config)
@ -83,7 +83,7 @@ def validate_config(config):
for key in config:
if key not in [CONF_NAME, CONF_CHILDREN, CONF_COMMANDS, CONF_ATTRS]:
_LOGGER.warning(
'Universal Media Player (%s) unrecognized parameter %s',
"Universal Media Player (%s) unrecognized parameter %s",
config[CONF_NAME], key)
del_keys.append(key)
for key in del_keys:
@ -96,13 +96,12 @@ def validate_children(config):
"""Validate children."""
if CONF_CHILDREN not in config:
_LOGGER.info(
'No children under Universal Media Player (%s)', config[CONF_NAME])
"No children under Universal Media Player (%s)", config[CONF_NAME])
config[CONF_CHILDREN] = []
elif not isinstance(config[CONF_CHILDREN], list):
_LOGGER.warning(
'Universal Media Player (%s) children not list in config. '
'They will be ignored.',
config[CONF_NAME])
"Universal Media Player (%s) children not list in config. "
"They will be ignored", config[CONF_NAME])
config[CONF_CHILDREN] = []
@ -112,9 +111,8 @@ def validate_commands(config):
config[CONF_COMMANDS] = {}
elif not isinstance(config[CONF_COMMANDS], dict):
_LOGGER.warning(
'Universal Media Player (%s) specified commands not dict in '
'config. They will be ignored.',
config[CONF_NAME])
"Universal Media Player (%s) specified commands not dict in "
"config. They will be ignored", config[CONF_NAME])
config[CONF_COMMANDS] = {}
@ -124,9 +122,8 @@ def validate_attributes(config):
config[CONF_ATTRS] = {}
elif not isinstance(config[CONF_ATTRS], dict):
_LOGGER.warning(
'Universal Media Player (%s) specified attributes '
'not dict in config. They will be ignored.',
config[CONF_NAME])
"Universal Media Player (%s) specified attributes "
"not dict in config. They will be ignored", config[CONF_NAME])
config[CONF_ATTRS] = {}
for key, val in config[CONF_ATTRS].items():
@ -173,8 +170,8 @@ class UniversalMediaPlayer(MediaPlayerDevice):
def _override_or_child_attr(self, attr_name):
"""Return either the override or the active child for attr_name."""
if attr_name in self._attrs:
return self._entity_lkp(self._attrs[attr_name][0],
self._attrs[attr_name][1])
return self._entity_lkp(
self._attrs[attr_name][0], self._attrs[attr_name][1])
return self._child_attr(attr_name)
@ -215,8 +212,8 @@ class UniversalMediaPlayer(MediaPlayerDevice):
def master_state(self):
"""Return the master state for entity or None."""
if CONF_STATE in self._attrs:
master_state = self._entity_lkp(self._attrs[CONF_STATE][0],
self._attrs[CONF_STATE][1])
master_state = self._entity_lkp(
self._attrs[CONF_STATE][0], self._attrs[CONF_STATE][1])
return master_state if master_state else STATE_OFF
else:
return None
@ -348,7 +345,7 @@ class UniversalMediaPlayer(MediaPlayerDevice):
@property
def source(self):
""""Return the current input source of the device."""
"""Return the current input source of the device."""
return self._override_or_child_attr(ATTR_INPUT_SOURCE)
@property

View File

@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the vlc platform."""
"""Set up the vlc platform."""
add_devices([VlcDevice(config.get(CONF_NAME, DEFAULT_NAME),
config.get(CONF_ARGUMENTS))])

View File

@ -140,7 +140,7 @@ class Volumio(MediaPlayerDevice):
if str(url[0:2]).lower() == 'ht':
mediaurl = url
else:
mediaurl = "http://" + self.host + ":" + str(self.port) + url
mediaurl = "http://{}:{}{}".format(self.host, self.port, url)
return mediaurl
@property

View File

@ -62,7 +62,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the LG WebOS TV platform."""
"""Set up the LG WebOS TV platform."""
if discovery_info is not None:
host = urlparse(discovery_info[1]).hostname
else:
@ -84,7 +84,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
def setup_tv(host, mac, name, customize, config, hass, add_devices):
"""Setup a LG WebOS TV based on host parameter."""
"""Set up a LG WebOS TV based on host parameter."""
from pylgtv import WebOsClient
from pylgtv import PyLGTVPairException
from websockets.exceptions import ConnectionClosed
@ -133,7 +133,7 @@ def request_configuration(
# pylint: disable=unused-argument
def lgtv_configuration_callback(data):
"""The actions to do when our configuration callback is called."""
"""Handle configuration changes."""
setup_tv(host, mac, name, customize, config, hass, add_devices)
_CONFIGURING[host] = configurator.request_config(

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Yamaha platform."""
"""Set up the Yamaha platform."""
import rxv
# keep track of configured receivers so that we don't end up
# discovering a receiver dynamically that we have static config
@ -241,7 +241,7 @@ class YamahaDevice(MediaPlayerDevice):
function()
except rxv.exceptions.ResponseException:
_LOGGER.warning(
'Failed to execute %s on %s', function_text, self._name)
"Failed to execute %s on %s", function_text, self._name)
def select_source(self, source):
"""Select input source."""

View File

@ -111,7 +111,7 @@ def face_person(hass, group, person, camera_entity):
@asyncio.coroutine
def async_setup(hass, config):
"""Setup microsoft face."""
"""Set up microsoft face."""
entities = {}
face = MicrosoftFace(
hass,

View File

@ -67,7 +67,7 @@ HUB = None
def setup(hass, config):
"""Setup Modbus component."""
"""Set up Modbus component."""
# Modbus connection type
# pylint: disable=global-statement, import-error
client_type = config[DOMAIN][CONF_TYPE]

View File

@ -214,8 +214,7 @@ def async_subscribe(hass, topic, msg_callback, qos=DEFAULT_QOS,
if encoding is not None:
try:
payload = dp_payload.decode(encoding)
_LOGGER.debug("Received message on %s: %s",
dp_topic, payload)
_LOGGER.debug("Received message on %s: %s", dp_topic, payload)
except (AttributeError, UnicodeDecodeError):
_LOGGER.error("Illegal payload encoding %s from "
"MQTT topic: %s, Payload: %s",

View File

@ -31,7 +31,7 @@ ALLOWED_PLATFORMS = {
@asyncio.coroutine
def async_start(hass, discovery_topic, hass_config):
"""Initialization of MQTT Discovery."""
"""Initialize of MQTT Discovery."""
# pylint: disable=unused-variable
@asyncio.coroutine
def async_device_message_received(topic, payload, qos):

View File

@ -47,7 +47,7 @@ def async_start(hass, server_config):
broker = Broker(server_config, hass.loop)
yield from broker.start()
except BrokerException:
logging.getLogger(__name__).exception('Error initializing MQTT server')
logging.getLogger(__name__).exception("Error initializing MQTT server")
return False, None
finally:
passwd.close()

View File

@ -68,7 +68,7 @@ def send_message(hass, message, title=None, data=None):
@asyncio.coroutine
def async_setup(hass, config):
"""Setup the notify services."""
"""Set up the notify services."""
descriptions = yield from hass.loop.run_in_executor(
None, load_yaml_config_file,
os.path.join(os.path.dirname(__file__), 'services.yaml'))
@ -166,7 +166,7 @@ def async_setup(hass, config):
@asyncio.coroutine
def async_platform_discovered(platform, info):
"""Callback to load a platform."""
"""Handle for discovered platform."""
yield from async_setup_platform(platform, discovery_info=info)
discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

View File

@ -77,18 +77,18 @@ class ApnsDevice(object):
@property
def push_id(self):
"""The APNS id for the device."""
"""Return the APNS id for the device."""
return self.device_push_id
@property
def name(self):
"""The friendly name for the device."""
"""Return the friendly name for the device."""
return self.device_name
@property
def tracking_device_id(self):
"""
Device Id.
Return the device Id.
The id of a device that is tracked by the device
tracking component.
@ -98,7 +98,7 @@ class ApnsDevice(object):
@property
def full_tracking_device_id(self):
"""
Fully qualified device id.
Return the fully qualified device id.
The full id of a device that is tracked by the device
tracking component.
@ -107,7 +107,7 @@ class ApnsDevice(object):
@property
def disabled(self):
"""Should receive notifications."""
"""Return the ."""
return self.device_disabled
def disable(self):
@ -177,9 +177,7 @@ class ApnsNotificationService(BaseNotificationService):
if device.tracking_device_id is not None
]
track_state_change(
hass,
tracking_ids,
self.device_state_changed_listener)
hass, tracking_ids, self.device_state_changed_listener)
def device_state_changed_listener(self, entity_id, from_s, to_s):
"""
@ -205,10 +203,7 @@ class ApnsNotificationService(BaseNotificationService):
current_tracking_id = None if current_device is None \
else current_device.tracking_device_id
device = ApnsDevice(
push_id,
device_name,
current_tracking_id)
device = ApnsDevice(push_id, device_name, current_tracking_id)
if current_device is None:
self.devices[push_id] = device
@ -244,15 +239,15 @@ class ApnsNotificationService(BaseNotificationService):
elif isinstance(message, template_helper.Template):
rendered_message = message.render()
else:
rendered_message = ""
rendered_message = ''
payload = Payload(
alert=rendered_message,
badge=message_data.get("badge"),
sound=message_data.get("sound"),
category=message_data.get("category"),
custom=message_data.get("custom", {}),
content_available=message_data.get("content_available", False))
badge=message_data.get('badge'),
sound=message_data.get('sound'),
category=message_data.get('category'),
custom=message_data.get('custom', {}),
content_available=message_data.get('content_available', False))
device_update = False
@ -266,13 +261,9 @@ class ApnsNotificationService(BaseNotificationService):
if device_state is None or state == str(device_state):
try:
apns.send_notification(
push_id,
payload,
topic=self.topic)
push_id, payload, topic=self.topic)
except Unregistered:
logging.error(
"Device %s has unregistered.",
push_id)
logging.error("Device %s has unregistered", push_id)
device_update = True
device.disable()

Some files were not shown because too many files have changed in this diff Show More