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 # pylint: disable=unused-argument
def setup_platform(hass, config: ConfigType, def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None): 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: 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 return False

View File

@ -34,8 +34,8 @@ PRESENCE_SENSOR_TYPES = {
"Outdoor vehicle": "motion" "Outdoor vehicle": "motion"
} }
TAG_SENSOR_TYPES = { TAG_SENSOR_TYPES = {
"Tag Vibration": 'vibration', "Tag Vibration": "vibration",
"Tag Open": 'opening' "Tag Open": "opening"
} }
CONF_HOME = 'home' CONF_HOME = 'home'
@ -117,7 +117,7 @@ class NetatmoBinarySensor(BinarySensorDevice):
def __init__(self, data, camera_name, module_name, home, def __init__(self, data, camera_name, module_name, home,
timeout, offset, camera_type, sensor): 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._data = data
self._camera_name = camera_name self._camera_name = camera_name
self._module_name = module_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.""" """Class to utilize calendar service object to get next event."""
def __init__(self, calendar_service, calendar_id, search=None): 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_service = calendar_service
self.calendar_id = calendar_id self.calendar_id = calendar_id
self.search = search self.search = search

View File

@ -55,7 +55,7 @@ class NetatmoCamera(Camera):
"""Representation of the images published from a Netatmo camera.""" """Representation of the images published from a Netatmo camera."""
def __init__(self, data, camera_name, home, camera_type, verify_ssl): 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__() super(NetatmoCamera, self).__init__()
self._data = data self._data = data
self._camera_name = camera_name self._camera_name = camera_name

View File

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

View File

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

View File

@ -35,7 +35,7 @@ STATES = [SPEED_OFF, SPEED_LOW, 'med', SPEED_HIGH]
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config: ConfigType, def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None): 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: 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 return False

View File

@ -19,7 +19,7 @@ SPEED_AUTO = 'auto'
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink platform.""" """Set up the Wink platform."""
import pywink import pywink
for fan in pywink.get_fans(): 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): 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([ add_devices_callback([
DemoLight("Bed Light", False, True, effect_list=LIGHT_EFFECT_LIST, DemoLight("Bed Light", False, True, effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0]), effect=LIGHT_EFFECT_LIST[0]),

View File

@ -56,12 +56,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the LIFX platform.""" """Set up the LIFX platform."""
import aiolifx import aiolifx
if sys.platform == 'win32': if sys.platform == 'win32':
_LOGGER.warning('The lifx platform is known to not work on Windows. ' _LOGGER.warning("The lifx platform is known to not work on Windows. "
'Consider using the lifx_legacy platform instead.') "Consider using the lifx_legacy platform instead")
server_addr = config.get(CONF_SERVER) server_addr = config.get(CONF_SERVER)
@ -420,9 +420,8 @@ class LIFXLight(Light):
self._bri = bri self._bri = bri
self._kel = kel self._kel = kel
red, green, blue = colorsys.hsv_to_rgb(hue / SHORT_MAX, red, green, blue = colorsys.hsv_to_rgb(
sat / SHORT_MAX, hue / SHORT_MAX, sat / SHORT_MAX, bri / SHORT_MAX)
bri / SHORT_MAX)
red = int(red * BYTE_MAX) red = int(red * BYTE_MAX)
green = int(green * 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_COLOR_NAME: cv.string,
ATTR_RGB_COLOR: vol.All(vol.ExactSequence((cv.byte, cv.byte, cv.byte)), ATTR_RGB_COLOR: vol.All(vol.ExactSequence((cv.byte, cv.byte, cv.byte)),
vol.Coerce(tuple)), vol.Coerce(tuple)),
vol.Optional(ATTR_PERIOD, default=1.0): vol.All(vol.Coerce(float), vol.Optional(ATTR_PERIOD, default=1.0):
vol.Range(min=0.05)), vol.All(vol.Coerce(float), vol.Range(min=0.05)),
vol.Optional(ATTR_CYCLES, default=1.0): vol.All(vol.Coerce(float), vol.Optional(ATTR_CYCLES, default=1.0):
vol.Range(min=1)), vol.All(vol.Coerce(float), vol.Range(min=1)),
}) })
LIFX_EFFECT_PULSE_SCHEMA = LIFX_EFFECT_BREATHE_SCHEMA LIFX_EFFECT_PULSE_SCHEMA = LIFX_EFFECT_BREATHE_SCHEMA
LIFX_EFFECT_COLORLOOP_SCHEMA = LIFX_EFFECT_SCHEMA.extend({ LIFX_EFFECT_COLORLOOP_SCHEMA = LIFX_EFFECT_SCHEMA.extend({
ATTR_BRIGHTNESS: vol.All(vol.Coerce(int), vol.Clamp(min=0, max=255)), 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.Optional(ATTR_PERIOD, default=60):
vol.Clamp(min=1)), vol.All(vol.Coerce(float), vol.Clamp(min=1)),
vol.Optional(ATTR_CHANGE, default=20): vol.All(vol.Coerce(float), vol.Optional(ATTR_CHANGE, default=20):
vol.Clamp(min=0, max=360)), vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)),
vol.Optional(ATTR_SPREAD, default=30): vol.All(vol.Coerce(float), vol.Optional(ATTR_SPREAD, default=30):
vol.Clamp(min=0, max=360)), vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)),
}) })
LIFX_EFFECT_STOP_SCHEMA = vol.Schema({ 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 import logging
from homeassistant.components.light import ( 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 import logging
from homeassistant.components.light import ( from homeassistant.components.light import (
@ -8,7 +13,6 @@ from homeassistant.components.light.lutron import (
from homeassistant.components.lutron_caseta import ( from homeassistant.components.lutron_caseta import (
LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice) LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron_caseta'] DEPENDENCIES = ['lutron_caseta']
@ -16,7 +20,7 @@ DEPENDENCIES = ['lutron_caseta']
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Lutron Caseta lights.""" """Set up the Lutron Caseta lights."""
devs = [] devs = []
bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE] bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE]
light_devices = bridge.get_devices_by_types(["WallDimmer", "PlugInDimmer"]) 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 @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 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: if discovery_info is not None:
config = PLATFORM_SCHEMA(discovery_info) config = PLATFORM_SCHEMA(discovery_info)
@ -142,7 +142,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class MqttLight(Light): class MqttLight(Light):
"""MQTT light.""" """Representation of a MQTT light."""
def __init__(self, name, effect_list, topic, templates, qos, def __init__(self, name, effect_list, topic, templates, qos,
retain, payload, optimistic, brightness_scale, retain, payload, optimistic, brightness_scale,
@ -197,7 +197,7 @@ class MqttLight(Light):
@asyncio.coroutine @asyncio.coroutine
def async_added_to_hass(self): def async_added_to_hass(self):
"""Subscribe mqtt events. """Subscribe to MQTT events.
This method is a coroutine. This method is a coroutine.
""" """
@ -211,7 +211,7 @@ class MqttLight(Light):
@callback @callback
def state_received(topic, payload, qos): def state_received(topic, payload, qos):
"""A new MQTT message has been received.""" """Handle new MQTT messages."""
payload = templates[CONF_STATE](payload) payload = templates[CONF_STATE](payload)
if payload == self._payload['on']: if payload == self._payload['on']:
self._state = True self._state = True
@ -226,7 +226,7 @@ class MqttLight(Light):
@callback @callback
def brightness_received(topic, payload, qos): 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)) device_value = float(templates[CONF_BRIGHTNESS](payload))
percent_bright = device_value / self._brightness_scale percent_bright = device_value / self._brightness_scale
self._brightness = int(percent_bright * 255) self._brightness = int(percent_bright * 255)
@ -244,7 +244,7 @@ class MqttLight(Light):
@callback @callback
def rgb_received(topic, payload, qos): 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 self._rgb = [int(val) for val in
templates[CONF_RGB](payload).split(',')] templates[CONF_RGB](payload).split(',')]
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())
@ -261,7 +261,7 @@ class MqttLight(Light):
@callback @callback
def color_temp_received(topic, payload, qos): 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._color_temp = int(templates[CONF_COLOR_TEMP](payload))
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())
@ -277,7 +277,7 @@ class MqttLight(Light):
@callback @callback
def effect_received(topic, payload, qos): 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._effect = templates[CONF_EFFECT](payload)
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())
@ -293,7 +293,7 @@ class MqttLight(Light):
@callback @callback
def white_value_received(topic, payload, qos): 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)) device_value = float(templates[CONF_WHITE_VALUE](payload))
percent_white = device_value / self._white_value_scale percent_white = device_value / self._white_value_scale
self._white_value = int(percent_white * 255) self._white_value = int(percent_white * 255)
@ -311,7 +311,7 @@ class MqttLight(Light):
@callback @callback
def xy_received(topic, payload, qos): 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 self._xy = [float(val) for val in
templates[CONF_XY](payload).split(',')] templates[CONF_XY](payload).split(',')]
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())

View File

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

View File

@ -104,7 +104,7 @@ class MqttTemplate(Light):
def __init__(self, hass, name, effect_list, topics, templates, optimistic, def __init__(self, hass, name, effect_list, topics, templates, optimistic,
qos, retain): qos, retain):
"""Initialize MQTT Template light.""" """Initialize a MQTT Template light."""
self._name = name self._name = name
self._effect_list = effect_list self._effect_list = effect_list
self._topics = topics self._topics = topics
@ -139,21 +139,19 @@ class MqttTemplate(Light):
self._rgb = None self._rgb = None
self._effect = None self._effect = None
# init hass to template
for tpl in self._templates.values(): for tpl in self._templates.values():
if tpl is not None: if tpl is not None:
tpl.hass = hass tpl.hass = hass
@asyncio.coroutine @asyncio.coroutine
def async_added_to_hass(self): def async_added_to_hass(self):
"""Subscribe mqtt events. """Subscribe to MQTT events.
This method is a coroutine. This method is a coroutine.
""" """
@callback @callback
def state_received(topic, payload, qos): def state_received(topic, payload, qos):
"""A new MQTT message has been received.""" """Handle new MQTT messages."""
# read state
state = self._templates[CONF_STATE_TEMPLATE].\ state = self._templates[CONF_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload) async_render_with_possible_json_value(payload)
if state == STATE_ON: if state == STATE_ON:
@ -161,9 +159,8 @@ class MqttTemplate(Light):
elif state == STATE_OFF: elif state == STATE_OFF:
self._state = False self._state = False
else: else:
_LOGGER.warning('Invalid state value received') _LOGGER.warning("Invalid state value received")
# read brightness
if self._brightness is not None: if self._brightness is not None:
try: try:
self._brightness = int( self._brightness = int(
@ -171,9 +168,8 @@ class MqttTemplate(Light):
async_render_with_possible_json_value(payload) async_render_with_possible_json_value(payload)
) )
except ValueError: except ValueError:
_LOGGER.warning('Invalid brightness value received') _LOGGER.warning("Invalid brightness value received")
# read color temperature
if self._color_temp is not None: if self._color_temp is not None:
try: try:
self._color_temp = int( self._color_temp = int(
@ -181,9 +177,8 @@ class MqttTemplate(Light):
async_render_with_possible_json_value(payload) async_render_with_possible_json_value(payload)
) )
except ValueError: except ValueError:
_LOGGER.warning('Invalid color temperature value received') _LOGGER.warning("Invalid color temperature value received")
# read color
if self._rgb is not None: if self._rgb is not None:
try: try:
self._rgb[0] = int( self._rgb[0] = int(
@ -196,9 +191,8 @@ class MqttTemplate(Light):
self._templates[CONF_BLUE_TEMPLATE]. self._templates[CONF_BLUE_TEMPLATE].
async_render_with_possible_json_value(payload)) async_render_with_possible_json_value(payload))
except ValueError: except ValueError:
_LOGGER.warning('Invalid color value received') _LOGGER.warning("Invalid color value received")
# read white value
if self._white_value is not None: if self._white_value is not None:
try: try:
self._white_value = int( self._white_value = int(
@ -208,16 +202,14 @@ class MqttTemplate(Light):
except ValueError: except ValueError:
_LOGGER.warning('Invalid white value received') _LOGGER.warning('Invalid white value received')
# read effect
if self._templates[CONF_EFFECT_TEMPLATE] is not None: if self._templates[CONF_EFFECT_TEMPLATE] is not None:
effect = self._templates[CONF_EFFECT_TEMPLATE].\ effect = self._templates[CONF_EFFECT_TEMPLATE].\
async_render_with_possible_json_value(payload) async_render_with_possible_json_value(payload)
# validate effect value
if effect in self._effect_list: if effect in self._effect_list:
self._effect = effect self._effect = effect
else: else:
_LOGGER.warning('Unsupported effect value received') _LOGGER.warning("Unsupported effect value received")
self.hass.async_add_job(self.async_update_ha_state()) self.hass.async_add_job(self.async_update_ha_state())
@ -285,26 +277,22 @@ class MqttTemplate(Light):
This method is a coroutine. This method is a coroutine.
""" """
# state
values = {'state': True} values = {'state': True}
if self._optimistic: if self._optimistic:
self._state = True self._state = True
# brightness
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:
values['brightness'] = int(kwargs[ATTR_BRIGHTNESS]) values['brightness'] = int(kwargs[ATTR_BRIGHTNESS])
if self._optimistic: if self._optimistic:
self._brightness = kwargs[ATTR_BRIGHTNESS] self._brightness = kwargs[ATTR_BRIGHTNESS]
# color_temp
if ATTR_COLOR_TEMP in kwargs: if ATTR_COLOR_TEMP in kwargs:
values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP]) values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])
if self._optimistic: if self._optimistic:
self._color_temp = kwargs[ATTR_COLOR_TEMP] self._color_temp = kwargs[ATTR_COLOR_TEMP]
# color
if ATTR_RGB_COLOR in kwargs: if ATTR_RGB_COLOR in kwargs:
values['red'] = kwargs[ATTR_RGB_COLOR][0] values['red'] = kwargs[ATTR_RGB_COLOR][0]
values['green'] = kwargs[ATTR_RGB_COLOR][1] values['green'] = kwargs[ATTR_RGB_COLOR][1]
@ -313,22 +301,18 @@ class MqttTemplate(Light):
if self._optimistic: if self._optimistic:
self._rgb = kwargs[ATTR_RGB_COLOR] self._rgb = kwargs[ATTR_RGB_COLOR]
# white value
if ATTR_WHITE_VALUE in kwargs: if ATTR_WHITE_VALUE in kwargs:
values['white_value'] = int(kwargs[ATTR_WHITE_VALUE]) values['white_value'] = int(kwargs[ATTR_WHITE_VALUE])
if self._optimistic: if self._optimistic:
self._white_value = kwargs[ATTR_WHITE_VALUE] self._white_value = kwargs[ATTR_WHITE_VALUE]
# effect
if ATTR_EFFECT in kwargs: if ATTR_EFFECT in kwargs:
values['effect'] = kwargs.get(ATTR_EFFECT) values['effect'] = kwargs.get(ATTR_EFFECT)
# flash
if ATTR_FLASH in kwargs: if ATTR_FLASH in kwargs:
values['flash'] = kwargs.get(ATTR_FLASH) values['flash'] = kwargs.get(ATTR_FLASH)
# transition
if ATTR_TRANSITION in kwargs: if ATTR_TRANSITION in kwargs:
values['transition'] = int(kwargs[ATTR_TRANSITION]) values['transition'] = int(kwargs[ATTR_TRANSITION])
@ -347,12 +331,10 @@ class MqttTemplate(Light):
This method is a coroutine. This method is a coroutine.
""" """
# state
values = {'state': False} values = {'state': False}
if self._optimistic: if self._optimistic:
self._state = False self._state = False
# transition
if ATTR_TRANSITION in kwargs: if ATTR_TRANSITION in kwargs:
values['transition'] = int(kwargs[ATTR_TRANSITION]) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mysensors/ https://home-assistant.io/components/light.mysensors/
""" """
import logging import logging
from homeassistant.components import mysensors from homeassistant.components import mysensors
from homeassistant.components.light import (ATTR_BRIGHTNESS, ATTR_RGB_COLOR, from homeassistant.components.light import (
ATTR_WHITE_VALUE, ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_WHITE_VALUE,
SUPPORT_BRIGHTNESS, SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, SUPPORT_WHITE_VALUE, Light)
SUPPORT_RGB_COLOR,
SUPPORT_WHITE_VALUE, Light)
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.util.color import rgb_hex_to_rgb_list 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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the mysensors platform for sensors.""" """Set up the MySensors platform for lights."""
# Only act if loaded via mysensors by discovery event.
# Otherwise gateway is not setup.
if discovery_info is None: if discovery_info is None:
return return
@ -62,10 +57,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): 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): def __init__(self, *args):
"""Set up instance attributes.""" """Initialize a MySensors Light."""
mysensors.MySensorsDeviceEntity.__init__(self, *args) mysensors.MySensorsDeviceEntity.__init__(self, *args)
self._state = None self._state = None
self._brightness = None self._brightness = None
@ -157,7 +152,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
elif white is not None: elif white is not None:
rgb.append(white) rgb.append(white)
else: else:
_LOGGER.error('White value is not updated for RGBW light') _LOGGER.error("White value is not updated for RGBW light")
return return
hex_color = hex_template % tuple(rgb) hex_color = hex_template % tuple(rgb)
if len(rgb) > 3: if len(rgb) > 3:
@ -206,9 +201,8 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
set_req = self.gateway.const.SetReq set_req = self.gateway.const.SetReq
if value_type is None or value is None: if value_type is None or value is None:
_LOGGER.warning( _LOGGER.warning(
'%s: value_type %s, value = %s, ' "%s: value_type %s, value = %s, None is not valid argument "
'None is not valid argument when setting child value' "when setting child value", self._name, value_type, value)
'', self._name, value_type, value)
return return
self.gateway.set_child_value( self.gateway.set_child_value(
self.node_id, self.child_id, value_type, 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] value = self._values[self.value_type]
if len(value) != 6 and len(value) != 8: if len(value) != 6 and len(value) != 8:
_LOGGER.error( _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 return
color_list = rgb_hex_to_rgb_list(value) color_list = rgb_hex_to_rgb_list(value)
if set_req.V_LIGHT not in self._values and \ 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 len(color_list) > 3:
if set_req.V_RGBW != self.value_type: if set_req.V_RGBW != self.value_type:
_LOGGER.error( _LOGGER.error(
'Wrong value %s for %s', "Wrong value %s for %s",
value, set_req(self.value_type).name) value, set_req(self.value_type).name)
return return
self._white = color_list.pop() self._white = color_list.pop()
@ -265,7 +259,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light):
child = node.children[self.child_id] child = node.children[self.child_id]
for value_type, value in child.values.items(): for value_type, value in child.values.items():
_LOGGER.debug( _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 self._values[value_type] = value

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@ DEPENDENCIES = ['qwikswitch']
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Add lights from the main Qwikswitch component.""" """Set up the lights from the main Qwikswitch component."""
if discovery_info is None: if discovery_info is None:
_LOGGER.error("Configure Qwikswitch component failed") _LOGGER.error("Configure Qwikswitch component failed")
return False 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 # 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][ hass.data[DATA_ENTITY_LOOKUP][
EVENT_KEY_COMMAND][device_id].append(device) EVENT_KEY_COMMAND][device_id].append(device)
if config[CONF_GROUP]: if config[CONF_GROUP]:
@ -188,7 +188,7 @@ class DimmableRflinkLight(SwitchableRflinkDevice, Light):
# rflink only support 16 brightness levels # rflink only support 16 brightness levels
self._brightness = int(kwargs[ATTR_BRIGHTNESS] / 17) * 17 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) yield from self._async_handle_command('dim', self._brightness)
@property @property

View File

@ -27,7 +27,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices(lights) add_devices(lights)
def light_update(event): 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 \ if not isinstance(event.device, rfxtrxmod.LightingDevice) or \
not event.device.known_to_be_dimmable: not event.device.known_to_be_dimmable:
return return
@ -38,13 +38,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
rfxtrx.apply_received_command(event) rfxtrx.apply_received_command(event)
# Subscribe to main rfxtrx events # Subscribe to main RFXtrx events
if light_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: if light_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS:
rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(light_update) rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(light_update)
class RfxtrxLight(rfxtrx.RfxtrxDevice, Light): class RfxtrxLight(rfxtrx.RfxtrxDevice, Light):
"""Represenation of a RFXtrx light.""" """Representation of a RFXtrx light."""
@property @property
def brightness(self): def brightness(self):
@ -61,8 +61,8 @@ class RfxtrxLight(rfxtrx.RfxtrxDevice, Light):
brightness = kwargs.get(ATTR_BRIGHTNESS) brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness is None: if brightness is None:
self._brightness = 255 self._brightness = 255
self._send_command("turn_on") self._send_command('turn_on')
else: else:
self._brightness = brightness self._brightness = brightness
_brightness = (brightness * 100 // 255) _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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.pwm/ https://home-assistant.io/components/light.pwm/
""" """
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -55,7 +54,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None): 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 import SimpleLed
from pwmled.led.rgb import RgbLed from pwmled.led.rgb import RgbLed
from pwmled.led.rgbw import RgbwLed 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] opt_args['address'] = led_conf[CONF_ADDRESS]
driver = Pca9685Driver(pins, **opt_args) driver = Pca9685Driver(pins, **opt_args)
else: else:
_LOGGER.error("Invalid driver type.") _LOGGER.error("Invalid driver type")
return return
name = led_conf[CONF_NAME] 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: elif led_type == CONF_LED_TYPE_RGBW:
led = PwmRgbLed(RgbwLed(driver), name) led = PwmRgbLed(RgbwLed(driver), name)
else: else:
_LOGGER.error("Invalid led type.") _LOGGER.error("Invalid led type")
return return
leds.append(led) leds.append(led)
@ -96,10 +95,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class PwmSimpleLed(Light): class PwmSimpleLed(Light):
"""Representation of a simple on-color pwm led.""" """Representation of a simple one-color PWM LED."""
def __init__(self, led, name): def __init__(self, led, name):
"""Initialize led.""" """Initialize one-color PWM LED."""
self._led = led self._led = led
self._name = name self._name = name
self._is_on = False self._is_on = False
@ -149,7 +148,7 @@ class PwmSimpleLed(Light):
self.schedule_update_ha_state() self.schedule_update_ha_state()
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
"""Turn off a led.""" """Turn off a LED."""
if self.is_on: if self.is_on:
if ATTR_TRANSITION in kwargs: if ATTR_TRANSITION in kwargs:
transition_time = kwargs[ATTR_TRANSITION] transition_time = kwargs[ATTR_TRANSITION]
@ -162,10 +161,10 @@ class PwmSimpleLed(Light):
class PwmRgbLed(PwmSimpleLed): class PwmRgbLed(PwmSimpleLed):
"""Representation of a rgb(w) pwm led.""" """Representation of a RGB(W) PWM LED."""
def __init__(self, led, name): def __init__(self, led, name):
"""Initialize led.""" """Initialize a RGB(W) PWM LED."""
super().__init__(led, name) super().__init__(led, name)
self._color = DEFAULT_COLOR self._color = DEFAULT_COLOR
@ -180,7 +179,7 @@ class PwmRgbLed(PwmSimpleLed):
return SUPPORT_RGB_LED return SUPPORT_RGB_LED
def turn_on(self, **kwargs): def turn_on(self, **kwargs):
"""Turn on a led.""" """Turn on a LED."""
if ATTR_RGB_COLOR in kwargs: if ATTR_RGB_COLOR in kwargs:
self._color = kwargs[ATTR_RGB_COLOR] self._color = kwargs[ATTR_RGB_COLOR]
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:

View File

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

View File

@ -58,10 +58,7 @@ class SenseHatLight(Light):
@property @property
def brightness(self): def brightness(self):
"""Read back the brightness of the light. """Read back the brightness of the light."""
Returns integer in the range of 1-255.
"""
return self._brightness return self._brightness
@property @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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.tellduslive/ https://home-assistant.io/components/light.tellduslive/
""" """
import logging import logging
@ -17,17 +16,17 @@ _LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up lights.""" """Set up the Tellstick Net lights."""
if discovery_info is None: if discovery_info is None:
return return
add_devices(TelldusLiveLight(hass, light) for light in discovery_info) add_devices(TelldusLiveLight(hass, light) for light in discovery_info)
class TelldusLiveLight(TelldusLiveEntity, Light): class TelldusLiveLight(TelldusLiveEntity, Light):
"""Representation of a light.""" """Representation of a Tellstick Net light."""
def __init__(self, hass, device_id): def __init__(self, hass, device_id):
"""Initialize the light.""" """Initialize the Tellstick Net light."""
super().__init__(hass, device_id) super().__init__(hass, device_id)
self._last_brightness = self.brightness self._last_brightness = self.brightness

View File

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

View File

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

View File

@ -59,7 +59,7 @@ class TradfriGroup(Light):
@property @property
def brightness(self): 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 return self._group.dimmer
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
@ -79,7 +79,7 @@ class TradfriGroup(Light):
class Tradfri(Light): class Tradfri(Light):
"""The platform class required by hass.""" """The platform class required by Home Asisstant."""
def __init__(self, light): def __init__(self, light):
"""Initialize a Light.""" """Initialize a Light."""
@ -118,7 +118,7 @@ class Tradfri(Light):
@property @property
def brightness(self): 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 return self._light_data.dimmer
@property @property
@ -134,7 +134,7 @@ class Tradfri(Light):
if hex_color == self._light_data.hex_color), None) if hex_color == self._light_data.hex_color), None)
if kelvin is None: if kelvin is None:
_LOGGER.error( _LOGGER.error(
'unexpected color temperature found for %s: %s', "Unexpected color temperature found for %s: %s",
self.name, self._light_data.hex_color) self.name, self._light_data.hex_color)
return return
return color_util.color_temperature_kelvin_to_mired(kelvin) return color_util.color_temperature_kelvin_to_mired(kelvin)

View File

@ -20,7 +20,7 @@ SUPPORT_VERA = SUPPORT_BRIGHTNESS
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up Vera lights.""" """Set up the Vera lights."""
add_devices( add_devices(
VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light']) 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): 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 import pywemo.discovery as discovery
if discovery_info is not None: if discovery_info is not None:
@ -64,7 +64,7 @@ class WemoLight(Light):
"""Representation of a WeMo light.""" """Representation of a WeMo light."""
def __init__(self, device, update_lights): def __init__(self, device, update_lights):
"""Initialize the light.""" """Initialize the WeMo light."""
self.light_id = device.name self.light_id = device.name
self.device = device self.device = device
self.update_lights = update_lights self.update_lights = update_lights
@ -97,7 +97,7 @@ class WemoLight(Light):
@property @property
def is_on(self): def is_on(self):
"""Set True if device is on.""" """Return true if device is on."""
return self.device.state['onoff'] != 0 return self.device.state['onoff'] != 0
@property @property

View File

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

View File

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

View File

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

View File

@ -67,7 +67,7 @@ class SunflowerBulb(Light):
@property @property
def brightness(self): 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) return int(self._brightness / 100 * 255)
@property @property

View File

@ -17,7 +17,7 @@ DEPENDENCIES = ['zha']
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 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) discovery_info = zha.get_discovery_info(hass, discovery_info)
if discovery_info is None: if discovery_info is None:
return return
@ -33,12 +33,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
class Light(zha.Entity, light.Light): class Light(zha.Entity, light.Light):
"""ZHA or ZLL light.""" """Representation of a ZHA or ZLL light."""
_domain = light.DOMAIN _domain = light.DOMAIN
def __init__(self, **kwargs): def __init__(self, **kwargs):
"""Initialize ZHA light.""" """Initialize the ZHA light."""
super().__init__(**kwargs) super().__init__(**kwargs)
self._supported_features = 0 self._supported_features = 0
self._color_temp = None self._color_temp = None
@ -61,7 +61,7 @@ class Light(zha.Entity, light.Light):
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:
"""Return True if entity is on.""" """Return true if entity is on."""
if self._state == 'unknown': if self._state == 'unknown':
return False return False
return bool(self._state) 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): 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)) name = '{}.{}'.format(DOMAIN, zwave.object_id(values.primary))
refresh = node_config.get(zwave.CONF_REFRESH_VALUE) refresh = node_config.get(zwave.CONF_REFRESH_VALUE)
delay = node_config.get(zwave.CONF_REFRESH_DELAY) delay = node_config.get(zwave.CONF_REFRESH_DELAY)
_LOGGER.debug('name=%s node_config=%s CONF_REFRESH_VALUE=%s' _LOGGER.debug("name=%s node_config=%s CONF_REFRESH_VALUE=%s"
' CONF_REFRESH_DELAY=%s', name, node_config, " CONF_REFRESH_DELAY=%s", name, node_config, refresh, delay)
refresh, delay)
if node.has_command_class(zwave.const.COMMAND_CLASS_SWITCH_COLOR): if node.has_command_class(zwave.const.COMMAND_CLASS_SWITCH_COLOR):
return ZwaveColorLight(values, refresh, delay) return ZwaveColorLight(values, refresh, delay)

View File

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

View File

@ -10,7 +10,7 @@ from homeassistant.const import (STATE_LOCKED, STATE_UNLOCKED)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo lock platform.""" """Set up the Demo lock platform."""
add_devices([ add_devices([
DemoLock('Front Door', STATE_LOCKED), DemoLock('Front Door', STATE_LOCKED),
DemoLock('Kitchen Door', STATE_UNLOCKED) 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): add_devices: Callable[[list], None], discovery_info=None):
"""Set up the ISY994 lock platform.""" """Set up the ISY994 lock platform."""
if isy.ISY is None or not isy.ISY.connected: 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 return False
devices = [] devices = []
@ -115,9 +115,9 @@ class ISYLockProgram(ISYLockDevice):
def lock(self, **kwargs) -> None: def lock(self, **kwargs) -> None:
"""Lock the device.""" """Lock the device."""
if not self._actions.runThen(): if not self._actions.runThen():
_LOGGER.error('Unable to lock device') _LOGGER.error("Unable to lock device")
def unlock(self, **kwargs) -> None: def unlock(self, **kwargs) -> None:
"""Unlock the device.""" """Unlock the device."""
if not self._actions.runElse(): 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 # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): 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) access_token = config.get(CONF_ACCESS_TOKEN)
device_id = config.get(CONF_ID) 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: if response.status_code == 200:
add_devices([Lockitron(response.json()['state'], access_token, add_devices([Lockitron(response.json()['state'], access_token,
device_id)]) device_id)])
else: else:
_LOGGER.error('Error retrieving lock status during init: %s', _LOGGER.error(
response.text) "Error retrieving lock status during init: %s", response.text)
class Lockitron(LockDevice): class Lockitron(LockDevice):
@ -72,21 +73,20 @@ class Lockitron(LockDevice):
def update(self): def update(self):
"""Update the internal state of the device.""" """Update the internal state of the device."""
response = requests \ response = requests.get(API_STATE_URL.format(
.get(API_STATE_URL.format(self.device_id, self.access_token)) self.device_id, self.access_token), timeout=5)
if response.status_code == 200: if response.status_code == 200:
self._state = response.json()['state'] self._state = response.json()['state']
else: 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): def do_change_request(self, requested_state):
"""Execute the change request and pull out the new state.""" """Execute the change request and pull out the new state."""
response = requests.put( response = requests.put(API_ACTION_URL.format(
API_ACTION_URL.format(self.device_id, self.access_token, self.device_id, self.access_token, requested_state), timeout=5)
requested_state))
if response.status_code == 200: if response.status_code == 200:
return response.json()['state'] return response.json()['state']
else: else:
_LOGGER.error('Error setting lock state: %s\n%s', _LOGGER.error("Error setting lock state: %s\n%s",
requested_state, response.text) requested_state, response.text)
return self._state return self._state

View File

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

View File

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

View File

@ -48,6 +48,6 @@ class VeraLock(VeraDevice, LockDevice):
return self._state == STATE_LOCKED return self._state == STATE_LOCKED
def update(self): 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) self._state = (STATE_LOCKED if self.vera_device.is_locked(True)
else STATE_UNLOCKED) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.volvooncall/ https://home-assistant.io/components/lock.volvooncall/
@ -14,9 +14,10 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the lock.""" """Set up the Volvo On Call lock."""
if discovery_info is None: if discovery_info is None:
return return
add_devices([VolvoLock(hass, *discovery_info)]) 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.wink/ https://home-assistant.io/components/lock.wink/
""" """
from homeassistant.components.lock import LockDevice from homeassistant.components.lock import LockDevice
from homeassistant.components.wink import WinkDevice, DOMAIN from homeassistant.components.wink import WinkDevice, DOMAIN
@ -12,7 +11,7 @@ DEPENDENCIES = ['wink']
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wink platform.""" """Set up the Wink platform."""
import pywink import pywink
for lock in pywink.get_locks(): 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.zwave/ https://home-assistant.io/components/lock.zwave/
@ -122,7 +122,7 @@ CLEAR_USERCODE_SCHEMA = vol.Schema({
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 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( yield from zwave.async_setup_platform(
hass, config, async_add_devices, discovery_info) 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: if value.index != code_slot:
continue continue
if len(str(usercode)) > 4: if len(str(usercode)) > 4:
_LOGGER.error('Invalid code provided: (%s)' _LOGGER.error("Invalid code provided: (%s) "
' usercode must %s or less digits', "usercode must %s or less digits",
usercode, len(value.data)) usercode, len(value.data))
break break
value.data = str(usercode) 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(): class_id=zwave.const.COMMAND_CLASS_USER_CODE).values():
if value.index != code_slot: if value.index != code_slot:
continue 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 break
def clear_usercode(service): def clear_usercode(service):
@ -178,28 +178,22 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
i += 1 i += 1
_LOGGER.debug('Data to clear lock: %s', data) _LOGGER.debug('Data to clear lock: %s', data)
value.data = 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 break
hass.services.async_register(DOMAIN, hass.services.async_register(
SERVICE_SET_USERCODE, DOMAIN, SERVICE_SET_USERCODE, set_usercode,
set_usercode, descriptions.get(SERVICE_SET_USERCODE), schema=SET_USERCODE_SCHEMA)
descriptions.get(SERVICE_SET_USERCODE), hass.services.async_register(
schema=SET_USERCODE_SCHEMA) DOMAIN, SERVICE_GET_USERCODE, get_usercode,
hass.services.async_register(DOMAIN, descriptions.get(SERVICE_GET_USERCODE), schema=GET_USERCODE_SCHEMA)
SERVICE_GET_USERCODE, hass.services.async_register(
get_usercode, DOMAIN, SERVICE_CLEAR_USERCODE, clear_usercode,
descriptions.get(SERVICE_GET_USERCODE), descriptions.get(SERVICE_CLEAR_USERCODE), schema=CLEAR_USERCODE_SCHEMA)
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): def get_device(node, values, **kwargs):
"""Create zwave entity device.""" """Create Z-Wave entity device."""
return ZwaveLock(values) return ZwaveLock(values)
@ -230,8 +224,7 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
def update_properties(self): def update_properties(self):
"""Callback on data changes for node values.""" """Callback on data changes for node values."""
self._state = self.values.primary.data self._state = self.values.primary.data
_LOGGER.debug('Lock state set from Bool value and' _LOGGER.debug("Lock state set from Bool value and is %s", self._state)
' is %s', self._state)
if self.values.access_control: if self.values.access_control:
notification_data = self.values.access_control.data notification_data = self.values.access_control.data
self._notification = LOCK_NOTIFICATION.get(str(notification_data)) self._notification = LOCK_NOTIFICATION.get(str(notification_data))
@ -240,21 +233,20 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
if self.values.v2btze_advanced and \ if self.values.v2btze_advanced and \
self.values.v2btze_advanced.data == CONFIG_ADVANCED: self.values.v2btze_advanced.data == CONFIG_ADVANCED:
self._state = LOCK_STATUS.get(str(notification_data)) self._state = LOCK_STATUS.get(str(notification_data))
_LOGGER.debug('Lock state set from Access Control ' _LOGGER.debug(
'value and is %s, get=%s', "Lock state set from Access Control value and is %s, "
str(notification_data), "get=%s", str(notification_data), self.state)
self.state)
if not self.values.alarm_type: if not self.values.alarm_type:
return return
alarm_type = self.values.alarm_type.data 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: if self.values.alarm_level:
alarm_level = self.values.alarm_level.data alarm_level = self.values.alarm_level.data
else: else:
alarm_level = None 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: if not alarm_type:
return return

View File

@ -897,7 +897,7 @@ class MediaPlayerDevice(Entity):
@asyncio.coroutine @asyncio.coroutine
def _async_fetch_image(hass, url): 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). 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.""" """Media player view to serve an image."""
requires_auth = False requires_auth = False
url = "/api/media_player_proxy/{entity_id}" url = '/api/media_player_proxy/{entity_id}'
name = "api:media_player:image" name = 'api:media_player:image'
def __init__(self, entities): def __init__(self, entities):
"""Initialize a media player view.""" """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) name = config.get(CONF_NAME)
device = None 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): def async_anthemav_update_callback(message):
"""Receive notification from transport that new data exists.""" """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()) hass.async_add_job(device.async_update_ha_state())
avr = yield from anthemav.Connection.create( 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) device = AnthemAVR(avr, name)
_LOGGER.debug('dump_devicedata: '+device.dump_avrdata) _LOGGER.debug("dump_devicedata: %s", device.dump_avrdata)
_LOGGER.debug('dump_conndata: '+avr.dump_conndata) _LOGGER.debug("dump_conndata: %s", avr.dump_conndata)
_LOGGER.debug('dump_rawdata: '+avr.protocol.dump_rawdata) _LOGGER.debug("dump_rawdata: %s", avr.protocol.dump_rawdata)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.avr.close) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.avr.close)
async_add_devices([device]) async_add_devices([device])
@ -70,7 +70,7 @@ class AnthemAVR(MediaPlayerDevice):
"""Entity reading values from Anthem AVR protocol.""" """Entity reading values from Anthem AVR protocol."""
def __init__(self, avr, name): def __init__(self, avr, name):
""""Initialize entity with transport.""" """Initialize entity with transport."""
super().__init__() super().__init__()
self.avr = avr self.avr = avr
self._name = name self._name = name
@ -163,7 +163,8 @@ class AnthemAVR(MediaPlayerDevice):
def _update_avr(self, propname, value): def _update_avr(self, propname, value):
"""Update a property in the AVR.""" """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) setattr(self.avr.protocol, propname, value)
@property @property

View File

@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 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 import pyatv
if discovery_info is not None: if discovery_info is not None:
@ -95,12 +95,13 @@ class AppleTvDevice(MediaPlayerDevice):
@asyncio.coroutine @asyncio.coroutine
def async_added_to_hass(self): 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: if not self._is_off:
self._atv.push_updater.start() self._atv.push_updater.start()
@callback @callback
def _set_power_off(self, is_off): def _set_power_off(self, is_off):
"""Set the power to off."""
self._playing = None self._playing = None
self._artwork_hash = None self._artwork_hash = None
self._is_off = is_off self._is_off = is_off

View File

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

View File

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

View File

@ -43,10 +43,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the cast platform.""" """Set up the cast platform."""
import pychromecast import pychromecast
# import CEC IGNORE attributes # Import CEC IGNORE attributes
pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, [])
hosts = [] hosts = []
@ -68,8 +68,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
casts = [] casts = []
# get_chromecasts() returns Chromecast objects # get_chromecasts() returns Chromecast objects with the correct friendly
# with the correct friendly name for grouped devices # name for grouped devices
all_chromecasts = pychromecast.get_chromecasts() all_chromecasts = pychromecast.get_chromecasts()
for host in hosts: for host in hosts:
@ -204,7 +204,7 @@ class CastDevice(MediaPlayerDevice):
@property @property
def media_series_title(self): 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 return self.media_status.series_title if self.media_status else None
@property @property
@ -310,12 +310,12 @@ class CastDevice(MediaPlayerDevice):
# Implementation of chromecast status_listener methods # Implementation of chromecast status_listener methods
def new_cast_status(self, status): 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.cast_status = status
self.schedule_update_ha_state() self.schedule_update_ha_state()
def new_media_status(self, status): 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 = status
self.media_status_received = dt_util.utcnow() self.media_status_received = dt_util.utcnow()
self.schedule_update_ha_state() self.schedule_update_ha_state()

View File

@ -28,6 +28,7 @@ SCAN_INTERVAL = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Clementine Remote' DEFAULT_NAME = 'Clementine Remote'
DEFAULT_PORT = 5500
SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \ SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
SUPPORT_PREVIOUS_TRACK | SUPPORT_VOLUME_SET | \ SUPPORT_PREVIOUS_TRACK | SUPPORT_VOLUME_SET | \
@ -35,19 +36,22 @@ SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
SUPPORT_SELECT_SOURCE | SUPPORT_PLAY SUPPORT_SELECT_SOURCE | SUPPORT_PLAY
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_HOST): 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_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 # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Clementine platform.""" """Set up the Clementine platform."""
from clementineremote import ClementineRemote from clementineremote import ClementineRemote
client = ClementineRemote(config.get(CONF_HOST), config.get(CONF_PORT), host = config.get(CONF_HOST)
config.get(CONF_ACCESS_TOKEN), reconnect=True) 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])]) 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): def setup_platform(hass, config, add_devices, discover_info=None):
"""Setup the CMUS platform.""" """Set up the CMUS platform."""
from pycmus import exceptions from pycmus import exceptions
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
@ -166,7 +166,7 @@ class CmusDevice(MediaPlayerDevice):
self.cmus.set_volume(int(volume * 100)) self.cmus.set_volume(int(volume * 100))
def volume_up(self): def volume_up(self):
"""Function to send CMUS the command for volume up.""" """Set the volume up."""
left = self.status['set'].get('vol_left') left = self.status['set'].get('vol_left')
right = self.status['set'].get('vol_right') right = self.status['set'].get('vol_right')
if left != right: if left != right:
@ -178,7 +178,7 @@ class CmusDevice(MediaPlayerDevice):
self.cmus.set_volume(int(current_volume) + 5) self.cmus.set_volume(int(current_volume) + 5)
def volume_down(self): def volume_down(self):
"""Function to send CMUS the command for volume down.""" """Set the volume down."""
left = self.status['set'].get('vol_left') left = self.status['set'].get('vol_left')
right = self.status['set'].get('vol_right') right = self.status['set'].get('vol_right')
if left != right: if left != right:

View File

@ -16,7 +16,7 @@ import homeassistant.util.dt as dt_util
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the media player demo platform.""" """Set up the media player demo platform."""
add_devices([ add_devices([
DemoYoutubePlayer( DemoYoutubePlayer(
'Living Room', 'eyU3bRy2x44', '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): 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)) denon = DenonDevice(config.get(CONF_NAME), config.get(CONF_HOST))
if denon.update(): if denon.update():
@ -101,7 +101,7 @@ class DenonDevice(MediaPlayerDevice):
@classmethod @classmethod
def telnet_request(cls, telnet, command, all_lines=False): def telnet_request(cls, telnet, command, all_lines=False):
"""Execute `command` and return the response.""" """Execute `command` and return the response."""
_LOGGER.debug('Sending: "%s"', command) _LOGGER.debug("Sending: %s", command)
telnet.write(command.encode('ASCII') + b'\r') telnet.write(command.encode('ASCII') + b'\r')
lines = [] lines = []
while True: while True:
@ -109,7 +109,7 @@ class DenonDevice(MediaPlayerDevice):
if not line: if not line:
break break
lines.append(line.decode('ASCII').strip()) lines.append(line.decode('ASCII').strip())
_LOGGER.debug('Recived: "%s"', line) _LOGGER.debug("Recived: %s", line)
if all_lines: if all_lines:
return lines return lines
@ -118,7 +118,7 @@ class DenonDevice(MediaPlayerDevice):
def telnet_command(self, command): def telnet_command(self, command):
"""Establish a telnet connection and sends `command`.""" """Establish a telnet connection and sends `command`."""
telnet = telnetlib.Telnet(self._host) telnet = telnetlib.Telnet(self._host)
_LOGGER.debug('Sending: "%s"', command) _LOGGER.debug("Sending: %s", command)
telnet.write(command.encode('ASCII') + b'\r') telnet.write(command.encode('ASCII') + b'\r')
telnet.read_very_eager() # skip response telnet.read_very_eager() # skip response
telnet.close() telnet.close()
@ -179,17 +179,17 @@ class DenonDevice(MediaPlayerDevice):
@property @property
def is_volume_muted(self): def is_volume_muted(self):
"""Boolean if volume is currently muted.""" """Return boolean if volume is currently muted."""
return self._muted return self._muted
@property @property
def source_list(self): def source_list(self):
"""List of available input sources.""" """Return the list of available input sources."""
return sorted(list(self._source_list.keys())) return sorted(list(self._source_list.keys()))
@property @property
def media_title(self): def media_title(self):
"""Current media info.""" """Return the current media info."""
return self._mediainfo return self._mediainfo
@property @property

View File

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

View File

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

View File

@ -48,7 +48,7 @@ class DuneHDPlayerEntity(MediaPlayerDevice):
"""Implementation of the Dune HD player.""" """Implementation of the Dune HD player."""
def __init__(self, player, name, sources): def __init__(self, player, name, sources):
"""Setup entity to control Dune HD.""" """Initialize entity to control Dune HD."""
self._player = player self._player = player
self._name = name self._name = name
self._sources = sources self._sources = sources
@ -83,17 +83,17 @@ class DuneHDPlayerEntity(MediaPlayerDevice):
@property @property
def volume_level(self): 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 return int(self._state.get('playback_volume', 0)) / 100
@property @property
def is_volume_muted(self): 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 return int(self._state.get('playback_mute', 0)) == 1
@property @property
def source_list(self): def source_list(self):
"""List of available input sources.""" """Return a list of available input sources."""
return list(self._sources.keys()) return list(self._sources.keys())
@property @property

View File

@ -52,7 +52,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
@asyncio.coroutine @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 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 from pyemby import EmbyServer
host = config.get(CONF_HOST) 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: if port is None:
port = DEFAULT_SSL_PORT if ssl else DEFAULT_PORT 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) 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) add.set_hidden(False)
if new_devices: 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) async_add_devices(new_devices, update_before_add=True)
@callback @callback
def device_removal_callback(data): 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: if data in active_emby_devices:
rem = active_emby_devices.pop(data) rem = active_emby_devices.pop(data)
inactive_emby_devices[data] = rem inactive_emby_devices[data] = rem
@ -109,12 +109,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
@callback @callback
def start_emby(event): def start_emby(event):
"""Start emby connection.""" """Start Emby connection."""
emby.start() emby.start()
@asyncio.coroutine @asyncio.coroutine
def stop_emby(event): def stop_emby(event):
"""Stop emby connection.""" """Stop Emby connection."""
yield from emby.stop() yield from emby.stop()
emby.add_new_devices_callback(device_update_callback) emby.add_new_devices_callback(device_update_callback)
@ -129,7 +129,7 @@ class EmbyDevice(MediaPlayerDevice):
def __init__(self, emby, device_id): def __init__(self, emby, device_id):
"""Initialize the Emby device.""" """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.emby = emby
self.device_id = device_id self.device_id = device_id
self.device = self.emby.devices[self.device_id] self.device = self.emby.devices[self.device_id]
@ -143,12 +143,12 @@ class EmbyDevice(MediaPlayerDevice):
@asyncio.coroutine @asyncio.coroutine
def async_added_to_hass(self): def async_added_to_hass(self):
"""Register callback.""" """Register callback."""
self.emby.add_update_callback(self.async_update_callback, self.emby.add_update_callback(
self.device_id) self.async_update_callback, self.device_id)
@callback @callback
def async_update_callback(self, msg): def async_update_callback(self, msg):
"""Callback for device updates.""" """Handle device updates."""
# Check if we should update progress # Check if we should update progress
if self.device.media_position: if self.device.media_position:
if self.device.media_position != self.media_status_last_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 # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the FireTV platform.""" """Set up the FireTV platform."""
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT) 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() response = requests.get(DEVICE_LIST_URL.format(host, port)).json()
if device_id in response[CONF_DEVICES].keys(): if device_id in response[CONF_DEVICES].keys():
add_devices([FireTVDevice(host, port, device_id, name)]) 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) device_id)
else: else:
_LOGGER.warning('Device %s is not registered with firetv-server', _LOGGER.warning("Device %s is not registered with firetv-server",
device_id) device_id)
except requests.exceptions.RequestException: 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): class FireTV(object):
@ -88,7 +88,7 @@ class FireTV(object):
return response.get('state', STATE_UNKNOWN) return response.get('state', STATE_UNKNOWN)
except requests.exceptions.RequestException: except requests.exceptions.RequestException:
_LOGGER.error( _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 return STATE_UNKNOWN
def action(self, action_id): def action(self, action_id):
@ -98,7 +98,7 @@ class FireTV(object):
self.host, self.port, self.device_id, action_id), timeout=10) self.host, self.port, self.device_id, action_id), timeout=10)
except requests.exceptions.RequestException: except requests.exceptions.RequestException:
_LOGGER.error( _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) action_id, self.device_id)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the MPD platform.""" """Set up the MPD platform."""
daemon = config.get(CONF_HOST) daemon = config.get(CONF_HOST)
port = config.get(CONF_PORT) port = config.get(CONF_PORT)
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
@ -136,23 +136,23 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def media_content_id(self): def media_content_id(self):
"""Content ID of current playing media.""" """Return the content ID of current playing media."""
return self.currentsong.get('file') return self.currentsong.get('file')
@property @property
def media_content_type(self): def media_content_type(self):
"""Content type of current playing media.""" """Return the content type of current playing media."""
return MEDIA_TYPE_MUSIC return MEDIA_TYPE_MUSIC
@property @property
def media_duration(self): 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 # Time does not exist for streams
return self.currentsong.get('time') return self.currentsong.get('time')
@property @property
def media_title(self): def media_title(self):
"""Title of current playing media.""" """Return the title of current playing media."""
name = self.currentsong.get('name', None) name = self.currentsong.get('name', None)
title = self.currentsong.get('title', None) title = self.currentsong.get('title', None)
@ -167,12 +167,12 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def media_artist(self): 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') return self.currentsong.get('artist')
@property @property
def media_album_name(self): 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') return self.currentsong.get('album')
@property @property
@ -192,7 +192,7 @@ class MpdDevice(MediaPlayerDevice):
@property @property
def source_list(self): def source_list(self):
"""List of available input sources.""" """Return the list of available input sources."""
return self.playlists return self.playlists
def select_source(self, source): 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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the NAD platform.""" """Set up the NAD platform."""
from nad_receiver import NADReceiver from nad_receiver import NADReceiver
add_devices([NAD( add_devices([NAD(
config.get(CONF_NAME), 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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Onkyo platform.""" """Set up the Onkyo platform."""
import eiscp import eiscp
from eiscp 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: if CONF_HOST in config and host not in KNOWN_HOSTS:
try: try:
hosts.append(OnkyoDevice(eiscp.eISCP(host), hosts.append(OnkyoDevice(
config.get(CONF_SOURCES), eiscp.eISCP(host), config.get(CONF_SOURCES),
name=config.get(CONF_NAME))) name=config.get(CONF_NAME)))
KNOWN_HOSTS.append(host) KNOWN_HOSTS.append(host)
except OSError: except OSError:
_LOGGER.error('Unable to connect to receiver at %s.', host) _LOGGER.error("Unable to connect to receiver at %s", host)
else: else:
for receiver in eISCP.discover(): for receiver in eISCP.discover():
if receiver.host not in KNOWN_HOSTS: if receiver.host not in KNOWN_HOSTS:
@ -90,9 +90,9 @@ class OnkyoDevice(MediaPlayerDevice):
except (ValueError, OSError, AttributeError, AssertionError): except (ValueError, OSError, AttributeError, AssertionError):
if self._receiver.command_socket: if self._receiver.command_socket:
self._receiver.command_socket = None self._receiver.command_socket = None
_LOGGER.info('Resetting connection to %s.', self._name) _LOGGER.info("Resetting connection to %s", self._name)
else: else:
_LOGGER.info('%s is disconnected. Attempting to reconnect.', _LOGGER.info("%s is disconnected. Attempting to reconnect",
self._name) self._name)
return False return False
return result return result
@ -142,7 +142,7 @@ class OnkyoDevice(MediaPlayerDevice):
@property @property
def volume_level(self): 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 return self._volume
@property @property
@ -157,7 +157,7 @@ class OnkyoDevice(MediaPlayerDevice):
@property @property
def source(self): def source(self):
""""Return the current input source of the device.""" """Return the current input source of the device."""
return self._current_source return self._current_source
@property @property

View File

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

View File

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

View File

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

View File

@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Philips TV platform.""" """Set up the Philips TV platform."""
import haphilipsjs import haphilipsjs
name = config.get(CONF_NAME) 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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Pioneer platform.""" """Set up the Pioneer platform."""
pioneer = PioneerDevice(config.get(CONF_NAME), pioneer = PioneerDevice(
config.get(CONF_HOST), config.get(CONF_NAME), config.get(CONF_HOST), config.get(CONF_PORT),
config.get(CONF_PORT), config.get(CONF_TIMEOUT))
config.get(CONF_TIMEOUT))
if pioneer.update(): if pioneer.update():
add_devices([pioneer]) add_devices([pioneer])
@ -126,9 +125,8 @@ class PioneerDevice(MediaPlayerDevice):
# Build the source name dictionaries if necessary # Build the source name dictionaries if necessary
if not self._source_name_to_number: if not self._source_name_to_number:
for i in range(MAX_SOURCE_NUMBERS): for i in range(MAX_SOURCE_NUMBERS):
result = self.telnet_request(telnet, result = self.telnet_request(
"?RGB" + str(i).zfill(2), telnet, "?RGB" + str(i).zfill(2), "RGB")
"RGB")
if not result: if not result:
continue 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): 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 # get config from plex.conf
file_config = config_from_file(hass.config.path(PLEX_CONFIG_FILE)) 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): 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.server
import plexapi.exceptions import plexapi.exceptions
@ -110,8 +110,7 @@ def setup_plexserver(host, token, hass, config, add_devices_callback):
plexapi.exceptions.NotFound) as error: plexapi.exceptions.NotFound) as error:
_LOGGER.info(error) _LOGGER.info(error)
# No token or wrong token # No token or wrong token
request_configuration(host, hass, config, request_configuration(host, hass, config, add_devices_callback)
add_devices_callback)
return return
# If we came here and configuring this host, mark as done # 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: try:
devices = plexserver.clients() devices = plexserver.clients()
except plexapi.exceptions.BadRequest: except plexapi.exceptions.BadRequest:
_LOGGER.exception('Error listing plex devices') _LOGGER.exception("Error listing plex devices")
return return
except OSError: except OSError:
_LOGGER.error("Could not connect to plex server at http://%s", _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 return
def plex_configuration_callback(data): def plex_configuration_callback(data):
"""The actions to do when our configuration callback is called.""" """Handle configuration changes."""
setup_plexserver(host, setup_plexserver(
data.get('token'), hass, config, host, data.get('token'), hass, config, add_devices_callback)
add_devices_callback)
_CONFIGURING[host] = configurator.request_config( _CONFIGURING[host] = configurator.request_config(
hass, hass,
@ -547,12 +545,12 @@ class PlexClient(MediaPlayerDevice):
@property @property
def media_content_id(self): def media_content_id(self):
"""Content ID of current playing media.""" """Return the content ID of current playing media."""
return self._media_content_id return self._media_content_id
@property @property
def media_content_type(self): def media_content_type(self):
"""Content type of current playing media.""" """Return the content type of current playing media."""
if self._session_type == 'clip': if self._session_type == 'clip':
_LOGGER.debug("Clip content type detected, " _LOGGER.debug("Clip content type detected, "
"compatibility may vary: %s", self.entity_id) "compatibility may vary: %s", self.entity_id)
@ -568,57 +566,57 @@ class PlexClient(MediaPlayerDevice):
@property @property
def media_artist(self): 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 return self._media_artist
@property @property
def media_album_name(self): 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 return self._media_album_name
@property @property
def media_album_artist(self): 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 return self._media_album_artist
@property @property
def media_track(self): 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 return self._media_track
@property @property
def media_duration(self): def media_duration(self):
"""Duration of current playing media in seconds.""" """Return the duration of current playing media in seconds."""
return self._media_duration return self._media_duration
@property @property
def media_image_url(self): def media_image_url(self):
"""Image url of current playing media.""" """Return the image URL of current playing media."""
return self._media_image_url return self._media_image_url
@property @property
def media_title(self): def media_title(self):
"""Title of current playing media.""" """Return the title of current playing media."""
return self._media_title return self._media_title
@property @property
def media_season(self): 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 return self._media_season
@property @property
def media_series_title(self): 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 return self._media_series_title
@property @property
def media_episode(self): 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 return self._media_episode
@property @property
def make(self): 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 return self._make
@property @property

View File

@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Roku platform.""" """Set up the Roku platform."""
hosts = [] hosts = []
if discovery_info: if discovery_info:
@ -48,7 +48,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if host in KNOWN_HOSTS: if host in KNOWN_HOSTS:
return return
_LOGGER.debug('Discovered Roku: %s', host) _LOGGER.debug("Discovered Roku: %s", host)
hosts.append(discovery_info.get("host")) hosts.append(discovery_info.get("host"))
elif CONF_HOST in config: elif CONF_HOST in config:
@ -175,9 +175,8 @@ class RokuDevice(MediaPlayerDevice):
elif self.current_app.id is None: elif self.current_app.id is None:
return None return None
return 'http://{0}:{1}/query/icon/{2}'.format(self.ip_address, return 'http://{0}:{1}/query/icon/{2}'.format(
DEFAULT_PORT, self.ip_address, DEFAULT_PORT, self.current_app.id)
self.current_app.id)
@property @property
def app_name(self): 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.russound_rnet/ https://home-assistant.io/components/media_player.russound_rnet/
""" """
import logging import logging
import voluptuous as vol import voluptuous as vol
from homeassistant.components.media_player import ( 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): 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) host = config.get(CONF_HOST)
port = config.get(CONF_PORT) port = config.get(CONF_PORT)
@ -163,5 +163,5 @@ class RussoundRNETDevice(MediaPlayerDevice):
@property @property
def source_list(self): def source_list(self):
"""List of available input sources.""" """Return a list of available input sources."""
return self._sources return self._sources

View File

@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Samsung TV platform.""" """Set up the Samsung TV platform."""
known_devices = hass.data.get(KNOWN_DEVICES_KEY) known_devices = hass.data.get(KNOWN_DEVICES_KEY)
if known_devices is None: if known_devices is None:
known_devices = set() known_devices = set()
@ -66,8 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
timeout = DEFAULT_TIMEOUT timeout = DEFAULT_TIMEOUT
mac = None mac = None
else: else:
_LOGGER.warning( _LOGGER.warning("Cannot determine device")
'Internal error on samsungtv component. Cannot determine device')
return return
# Only add a device once, so discovered devices do not override manual # 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 # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Snapcast platform.""" """Set up the Snapcast platform."""
import snapcast.control import snapcast.control
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT, snapcast.control.CONTROL_PORT) port = config.get(CONF_PORT, snapcast.control.CONTROL_PORT)
@ -42,8 +42,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
try: try:
server = snapcast.control.Snapserver(host, port) server = snapcast.control.Snapserver(host, port)
except socket.gaierror: except socket.gaierror:
_LOGGER.error('Could not connect to Snapcast server at %s:%d', _LOGGER.error(
host, port) "Could not connect to Snapcast server at %s:%d", host, port)
return False return False
add_devices([SnapcastDevice(client) for client in server.clients]) 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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Sonos platform.""" """Set up the Sonos platform."""
import soco import soco
if DATA_SONOS not in hass.data: if DATA_SONOS not in hass.data:
@ -105,7 +105,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
if discovery_info: if discovery_info:
player = soco.SoCo(discovery_info.get('host')) 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]]: if player.uid in [x.unique_id for x in hass.data[DATA_SONOS]]:
return return
@ -132,18 +132,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
interface_addr=config.get(CONF_INTERFACE_ADDR)) interface_addr=config.get(CONF_INTERFACE_ADDR))
if not players: if not players:
_LOGGER.warning('No Sonos speakers found.') _LOGGER.warning("No Sonos speakers found")
return return
hass.data[DATA_SONOS] = [SonosDevice(p) for p in players] hass.data[DATA_SONOS] = [SonosDevice(p) for p in players]
add_devices(hass.data[DATA_SONOS], True) 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( descriptions = load_yaml_config_file(
path.join(path.dirname(__file__), 'services.yaml')) path.join(path.dirname(__file__), 'services.yaml'))
def service_handle(service): def service_handle(service):
"""Internal func for applying a service.""" """Handle for services."""
entity_ids = service.data.get('entity_id') entity_ids = service.data.get('entity_id')
if entity_ids: if entity_ids:
@ -221,28 +221,28 @@ def _get_entity_from_soco(hass, soco):
for device in hass.data[DATA_SONOS]: for device in hass.data[DATA_SONOS]:
if soco == device.soco: if soco == device.soco:
return device return device
raise ValueError("No entity for SoCo device!") raise ValueError("No entity for SoCo device")
def soco_error(funct): def soco_error(funct):
"""Decorator to catch soco exceptions.""" """Catch soco exceptions."""
@ft.wraps(funct) @ft.wraps(funct)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
"""Wrapper for all soco exception.""" """Wrap for all soco exception."""
from soco.exceptions import SoCoException from soco.exceptions import SoCoException
try: try:
return funct(*args, **kwargs) return funct(*args, **kwargs)
except SoCoException as err: 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 return wrapper
def soco_coordinator(funct): def soco_coordinator(funct):
"""Decorator to call funct on coordinator.""" """Call function on coordinator."""
@ft.wraps(funct) @ft.wraps(funct)
def wrapper(device, *args, **kwargs): def wrapper(device, *args, **kwargs):
"""Wrapper for call to coordinator.""" """Wrap for call to coordinator."""
if device.is_coordinator: if device.is_coordinator:
return funct(device, *args, **kwargs) return funct(device, *args, **kwargs)
return funct(device.coordinator, *args, **kwargs) return funct(device.coordinator, *args, **kwargs)
@ -296,7 +296,7 @@ class SonosDevice(MediaPlayerDevice):
@property @property
def should_poll(self): def should_poll(self):
"""Polling needed.""" """Return the polling state."""
return True return True
@property @property
@ -340,8 +340,7 @@ class SonosDevice(MediaPlayerDevice):
def _is_available(self): def _is_available(self):
try: try:
sock = socket.create_connection( sock = socket.create_connection(
address=(self._player.ip_address, 1443), address=(self._player.ip_address, 1443), timeout=3)
timeout=3)
sock.close() sock.close()
return True return True
except socket.error: 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 import logging
from os import path from os import path
@ -69,14 +74,14 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None): 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: if DATA_SOUNDTOUCH not in hass.data:
hass.data[DATA_SOUNDTOUCH] = [] hass.data[DATA_SOUNDTOUCH] = []
if discovery_info: if discovery_info:
# Discovery # Discovery
host = discovery_info["host"] host = discovery_info['host']
port = int(discovery_info["port"]) port = int(discovery_info['port'])
# if device already exists by config # if device already exists by config
if host in [device.config['host'] for device in 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) device.entity_id == master_device_id].__iter__(), None)
if master is None: if master is None:
_LOGGER.warning("Unable to find master with entity_id:" + str( _LOGGER.warning("Unable to find master with entity_id: %s",
master_device_id)) str(master_device_id))
return return
if service.service == SERVICE_PLAY_EVERYWHERE: 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 For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.spotify/ https://home-assistant.io/components/media_player.spotify/
""" """
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -22,7 +21,6 @@ from homeassistant.const import (
CONF_NAME, STATE_PLAYING, STATE_PAUSED, STATE_IDLE, STATE_UNKNOWN) CONF_NAME, STATE_PLAYING, STATE_PAUSED, STATE_IDLE, STATE_UNKNOWN)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
COMMIT = '544614f4b1d508201d363e84e871f86c90aa26b2' COMMIT = '544614f4b1d508201d363e84e871f86c90aa26b2'
REQUIREMENTS = ['https://github.com/happyleavesaoc/spotipy/' REQUIREMENTS = ['https://github.com/happyleavesaoc/spotipy/'
'archive/%s.zip#spotipy==2.4.4' % COMMIT] '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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Spotify platform.""" """Set up the Spotify platform."""
import spotipy.oauth2 import spotipy.oauth2
callback_url = '{}{}'.format(hass.config.api.base_url, AUTH_CALLBACK_PATH) callback_url = '{}{}'.format(hass.config.api.base_url, AUTH_CALLBACK_PATH)
cache = config.get(CONF_CACHE_PATH, hass.config.path(DEFAULT_CACHE_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) cache_path=cache)
token_info = oauth.get_cached_token() token_info = oauth.get_cached_token()
if not token_info: if not token_info:
_LOGGER.info('no token; requesting authorization') _LOGGER.info("no token; requesting authorization")
hass.http.register_view(SpotifyAuthCallbackView( hass.http.register_view(SpotifyAuthCallbackView(
config, add_devices, oauth)) config, add_devices, oauth))
request_configuration(hass, config, add_devices, oauth) request_configuration(hass, config, add_devices, oauth)
@ -225,31 +223,31 @@ class SpotifyMediaPlayer(MediaPlayerDevice):
elif media_type == MEDIA_TYPE_PLAYLIST: elif media_type == MEDIA_TYPE_PLAYLIST:
kwargs['context_uri'] = media_id kwargs['context_uri'] = media_id
else: else:
_LOGGER.error('media type %s is not supported', media_type) _LOGGER.error("media type %s is not supported", media_type)
return return
if not media_id.startswith('spotify:'): if not media_id.startswith('spotify:'):
_LOGGER.error('media id must be spotify uri') _LOGGER.error("media id must be spotify uri")
return return
self._player.start_playback(**kwargs) self._player.start_playback(**kwargs)
@property @property
def name(self): def name(self):
"""Name.""" """Return the name."""
return self._name return self._name
@property @property
def icon(self): def icon(self):
"""Icon.""" """Return the icon."""
return ICON return ICON
@property @property
def state(self): def state(self):
"""Playback state.""" """Return the playback state."""
return self._state return self._state
@property @property
def volume_level(self): def volume_level(self):
"""Device volume.""" """Return the device volume."""
return self._volume return self._volume
@property @property
@ -259,40 +257,40 @@ class SpotifyMediaPlayer(MediaPlayerDevice):
@property @property
def source_list(self): def source_list(self):
"""Playback devices.""" """Return a list of source devices."""
return list(self._devices.keys()) return list(self._devices.keys())
@property @property
def source(self): def source(self):
"""Current playback device.""" """Return the current playback device."""
return self._current_device return self._current_device
@property @property
def media_content_id(self): def media_content_id(self):
"""Media URL.""" """Return the media URL."""
return self._uri return self._uri
@property @property
def media_image_url(self): def media_image_url(self):
"""Media image url.""" """Return the media image URL."""
return self._image_url return self._image_url
@property @property
def media_artist(self): def media_artist(self):
"""Media artist.""" """Return the media artist."""
return self._artist return self._artist
@property @property
def media_album_name(self): def media_album_name(self):
"""Media album.""" """Return the media album."""
return self._album return self._album
@property @property
def media_title(self): def media_title(self):
"""Media title.""" """Return the media title."""
return self._title return self._title
@property @property
def supported_features(self): def supported_features(self):
"""Media player features that are supported.""" """Return the media player features that are supported."""
return SUPPORT_SPOTIFY return SUPPORT_SPOTIFY

View File

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

View File

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

View File

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

View File

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

View File

@ -62,7 +62,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument # pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the LG WebOS TV platform.""" """Set up the LG WebOS TV platform."""
if discovery_info is not None: if discovery_info is not None:
host = urlparse(discovery_info[1]).hostname host = urlparse(discovery_info[1]).hostname
else: 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): 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 WebOsClient
from pylgtv import PyLGTVPairException from pylgtv import PyLGTVPairException
from websockets.exceptions import ConnectionClosed from websockets.exceptions import ConnectionClosed
@ -133,7 +133,7 @@ def request_configuration(
# pylint: disable=unused-argument # pylint: disable=unused-argument
def lgtv_configuration_callback(data): 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) setup_tv(host, mac, name, customize, config, hass, add_devices)
_CONFIGURING[host] = configurator.request_config( _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): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Yamaha platform.""" """Set up the Yamaha platform."""
import rxv import rxv
# keep track of configured receivers so that we don't end up # keep track of configured receivers so that we don't end up
# discovering a receiver dynamically that we have static config # discovering a receiver dynamically that we have static config
@ -241,7 +241,7 @@ class YamahaDevice(MediaPlayerDevice):
function() function()
except rxv.exceptions.ResponseException: except rxv.exceptions.ResponseException:
_LOGGER.warning( _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): def select_source(self, source):
"""Select input source.""" """Select input source."""

View File

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

View File

@ -67,7 +67,7 @@ HUB = None
def setup(hass, config): def setup(hass, config):
"""Setup Modbus component.""" """Set up Modbus component."""
# Modbus connection type # Modbus connection type
# pylint: disable=global-statement, import-error # pylint: disable=global-statement, import-error
client_type = config[DOMAIN][CONF_TYPE] 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: if encoding is not None:
try: try:
payload = dp_payload.decode(encoding) payload = dp_payload.decode(encoding)
_LOGGER.debug("Received message on %s: %s", _LOGGER.debug("Received message on %s: %s", dp_topic, payload)
dp_topic, payload)
except (AttributeError, UnicodeDecodeError): except (AttributeError, UnicodeDecodeError):
_LOGGER.error("Illegal payload encoding %s from " _LOGGER.error("Illegal payload encoding %s from "
"MQTT topic: %s, Payload: %s", "MQTT topic: %s, Payload: %s",

View File

@ -31,7 +31,7 @@ ALLOWED_PLATFORMS = {
@asyncio.coroutine @asyncio.coroutine
def async_start(hass, discovery_topic, hass_config): def async_start(hass, discovery_topic, hass_config):
"""Initialization of MQTT Discovery.""" """Initialize of MQTT Discovery."""
# pylint: disable=unused-variable # pylint: disable=unused-variable
@asyncio.coroutine @asyncio.coroutine
def async_device_message_received(topic, payload, qos): 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) broker = Broker(server_config, hass.loop)
yield from broker.start() yield from broker.start()
except BrokerException: except BrokerException:
logging.getLogger(__name__).exception('Error initializing MQTT server') logging.getLogger(__name__).exception("Error initializing MQTT server")
return False, None return False, None
finally: finally:
passwd.close() passwd.close()

View File

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

View File

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

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