diff --git a/homeassistant/components/binary_sensor/isy994.py b/homeassistant/components/binary_sensor/isy994.py index 2c4b9e0b97f..fd6269e3630 100644 --- a/homeassistant/components/binary_sensor/isy994.py +++ b/homeassistant/components/binary_sensor/isy994.py @@ -26,7 +26,7 @@ STATES = [STATE_OFF, STATE_ON, 'true', 'false'] # pylint: disable=unused-argument def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): - """Setup the ISY994 binary sensor platform.""" + """Set up the ISY994 binary sensor platform.""" if isy.ISY is None or not isy.ISY.connected: _LOGGER.error("A connection has not been made to the ISY controller") return False diff --git a/homeassistant/components/binary_sensor/netatmo.py b/homeassistant/components/binary_sensor/netatmo.py index e0841e2e286..70887e9391d 100644 --- a/homeassistant/components/binary_sensor/netatmo.py +++ b/homeassistant/components/binary_sensor/netatmo.py @@ -34,8 +34,8 @@ PRESENCE_SENSOR_TYPES = { "Outdoor vehicle": "motion" } TAG_SENSOR_TYPES = { - "Tag Vibration": 'vibration', - "Tag Open": 'opening' + "Tag Vibration": "vibration", + "Tag Open": "opening" } CONF_HOME = 'home' @@ -117,7 +117,7 @@ class NetatmoBinarySensor(BinarySensorDevice): def __init__(self, data, camera_name, module_name, home, timeout, offset, camera_type, sensor): - """Setup for access to the Netatmo camera events.""" + """Set up for access to the Netatmo camera events.""" self._data = data self._camera_name = camera_name self._module_name = module_name diff --git a/homeassistant/components/calendar/google.py b/homeassistant/components/calendar/google.py index 8a2e77d1915..26c2c251afb 100644 --- a/homeassistant/components/calendar/google.py +++ b/homeassistant/components/calendar/google.py @@ -54,7 +54,7 @@ class GoogleCalendarData(object): """Class to utilize calendar service object to get next event.""" def __init__(self, calendar_service, calendar_id, search=None): - """Setup how we are going to search the google calendar.""" + """Set up how we are going to search the google calendar.""" self.calendar_service = calendar_service self.calendar_id = calendar_id self.search = search diff --git a/homeassistant/components/camera/netatmo.py b/homeassistant/components/camera/netatmo.py index ca94db797a9..e5f22cced16 100644 --- a/homeassistant/components/camera/netatmo.py +++ b/homeassistant/components/camera/netatmo.py @@ -55,7 +55,7 @@ class NetatmoCamera(Camera): """Representation of the images published from a Netatmo camera.""" def __init__(self, data, camera_name, home, camera_type, verify_ssl): - """Set up access to the Netatmo camera images.""" + """Set up for access to the Netatmo camera images.""" super(NetatmoCamera, self).__init__() self._data = data self._camera_name = camera_name diff --git a/homeassistant/components/climate/__init__.py b/homeassistant/components/climate/__init__.py index 44cbdc99c04..10b5984500b 100644 --- a/homeassistant/components/climate/__init__.py +++ b/homeassistant/components/climate/__init__.py @@ -208,7 +208,7 @@ def set_swing_mode(hass, swing_mode, entity_id=None): @asyncio.coroutine def async_setup(hass, config): - """Setup climate devices.""" + """Set up climate devices.""" component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL) yield from component.async_setup(config) diff --git a/homeassistant/components/device_tracker/mikrotik.py b/homeassistant/components/device_tracker/mikrotik.py index 5b28a9eb664..f22b297b78d 100644 --- a/homeassistant/components/device_tracker/mikrotik.py +++ b/homeassistant/components/device_tracker/mikrotik.py @@ -63,10 +63,10 @@ class MikrotikScanner(DeviceScanner): self.success_init = self.connect_to_device() if self.success_init: - _LOGGER.info('Start polling Mikrotik router...') + _LOGGER.info("Start polling Mikrotik router...") self._update_info() else: - _LOGGER.error('Connection to Mikrotik failed.') + _LOGGER.error("Connection to Mikrotik failed") def connect_to_device(self): """Connect to Mikrotik method.""" @@ -83,14 +83,14 @@ class MikrotikScanner(DeviceScanner): routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: - _LOGGER.info('Connected to Mikrotik %s with ip %s.', + _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True except (librouteros.exceptions.TrapError, librouteros.exceptions.ConnectionError) as api_error: - _LOGGER.error('Connection error: %s', api_error) + _LOGGER.error("Connection error: %s", api_error) return self.connected @@ -108,7 +108,7 @@ class MikrotikScanner(DeviceScanner): def _update_info(self): """Retrieve latest information from the Mikrotik box.""" with self.lock: - _LOGGER.info('Loading wireless device from Mikrotik...') + _LOGGER.info("Loading wireless device from Mikrotik...") wireless_clients = self.client( cmd='/interface/wireless/registration-table/getall' diff --git a/homeassistant/components/fan/isy994.py b/homeassistant/components/fan/isy994.py index 4e61a0c209b..8b9236fdb32 100644 --- a/homeassistant/components/fan/isy994.py +++ b/homeassistant/components/fan/isy994.py @@ -35,7 +35,7 @@ STATES = [SPEED_OFF, SPEED_LOW, 'med', SPEED_HIGH] # pylint: disable=unused-argument def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): - """Setup the ISY994 fan platform.""" + """Set up the ISY994 fan platform.""" if isy.ISY is None or not isy.ISY.connected: _LOGGER.error("A connection has not been made to the ISY controller") return False diff --git a/homeassistant/components/fan/wink.py b/homeassistant/components/fan/wink.py index 98e301f5a48..e8f5d6fd17a 100644 --- a/homeassistant/components/fan/wink.py +++ b/homeassistant/components/fan/wink.py @@ -19,7 +19,7 @@ SPEED_AUTO = 'auto' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink platform.""" + """Set up the Wink platform.""" import pywink for fan in pywink.get_fans(): diff --git a/homeassistant/components/light/demo.py b/homeassistant/components/light/demo.py index 6482e31fbaa..22ab404a3b2 100644 --- a/homeassistant/components/light/demo.py +++ b/homeassistant/components/light/demo.py @@ -27,7 +27,7 @@ SUPPORT_DEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the demo light platform.""" + """Set up the demo light platform.""" add_devices_callback([ DemoLight("Bed Light", False, True, effect_list=LIGHT_EFFECT_LIST, effect=LIGHT_EFFECT_LIST[0]), diff --git a/homeassistant/components/light/lifx/__init__.py b/homeassistant/components/light/lifx/__init__.py index 9a44938308e..e0181f9fef9 100644 --- a/homeassistant/components/light/lifx/__init__.py +++ b/homeassistant/components/light/lifx/__init__.py @@ -56,12 +56,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the LIFX platform.""" + """Set up the LIFX platform.""" import aiolifx if sys.platform == 'win32': - _LOGGER.warning('The lifx platform is known to not work on Windows. ' - 'Consider using the lifx_legacy platform instead.') + _LOGGER.warning("The lifx platform is known to not work on Windows. " + "Consider using the lifx_legacy platform instead") server_addr = config.get(CONF_SERVER) @@ -420,9 +420,8 @@ class LIFXLight(Light): self._bri = bri self._kel = kel - red, green, blue = colorsys.hsv_to_rgb(hue / SHORT_MAX, - sat / SHORT_MAX, - bri / SHORT_MAX) + red, green, blue = colorsys.hsv_to_rgb( + hue / SHORT_MAX, sat / SHORT_MAX, bri / SHORT_MAX) red = int(red * BYTE_MAX) green = int(green * BYTE_MAX) diff --git a/homeassistant/components/light/lifx/effects.py b/homeassistant/components/light/lifx/effects.py index e2ba0a73534..0714450a7cd 100644 --- a/homeassistant/components/light/lifx/effects.py +++ b/homeassistant/components/light/lifx/effects.py @@ -40,22 +40,22 @@ LIFX_EFFECT_BREATHE_SCHEMA = LIFX_EFFECT_SCHEMA.extend({ ATTR_COLOR_NAME: cv.string, ATTR_RGB_COLOR: vol.All(vol.ExactSequence((cv.byte, cv.byte, cv.byte)), vol.Coerce(tuple)), - vol.Optional(ATTR_PERIOD, default=1.0): vol.All(vol.Coerce(float), - vol.Range(min=0.05)), - vol.Optional(ATTR_CYCLES, default=1.0): vol.All(vol.Coerce(float), - vol.Range(min=1)), + vol.Optional(ATTR_PERIOD, default=1.0): + vol.All(vol.Coerce(float), vol.Range(min=0.05)), + vol.Optional(ATTR_CYCLES, default=1.0): + vol.All(vol.Coerce(float), vol.Range(min=1)), }) LIFX_EFFECT_PULSE_SCHEMA = LIFX_EFFECT_BREATHE_SCHEMA LIFX_EFFECT_COLORLOOP_SCHEMA = LIFX_EFFECT_SCHEMA.extend({ ATTR_BRIGHTNESS: vol.All(vol.Coerce(int), vol.Clamp(min=0, max=255)), - vol.Optional(ATTR_PERIOD, default=60): vol.All(vol.Coerce(float), - vol.Clamp(min=1)), - vol.Optional(ATTR_CHANGE, default=20): vol.All(vol.Coerce(float), - vol.Clamp(min=0, max=360)), - vol.Optional(ATTR_SPREAD, default=30): vol.All(vol.Coerce(float), - vol.Clamp(min=0, max=360)), + vol.Optional(ATTR_PERIOD, default=60): + vol.All(vol.Coerce(float), vol.Clamp(min=1)), + vol.Optional(ATTR_CHANGE, default=20): + vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)), + vol.Optional(ATTR_SPREAD, default=30): + vol.All(vol.Coerce(float), vol.Clamp(min=0, max=360)), }) LIFX_EFFECT_STOP_SCHEMA = vol.Schema({ diff --git a/homeassistant/components/light/lutron.py b/homeassistant/components/light/lutron.py index d9dfdbdd8f9..47cadec0f7d 100644 --- a/homeassistant/components/light/lutron.py +++ b/homeassistant/components/light/lutron.py @@ -1,4 +1,9 @@ -"""Support for Lutron lights.""" +""" +Support for Lutron lights. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/light.lutron/ +""" import logging from homeassistant.components.light import ( diff --git a/homeassistant/components/light/lutron_caseta.py b/homeassistant/components/light/lutron_caseta.py index 7b842cd0ff7..8e4e9d7450e 100644 --- a/homeassistant/components/light/lutron_caseta.py +++ b/homeassistant/components/light/lutron_caseta.py @@ -1,4 +1,9 @@ -"""Support for Lutron Caseta lights.""" +""" +Support for Lutron Caseta lights. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/light.lutron_caseta/ +""" import logging from homeassistant.components.light import ( @@ -8,7 +13,6 @@ from homeassistant.components.light.lutron import ( from homeassistant.components.lutron_caseta import ( LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice) - _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['lutron_caseta'] @@ -16,7 +20,7 @@ DEPENDENCIES = ['lutron_caseta'] # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up Lutron Caseta lights.""" + """Set up the Lutron Caseta lights.""" devs = [] bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE] light_devices = bridge.get_devices_by_types(["WallDimmer", "PlugInDimmer"]) diff --git a/homeassistant/components/light/mqtt.py b/homeassistant/components/light/mqtt.py index 018d7a40639..038cacd300e 100644 --- a/homeassistant/components/light/mqtt.py +++ b/homeassistant/components/light/mqtt.py @@ -92,7 +92,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Add MQTT Light.""" + """Set up a MQTT Light.""" if discovery_info is not None: config = PLATFORM_SCHEMA(discovery_info) @@ -142,7 +142,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class MqttLight(Light): - """MQTT light.""" + """Representation of a MQTT light.""" def __init__(self, name, effect_list, topic, templates, qos, retain, payload, optimistic, brightness_scale, @@ -197,7 +197,7 @@ class MqttLight(Light): @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method is a coroutine. """ @@ -211,7 +211,7 @@ class MqttLight(Light): @callback def state_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages.""" payload = templates[CONF_STATE](payload) if payload == self._payload['on']: self._state = True @@ -226,7 +226,7 @@ class MqttLight(Light): @callback def brightness_received(topic, payload, qos): - """A new MQTT message for the brightness has been received.""" + """Handle new MQTT messages for the brightness.""" device_value = float(templates[CONF_BRIGHTNESS](payload)) percent_bright = device_value / self._brightness_scale self._brightness = int(percent_bright * 255) @@ -244,7 +244,7 @@ class MqttLight(Light): @callback def rgb_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages for RGB.""" self._rgb = [int(val) for val in templates[CONF_RGB](payload).split(',')] self.hass.async_add_job(self.async_update_ha_state()) @@ -261,7 +261,7 @@ class MqttLight(Light): @callback def color_temp_received(topic, payload, qos): - """A new MQTT message for color temp has been received.""" + """Handle new MQTT messages for color temperature.""" self._color_temp = int(templates[CONF_COLOR_TEMP](payload)) self.hass.async_add_job(self.async_update_ha_state()) @@ -277,7 +277,7 @@ class MqttLight(Light): @callback def effect_received(topic, payload, qos): - """A new MQTT message for effect has been received.""" + """Handle new MQTT messages for effect.""" self._effect = templates[CONF_EFFECT](payload) self.hass.async_add_job(self.async_update_ha_state()) @@ -293,7 +293,7 @@ class MqttLight(Light): @callback def white_value_received(topic, payload, qos): - """A new MQTT message for the white value has been received.""" + """Handle new MQTT messages for white value.""" device_value = float(templates[CONF_WHITE_VALUE](payload)) percent_white = device_value / self._white_value_scale self._white_value = int(percent_white * 255) @@ -311,7 +311,7 @@ class MqttLight(Light): @callback def xy_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages for color.""" self._xy = [float(val) for val in templates[CONF_XY](payload).split(',')] self.hass.async_add_job(self.async_update_ha_state()) diff --git a/homeassistant/components/light/mqtt_json.py b/homeassistant/components/light/mqtt_json.py index eaa36992012..4fee1138909 100755 --- a/homeassistant/components/light/mqtt_json.py +++ b/homeassistant/components/light/mqtt_json.py @@ -157,13 +157,13 @@ class MqttJson(Light): @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method is a coroutine. """ @callback def state_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages.""" values = json.loads(payload) if values['state'] == 'ON': @@ -189,7 +189,7 @@ class MqttJson(Light): except KeyError: pass except ValueError: - _LOGGER.warning('Invalid brightness value received') + _LOGGER.warning("Invalid brightness value received") if self._color_temp is not None: try: @@ -197,7 +197,7 @@ class MqttJson(Light): except KeyError: pass except ValueError: - _LOGGER.warning('Invalid color temp value received') + _LOGGER.warning("Invalid color temp value received") if self._effect is not None: try: @@ -205,7 +205,7 @@ class MqttJson(Light): except KeyError: pass except ValueError: - _LOGGER.warning('Invalid effect value received') + _LOGGER.warning("Invalid effect value received") if self._white_value is not None: try: @@ -213,7 +213,7 @@ class MqttJson(Light): except KeyError: pass except ValueError: - _LOGGER.warning('Invalid white value value received') + _LOGGER.warning("Invalid white value value received") if self._xy is not None: try: diff --git a/homeassistant/components/light/mqtt_template.py b/homeassistant/components/light/mqtt_template.py index 422c9c951de..07fd6d45d8c 100755 --- a/homeassistant/components/light/mqtt_template.py +++ b/homeassistant/components/light/mqtt_template.py @@ -104,7 +104,7 @@ class MqttTemplate(Light): def __init__(self, hass, name, effect_list, topics, templates, optimistic, qos, retain): - """Initialize MQTT Template light.""" + """Initialize a MQTT Template light.""" self._name = name self._effect_list = effect_list self._topics = topics @@ -139,21 +139,19 @@ class MqttTemplate(Light): self._rgb = None self._effect = None - # init hass to template for tpl in self._templates.values(): if tpl is not None: tpl.hass = hass @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method is a coroutine. """ @callback def state_received(topic, payload, qos): - """A new MQTT message has been received.""" - # read state + """Handle new MQTT messages.""" state = self._templates[CONF_STATE_TEMPLATE].\ async_render_with_possible_json_value(payload) if state == STATE_ON: @@ -161,9 +159,8 @@ class MqttTemplate(Light): elif state == STATE_OFF: self._state = False else: - _LOGGER.warning('Invalid state value received') + _LOGGER.warning("Invalid state value received") - # read brightness if self._brightness is not None: try: self._brightness = int( @@ -171,9 +168,8 @@ class MqttTemplate(Light): async_render_with_possible_json_value(payload) ) except ValueError: - _LOGGER.warning('Invalid brightness value received') + _LOGGER.warning("Invalid brightness value received") - # read color temperature if self._color_temp is not None: try: self._color_temp = int( @@ -181,9 +177,8 @@ class MqttTemplate(Light): async_render_with_possible_json_value(payload) ) except ValueError: - _LOGGER.warning('Invalid color temperature value received') + _LOGGER.warning("Invalid color temperature value received") - # read color if self._rgb is not None: try: self._rgb[0] = int( @@ -196,9 +191,8 @@ class MqttTemplate(Light): self._templates[CONF_BLUE_TEMPLATE]. async_render_with_possible_json_value(payload)) except ValueError: - _LOGGER.warning('Invalid color value received') + _LOGGER.warning("Invalid color value received") - # read white value if self._white_value is not None: try: self._white_value = int( @@ -208,16 +202,14 @@ class MqttTemplate(Light): except ValueError: _LOGGER.warning('Invalid white value received') - # read effect if self._templates[CONF_EFFECT_TEMPLATE] is not None: effect = self._templates[CONF_EFFECT_TEMPLATE].\ async_render_with_possible_json_value(payload) - # validate effect value if effect in self._effect_list: self._effect = effect else: - _LOGGER.warning('Unsupported effect value received') + _LOGGER.warning("Unsupported effect value received") self.hass.async_add_job(self.async_update_ha_state()) @@ -285,26 +277,22 @@ class MqttTemplate(Light): This method is a coroutine. """ - # state values = {'state': True} if self._optimistic: self._state = True - # brightness if ATTR_BRIGHTNESS in kwargs: values['brightness'] = int(kwargs[ATTR_BRIGHTNESS]) if self._optimistic: self._brightness = kwargs[ATTR_BRIGHTNESS] - # color_temp if ATTR_COLOR_TEMP in kwargs: values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP]) if self._optimistic: self._color_temp = kwargs[ATTR_COLOR_TEMP] - # color if ATTR_RGB_COLOR in kwargs: values['red'] = kwargs[ATTR_RGB_COLOR][0] values['green'] = kwargs[ATTR_RGB_COLOR][1] @@ -313,22 +301,18 @@ class MqttTemplate(Light): if self._optimistic: self._rgb = kwargs[ATTR_RGB_COLOR] - # white value if ATTR_WHITE_VALUE in kwargs: values['white_value'] = int(kwargs[ATTR_WHITE_VALUE]) if self._optimistic: self._white_value = kwargs[ATTR_WHITE_VALUE] - # effect if ATTR_EFFECT in kwargs: values['effect'] = kwargs.get(ATTR_EFFECT) - # flash if ATTR_FLASH in kwargs: values['flash'] = kwargs.get(ATTR_FLASH) - # transition if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) @@ -347,12 +331,10 @@ class MqttTemplate(Light): This method is a coroutine. """ - # state values = {'state': False} if self._optimistic: self._state = False - # transition if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) diff --git a/homeassistant/components/light/mysensors.py b/homeassistant/components/light/mysensors.py index e25067916b2..203119e5e51 100644 --- a/homeassistant/components/light/mysensors.py +++ b/homeassistant/components/light/mysensors.py @@ -4,15 +4,12 @@ Support for MySensors lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mysensors/ """ - import logging from homeassistant.components import mysensors -from homeassistant.components.light import (ATTR_BRIGHTNESS, ATTR_RGB_COLOR, - ATTR_WHITE_VALUE, - SUPPORT_BRIGHTNESS, - SUPPORT_RGB_COLOR, - SUPPORT_WHITE_VALUE, Light) +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_WHITE_VALUE, + SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, SUPPORT_WHITE_VALUE, Light) from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.util.color import rgb_hex_to_rgb_list @@ -25,9 +22,7 @@ SUPPORT_MYSENSORS = (SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR | def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the mysensors platform for sensors.""" - # Only act if loaded via mysensors by discovery event. - # Otherwise gateway is not setup. + """Set up the MySensors platform for lights.""" if discovery_info is None: return @@ -62,10 +57,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): - """Represent the value of a MySensors Light child node.""" + """Representation of a MySensors Light child node.""" def __init__(self, *args): - """Set up instance attributes.""" + """Initialize a MySensors Light.""" mysensors.MySensorsDeviceEntity.__init__(self, *args) self._state = None self._brightness = None @@ -157,7 +152,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): elif white is not None: rgb.append(white) else: - _LOGGER.error('White value is not updated for RGBW light') + _LOGGER.error("White value is not updated for RGBW light") return hex_color = hex_template % tuple(rgb) if len(rgb) > 3: @@ -206,9 +201,8 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): set_req = self.gateway.const.SetReq if value_type is None or value is None: _LOGGER.warning( - '%s: value_type %s, value = %s, ' - 'None is not valid argument when setting child value' - '', self._name, value_type, value) + "%s: value_type %s, value = %s, None is not valid argument " + "when setting child value", self._name, value_type, value) return self.gateway.set_child_value( self.node_id, self.child_id, value_type, value) @@ -244,7 +238,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): value = self._values[self.value_type] if len(value) != 6 and len(value) != 8: _LOGGER.error( - 'Wrong value %s for %s', value, set_req(self.value_type).name) + "Wrong value %s for %s", value, set_req(self.value_type).name) return color_list = rgb_hex_to_rgb_list(value) if set_req.V_LIGHT not in self._values and \ @@ -253,7 +247,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): if len(color_list) > 3: if set_req.V_RGBW != self.value_type: _LOGGER.error( - 'Wrong value %s for %s', + "Wrong value %s for %s", value, set_req(self.value_type).name) return self._white = color_list.pop() @@ -265,7 +259,7 @@ class MySensorsLight(mysensors.MySensorsDeviceEntity, Light): child = node.children[self.child_id] for value_type, value in child.values.items(): _LOGGER.debug( - '%s: value_type %s, value = %s', self._name, value_type, value) + "%s: value_type %s, value = %s", self._name, value_type, value) self._values[value_type] = value diff --git a/homeassistant/components/light/mystrom.py b/homeassistant/components/light/mystrom.py index e29535d60e6..2eb7c106bf2 100644 --- a/homeassistant/components/light/mystrom.py +++ b/homeassistant/components/light/mystrom.py @@ -72,7 +72,7 @@ class MyStromLight(Light): @property def brightness(self): - """Brightness of the light.""" + """Return the brightness of the light.""" return self._brightness @property diff --git a/homeassistant/components/light/osramlightify.py b/homeassistant/components/light/osramlightify.py index e93c2092f98..3faeb1a9d71 100644 --- a/homeassistant/components/light/osramlightify.py +++ b/homeassistant/components/light/osramlightify.py @@ -46,13 +46,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: bridge = lightify.Lightify(host) except socket.error as err: - msg = 'Error connecting to bridge: {} due to: {}'.format(host, - str(err)) + msg = "Error connecting to bridge: {} due to: {}".format( + host, str(err)) _LOGGER.exception(msg) return False setup_bridge(bridge, add_devices) else: - _LOGGER.error('No host found in configuration') + _LOGGER.error("No host found in configuration") return False @@ -105,8 +105,8 @@ class OsramLightifyLight(Light): @property def rgb_color(self): - """Last RGB color value set.""" - _LOGGER.debug("rgb_color light state for light: %s is: %s %s %s ", + """Return the last RGB color value set.""" + _LOGGER.debug("rgb_color light state for light: %s is: %s %s %s", self._name, self._rgb[0], self._rgb[1], self._rgb[2]) return self._rgb @@ -117,16 +117,16 @@ class OsramLightifyLight(Light): @property def brightness(self): - """Brightness of this light between 0..255.""" - _LOGGER.debug("brightness for light %s is: %s", - self._name, self._brightness) + """Return the brightness of this light between 0..255.""" + _LOGGER.debug( + "Brightness for light %s is: %s", self._name, self._brightness) return self._brightness @property def is_on(self): """Update Status to True if device is on.""" - _LOGGER.debug("is_on light state for light: %s is: %s", - self._name, self._state) + _LOGGER.debug( + "is_on light state for light: %s is: %s", self._name, self._state) return self._state @property @@ -136,35 +136,31 @@ class OsramLightifyLight(Light): def turn_on(self, **kwargs): """Turn the device on.""" - _LOGGER.debug("turn_on Attempting to turn on light: %s ", - self._name) + _LOGGER.debug("turn_on Attempting to turn on light: %s ", self._name) self._light.set_onoff(1) self._state = self._light.on() if ATTR_TRANSITION in kwargs: transition = int(kwargs[ATTR_TRANSITION] * 10) - _LOGGER.debug("turn_on requested transition time for light:" - " %s is: %s ", - self._name, transition) + _LOGGER.debug("turn_on requested transition time for light: " + "%s is: %s", self._name, transition) else: transition = 0 - _LOGGER.debug("turn_on requested transition time for light:" - " %s is: %s ", - self._name, transition) + _LOGGER.debug("turn_on requested transition time for light: " + "%s is: %s", self._name, transition) if ATTR_RGB_COLOR in kwargs: red, green, blue = kwargs[ATTR_RGB_COLOR] - _LOGGER.debug("turn_on requested ATTR_RGB_COLOR for light:" - " %s is: %s %s %s ", - self._name, red, green, blue) + _LOGGER.debug("turn_on requested ATTR_RGB_COLOR for light: " + "%s is: %s %s %s", self._name, red, green, blue) self._light.set_rgb(red, green, blue, transition) if ATTR_COLOR_TEMP in kwargs: color_t = kwargs[ATTR_COLOR_TEMP] kelvin = int(color_temperature_mired_to_kelvin(color_t)) - _LOGGER.debug("turn_on requested set_temperature for light:" - " %s: %s ", self._name, kelvin) + _LOGGER.debug("turn_on requested set_temperature for light: " + "%s: %s", self._name, kelvin) self._light.set_temperature(kelvin, transition) if ATTR_BRIGHTNESS in kwargs: @@ -182,9 +178,8 @@ class OsramLightifyLight(Light): random.randrange(0, 255), random.randrange(0, 255), transition) - _LOGGER.debug("turn_on requested random effect for light:" - " %s with transition %s ", - self._name, transition) + _LOGGER.debug("turn_on requested random effect for light: " + "%s with transition %s", self._name, transition) self.schedule_update_ha_state() @@ -194,15 +189,13 @@ class OsramLightifyLight(Light): self._name) if ATTR_TRANSITION in kwargs: transition = int(kwargs[ATTR_TRANSITION] * 10) - _LOGGER.debug("turn_off requested transition time for light:" - " %s is: %s ", - self._name, transition) + _LOGGER.debug("turn_off requested transition time for light: " + "%s is: %s", self._name, transition) self._light.set_luminance(0, transition) else: transition = 0 - _LOGGER.debug("turn_off requested transition time for light:" - " %s is: %s ", - self._name, transition) + _LOGGER.debug("turn_off requested transition time for light: " + "%s is: %s ", self._name, transition) self._light.set_onoff(0) self._state = self._light.on() diff --git a/homeassistant/components/light/piglow.py b/homeassistant/components/light/piglow.py index afdda745721..d08776551f8 100644 --- a/homeassistant/components/light/piglow.py +++ b/homeassistant/components/light/piglow.py @@ -59,7 +59,7 @@ class PiglowLight(Light): @property def brightness(self): - """Brightness of the light (an integer in the range 1-255).""" + """Return the brightness of the light.""" return self._brightness @property diff --git a/homeassistant/components/light/qwikswitch.py b/homeassistant/components/light/qwikswitch.py index b5b4378d526..63051d2ea8c 100644 --- a/homeassistant/components/light/qwikswitch.py +++ b/homeassistant/components/light/qwikswitch.py @@ -15,7 +15,7 @@ DEPENDENCIES = ['qwikswitch'] # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Add lights from the main Qwikswitch component.""" + """Set up the lights from the main Qwikswitch component.""" if discovery_info is None: _LOGGER.error("Configure Qwikswitch component failed") return False diff --git a/homeassistant/components/light/rflink.py b/homeassistant/components/light/rflink.py index e0b627f1ffa..fb054407dff 100644 --- a/homeassistant/components/light/rflink.py +++ b/homeassistant/components/light/rflink.py @@ -119,7 +119,7 @@ def devices_from_config(domain_config, hass=None): # Register entity (and aliasses) to listen to incoming rflink events - # device id and normal aliasses respond to normal and group command + # Device id and normal aliasses respond to normal and group command hass.data[DATA_ENTITY_LOOKUP][ EVENT_KEY_COMMAND][device_id].append(device) if config[CONF_GROUP]: @@ -188,7 +188,7 @@ class DimmableRflinkLight(SwitchableRflinkDevice, Light): # rflink only support 16 brightness levels self._brightness = int(kwargs[ATTR_BRIGHTNESS] / 17) * 17 - # turn on light at the requested dim level + # Turn on light at the requested dim level yield from self._async_handle_command('dim', self._brightness) @property diff --git a/homeassistant/components/light/rfxtrx.py b/homeassistant/components/light/rfxtrx.py index b3bfc82a26b..9248b0131f1 100644 --- a/homeassistant/components/light/rfxtrx.py +++ b/homeassistant/components/light/rfxtrx.py @@ -27,7 +27,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): add_devices(lights) def light_update(event): - """Define callback for light updates from the RFXtrx gateway.""" + """Handle light updates from the RFXtrx gateway.""" if not isinstance(event.device, rfxtrxmod.LightingDevice) or \ not event.device.known_to_be_dimmable: return @@ -38,13 +38,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): rfxtrx.apply_received_command(event) - # Subscribe to main rfxtrx events + # Subscribe to main RFXtrx events if light_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(light_update) class RfxtrxLight(rfxtrx.RfxtrxDevice, Light): - """Represenation of a RFXtrx light.""" + """Representation of a RFXtrx light.""" @property def brightness(self): @@ -61,8 +61,8 @@ class RfxtrxLight(rfxtrx.RfxtrxDevice, Light): brightness = kwargs.get(ATTR_BRIGHTNESS) if brightness is None: self._brightness = 255 - self._send_command("turn_on") + self._send_command('turn_on') else: self._brightness = brightness _brightness = (brightness * 100 // 255) - self._send_command("dim", _brightness) + self._send_command('dim', _brightness) diff --git a/homeassistant/components/light/rpi_gpio_pwm.py b/homeassistant/components/light/rpi_gpio_pwm.py index 0248ca49dd6..f2d39dea633 100644 --- a/homeassistant/components/light/rpi_gpio_pwm.py +++ b/homeassistant/components/light/rpi_gpio_pwm.py @@ -4,7 +4,6 @@ Support for LED lights that can be controlled using PWM. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.pwm/ """ - import logging import voluptuous as vol @@ -55,7 +54,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the pwm lights.""" + """Set up the PWM LED lights.""" from pwmled.led import SimpleLed from pwmled.led.rgb import RgbLed from pwmled.led.rgbw import RgbwLed @@ -76,7 +75,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): opt_args['address'] = led_conf[CONF_ADDRESS] driver = Pca9685Driver(pins, **opt_args) else: - _LOGGER.error("Invalid driver type.") + _LOGGER.error("Invalid driver type") return name = led_conf[CONF_NAME] @@ -88,7 +87,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): elif led_type == CONF_LED_TYPE_RGBW: led = PwmRgbLed(RgbwLed(driver), name) else: - _LOGGER.error("Invalid led type.") + _LOGGER.error("Invalid led type") return leds.append(led) @@ -96,10 +95,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class PwmSimpleLed(Light): - """Representation of a simple on-color pwm led.""" + """Representation of a simple one-color PWM LED.""" def __init__(self, led, name): - """Initialize led.""" + """Initialize one-color PWM LED.""" self._led = led self._name = name self._is_on = False @@ -149,7 +148,7 @@ class PwmSimpleLed(Light): self.schedule_update_ha_state() def turn_off(self, **kwargs): - """Turn off a led.""" + """Turn off a LED.""" if self.is_on: if ATTR_TRANSITION in kwargs: transition_time = kwargs[ATTR_TRANSITION] @@ -162,10 +161,10 @@ class PwmSimpleLed(Light): class PwmRgbLed(PwmSimpleLed): - """Representation of a rgb(w) pwm led.""" + """Representation of a RGB(W) PWM LED.""" def __init__(self, led, name): - """Initialize led.""" + """Initialize a RGB(W) PWM LED.""" super().__init__(led, name) self._color = DEFAULT_COLOR @@ -180,7 +179,7 @@ class PwmRgbLed(PwmSimpleLed): return SUPPORT_RGB_LED def turn_on(self, **kwargs): - """Turn on a led.""" + """Turn on a LED.""" if ATTR_RGB_COLOR in kwargs: self._color = kwargs[ATTR_RGB_COLOR] if ATTR_BRIGHTNESS in kwargs: diff --git a/homeassistant/components/light/scsgate.py b/homeassistant/components/light/scsgate.py index 1de2e31af5f..214a2d99449 100644 --- a/homeassistant/components/light/scsgate.py +++ b/homeassistant/components/light/scsgate.py @@ -47,7 +47,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class SCSGateLight(Light): - """representation of a SCSGate light.""" + """Representation of a SCSGate light.""" def __init__(self, scs_id, name, logger): """Initialize the light.""" diff --git a/homeassistant/components/light/sensehat.py b/homeassistant/components/light/sensehat.py index 869963d3545..2cf9c4f9b31 100644 --- a/homeassistant/components/light/sensehat.py +++ b/homeassistant/components/light/sensehat.py @@ -58,10 +58,7 @@ class SenseHatLight(Light): @property def brightness(self): - """Read back the brightness of the light. - - Returns integer in the range of 1-255. - """ + """Read back the brightness of the light.""" return self._brightness @property diff --git a/homeassistant/components/light/tellduslive.py b/homeassistant/components/light/tellduslive.py index b2cbd856075..321cfd677b5 100644 --- a/homeassistant/components/light/tellduslive.py +++ b/homeassistant/components/light/tellduslive.py @@ -5,7 +5,6 @@ This platform uses the Telldus Live online service. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.tellduslive/ - """ import logging @@ -17,17 +16,17 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up lights.""" + """Set up the Tellstick Net lights.""" if discovery_info is None: return add_devices(TelldusLiveLight(hass, light) for light in discovery_info) class TelldusLiveLight(TelldusLiveEntity, Light): - """Representation of a light.""" + """Representation of a Tellstick Net light.""" def __init__(self, hass, device_id): - """Initialize the light.""" + """Initialize the Tellstick Net light.""" super().__init__(hass, device_id) self._last_brightness = self.brightness diff --git a/homeassistant/components/light/tellstick.py b/homeassistant/components/light/tellstick.py index 2c1401e34d8..d2a6dadd9da 100644 --- a/homeassistant/components/light/tellstick.py +++ b/homeassistant/components/light/tellstick.py @@ -6,12 +6,11 @@ https://home-assistant.io/components/light.tellstick/ """ import voluptuous as vol -from homeassistant.components.light import (ATTR_BRIGHTNESS, - SUPPORT_BRIGHTNESS, Light) -from homeassistant.components.tellstick import (DEFAULT_SIGNAL_REPETITIONS, - ATTR_DISCOVER_DEVICES, - ATTR_DISCOVER_CONFIG, - DOMAIN, TellstickDevice) +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light) +from homeassistant.components.tellstick import ( + DEFAULT_SIGNAL_REPETITIONS, ATTR_DISCOVER_DEVICES, ATTR_DISCOVER_CONFIG, + DOMAIN, TellstickDevice) PLATFORM_SCHEMA = vol.Schema({vol.Required("platform"): DOMAIN}) @@ -20,14 +19,13 @@ SUPPORT_TELLSTICK = SUPPORT_BRIGHTNESS # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up Tellstick lights.""" + """Set up the Tellstick lights.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None): return - # Allow platform level override, fallback to module config - signal_repetitions = discovery_info.get(ATTR_DISCOVER_CONFIG, - DEFAULT_SIGNAL_REPETITIONS) + signal_repetitions = discovery_info.get( + ATTR_DISCOVER_CONFIG, DEFAULT_SIGNAL_REPETITIONS) add_devices(TellstickLight(tellcore_id, hass.data['tellcore_registry'], signal_repetitions) @@ -38,7 +36,7 @@ class TellstickLight(TellstickDevice, Light): """Representation of a Tellstick light.""" def __init__(self, tellcore_id, tellcore_registry, signal_repetitions): - """Initialize the light.""" + """Initialize the Tellstick light.""" super().__init__(tellcore_id, tellcore_registry, signal_repetitions) self._brightness = 255 diff --git a/homeassistant/components/light/tikteck.py b/homeassistant/components/light/tikteck.py index 7b0222107a2..07d4b63e99a 100644 --- a/homeassistant/components/light/tikteck.py +++ b/homeassistant/components/light/tikteck.py @@ -60,8 +60,8 @@ class TikteckLight(Light): self._rgb = [255, 255, 255] self._state = False self.is_valid = True - self._bulb = tikteck.tikteck(self._address, "Smart Light", - self._password) + self._bulb = tikteck.tikteck( + self._address, "Smart Light", self._password) if self._bulb.connect() is False: self.is_valid = False _LOGGER.error( @@ -99,12 +99,12 @@ class TikteckLight(Light): @property def should_poll(self): - """Don't poll.""" + """Return the polling state.""" return False @property def assumed_state(self): - """We can't read the actual state, so assume it matches.""" + """Return the assumed state.""" return True def set_state(self, red, green, blue, brightness): diff --git a/homeassistant/components/light/tradfri.py b/homeassistant/components/light/tradfri.py index 488cea05494..016771a15ca 100644 --- a/homeassistant/components/light/tradfri.py +++ b/homeassistant/components/light/tradfri.py @@ -59,7 +59,7 @@ class TradfriGroup(Light): @property def brightness(self): - """Brightness of the group lights (an integer in the range 1-255).""" + """Return the brightness of the group lights.""" return self._group.dimmer def turn_off(self, **kwargs): @@ -79,7 +79,7 @@ class TradfriGroup(Light): class Tradfri(Light): - """The platform class required by hass.""" + """The platform class required by Home Asisstant.""" def __init__(self, light): """Initialize a Light.""" @@ -118,7 +118,7 @@ class Tradfri(Light): @property def brightness(self): - """Brightness of the light (an integer in the range 1-255).""" + """Return the brightness of the light.""" return self._light_data.dimmer @property @@ -134,7 +134,7 @@ class Tradfri(Light): if hex_color == self._light_data.hex_color), None) if kelvin is None: _LOGGER.error( - 'unexpected color temperature found for %s: %s', + "Unexpected color temperature found for %s: %s", self.name, self._light_data.hex_color) return return color_util.color_temperature_kelvin_to_mired(kelvin) diff --git a/homeassistant/components/light/vera.py b/homeassistant/components/light/vera.py index 8565cf5a9a4..70432de6644 100644 --- a/homeassistant/components/light/vera.py +++ b/homeassistant/components/light/vera.py @@ -20,7 +20,7 @@ SUPPORT_VERA = SUPPORT_BRIGHTNESS # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up Vera lights.""" + """Set up the Vera lights.""" add_devices( VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light']) diff --git a/homeassistant/components/light/wemo.py b/homeassistant/components/light/wemo.py index 71c2e333c9a..620271a1071 100644 --- a/homeassistant/components/light/wemo.py +++ b/homeassistant/components/light/wemo.py @@ -26,7 +26,7 @@ SUPPORT_WEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_RGB_COLOR | def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up WeMo bridges and register connected lights.""" + """Set up the WeMo bridges and register connected lights.""" import pywemo.discovery as discovery if discovery_info is not None: @@ -64,7 +64,7 @@ class WemoLight(Light): """Representation of a WeMo light.""" def __init__(self, device, update_lights): - """Initialize the light.""" + """Initialize the WeMo light.""" self.light_id = device.name self.device = device self.update_lights = update_lights @@ -97,7 +97,7 @@ class WemoLight(Light): @property def is_on(self): - """Set True if device is on.""" + """Return true if device is on.""" return self.device.state['onoff'] != 0 @property diff --git a/homeassistant/components/light/wink.py b/homeassistant/components/light/wink.py index 9ffc7b5f4c6..82b7c9f4f8c 100644 --- a/homeassistant/components/light/wink.py +++ b/homeassistant/components/light/wink.py @@ -105,8 +105,8 @@ class WinkLight(WinkDevice, Light): state_kwargs['color_xy'] = xyb[0], xyb[1] state_kwargs['brightness'] = xyb[2] elif self.wink.supports_hue_saturation(): - hsv = colorsys.rgb_to_hsv(rgb_color[0], - rgb_color[1], rgb_color[2]) + hsv = colorsys.rgb_to_hsv( + rgb_color[0], rgb_color[1], rgb_color[2]) state_kwargs['color_hue_saturation'] = hsv[0], hsv[1] if color_temp_mired: diff --git a/homeassistant/components/light/x10.py b/homeassistant/components/light/x10.py index 7062665c42b..e782e664801 100644 --- a/homeassistant/components/light/x10.py +++ b/homeassistant/components/light/x10.py @@ -67,7 +67,7 @@ class X10Light(Light): @property def brightness(self): - """Brightness of the light (an integer in the range 1-255).""" + """Return the brightness of the light.""" return self._brightness @property diff --git a/homeassistant/components/light/yeelight.py b/homeassistant/components/light/yeelight.py index 7ba2b3ad4f3..dbb1e4e26ca 100644 --- a/homeassistant/components/light/yeelight.py +++ b/homeassistant/components/light/yeelight.py @@ -26,11 +26,11 @@ REQUIREMENTS = ['yeelight==0.2.2'] _LOGGER = logging.getLogger(__name__) -CONF_TRANSITION = "transition" +CONF_TRANSITION = 'transition' DEFAULT_TRANSITION = 350 -CONF_SAVE_ON_CHANGE = "save_on_change" -CONF_MODE_MUSIC = "use_music_mode" +CONF_SAVE_ON_CHANGE = 'save_on_change' +CONF_MODE_MUSIC = 'use_music_mode' DOMAIN = 'yeelight' @@ -67,14 +67,14 @@ def _cmd(func): def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up Yeelight bulbs.""" + """Set up the Yeelight bulbs.""" lights = [] if discovery_info is not None: _LOGGER.debug("Adding autodetected %s", discovery_info['hostname']) - # not using hostname, as it seems to vary. - name = "yeelight_%s_%s" % (discovery_info["device_type"], - discovery_info["properties"]["mac"]) + # Not using hostname, as it seems to vary. + name = "yeelight_%s_%s" % (discovery_info['device_type'], + discovery_info['properties']['mac']) device = {'name': name, 'ipaddr': discovery_info['host']} lights.append(YeelightLight(device, DEVICE_SCHEMA({}))) @@ -85,14 +85,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None): device = {'name': device_config[CONF_NAME], 'ipaddr': ipaddr} lights.append(YeelightLight(device, device_config)) - add_devices(lights, True) # true to request an update before adding. + add_devices(lights, True) class YeelightLight(Light): """Representation of a Yeelight light.""" def __init__(self, device, config): - """Initialize the light.""" + """Initialize the Yeelight light.""" self.config = config self._name = device['name'] self._ipaddr = device['ipaddr'] @@ -142,8 +142,8 @@ class YeelightLight(Light): return self._brightness def _get_rgb_from_properties(self): - rgb = self._properties.get("rgb", None) - color_mode = self._properties.get("color_mode", None) + rgb = self._properties.get('rgb', None) + color_mode = self._properties.get('color_mode', None) if not rgb or not color_mode: return rgb @@ -151,9 +151,9 @@ class YeelightLight(Light): if color_mode == 2: # color temperature return color_temperature_to_rgb(self.color_temp) if color_mode == 3: # hsv - hue = self._properties.get("hue") - sat = self._properties.get("sat") - val = self._properties.get("bright") + hue = self._properties.get('hue') + sat = self._properties.get('sat') + val = self._properties.get('bright') return colorsys.hsv_to_rgb(hue, sat, val) rgb = int(rgb) @@ -204,13 +204,13 @@ class YeelightLight(Light): if self._bulb_device.bulb_type == yeelight.BulbType.Color: self._supported_features = SUPPORT_YEELIGHT_RGB - self._is_on = self._properties.get("power") == "on" + self._is_on = self._properties.get('power') == 'on' - bright = self._properties.get("bright", None) + bright = self._properties.get('bright', None) if bright: self._brightness = 255 * (int(bright) / 100) - temp_in_k = self._properties.get("ct", None) + temp_in_k = self._properties.get('ct', None) if temp_in_k: self._color_temp = kelvin_to_mired(int(temp_in_k)) diff --git a/homeassistant/components/light/yeelightsunflower.py b/homeassistant/components/light/yeelightsunflower.py index 70df2136716..5f48e3a0a71 100644 --- a/homeassistant/components/light/yeelightsunflower.py +++ b/homeassistant/components/light/yeelightsunflower.py @@ -67,7 +67,7 @@ class SunflowerBulb(Light): @property def brightness(self): - """HA brightness is 0-255; Yeelight Sunflower's brightness is 0-100.""" + """Return the brightness is 0-255; Yeelight's brightness is 0-100.""" return int(self._brightness / 100 * 255) @property diff --git a/homeassistant/components/light/zha.py b/homeassistant/components/light/zha.py index 8959fa9ef0e..0c230877625 100644 --- a/homeassistant/components/light/zha.py +++ b/homeassistant/components/light/zha.py @@ -17,7 +17,7 @@ DEPENDENCIES = ['zha'] @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up Zigbee Home Automation lights.""" + """Set up the Zigbee Home Automation lights.""" discovery_info = zha.get_discovery_info(hass, discovery_info) if discovery_info is None: return @@ -33,12 +33,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class Light(zha.Entity, light.Light): - """ZHA or ZLL light.""" + """Representation of a ZHA or ZLL light.""" _domain = light.DOMAIN def __init__(self, **kwargs): - """Initialize ZHA light.""" + """Initialize the ZHA light.""" super().__init__(**kwargs) self._supported_features = 0 self._color_temp = None @@ -61,7 +61,7 @@ class Light(zha.Entity, light.Light): @property def is_on(self) -> bool: - """Return True if entity is on.""" + """Return true if entity is on.""" if self._state == 'unknown': return False return bool(self._state) diff --git a/homeassistant/components/light/zwave.py b/homeassistant/components/light/zwave.py index 81d36b4779b..9488ad38a59 100644 --- a/homeassistant/components/light/zwave.py +++ b/homeassistant/components/light/zwave.py @@ -46,13 +46,12 @@ TEMP_COLD_HASS = (TEMP_COLOR_MAX - TEMP_COLOR_MIN) / 3 + TEMP_COLOR_MIN def get_device(node, values, node_config, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" name = '{}.{}'.format(DOMAIN, zwave.object_id(values.primary)) refresh = node_config.get(zwave.CONF_REFRESH_VALUE) delay = node_config.get(zwave.CONF_REFRESH_DELAY) - _LOGGER.debug('name=%s node_config=%s CONF_REFRESH_VALUE=%s' - ' CONF_REFRESH_DELAY=%s', name, node_config, - refresh, delay) + _LOGGER.debug("name=%s node_config=%s CONF_REFRESH_VALUE=%s" + " CONF_REFRESH_DELAY=%s", name, node_config, refresh, delay) if node.has_command_class(zwave.const.COMMAND_CLASS_SWITCH_COLOR): return ZwaveColorLight(values, refresh, delay) diff --git a/homeassistant/components/lock/__init__.py b/homeassistant/components/lock/__init__.py index 3d83ae5895d..7d3e75595e2 100644 --- a/homeassistant/components/lock/__init__.py +++ b/homeassistant/components/lock/__init__.py @@ -22,17 +22,19 @@ from homeassistant.const import ( STATE_UNKNOWN, SERVICE_LOCK, SERVICE_UNLOCK) from homeassistant.components import group -DOMAIN = 'lock' -SCAN_INTERVAL = timedelta(seconds=30) ATTR_CHANGED_BY = 'changed_by' -GROUP_NAME_ALL_LOCKS = 'all locks' -ENTITY_ID_ALL_LOCKS = group.ENTITY_ID_FORMAT.format('all_locks') +DOMAIN = 'lock' +ENTITY_ID_ALL_LOCKS = group.ENTITY_ID_FORMAT.format('all_locks') ENTITY_ID_FORMAT = DOMAIN + '.{}' +GROUP_NAME_ALL_LOCKS = 'all locks' + MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) +SCAN_INTERVAL = timedelta(seconds=30) + LOCK_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_CODE): cv.string, diff --git a/homeassistant/components/lock/demo.py b/homeassistant/components/lock/demo.py index fca922b11e2..aca25e7e16d 100644 --- a/homeassistant/components/lock/demo.py +++ b/homeassistant/components/lock/demo.py @@ -10,7 +10,7 @@ from homeassistant.const import (STATE_LOCKED, STATE_UNLOCKED) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo lock platform.""" + """Set up the Demo lock platform.""" add_devices([ DemoLock('Front Door', STATE_LOCKED), DemoLock('Kitchen Door', STATE_UNLOCKED) diff --git a/homeassistant/components/lock/isy994.py b/homeassistant/components/lock/isy994.py index d7e921a16e5..edbb8a34f24 100644 --- a/homeassistant/components/lock/isy994.py +++ b/homeassistant/components/lock/isy994.py @@ -28,7 +28,7 @@ def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): """Set up the ISY994 lock platform.""" if isy.ISY is None or not isy.ISY.connected: - _LOGGER.error('A connection has not been made to the ISY controller.') + _LOGGER.error("A connection has not been made to the ISY controller") return False devices = [] @@ -115,9 +115,9 @@ class ISYLockProgram(ISYLockDevice): def lock(self, **kwargs) -> None: """Lock the device.""" if not self._actions.runThen(): - _LOGGER.error('Unable to lock device') + _LOGGER.error("Unable to lock device") def unlock(self, **kwargs) -> None: """Unlock the device.""" if not self._actions.runElse(): - _LOGGER.error('Unable to unlock device') + _LOGGER.error("Unable to unlock device") diff --git a/homeassistant/components/lock/lockitron.py b/homeassistant/components/lock/lockitron.py index 86821711fd2..eb301eeb013 100644 --- a/homeassistant/components/lock/lockitron.py +++ b/homeassistant/components/lock/lockitron.py @@ -28,16 +28,17 @@ API_ACTION_URL = BASE_URL + '/v2/locks/{}?access_token={}&state={}' # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Lockitron platform.""" + """Set up the Lockitron platform.""" access_token = config.get(CONF_ACCESS_TOKEN) device_id = config.get(CONF_ID) - response = requests.get(API_STATE_URL.format(device_id, access_token)) + response = requests.get( + API_STATE_URL.format(device_id, access_token), timeout=5) if response.status_code == 200: add_devices([Lockitron(response.json()['state'], access_token, device_id)]) else: - _LOGGER.error('Error retrieving lock status during init: %s', - response.text) + _LOGGER.error( + "Error retrieving lock status during init: %s", response.text) class Lockitron(LockDevice): @@ -72,21 +73,20 @@ class Lockitron(LockDevice): def update(self): """Update the internal state of the device.""" - response = requests \ - .get(API_STATE_URL.format(self.device_id, self.access_token)) + response = requests.get(API_STATE_URL.format( + self.device_id, self.access_token), timeout=5) if response.status_code == 200: self._state = response.json()['state'] else: - _LOGGER.error('Error retrieving lock status: %s', response.text) + _LOGGER.error("Error retrieving lock status: %s", response.text) def do_change_request(self, requested_state): """Execute the change request and pull out the new state.""" - response = requests.put( - API_ACTION_URL.format(self.device_id, self.access_token, - requested_state)) + response = requests.put(API_ACTION_URL.format( + self.device_id, self.access_token, requested_state), timeout=5) if response.status_code == 200: return response.json()['state'] else: - _LOGGER.error('Error setting lock state: %s\n%s', + _LOGGER.error("Error setting lock state: %s\n%s", requested_state, response.text) return self._state diff --git a/homeassistant/components/lock/mqtt.py b/homeassistant/components/lock/mqtt.py index 43d5788af9b..de14d21a09b 100644 --- a/homeassistant/components/lock/mqtt.py +++ b/homeassistant/components/lock/mqtt.py @@ -20,7 +20,6 @@ import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) - CONF_PAYLOAD_LOCK = 'payload_lock' CONF_PAYLOAD_UNLOCK = 'payload_unlock' @@ -42,7 +41,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the MQTT lock.""" + """Set up the MQTT lock.""" value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass @@ -61,7 +60,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class MqttLock(LockDevice): - """Represents a lock that can be toggled using MQTT.""" + """Representation of a lock that can be toggled using MQTT.""" def __init__(self, name, state_topic, command_topic, qos, retain, payload_lock, payload_unlock, optimistic, value_template): @@ -79,13 +78,13 @@ class MqttLock(LockDevice): @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method is a coroutine. """ @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) @@ -110,7 +109,7 @@ class MqttLock(LockDevice): @property def name(self): - """The name of the lock.""" + """Return the name of the lock.""" return self._name @property diff --git a/homeassistant/components/lock/nuki.py b/homeassistant/components/lock/nuki.py index bb3f2f030a2..144bfc3ec45 100644 --- a/homeassistant/components/lock/nuki.py +++ b/homeassistant/components/lock/nuki.py @@ -6,13 +6,13 @@ https://home-assistant.io/components/lock.nuki/ """ from datetime import timedelta import logging + import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import (LockDevice, PLATFORM_SCHEMA) from homeassistant.const import (CONF_HOST, CONF_PORT, CONF_TOKEN) from homeassistant.util import Throttle -import homeassistant.helpers.config_validation as cv - REQUIREMENTS = ['pynuki==1.2.2'] @@ -33,7 +33,7 @@ MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo lock platform.""" + """Set up the Nuki lock platform.""" from pynuki import NukiBridge bridge = NukiBridge(config.get(CONF_HOST), config.get(CONF_TOKEN)) add_devices([NukiLock(lock) for lock in bridge.locks]) diff --git a/homeassistant/components/lock/vera.py b/homeassistant/components/lock/vera.py index da2a465d570..04962566821 100644 --- a/homeassistant/components/lock/vera.py +++ b/homeassistant/components/lock/vera.py @@ -48,6 +48,6 @@ class VeraLock(VeraDevice, LockDevice): return self._state == STATE_LOCKED def update(self): - """Called by the Vera device callback to update state.""" + """Update state by the Vera device callback.""" self._state = (STATE_LOCKED if self.vera_device.is_locked(True) else STATE_UNLOCKED) diff --git a/homeassistant/components/lock/volvooncall.py b/homeassistant/components/lock/volvooncall.py index b308ec61fba..ab1d2fabefe 100644 --- a/homeassistant/components/lock/volvooncall.py +++ b/homeassistant/components/lock/volvooncall.py @@ -1,5 +1,5 @@ """ -Support for Volvo locks. +Support for Volvo On Call locks. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/lock.volvooncall/ @@ -14,9 +14,10 @@ _LOGGER = logging.getLogger(__name__) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the lock.""" + """Set up the Volvo On Call lock.""" if discovery_info is None: return + add_devices([VolvoLock(hass, *discovery_info)]) diff --git a/homeassistant/components/lock/wink.py b/homeassistant/components/lock/wink.py index 76922cf9d62..9ac5c579ab5 100644 --- a/homeassistant/components/lock/wink.py +++ b/homeassistant/components/lock/wink.py @@ -4,7 +4,6 @@ Support for Wink locks. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/lock.wink/ """ - from homeassistant.components.lock import LockDevice from homeassistant.components.wink import WinkDevice, DOMAIN @@ -12,7 +11,7 @@ DEPENDENCIES = ['wink'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink platform.""" + """Set up the Wink platform.""" import pywink for lock in pywink.get_locks(): diff --git a/homeassistant/components/lock/zwave.py b/homeassistant/components/lock/zwave.py index 9a3e2e34fcc..7e2d328c34a 100644 --- a/homeassistant/components/lock/zwave.py +++ b/homeassistant/components/lock/zwave.py @@ -1,5 +1,5 @@ """ -Zwave platform that handles simple door locks. +Z-Wave platform that handles simple door locks. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/lock.zwave/ @@ -122,7 +122,7 @@ CLEAR_USERCODE_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Generic Z-Wave platform setup.""" + """Set up the Z-Wave Lock platform.""" yield from zwave.async_setup_platform( hass, config, async_add_devices, discovery_info) @@ -142,8 +142,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): if value.index != code_slot: continue if len(str(usercode)) > 4: - _LOGGER.error('Invalid code provided: (%s)' - ' usercode must %s or less digits', + _LOGGER.error("Invalid code provided: (%s) " + "usercode must %s or less digits", usercode, len(value.data)) break value.data = str(usercode) @@ -159,7 +159,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class_id=zwave.const.COMMAND_CLASS_USER_CODE).values(): if value.index != code_slot: continue - _LOGGER.info('Usercode at slot %s is: %s', value.index, value.data) + _LOGGER.info("Usercode at slot %s is: %s", value.index, value.data) break def clear_usercode(service): @@ -178,28 +178,22 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): i += 1 _LOGGER.debug('Data to clear lock: %s', data) value.data = data - _LOGGER.info('Usercode at slot %s is cleared', value.index) + _LOGGER.info("Usercode at slot %s is cleared", value.index) break - hass.services.async_register(DOMAIN, - SERVICE_SET_USERCODE, - set_usercode, - descriptions.get(SERVICE_SET_USERCODE), - schema=SET_USERCODE_SCHEMA) - hass.services.async_register(DOMAIN, - SERVICE_GET_USERCODE, - get_usercode, - descriptions.get(SERVICE_GET_USERCODE), - schema=GET_USERCODE_SCHEMA) - hass.services.async_register(DOMAIN, - SERVICE_CLEAR_USERCODE, - clear_usercode, - descriptions.get(SERVICE_CLEAR_USERCODE), - schema=CLEAR_USERCODE_SCHEMA) + hass.services.async_register( + DOMAIN, SERVICE_SET_USERCODE, set_usercode, + descriptions.get(SERVICE_SET_USERCODE), schema=SET_USERCODE_SCHEMA) + hass.services.async_register( + DOMAIN, SERVICE_GET_USERCODE, get_usercode, + descriptions.get(SERVICE_GET_USERCODE), schema=GET_USERCODE_SCHEMA) + hass.services.async_register( + DOMAIN, SERVICE_CLEAR_USERCODE, clear_usercode, + descriptions.get(SERVICE_CLEAR_USERCODE), schema=CLEAR_USERCODE_SCHEMA) def get_device(node, values, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" return ZwaveLock(values) @@ -230,8 +224,7 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice): def update_properties(self): """Callback on data changes for node values.""" self._state = self.values.primary.data - _LOGGER.debug('Lock state set from Bool value and' - ' is %s', self._state) + _LOGGER.debug("Lock state set from Bool value and is %s", self._state) if self.values.access_control: notification_data = self.values.access_control.data self._notification = LOCK_NOTIFICATION.get(str(notification_data)) @@ -240,21 +233,20 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice): if self.values.v2btze_advanced and \ self.values.v2btze_advanced.data == CONFIG_ADVANCED: self._state = LOCK_STATUS.get(str(notification_data)) - _LOGGER.debug('Lock state set from Access Control ' - 'value and is %s, get=%s', - str(notification_data), - self.state) + _LOGGER.debug( + "Lock state set from Access Control value and is %s, " + "get=%s", str(notification_data), self.state) if not self.values.alarm_type: return alarm_type = self.values.alarm_type.data - _LOGGER.debug('Lock alarm_type is %s', str(alarm_type)) + _LOGGER.debug("Lock alarm_type is %s", str(alarm_type)) if self.values.alarm_level: alarm_level = self.values.alarm_level.data else: alarm_level = None - _LOGGER.debug('Lock alarm_level is %s', str(alarm_level)) + _LOGGER.debug("Lock alarm_level is %s", str(alarm_level)) if not alarm_type: return diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index bd29fe24aec..be7fce16821 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -897,7 +897,7 @@ class MediaPlayerDevice(Entity): @asyncio.coroutine def _async_fetch_image(hass, url): - """Helper method to fetch image. + """Fetch image. Images are cached in memory (the images are typically 10-100kB in size). """ @@ -942,8 +942,8 @@ class MediaPlayerImageView(HomeAssistantView): """Media player view to serve an image.""" requires_auth = False - url = "/api/media_player_proxy/{entity_id}" - name = "api:media_player:image" + url = '/api/media_player_proxy/{entity_id}' + name = 'api:media_player:image' def __init__(self, entities): """Initialize a media player view.""" diff --git a/homeassistant/components/media_player/anthemav.py b/homeassistant/components/media_player/anthemav.py index e6fd4e286ab..64b8e826cfb 100644 --- a/homeassistant/components/media_player/anthemav.py +++ b/homeassistant/components/media_player/anthemav.py @@ -45,11 +45,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): name = config.get(CONF_NAME) device = None - _LOGGER.info('Provisioning Anthem AVR device at %s:%d', host, port) + _LOGGER.info("Provisioning Anthem AVR device at %s:%d", host, port) def async_anthemav_update_callback(message): """Receive notification from transport that new data exists.""" - _LOGGER.info('Received update calback from AVR: %s', message) + _LOGGER.info("Received update calback from AVR: %s", message) hass.async_add_job(device.async_update_ha_state()) avr = yield from anthemav.Connection.create( @@ -58,9 +58,9 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): device = AnthemAVR(avr, name) - _LOGGER.debug('dump_devicedata: '+device.dump_avrdata) - _LOGGER.debug('dump_conndata: '+avr.dump_conndata) - _LOGGER.debug('dump_rawdata: '+avr.protocol.dump_rawdata) + _LOGGER.debug("dump_devicedata: %s", device.dump_avrdata) + _LOGGER.debug("dump_conndata: %s", avr.dump_conndata) + _LOGGER.debug("dump_rawdata: %s", avr.protocol.dump_rawdata) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.avr.close) async_add_devices([device]) @@ -70,7 +70,7 @@ class AnthemAVR(MediaPlayerDevice): """Entity reading values from Anthem AVR protocol.""" def __init__(self, avr, name): - """"Initialize entity with transport.""" + """Initialize entity with transport.""" super().__init__() self.avr = avr self._name = name @@ -163,7 +163,8 @@ class AnthemAVR(MediaPlayerDevice): def _update_avr(self, propname, value): """Update a property in the AVR.""" - _LOGGER.info('Sending command to AVR: set '+propname+' to '+str(value)) + _LOGGER.info( + "Sending command to AVR: set %s to %s", propname, str(value)) setattr(self.avr.protocol, propname, value) @property diff --git a/homeassistant/components/media_player/apple_tv.py b/homeassistant/components/media_player/apple_tv.py index 580870cf375..97114a6bc84 100644 --- a/homeassistant/components/media_player/apple_tv.py +++ b/homeassistant/components/media_player/apple_tv.py @@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Apple TV platform.""" + """Set up the Apple TV platform.""" import pyatv if discovery_info is not None: @@ -95,12 +95,13 @@ class AppleTvDevice(MediaPlayerDevice): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity is about to be added to HASS.""" + """Handle when an entity is about to be added to Home Assistant.""" if not self._is_off: self._atv.push_updater.start() @callback def _set_power_off(self, is_off): + """Set the power to off.""" self._playing = None self._artwork_hash = None self._is_off = is_off diff --git a/homeassistant/components/media_player/aquostv.py b/homeassistant/components/media_player/aquostv.py index 65d3e2c93fd..2d51cacadff 100644 --- a/homeassistant/components/media_player/aquostv.py +++ b/homeassistant/components/media_player/aquostv.py @@ -61,7 +61,7 @@ SOURCES = {0: 'TV / Antenna', # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Sharp Aquos TV platform.""" + """Set up the Sharp Aquos TV platform.""" import sharp_aquos_rc name = config.get(CONF_NAME) @@ -77,30 +77,21 @@ def setup_platform(hass, config, add_devices, discovery_info=None): port = vals[1] host = vals[0] - remote = sharp_aquos_rc.TV(host, - port, - username, - password, - timeout=20) + remote = sharp_aquos_rc.TV(host, port, username, password, timeout=20) add_devices([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True host = config.get(CONF_HOST) - remote = sharp_aquos_rc.TV(host, - port, - username, - password, - 15, - 1) + remote = sharp_aquos_rc.TV(host, port, username, password, 15, 1) add_devices([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True def _retry(func): - """Decorator to handle query retries.""" + """Handle query retries.""" def wrapper(obj, *args, **kwargs): - """Wrapper for all query functions.""" + """Wrap all query functions.""" update_retries = 5 while update_retries > 0: try: diff --git a/homeassistant/components/media_player/braviatv.py b/homeassistant/components/media_player/braviatv.py index 96c1e3726a8..1c8419ba144 100644 --- a/homeassistant/components/media_player/braviatv.py +++ b/homeassistant/components/media_player/braviatv.py @@ -76,7 +76,7 @@ def _config_from_file(filename, config=None): with open(filename, 'w') as fdesc: fdesc.write(json.dumps(new_config)) except IOError as error: - _LOGGER.error('Saving config file failed: %s', error) + _LOGGER.error("Saving config file failed: %s", error) return False return True else: @@ -88,7 +88,7 @@ def _config_from_file(filename, config=None): except ValueError as error: return {} except IOError as error: - _LOGGER.error('Reading config file failed: %s', error) + _LOGGER.error("Reading config file failed: %s", error) # This won't work yet return False else: @@ -135,13 +135,13 @@ def setup_bravia(config, pin, hass, add_devices): request_id = _CONFIGURING.pop(host) configurator = get_component('configurator') configurator.request_done(request_id) - _LOGGER.info('Discovery configuration done!') + _LOGGER.info("Discovery configuration done") # Save config if not _config_from_file( hass.config.path(BRAVIA_CONFIG_FILE), {host: {'pin': pin, 'host': host, 'mac': mac}}): - _LOGGER.error('failed to save config file') + _LOGGER.error("Failed to save configuration file") add_devices([BraviaTVDevice(host, mac, name, pin)]) @@ -160,7 +160,7 @@ def request_configuration(config, hass, add_devices): return def bravia_configuration_callback(data): - """Callback after user enter PIN.""" + """Handle the entry of user PIN.""" from braviarc import braviarc pin = data.get('pin') diff --git a/homeassistant/components/media_player/cast.py b/homeassistant/components/media_player/cast.py index 148cdee1d48..e4ecd1bd37d 100644 --- a/homeassistant/components/media_player/cast.py +++ b/homeassistant/components/media_player/cast.py @@ -43,10 +43,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the cast platform.""" + """Set up the cast platform.""" import pychromecast - # import CEC IGNORE attributes + # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) hosts = [] @@ -68,8 +68,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): casts = [] - # get_chromecasts() returns Chromecast objects - # with the correct friendly name for grouped devices + # get_chromecasts() returns Chromecast objects with the correct friendly + # name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: @@ -204,7 +204,7 @@ class CastDevice(MediaPlayerDevice): @property def media_series_title(self): - """The title of the series of current playing media (TV Show only).""" + """Return the title of the series of current playing media.""" return self.media_status.series_title if self.media_status else None @property @@ -310,12 +310,12 @@ class CastDevice(MediaPlayerDevice): # Implementation of chromecast status_listener methods def new_cast_status(self, status): - """Called when a new cast status is received.""" + """Handle updates of the cast status.""" self.cast_status = status self.schedule_update_ha_state() def new_media_status(self, status): - """Called when a new media status is received.""" + """Handle updates of the media status.""" self.media_status = status self.media_status_received = dt_util.utcnow() self.schedule_update_ha_state() diff --git a/homeassistant/components/media_player/clementine.py b/homeassistant/components/media_player/clementine.py index e85019b7991..d9688badcd1 100644 --- a/homeassistant/components/media_player/clementine.py +++ b/homeassistant/components/media_player/clementine.py @@ -28,6 +28,7 @@ SCAN_INTERVAL = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Clementine Remote' +DEFAULT_PORT = 5500 SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \ SUPPORT_PREVIOUS_TRACK | SUPPORT_VOLUME_SET | \ @@ -35,19 +36,22 @@ SUPPORT_CLEMENTINE = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \ SUPPORT_SELECT_SOURCE | SUPPORT_PLAY PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_PORT, default=5500): cv.positive_int, vol.Optional(CONF_ACCESS_TOKEN, default=None): cv.positive_int, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, }) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Clementine platform.""" + """Set up the Clementine platform.""" from clementineremote import ClementineRemote - client = ClementineRemote(config.get(CONF_HOST), config.get(CONF_PORT), - config.get(CONF_ACCESS_TOKEN), reconnect=True) + host = config.get(CONF_HOST) + port = config.get(CONF_PORT) + token = config.get(CONF_ACCESS_TOKEN) + + client = ClementineRemote(host, port, token, reconnect=True) add_devices([ClementineDevice(client, config[CONF_NAME])]) diff --git a/homeassistant/components/media_player/cmus.py b/homeassistant/components/media_player/cmus.py index 136d26974fe..aefe5bced18 100644 --- a/homeassistant/components/media_player/cmus.py +++ b/homeassistant/components/media_player/cmus.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discover_info=None): - """Setup the CMUS platform.""" + """Set up the CMUS platform.""" from pycmus import exceptions host = config.get(CONF_HOST) @@ -166,7 +166,7 @@ class CmusDevice(MediaPlayerDevice): self.cmus.set_volume(int(volume * 100)) def volume_up(self): - """Function to send CMUS the command for volume up.""" + """Set the volume up.""" left = self.status['set'].get('vol_left') right = self.status['set'].get('vol_right') if left != right: @@ -178,7 +178,7 @@ class CmusDevice(MediaPlayerDevice): self.cmus.set_volume(int(current_volume) + 5) def volume_down(self): - """Function to send CMUS the command for volume down.""" + """Set the volume down.""" left = self.status['set'].get('vol_left') right = self.status['set'].get('vol_right') if left != right: diff --git a/homeassistant/components/media_player/demo.py b/homeassistant/components/media_player/demo.py index 0319ccf98b3..9e4e912f314 100644 --- a/homeassistant/components/media_player/demo.py +++ b/homeassistant/components/media_player/demo.py @@ -16,7 +16,7 @@ import homeassistant.util.dt as dt_util # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the media player demo platform.""" + """Set up the media player demo platform.""" add_devices([ DemoYoutubePlayer( 'Living Room', 'eyU3bRy2x44', diff --git a/homeassistant/components/media_player/denon.py b/homeassistant/components/media_player/denon.py index 4b3347a832a..08e08dd1650 100755 --- a/homeassistant/components/media_player/denon.py +++ b/homeassistant/components/media_player/denon.py @@ -50,7 +50,7 @@ MEDIA_MODES = {'Tuner': 'TUNER', 'Media server': 'SERVER', def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Denon platform.""" + """Set up the Denon platform.""" denon = DenonDevice(config.get(CONF_NAME), config.get(CONF_HOST)) if denon.update(): @@ -101,7 +101,7 @@ class DenonDevice(MediaPlayerDevice): @classmethod def telnet_request(cls, telnet, command, all_lines=False): """Execute `command` and return the response.""" - _LOGGER.debug('Sending: "%s"', command) + _LOGGER.debug("Sending: %s", command) telnet.write(command.encode('ASCII') + b'\r') lines = [] while True: @@ -109,7 +109,7 @@ class DenonDevice(MediaPlayerDevice): if not line: break lines.append(line.decode('ASCII').strip()) - _LOGGER.debug('Recived: "%s"', line) + _LOGGER.debug("Recived: %s", line) if all_lines: return lines @@ -118,7 +118,7 @@ class DenonDevice(MediaPlayerDevice): def telnet_command(self, command): """Establish a telnet connection and sends `command`.""" telnet = telnetlib.Telnet(self._host) - _LOGGER.debug('Sending: "%s"', command) + _LOGGER.debug("Sending: %s", command) telnet.write(command.encode('ASCII') + b'\r') telnet.read_very_eager() # skip response telnet.close() @@ -179,17 +179,17 @@ class DenonDevice(MediaPlayerDevice): @property def is_volume_muted(self): - """Boolean if volume is currently muted.""" + """Return boolean if volume is currently muted.""" return self._muted @property def source_list(self): - """List of available input sources.""" + """Return the list of available input sources.""" return sorted(list(self._source_list.keys())) @property def media_title(self): - """Current media info.""" + """Return the current media info.""" return self._mediainfo @property diff --git a/homeassistant/components/media_player/denonavr.py b/homeassistant/components/media_player/denonavr.py index 0b54bbe5d5a..494a3f69e6d 100644 --- a/homeassistant/components/media_player/denonavr.py +++ b/homeassistant/components/media_player/denonavr.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Denon platform.""" + """Set up the Denon platform.""" import denonavr # Initialize list with receivers to be started @@ -116,9 +116,7 @@ class DenonDevice(MediaPlayerDevice): def update(self): """Get the latest status information from device.""" - # Update denonavr self._receiver.update() - # Refresh own data self._name = self._receiver.name self._muted = self._receiver.muted self._volume = self._receiver.volume @@ -146,7 +144,7 @@ class DenonDevice(MediaPlayerDevice): @property def is_volume_muted(self): - """Boolean if volume is currently muted.""" + """Return boolean if volume is currently muted.""" return self._muted @property @@ -163,7 +161,7 @@ class DenonDevice(MediaPlayerDevice): @property def source_list(self): - """List of available input sources.""" + """Return a list of available input sources.""" return self._source_list @property diff --git a/homeassistant/components/media_player/directv.py b/homeassistant/components/media_player/directv.py index ef3333d4da3..c1b690bc370 100644 --- a/homeassistant/components/media_player/directv.py +++ b/homeassistant/components/media_player/directv.py @@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the DirecTV platform.""" + """Set up the DirecTV platform.""" hosts = [] if discovery_info: @@ -94,13 +94,13 @@ class DirecTvDevice(MediaPlayerDevice): """Return the state of the device.""" if self._is_standby: return STATE_OFF - # haven't determined a way to see if the content is paused + # Haven't determined a way to see if the content is paused else: return STATE_PLAYING @property def media_content_id(self): - """Content ID of current playing media.""" + """Return the content ID of current playing media.""" if self._is_standby: return None else: @@ -108,7 +108,7 @@ class DirecTvDevice(MediaPlayerDevice): @property def media_duration(self): - """Duration of current playing media in seconds.""" + """Return the duration of current playing media in seconds.""" if self._is_standby: return None else: @@ -116,7 +116,7 @@ class DirecTvDevice(MediaPlayerDevice): @property def media_title(self): - """Title of current playing media.""" + """Return the title of current playing media.""" if self._is_standby: return None else: @@ -124,7 +124,7 @@ class DirecTvDevice(MediaPlayerDevice): @property def media_series_title(self): - """Title of current episode of TV show.""" + """Return the title of current episode of TV show.""" if self._is_standby: return None else: @@ -140,7 +140,7 @@ class DirecTvDevice(MediaPlayerDevice): @property def media_content_type(self): - """Content type of current playing media.""" + """Return the content type of current playing media.""" if 'episodeTitle' in self._current: return MEDIA_TYPE_TVSHOW else: @@ -148,38 +148,38 @@ class DirecTvDevice(MediaPlayerDevice): @property def media_channel(self): - """Channel current playing media.""" + """Return the channel current playing media.""" if self._is_standby: return None else: - chan = "{} ({})".format(self._current['callsign'], - self._current['major']) + chan = "{} ({})".format( + self._current['callsign'], self._current['major']) return chan def turn_on(self): - """Turn on the reciever.""" + """Turn on the receiver.""" self.dtv.key_press('poweron') def turn_off(self): - """Turn off the reciever.""" + """Turn off the receiver.""" self.dtv.key_press('poweroff') def media_play(self): - """Send play commmand.""" + """Send play command.""" self.dtv.key_press('play') def media_pause(self): - """Send pause commmand.""" + """Send pause command.""" self.dtv.key_press('pause') def media_stop(self): - """Send stop commmand.""" + """Send stop command.""" self.dtv.key_press('stop') def media_previous_track(self): - """Send rewind commmand.""" + """Send rewind command.""" self.dtv.key_press('rew') def media_next_track(self): - """Send fast forward commmand.""" + """Send fast forward command.""" self.dtv.key_press('ffwd') diff --git a/homeassistant/components/media_player/dunehd.py b/homeassistant/components/media_player/dunehd.py index 4ff1d57c558..9e63fd6d21c 100644 --- a/homeassistant/components/media_player/dunehd.py +++ b/homeassistant/components/media_player/dunehd.py @@ -48,7 +48,7 @@ class DuneHDPlayerEntity(MediaPlayerDevice): """Implementation of the Dune HD player.""" def __init__(self, player, name, sources): - """Setup entity to control Dune HD.""" + """Initialize entity to control Dune HD.""" self._player = player self._name = name self._sources = sources @@ -83,17 +83,17 @@ class DuneHDPlayerEntity(MediaPlayerDevice): @property def volume_level(self): - """Volume level of the media player (0..1).""" + """Return the volume level of the media player (0..1).""" return int(self._state.get('playback_volume', 0)) / 100 @property def is_volume_muted(self): - """Boolean if volume is currently muted.""" + """Return a boolean if volume is currently muted.""" return int(self._state.get('playback_mute', 0)) == 1 @property def source_list(self): - """List of available input sources.""" + """Return a list of available input sources.""" return list(self._sources.keys()) @property diff --git a/homeassistant/components/media_player/emby.py b/homeassistant/components/media_player/emby.py index 3ed6d42e76a..27616b1c265 100644 --- a/homeassistant/components/media_player/emby.py +++ b/homeassistant/components/media_player/emby.py @@ -52,7 +52,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Emby platform.""" + """Set up the Emby platform.""" from pyemby import EmbyServer host = config.get(CONF_HOST) @@ -64,7 +64,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): if port is None: port = DEFAULT_SSL_PORT if ssl else DEFAULT_PORT - _LOGGER.debug('Setting up Emby server at: %s:%s', host, port) + _LOGGER.debug("Setting up Emby server at: %s:%s", host, port) emby = EmbyServer(host, key, port, ssl, hass.loop) @@ -93,12 +93,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): add.set_hidden(False) if new_devices: - _LOGGER.debug("Adding new devices to HASS: %s", new_devices) + _LOGGER.debug("Adding new devices: %s", new_devices) async_add_devices(new_devices, update_before_add=True) @callback def device_removal_callback(data): - """Callback for when devices are removed from emby.""" + """Handle the removal of devices from Emby.""" if data in active_emby_devices: rem = active_emby_devices.pop(data) inactive_emby_devices[data] = rem @@ -109,12 +109,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): @callback def start_emby(event): - """Start emby connection.""" + """Start Emby connection.""" emby.start() @asyncio.coroutine def stop_emby(event): - """Stop emby connection.""" + """Stop Emby connection.""" yield from emby.stop() emby.add_new_devices_callback(device_update_callback) @@ -129,7 +129,7 @@ class EmbyDevice(MediaPlayerDevice): def __init__(self, emby, device_id): """Initialize the Emby device.""" - _LOGGER.debug('New Emby Device initialized with ID: %s', device_id) + _LOGGER.debug("New Emby Device initialized with ID: %s", device_id) self.emby = emby self.device_id = device_id self.device = self.emby.devices[self.device_id] @@ -143,12 +143,12 @@ class EmbyDevice(MediaPlayerDevice): @asyncio.coroutine def async_added_to_hass(self): """Register callback.""" - self.emby.add_update_callback(self.async_update_callback, - self.device_id) + self.emby.add_update_callback( + self.async_update_callback, self.device_id) @callback def async_update_callback(self, msg): - """Callback for device updates.""" + """Handle device updates.""" # Check if we should update progress if self.device.media_position: if self.device.media_position != self.media_status_last_position: diff --git a/homeassistant/components/media_player/firetv.py b/homeassistant/components/media_player/firetv.py index 237faddaaea..fbf1d1fd03b 100644 --- a/homeassistant/components/media_player/firetv.py +++ b/homeassistant/components/media_player/firetv.py @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the FireTV platform.""" + """Set up the FireTV platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -52,13 +52,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): response = requests.get(DEVICE_LIST_URL.format(host, port)).json() if device_id in response[CONF_DEVICES].keys(): add_devices([FireTVDevice(host, port, device_id, name)]) - _LOGGER.info('Device %s accessible and ready for control', + _LOGGER.info("Device %s accessible and ready for control", device_id) else: - _LOGGER.warning('Device %s is not registered with firetv-server', + _LOGGER.warning("Device %s is not registered with firetv-server", device_id) except requests.exceptions.RequestException: - _LOGGER.error('Could not connect to firetv-server at %s', host) + _LOGGER.error("Could not connect to firetv-server at %s", host) class FireTV(object): @@ -88,7 +88,7 @@ class FireTV(object): return response.get('state', STATE_UNKNOWN) except requests.exceptions.RequestException: _LOGGER.error( - 'Could not retrieve device state for %s', self.device_id) + "Could not retrieve device state for %s", self.device_id) return STATE_UNKNOWN def action(self, action_id): @@ -98,7 +98,7 @@ class FireTV(object): self.host, self.port, self.device_id, action_id), timeout=10) except requests.exceptions.RequestException: _LOGGER.error( - 'Action request for %s was not accepted for device %s', + "Action request for %s was not accepted for device %s", action_id, self.device_id) diff --git a/homeassistant/components/media_player/gpmdp.py b/homeassistant/components/media_player/gpmdp.py index ca79d0a7f35..6bf5c684697 100644 --- a/homeassistant/components/media_player/gpmdp.py +++ b/homeassistant/components/media_player/gpmdp.py @@ -79,8 +79,8 @@ def request_configuration(hass, config, url, add_devices_callback): 'arguments': ['Home Assistant', pin]})) tmpmsg = json.loads(websocket.recv()) if tmpmsg['channel'] == 'time': - _LOGGER.error('Error setting up GPMDP. Please pause' - ' the desktop player and try again.') + _LOGGER.error("Error setting up GPMDP. Please pause " + "the desktop player and try again") break code = tmpmsg['payload'] if code == 'CODE_REQUIRED': @@ -106,7 +106,7 @@ def request_configuration(hass, config, url, add_devices_callback): def setup_gpmdp(hass, config, code, add_devices): - """Setup gpmdp.""" + """Set up gpmdp.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) diff --git a/homeassistant/components/media_player/gstreamer.py b/homeassistant/components/media_player/gstreamer.py index f9c20c4d4ea..064ca68ea95 100644 --- a/homeassistant/components/media_player/gstreamer.py +++ b/homeassistant/components/media_player/gstreamer.py @@ -36,7 +36,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Gstreamer platform.""" + """Set up the Gstreamer platform.""" from gsp import GstreamerPlayer name = config.get(CONF_NAME) pipeline = config.get(CONF_PIPELINE) diff --git a/homeassistant/components/media_player/hdmi_cec.py b/homeassistant/components/media_player/hdmi_cec.py index aa3b44e9e90..7054c83d36a 100644 --- a/homeassistant/components/media_player/hdmi_cec.py +++ b/homeassistant/components/media_player/hdmi_cec.py @@ -134,7 +134,7 @@ class CecPlayerDevice(CecDevice, MediaPlayerDevice): @property def state(self) -> str: - """Cached state of device.""" + """Cache state of device.""" return self._state def _update(self, device=None): diff --git a/homeassistant/components/media_player/itunes.py b/homeassistant/components/media_player/itunes.py index ab7d89e9b2a..514bf24a21a 100644 --- a/homeassistant/components/media_player/itunes.py +++ b/homeassistant/components/media_player/itunes.py @@ -154,7 +154,7 @@ class Itunes(object): def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the iTunes platform.""" + """Set up the iTunes platform.""" add_devices([ ItunesDevice( config.get(CONF_NAME), diff --git a/homeassistant/components/media_player/kodi.py b/homeassistant/components/media_player/kodi.py index 9993ed2cdc6..10d13002625 100644 --- a/homeassistant/components/media_player/kodi.py +++ b/homeassistant/components/media_player/kodi.py @@ -47,17 +47,17 @@ TURN_OFF_ACTION = [None, 'quit', 'hibernate', 'suspend', 'reboot', 'shutdown'] # https://github.com/xbmc/xbmc/blob/master/xbmc/media/MediaType.h MEDIA_TYPES = { - "music": MEDIA_TYPE_MUSIC, - "artist": MEDIA_TYPE_MUSIC, - "album": MEDIA_TYPE_MUSIC, - "song": MEDIA_TYPE_MUSIC, - "video": MEDIA_TYPE_VIDEO, - "set": MEDIA_TYPE_PLAYLIST, - "musicvideo": MEDIA_TYPE_VIDEO, - "movie": MEDIA_TYPE_VIDEO, - "tvshow": MEDIA_TYPE_TVSHOW, - "season": MEDIA_TYPE_TVSHOW, - "episode": MEDIA_TYPE_TVSHOW, + 'music': MEDIA_TYPE_MUSIC, + 'artist': MEDIA_TYPE_MUSIC, + 'album': MEDIA_TYPE_MUSIC, + 'song': MEDIA_TYPE_MUSIC, + 'video': MEDIA_TYPE_VIDEO, + 'set': MEDIA_TYPE_PLAYLIST, + 'musicvideo': MEDIA_TYPE_VIDEO, + 'movie': MEDIA_TYPE_VIDEO, + 'tvshow': MEDIA_TYPE_TVSHOW, + 'season': MEDIA_TYPE_TVSHOW, + 'episode': MEDIA_TYPE_TVSHOW, } SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ @@ -161,11 +161,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): def cmd(func): - """Decorator to catch command exceptions.""" + """Catch command exceptions.""" @wraps(func) @asyncio.coroutine def wrapper(obj, *args, **kwargs): - """Wrapper for all command methods.""" + """Wrap all command methods.""" import jsonrpc_base try: yield from func(obj, *args, **kwargs) @@ -245,7 +245,7 @@ class KodiDevice(MediaPlayerDevice): @callback def async_on_speed_event(self, sender, data): - """Called when player changes between playing and paused.""" + """Handle player changes between playing and paused.""" self._properties['speed'] = data['player']['speed'] if not hasattr(data['item'], 'id'): @@ -259,7 +259,7 @@ class KodiDevice(MediaPlayerDevice): @callback def async_on_stop(self, sender, data): - """Called when the player stops playback.""" + """Handle the stop of the player playback.""" # Prevent stop notifications which are sent after quit notification if self._players is None: return @@ -271,14 +271,14 @@ class KodiDevice(MediaPlayerDevice): @callback def async_on_volume_changed(self, sender, data): - """Called when the volume is changed.""" + """Handle the volume changes.""" self._app_properties['volume'] = data['volume'] self._app_properties['muted'] = data['muted'] self.hass.async_add_job(self.async_update_ha_state()) @callback def async_on_quit(self, sender, data): - """Called when the volume is changed.""" + """Handle the muted volume.""" self._players = None self._properties = {} self._item = {} @@ -293,8 +293,8 @@ class KodiDevice(MediaPlayerDevice): return (yield from self.server.Player.GetActivePlayers()) except jsonrpc_base.jsonrpc.TransportError: if self._players is not None: - _LOGGER.info('Unable to fetch kodi data') - _LOGGER.debug('Unable to fetch kodi data', exc_info=True) + _LOGGER.info("Unable to fetch kodi data") + _LOGGER.debug("Unable to fetch kodi data", exc_info=True) return None @property @@ -548,7 +548,7 @@ class KodiDevice(MediaPlayerDevice): @asyncio.coroutine def async_set_play_state(self, state): - """Helper method for play/pause/toggle.""" + """Handle play/pause/toggle.""" players = yield from self._get_players() if players is not None and players: @@ -590,7 +590,7 @@ class KodiDevice(MediaPlayerDevice): @asyncio.coroutine def _goto(self, direction): - """Helper method used for previous/next track.""" + """Handle for previous/next track.""" players = yield from self._get_players() if players: diff --git a/homeassistant/components/media_player/lg_netcast.py b/homeassistant/components/media_player/lg_netcast.py index 8afdf89a2e4..9e8fcbf2462 100644 --- a/homeassistant/components/media_player/lg_netcast.py +++ b/homeassistant/components/media_player/lg_netcast.py @@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the LG TV platform.""" + """Set up the LG TV platform.""" from pylgnetcast import LgNetCastClient client = LgNetCastClient( config.get(CONF_HOST), config.get(CONF_ACCESS_TOKEN)) diff --git a/homeassistant/components/media_player/liveboxplaytv.py b/homeassistant/components/media_player/liveboxplaytv.py index 52a37eb8faa..eef5a890e8e 100644 --- a/homeassistant/components/media_player/liveboxplaytv.py +++ b/homeassistant/components/media_player/liveboxplaytv.py @@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Orange Livebox Play TV platform.""" + """Set up the Orange Livebox Play TV platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) @@ -56,8 +56,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): device = LiveboxPlayTvDevice(host, port, name) livebox_devices.append(device) except IOError: - _LOGGER.error('Failed to connect to Livebox Play TV at %s:%s. ' - 'Please check your configuration.', host, port) + _LOGGER.error("Failed to connect to Livebox Play TV at %s:%s. " + "Please check your configuration", host, port) add_devices(livebox_devices, True) diff --git a/homeassistant/components/media_player/mpchc.py b/homeassistant/components/media_player/mpchc.py index 168497c4052..964c2b5d009 100644 --- a/homeassistant/components/media_player/mpchc.py +++ b/homeassistant/components/media_player/mpchc.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the MPC-HC platform.""" + """Set up the MPC-HC platform.""" name = config.get(CONF_NAME) url = '{}:{}'.format(config.get(CONF_HOST), config.get(CONF_PORT)) @@ -59,8 +59,8 @@ class MpcHcDevice(MediaPlayerDevice): self._player_variables = dict() try: - response = requests.get('{}/variables.html'.format(self._url), - data=None, timeout=3) + response = requests.get( + '{}/variables.html'.format(self._url), data=None, timeout=3) mpchc_variables = re.findall(r'

(.+?)

', response.text) @@ -102,24 +102,24 @@ class MpcHcDevice(MediaPlayerDevice): @property def media_title(self): - """Title of current playing media.""" + """Return the title of current playing media.""" return self._player_variables.get('file', None) @property def volume_level(self): - """Volume level of the media player (0..1).""" + """Return the volume level of the media player (0..1).""" return int(self._player_variables.get('volumelevel', 0)) / 100.0 @property def is_volume_muted(self): - """Boolean if volume is currently muted.""" + """Return boolean if volume is currently muted.""" return self._player_variables.get('muted', '0') == '1' @property def media_duration(self): - """Duration of current playing media in seconds.""" - duration = self._player_variables.get('durationstring', - "00:00:00").split(':') + """Return the duration of the current playing media in seconds.""" + duration = self._player_variables.get( + 'durationstring', "00:00:00").split(':') return \ int(duration[0]) * 3600 + \ int(duration[1]) * 60 + \ diff --git a/homeassistant/components/media_player/mpd.py b/homeassistant/components/media_player/mpd.py index f6891d23f3f..572898dd60a 100644 --- a/homeassistant/components/media_player/mpd.py +++ b/homeassistant/components/media_player/mpd.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the MPD platform.""" + """Set up the MPD platform.""" daemon = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) @@ -136,23 +136,23 @@ class MpdDevice(MediaPlayerDevice): @property def media_content_id(self): - """Content ID of current playing media.""" + """Return the content ID of current playing media.""" return self.currentsong.get('file') @property def media_content_type(self): - """Content type of current playing media.""" + """Return the content type of current playing media.""" return MEDIA_TYPE_MUSIC @property def media_duration(self): - """Duration of current playing media in seconds.""" + """Return the duration of current playing media in seconds.""" # Time does not exist for streams return self.currentsong.get('time') @property def media_title(self): - """Title of current playing media.""" + """Return the title of current playing media.""" name = self.currentsong.get('name', None) title = self.currentsong.get('title', None) @@ -167,12 +167,12 @@ class MpdDevice(MediaPlayerDevice): @property def media_artist(self): - """Artist of current playing media (Music track only).""" + """Return the artist of current playing media (Music track only).""" return self.currentsong.get('artist') @property def media_album_name(self): - """Album of current playing media (Music track only).""" + """Return the album of current playing media (Music track only).""" return self.currentsong.get('album') @property @@ -192,7 +192,7 @@ class MpdDevice(MediaPlayerDevice): @property def source_list(self): - """List of available input sources.""" + """Return the list of available input sources.""" return self.playlists def select_source(self, source): diff --git a/homeassistant/components/media_player/nad.py b/homeassistant/components/media_player/nad.py index 332aed4a839..c1b7b867c3b 100644 --- a/homeassistant/components/media_player/nad.py +++ b/homeassistant/components/media_player/nad.py @@ -49,7 +49,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the NAD platform.""" + """Set up the NAD platform.""" from nad_receiver import NADReceiver add_devices([NAD( config.get(CONF_NAME), diff --git a/homeassistant/components/media_player/onkyo.py b/homeassistant/components/media_player/onkyo.py index 67197d7d0da..18690cca871 100644 --- a/homeassistant/components/media_player/onkyo.py +++ b/homeassistant/components/media_player/onkyo.py @@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Onkyo platform.""" + """Set up the Onkyo platform.""" import eiscp from eiscp import eISCP @@ -52,12 +52,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if CONF_HOST in config and host not in KNOWN_HOSTS: try: - hosts.append(OnkyoDevice(eiscp.eISCP(host), - config.get(CONF_SOURCES), - name=config.get(CONF_NAME))) + hosts.append(OnkyoDevice( + eiscp.eISCP(host), config.get(CONF_SOURCES), + name=config.get(CONF_NAME))) KNOWN_HOSTS.append(host) except OSError: - _LOGGER.error('Unable to connect to receiver at %s.', host) + _LOGGER.error("Unable to connect to receiver at %s", host) else: for receiver in eISCP.discover(): if receiver.host not in KNOWN_HOSTS: @@ -90,9 +90,9 @@ class OnkyoDevice(MediaPlayerDevice): except (ValueError, OSError, AttributeError, AssertionError): if self._receiver.command_socket: self._receiver.command_socket = None - _LOGGER.info('Resetting connection to %s.', self._name) + _LOGGER.info("Resetting connection to %s", self._name) else: - _LOGGER.info('%s is disconnected. Attempting to reconnect.', + _LOGGER.info("%s is disconnected. Attempting to reconnect", self._name) return False return result @@ -142,7 +142,7 @@ class OnkyoDevice(MediaPlayerDevice): @property def volume_level(self): - """Volume level of the media player (0..1).""" + """Return the volume level of the media player (0..1).""" return self._volume @property @@ -157,7 +157,7 @@ class OnkyoDevice(MediaPlayerDevice): @property def source(self): - """"Return the current input source of the device.""" + """Return the current input source of the device.""" return self._current_source @property diff --git a/homeassistant/components/media_player/openhome.py b/homeassistant/components/media_player/openhome.py index c70822381a4..ab061eb5fa4 100644 --- a/homeassistant/components/media_player/openhome.py +++ b/homeassistant/components/media_player/openhome.py @@ -22,13 +22,12 @@ SUPPORT_OPENHOME = SUPPORT_SELECT_SOURCE | \ _LOGGER = logging.getLogger(__name__) -# List of devices that have been registered DEVICES = [] # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Openhome Platform.""" + """Set up the Openhome platform.""" from openhomedevice.Device import Device if not discovery_info: @@ -36,7 +35,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): name = discovery_info.get('name') description = discovery_info.get('ssdp_description') - _LOGGER.info('Openhome device found, (%s)', name) + _LOGGER.info('Openhome device found: %s', name) device = Device(description) # if device has already been discovered diff --git a/homeassistant/components/media_player/panasonic_viera.py b/homeassistant/components/media_player/panasonic_viera.py index a5f9979d2d4..8c946ec0f0f 100644 --- a/homeassistant/components/media_player/panasonic_viera.py +++ b/homeassistant/components/media_player/panasonic_viera.py @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Panasonic Viera TV platform.""" + """Set up the Panasonic Viera TV platform.""" from panasonic_viera import RemoteControl mac = config.get(CONF_MAC) diff --git a/homeassistant/components/media_player/pandora.py b/homeassistant/components/media_player/pandora.py index f742618822a..2ea94885620 100644 --- a/homeassistant/components/media_player/pandora.py +++ b/homeassistant/components/media_player/pandora.py @@ -46,12 +46,12 @@ STATION_PATTERN = re.compile(r'Station\s"(.+?)"', re.MULTILINE) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the media player pandora platform.""" + """Set up the Pandora media player platform.""" if not _pianobar_exists(): return False pandora = PandoraMediaPlayer('Pandora') - # make sure we end the pandora subprocess on exit in case user doesn't + # Make sure we end the pandora subprocess on exit in case user doesn't # power it down. def _stop_pianobar(_event): pandora.turn_off() @@ -98,7 +98,7 @@ class PandoraMediaPlayer(MediaPlayerDevice): if self._player_state != STATE_OFF: return self._pianobar = pexpect.spawn('pianobar') - _LOGGER.info('Started pianobar subprocess') + _LOGGER.info("Started pianobar subprocess") mode = self._pianobar.expect(['Receiving new playlist', 'Select station:', 'Email:']) @@ -106,10 +106,10 @@ class PandoraMediaPlayer(MediaPlayerDevice): # station list was presented. dismiss it. self._pianobar.sendcontrol('m') elif mode == 2: - _LOGGER.warning('The pianobar client is not configured to log in. ' - 'Please create a config file for it as described ' - 'at https://home-assistant.io' - '/components/media_player.pandora/') + _LOGGER.warning( + "The pianobar client is not configured to log in. " + "Please create a config file for it as described at " + "https://home-assistant.io/components/media_player.pandora/") # pass through the email/password prompts to quit cleanly self._pianobar.sendcontrol('m') self._pianobar.sendcontrol('m') @@ -126,16 +126,16 @@ class PandoraMediaPlayer(MediaPlayerDevice): """Turn the media player off.""" import pexpect if self._pianobar is None: - _LOGGER.info('Pianobar subprocess already stopped') + _LOGGER.info("Pianobar subprocess already stopped") return self._pianobar.send('q') try: - _LOGGER.info('Stopped Pianobar subprocess') + _LOGGER.debug("Stopped Pianobar subprocess") self._pianobar.terminate() except pexpect.exceptions.TIMEOUT: # kill the process group os.killpg(os.getpgid(self._pianobar.pid), signal.SIGTERM) - _LOGGER.info('Killed Pianobar subprocess') + _LOGGER.debug("Killed Pianobar subprocess") self._pianobar = None self._player_state = STATE_OFF self.schedule_update_ha_state() @@ -203,9 +203,9 @@ class PandoraMediaPlayer(MediaPlayerDevice): try: station_index = self._stations.index(source) except ValueError: - _LOGGER.warning('Station `%s` is not in list', source) + _LOGGER.warning("Station %s is not in list", source) return - _LOGGER.info('Setting station %s, %d', source, station_index) + _LOGGER.debug("Setting station %s, %d", source, station_index) self._send_station_list_command() self._pianobar.sendline('{}'.format(station_index)) self._pianobar.expect('\r\n') @@ -243,7 +243,7 @@ class PandoraMediaPlayer(MediaPlayerDevice): 'Select station', 'Receiving new playlist']) except pexpect.exceptions.EOF: - _LOGGER.info('Pianobar process already exited.') + _LOGGER.info("Pianobar process already exited") return None self._log_match() @@ -252,12 +252,12 @@ class PandoraMediaPlayer(MediaPlayerDevice): response = None elif match_idx == 2: # stuck on a station selection dialog. Clear it. - _LOGGER.warning('On unexpected station list page.') + _LOGGER.warning("On unexpected station list page") self._pianobar.sendcontrol('m') # press enter self._pianobar.sendcontrol('m') # do it again b/c an 'i' got in response = self.update_playing_status() elif match_idx == 3: - _LOGGER.debug('Received new playlist list.') + _LOGGER.debug("Received new playlist list") response = self.update_playing_status() else: response = self._pianobar.before.decode('utf-8') @@ -268,9 +268,9 @@ class PandoraMediaPlayer(MediaPlayerDevice): station_match = re.search(STATION_PATTERN, response) if station_match: self._station = station_match.group(1) - _LOGGER.debug('Got station as: %s', self._station) + _LOGGER.debug("Got station as: %s", self._station) else: - _LOGGER.warning('No station match. ') + _LOGGER.warning("No station match") def _update_current_song(self, response): """Update info about current song.""" @@ -278,9 +278,9 @@ class PandoraMediaPlayer(MediaPlayerDevice): if song_match: (self._media_title, self._media_artist, self._media_album) = song_match.groups() - _LOGGER.debug('Got song as: %s', self._media_title) + _LOGGER.debug("Got song as: %s", self._media_title) else: - _LOGGER.warning('No song match.') + _LOGGER.warning("No song match") @util.Throttle(MIN_TIME_BETWEEN_UPDATES) def _update_song_position(self): @@ -305,7 +305,7 @@ class PandoraMediaPlayer(MediaPlayerDevice): def _log_match(self): """Log grabbed values from console.""" - _LOGGER.debug('Before: %s\nMatch: %s\nAfter: %s', + _LOGGER.debug("Before: %s\nMatch: %s\nAfter: %s", repr(self._pianobar.before), repr(self._pianobar.match), repr(self._pianobar.after)) @@ -313,10 +313,10 @@ class PandoraMediaPlayer(MediaPlayerDevice): def _send_pianobar_command(self, service_cmd): """Send a command to Pianobar.""" command = CMD_MAP.get(service_cmd) - _LOGGER.debug('Sending pinaobar command %s for %s', - command, service_cmd) + _LOGGER.debug( + "Sending pinaobar command %s for %s", command, service_cmd) if command is None: - _LOGGER.info('Command %s not supported yet', service_cmd) + _LOGGER.info("Command %s not supported yet", service_cmd) self._clear_buffer() self._pianobar.sendline(command) @@ -324,16 +324,16 @@ class PandoraMediaPlayer(MediaPlayerDevice): """List defined Pandora stations.""" self._send_station_list_command() station_lines = self._pianobar.before.decode('utf-8') - _LOGGER.debug('Getting stations: %s', station_lines) + _LOGGER.debug("Getting stations: %s", station_lines) self._stations = [] for line in station_lines.split('\r\n'): match = re.search(r'\d+\).....(.+)', line) if match: station = match.group(1).strip() - _LOGGER.debug('Found station %s', station) + _LOGGER.debug("Found station %s", station) self._stations.append(station) else: - _LOGGER.debug('No station match on `%s`', line) + _LOGGER.debug("No station match on %s", line) self._pianobar.sendcontrol('m') # press enter with blank line self._pianobar.sendcontrol('m') # do it twice in case an 'i' got in @@ -360,9 +360,8 @@ def _pianobar_exists(): if pianobar_exe: return True else: - _LOGGER.warning('The Pandora component depends on the Pianobar ' - 'client, which cannot be found. Please install ' - 'using instructions at' - 'https://home-assistant.io' - '/components/media_player.pandora/') + _LOGGER.warning( + "The Pandora component depends on the Pianobar client, which " + "cannot be found. Please install using instructions at " + "https://home-assistant.io/components/media_player.pandora/") return False diff --git a/homeassistant/components/media_player/philips_js.py b/homeassistant/components/media_player/philips_js.py index a4d3b02381a..b79f3eeeb89 100644 --- a/homeassistant/components/media_player/philips_js.py +++ b/homeassistant/components/media_player/philips_js.py @@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Philips TV platform.""" + """Set up the Philips TV platform.""" import haphilipsjs name = config.get(CONF_NAME) diff --git a/homeassistant/components/media_player/pioneer.py b/homeassistant/components/media_player/pioneer.py index 73f0d18f597..eb346502d95 100644 --- a/homeassistant/components/media_player/pioneer.py +++ b/homeassistant/components/media_player/pioneer.py @@ -40,11 +40,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Pioneer platform.""" - pioneer = PioneerDevice(config.get(CONF_NAME), - config.get(CONF_HOST), - config.get(CONF_PORT), - config.get(CONF_TIMEOUT)) + """Set up the Pioneer platform.""" + pioneer = PioneerDevice( + config.get(CONF_NAME), config.get(CONF_HOST), config.get(CONF_PORT), + config.get(CONF_TIMEOUT)) if pioneer.update(): add_devices([pioneer]) @@ -126,9 +125,8 @@ class PioneerDevice(MediaPlayerDevice): # Build the source name dictionaries if necessary if not self._source_name_to_number: for i in range(MAX_SOURCE_NUMBERS): - result = self.telnet_request(telnet, - "?RGB" + str(i).zfill(2), - "RGB") + result = self.telnet_request( + telnet, "?RGB" + str(i).zfill(2), "RGB") if not result: continue diff --git a/homeassistant/components/media_player/plex.py b/homeassistant/components/media_player/plex.py index f601bf86944..e2f322a8ec8 100644 --- a/homeassistant/components/media_player/plex.py +++ b/homeassistant/components/media_player/plex.py @@ -76,7 +76,7 @@ def config_from_file(filename, config=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the Plex platform.""" + """Set up the Plex platform.""" # get config from plex.conf file_config = config_from_file(hass.config.path(PLEX_CONFIG_FILE)) @@ -100,7 +100,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_plexserver(host, token, hass, config, add_devices_callback): - """Setup a plexserver based on host parameter.""" + """Set up a plexserver based on host parameter.""" import plexapi.server import plexapi.exceptions @@ -110,8 +110,7 @@ def setup_plexserver(host, token, hass, config, add_devices_callback): plexapi.exceptions.NotFound) as error: _LOGGER.info(error) # No token or wrong token - request_configuration(host, hass, config, - add_devices_callback) + request_configuration(host, hass, config, add_devices_callback) return # If we came here and configuring this host, mark as done @@ -141,7 +140,7 @@ def setup_plexserver(host, token, hass, config, add_devices_callback): try: devices = plexserver.clients() except plexapi.exceptions.BadRequest: - _LOGGER.exception('Error listing plex devices') + _LOGGER.exception("Error listing plex devices") return except OSError: _LOGGER.error("Could not connect to plex server at http://%s", @@ -214,10 +213,9 @@ def request_configuration(host, hass, config, add_devices_callback): return def plex_configuration_callback(data): - """The actions to do when our configuration callback is called.""" - setup_plexserver(host, - data.get('token'), hass, config, - add_devices_callback) + """Handle configuration changes.""" + setup_plexserver( + host, data.get('token'), hass, config, add_devices_callback) _CONFIGURING[host] = configurator.request_config( hass, @@ -547,12 +545,12 @@ class PlexClient(MediaPlayerDevice): @property def media_content_id(self): - """Content ID of current playing media.""" + """Return the content ID of current playing media.""" return self._media_content_id @property def media_content_type(self): - """Content type of current playing media.""" + """Return the content type of current playing media.""" if self._session_type == 'clip': _LOGGER.debug("Clip content type detected, " "compatibility may vary: %s", self.entity_id) @@ -568,57 +566,57 @@ class PlexClient(MediaPlayerDevice): @property def media_artist(self): - """Artist of current playing media, music track only.""" + """Return the artist of current playing media, music track only.""" return self._media_artist @property def media_album_name(self): - """Album name of current playing media, music track only.""" + """Return the album name of current playing media, music track only.""" return self._media_album_name @property def media_album_artist(self): - """Album artist of current playing media, music track only.""" + """Return the album artist of current playing media, music only.""" return self._media_album_artist @property def media_track(self): - """Track number of current playing media, music track only.""" + """Return the track number of current playing media, music only.""" return self._media_track @property def media_duration(self): - """Duration of current playing media in seconds.""" + """Return the duration of current playing media in seconds.""" return self._media_duration @property def media_image_url(self): - """Image url of current playing media.""" + """Return the image URL of current playing media.""" return self._media_image_url @property def media_title(self): - """Title of current playing media.""" + """Return the title of current playing media.""" return self._media_title @property def media_season(self): - """Season of curent playing media (TV Show only).""" + """Return the season of current playing media (TV Show only).""" return self._media_season @property def media_series_title(self): - """The title of the series of current playing media (TV Show only).""" + """Return the title of the series of current playing media.""" return self._media_series_title @property def media_episode(self): - """Episode of current playing media (TV Show only).""" + """Return the episode of current playing media (TV Show only).""" return self._media_episode @property def make(self): - """The make of the device (ex. SHIELD Android TV).""" + """Return the make of the device (ex. SHIELD Android TV).""" return self._make @property diff --git a/homeassistant/components/media_player/roku.py b/homeassistant/components/media_player/roku.py index 8d45945eee1..97f7ba2e716 100644 --- a/homeassistant/components/media_player/roku.py +++ b/homeassistant/components/media_player/roku.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Roku platform.""" + """Set up the Roku platform.""" hosts = [] if discovery_info: @@ -48,7 +48,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if host in KNOWN_HOSTS: return - _LOGGER.debug('Discovered Roku: %s', host) + _LOGGER.debug("Discovered Roku: %s", host) hosts.append(discovery_info.get("host")) elif CONF_HOST in config: @@ -175,9 +175,8 @@ class RokuDevice(MediaPlayerDevice): elif self.current_app.id is None: return None - return 'http://{0}:{1}/query/icon/{2}'.format(self.ip_address, - DEFAULT_PORT, - self.current_app.id) + return 'http://{0}:{1}/query/icon/{2}'.format( + self.ip_address, DEFAULT_PORT, self.current_app.id) @property def app_name(self): diff --git a/homeassistant/components/media_player/russound_rnet.py b/homeassistant/components/media_player/russound_rnet.py index 7ae16adcce3..6615f85db65 100644 --- a/homeassistant/components/media_player/russound_rnet.py +++ b/homeassistant/components/media_player/russound_rnet.py @@ -4,8 +4,8 @@ Support for interfacing with Russound via RNET Protocol. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.russound_rnet/ """ - import logging + import voluptuous as vol from homeassistant.components.media_player import ( @@ -45,7 +45,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Russound RNET platform.""" + """Set up the Russound RNET platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -163,5 +163,5 @@ class RussoundRNETDevice(MediaPlayerDevice): @property def source_list(self): - """List of available input sources.""" + """Return a list of available input sources.""" return self._sources diff --git a/homeassistant/components/media_player/samsungtv.py b/homeassistant/components/media_player/samsungtv.py index c99ad49577c..0153eb687ff 100644 --- a/homeassistant/components/media_player/samsungtv.py +++ b/homeassistant/components/media_player/samsungtv.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Samsung TV platform.""" + """Set up the Samsung TV platform.""" known_devices = hass.data.get(KNOWN_DEVICES_KEY) if known_devices is None: known_devices = set() @@ -66,8 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): timeout = DEFAULT_TIMEOUT mac = None else: - _LOGGER.warning( - 'Internal error on samsungtv component. Cannot determine device') + _LOGGER.warning("Cannot determine device") return # Only add a device once, so discovered devices do not override manual diff --git a/homeassistant/components/media_player/snapcast.py b/homeassistant/components/media_player/snapcast.py index 3e06cca38a5..f893dcdeed1 100644 --- a/homeassistant/components/media_player/snapcast.py +++ b/homeassistant/components/media_player/snapcast.py @@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Snapcast platform.""" + """Set up the Snapcast platform.""" import snapcast.control host = config.get(CONF_HOST) port = config.get(CONF_PORT, snapcast.control.CONTROL_PORT) @@ -42,8 +42,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: server = snapcast.control.Snapserver(host, port) except socket.gaierror: - _LOGGER.error('Could not connect to Snapcast server at %s:%d', - host, port) + _LOGGER.error( + "Could not connect to Snapcast server at %s:%d", host, port) return False add_devices([SnapcastDevice(client) for client in server.clients]) diff --git a/homeassistant/components/media_player/sonos.py b/homeassistant/components/media_player/sonos.py index 00cc52ab3a1..da75b89c19d 100644 --- a/homeassistant/components/media_player/sonos.py +++ b/homeassistant/components/media_player/sonos.py @@ -92,7 +92,7 @@ SONOS_SET_TIMER_SCHEMA = SONOS_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Sonos platform.""" + """Set up the Sonos platform.""" import soco if DATA_SONOS not in hass.data: @@ -105,7 +105,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if discovery_info: player = soco.SoCo(discovery_info.get('host')) - # if device allready exists by config + # if device already exists by config if player.uid in [x.unique_id for x in hass.data[DATA_SONOS]]: return @@ -132,18 +132,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None): interface_addr=config.get(CONF_INTERFACE_ADDR)) if not players: - _LOGGER.warning('No Sonos speakers found.') + _LOGGER.warning("No Sonos speakers found") return hass.data[DATA_SONOS] = [SonosDevice(p) for p in players] add_devices(hass.data[DATA_SONOS], True) - _LOGGER.info('Added %s Sonos speakers', len(players)) + _LOGGER.info("Added %s Sonos speakers", len(players)) descriptions = load_yaml_config_file( path.join(path.dirname(__file__), 'services.yaml')) def service_handle(service): - """Internal func for applying a service.""" + """Handle for services.""" entity_ids = service.data.get('entity_id') if entity_ids: @@ -221,28 +221,28 @@ def _get_entity_from_soco(hass, soco): for device in hass.data[DATA_SONOS]: if soco == device.soco: return device - raise ValueError("No entity for SoCo device!") + raise ValueError("No entity for SoCo device") def soco_error(funct): - """Decorator to catch soco exceptions.""" + """Catch soco exceptions.""" @ft.wraps(funct) def wrapper(*args, **kwargs): - """Wrapper for all soco exception.""" + """Wrap for all soco exception.""" from soco.exceptions import SoCoException try: return funct(*args, **kwargs) except SoCoException as err: - _LOGGER.error("Error on %s with %s.", funct.__name__, err) + _LOGGER.error("Error on %s with %s", funct.__name__, err) return wrapper def soco_coordinator(funct): - """Decorator to call funct on coordinator.""" + """Call function on coordinator.""" @ft.wraps(funct) def wrapper(device, *args, **kwargs): - """Wrapper for call to coordinator.""" + """Wrap for call to coordinator.""" if device.is_coordinator: return funct(device, *args, **kwargs) return funct(device.coordinator, *args, **kwargs) @@ -296,7 +296,7 @@ class SonosDevice(MediaPlayerDevice): @property def should_poll(self): - """Polling needed.""" + """Return the polling state.""" return True @property @@ -340,8 +340,7 @@ class SonosDevice(MediaPlayerDevice): def _is_available(self): try: sock = socket.create_connection( - address=(self._player.ip_address, 1443), - timeout=3) + address=(self._player.ip_address, 1443), timeout=3) sock.close() return True except socket.error: diff --git a/homeassistant/components/media_player/soundtouch.py b/homeassistant/components/media_player/soundtouch.py index fb2e02494df..4827732bd21 100644 --- a/homeassistant/components/media_player/soundtouch.py +++ b/homeassistant/components/media_player/soundtouch.py @@ -1,4 +1,9 @@ -"""Support for interface with a Bose Soundtouch.""" +""" +Support for interface with a Bose Soundtouch. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/media_player.soundtouch/ +""" import logging from os import path @@ -69,14 +74,14 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Bose Soundtouch platform.""" + """Set up the Bose Soundtouch platform.""" if DATA_SOUNDTOUCH not in hass.data: hass.data[DATA_SOUNDTOUCH] = [] if discovery_info: # Discovery - host = discovery_info["host"] - port = int(discovery_info["port"]) + host = discovery_info['host'] + port = int(discovery_info['port']) # if device already exists by config if host in [device.config['host'] for device in @@ -119,8 +124,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): device.entity_id == master_device_id].__iter__(), None) if master is None: - _LOGGER.warning("Unable to find master with entity_id:" + str( - master_device_id)) + _LOGGER.warning("Unable to find master with entity_id: %s", + str(master_device_id)) return if service.service == SERVICE_PLAY_EVERYWHERE: diff --git a/homeassistant/components/media_player/spotify.py b/homeassistant/components/media_player/spotify.py index fcb54245ead..a73a4a922ca 100644 --- a/homeassistant/components/media_player/spotify.py +++ b/homeassistant/components/media_player/spotify.py @@ -4,7 +4,6 @@ Support for interacting with Spotify Connect. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.spotify/ """ - import logging from datetime import timedelta @@ -22,7 +21,6 @@ from homeassistant.const import ( CONF_NAME, STATE_PLAYING, STATE_PAUSED, STATE_IDLE, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv - COMMIT = '544614f4b1d508201d363e84e871f86c90aa26b2' REQUIREMENTS = ['https://github.com/happyleavesaoc/spotipy/' 'archive/%s.zip#spotipy==2.4.4' % COMMIT] @@ -72,7 +70,7 @@ def request_configuration(hass, config, add_devices, oauth): def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Spotify platform.""" + """Set up the Spotify platform.""" import spotipy.oauth2 callback_url = '{}{}'.format(hass.config.api.base_url, AUTH_CALLBACK_PATH) cache = config.get(CONF_CACHE_PATH, hass.config.path(DEFAULT_CACHE_PATH)) @@ -82,7 +80,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): cache_path=cache) token_info = oauth.get_cached_token() if not token_info: - _LOGGER.info('no token; requesting authorization') + _LOGGER.info("no token; requesting authorization") hass.http.register_view(SpotifyAuthCallbackView( config, add_devices, oauth)) request_configuration(hass, config, add_devices, oauth) @@ -225,31 +223,31 @@ class SpotifyMediaPlayer(MediaPlayerDevice): elif media_type == MEDIA_TYPE_PLAYLIST: kwargs['context_uri'] = media_id else: - _LOGGER.error('media type %s is not supported', media_type) + _LOGGER.error("media type %s is not supported", media_type) return if not media_id.startswith('spotify:'): - _LOGGER.error('media id must be spotify uri') + _LOGGER.error("media id must be spotify uri") return self._player.start_playback(**kwargs) @property def name(self): - """Name.""" + """Return the name.""" return self._name @property def icon(self): - """Icon.""" + """Return the icon.""" return ICON @property def state(self): - """Playback state.""" + """Return the playback state.""" return self._state @property def volume_level(self): - """Device volume.""" + """Return the device volume.""" return self._volume @property @@ -259,40 +257,40 @@ class SpotifyMediaPlayer(MediaPlayerDevice): @property def source_list(self): - """Playback devices.""" + """Return a list of source devices.""" return list(self._devices.keys()) @property def source(self): - """Current playback device.""" + """Return the current playback device.""" return self._current_device @property def media_content_id(self): - """Media URL.""" + """Return the media URL.""" return self._uri @property def media_image_url(self): - """Media image url.""" + """Return the media image URL.""" return self._image_url @property def media_artist(self): - """Media artist.""" + """Return the media artist.""" return self._artist @property def media_album_name(self): - """Media album.""" + """Return the media album.""" return self._album @property def media_title(self): - """Media title.""" + """Return the media title.""" return self._title @property def supported_features(self): - """Media player features that are supported.""" + """Return the media player features that are supported.""" return SUPPORT_SPOTIFY diff --git a/homeassistant/components/media_player/squeezebox.py b/homeassistant/components/media_player/squeezebox.py index 40c48f55215..42efe183421 100644 --- a/homeassistant/components/media_player/squeezebox.py +++ b/homeassistant/components/media_player/squeezebox.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the squeezebox platform.""" + """Set up the squeezebox platform.""" import socket username = config.get(CONF_USERNAME) @@ -65,8 +65,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): try: ipaddr = socket.gethostbyname(host) except (OSError) as error: - _LOGGER.error("Could not communicate with %s:%d: %s", - host, port, error) + _LOGGER.error( + "Could not communicate with %s:%d: %s", host, port, error) return False _LOGGER.debug("Creating LMS object for %s", ipaddr) diff --git a/homeassistant/components/media_player/universal.py b/homeassistant/components/media_player/universal.py index ba671f25f38..9709ad80c0a 100644 --- a/homeassistant/components/media_player/universal.py +++ b/homeassistant/components/media_player/universal.py @@ -51,7 +51,7 @@ _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the universal media players.""" + """Set up the universal media players.""" if not validate_config(config): return @@ -72,7 +72,7 @@ def validate_config(config): # Validate name if CONF_NAME not in config: - _LOGGER.error('Universal Media Player configuration requires name') + _LOGGER.error("Universal Media Player configuration requires name") return False validate_children(config) @@ -83,7 +83,7 @@ def validate_config(config): for key in config: if key not in [CONF_NAME, CONF_CHILDREN, CONF_COMMANDS, CONF_ATTRS]: _LOGGER.warning( - 'Universal Media Player (%s) unrecognized parameter %s', + "Universal Media Player (%s) unrecognized parameter %s", config[CONF_NAME], key) del_keys.append(key) for key in del_keys: @@ -96,13 +96,12 @@ def validate_children(config): """Validate children.""" if CONF_CHILDREN not in config: _LOGGER.info( - 'No children under Universal Media Player (%s)', config[CONF_NAME]) + "No children under Universal Media Player (%s)", config[CONF_NAME]) config[CONF_CHILDREN] = [] elif not isinstance(config[CONF_CHILDREN], list): _LOGGER.warning( - 'Universal Media Player (%s) children not list in config. ' - 'They will be ignored.', - config[CONF_NAME]) + "Universal Media Player (%s) children not list in config. " + "They will be ignored", config[CONF_NAME]) config[CONF_CHILDREN] = [] @@ -112,9 +111,8 @@ def validate_commands(config): config[CONF_COMMANDS] = {} elif not isinstance(config[CONF_COMMANDS], dict): _LOGGER.warning( - 'Universal Media Player (%s) specified commands not dict in ' - 'config. They will be ignored.', - config[CONF_NAME]) + "Universal Media Player (%s) specified commands not dict in " + "config. They will be ignored", config[CONF_NAME]) config[CONF_COMMANDS] = {} @@ -124,9 +122,8 @@ def validate_attributes(config): config[CONF_ATTRS] = {} elif not isinstance(config[CONF_ATTRS], dict): _LOGGER.warning( - 'Universal Media Player (%s) specified attributes ' - 'not dict in config. They will be ignored.', - config[CONF_NAME]) + "Universal Media Player (%s) specified attributes " + "not dict in config. They will be ignored", config[CONF_NAME]) config[CONF_ATTRS] = {} for key, val in config[CONF_ATTRS].items(): @@ -173,8 +170,8 @@ class UniversalMediaPlayer(MediaPlayerDevice): def _override_or_child_attr(self, attr_name): """Return either the override or the active child for attr_name.""" if attr_name in self._attrs: - return self._entity_lkp(self._attrs[attr_name][0], - self._attrs[attr_name][1]) + return self._entity_lkp( + self._attrs[attr_name][0], self._attrs[attr_name][1]) return self._child_attr(attr_name) @@ -215,8 +212,8 @@ class UniversalMediaPlayer(MediaPlayerDevice): def master_state(self): """Return the master state for entity or None.""" if CONF_STATE in self._attrs: - master_state = self._entity_lkp(self._attrs[CONF_STATE][0], - self._attrs[CONF_STATE][1]) + master_state = self._entity_lkp( + self._attrs[CONF_STATE][0], self._attrs[CONF_STATE][1]) return master_state if master_state else STATE_OFF else: return None @@ -348,7 +345,7 @@ class UniversalMediaPlayer(MediaPlayerDevice): @property def source(self): - """"Return the current input source of the device.""" + """Return the current input source of the device.""" return self._override_or_child_attr(ATTR_INPUT_SOURCE) @property diff --git a/homeassistant/components/media_player/vlc.py b/homeassistant/components/media_player/vlc.py index 9439e6da5ad..f77b06054e1 100644 --- a/homeassistant/components/media_player/vlc.py +++ b/homeassistant/components/media_player/vlc.py @@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the vlc platform.""" + """Set up the vlc platform.""" add_devices([VlcDevice(config.get(CONF_NAME, DEFAULT_NAME), config.get(CONF_ARGUMENTS))]) diff --git a/homeassistant/components/media_player/volumio.py b/homeassistant/components/media_player/volumio.py index 5944921f94f..9bf0351d200 100755 --- a/homeassistant/components/media_player/volumio.py +++ b/homeassistant/components/media_player/volumio.py @@ -140,7 +140,7 @@ class Volumio(MediaPlayerDevice): if str(url[0:2]).lower() == 'ht': mediaurl = url else: - mediaurl = "http://" + self.host + ":" + str(self.port) + url + mediaurl = "http://{}:{}{}".format(self.host, self.port, url) return mediaurl @property diff --git a/homeassistant/components/media_player/webostv.py b/homeassistant/components/media_player/webostv.py index 67f2afc8520..112b84ec5f0 100644 --- a/homeassistant/components/media_player/webostv.py +++ b/homeassistant/components/media_player/webostv.py @@ -62,7 +62,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the LG WebOS TV platform.""" + """Set up the LG WebOS TV platform.""" if discovery_info is not None: host = urlparse(discovery_info[1]).hostname else: @@ -84,7 +84,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): def setup_tv(host, mac, name, customize, config, hass, add_devices): - """Setup a LG WebOS TV based on host parameter.""" + """Set up a LG WebOS TV based on host parameter.""" from pylgtv import WebOsClient from pylgtv import PyLGTVPairException from websockets.exceptions import ConnectionClosed @@ -133,7 +133,7 @@ def request_configuration( # pylint: disable=unused-argument def lgtv_configuration_callback(data): - """The actions to do when our configuration callback is called.""" + """Handle configuration changes.""" setup_tv(host, mac, name, customize, config, hass, add_devices) _CONFIGURING[host] = configurator.request_config( diff --git a/homeassistant/components/media_player/yamaha.py b/homeassistant/components/media_player/yamaha.py index 243b96220c9..de19ab238b5 100644 --- a/homeassistant/components/media_player/yamaha.py +++ b/homeassistant/components/media_player/yamaha.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Yamaha platform.""" + """Set up the Yamaha platform.""" import rxv # keep track of configured receivers so that we don't end up # discovering a receiver dynamically that we have static config @@ -241,7 +241,7 @@ class YamahaDevice(MediaPlayerDevice): function() except rxv.exceptions.ResponseException: _LOGGER.warning( - 'Failed to execute %s on %s', function_text, self._name) + "Failed to execute %s on %s", function_text, self._name) def select_source(self, source): """Select input source.""" diff --git a/homeassistant/components/microsoft_face.py b/homeassistant/components/microsoft_face.py index 53a856e0eb4..a0ff2ed99e7 100644 --- a/homeassistant/components/microsoft_face.py +++ b/homeassistant/components/microsoft_face.py @@ -111,7 +111,7 @@ def face_person(hass, group, person, camera_entity): @asyncio.coroutine def async_setup(hass, config): - """Setup microsoft face.""" + """Set up microsoft face.""" entities = {} face = MicrosoftFace( hass, diff --git a/homeassistant/components/modbus.py b/homeassistant/components/modbus.py index 416ce7ec6ce..b7b6193f6c0 100644 --- a/homeassistant/components/modbus.py +++ b/homeassistant/components/modbus.py @@ -67,7 +67,7 @@ HUB = None def setup(hass, config): - """Setup Modbus component.""" + """Set up Modbus component.""" # Modbus connection type # pylint: disable=global-statement, import-error client_type = config[DOMAIN][CONF_TYPE] diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 89c003c070c..b4701ad4690 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -214,8 +214,7 @@ def async_subscribe(hass, topic, msg_callback, qos=DEFAULT_QOS, if encoding is not None: try: payload = dp_payload.decode(encoding) - _LOGGER.debug("Received message on %s: %s", - dp_topic, payload) + _LOGGER.debug("Received message on %s: %s", dp_topic, payload) except (AttributeError, UnicodeDecodeError): _LOGGER.error("Illegal payload encoding %s from " "MQTT topic: %s, Payload: %s", diff --git a/homeassistant/components/mqtt/discovery.py b/homeassistant/components/mqtt/discovery.py index c3ff0f9dce5..dbee9dce571 100644 --- a/homeassistant/components/mqtt/discovery.py +++ b/homeassistant/components/mqtt/discovery.py @@ -31,7 +31,7 @@ ALLOWED_PLATFORMS = { @asyncio.coroutine def async_start(hass, discovery_topic, hass_config): - """Initialization of MQTT Discovery.""" + """Initialize of MQTT Discovery.""" # pylint: disable=unused-variable @asyncio.coroutine def async_device_message_received(topic, payload, qos): diff --git a/homeassistant/components/mqtt/server.py b/homeassistant/components/mqtt/server.py index c51649a3bef..0e866723b34 100644 --- a/homeassistant/components/mqtt/server.py +++ b/homeassistant/components/mqtt/server.py @@ -47,7 +47,7 @@ def async_start(hass, server_config): broker = Broker(server_config, hass.loop) yield from broker.start() except BrokerException: - logging.getLogger(__name__).exception('Error initializing MQTT server') + logging.getLogger(__name__).exception("Error initializing MQTT server") return False, None finally: passwd.close() diff --git a/homeassistant/components/notify/__init__.py b/homeassistant/components/notify/__init__.py index 35a01e25475..cf05629ce1b 100644 --- a/homeassistant/components/notify/__init__.py +++ b/homeassistant/components/notify/__init__.py @@ -68,7 +68,7 @@ def send_message(hass, message, title=None, data=None): @asyncio.coroutine def async_setup(hass, config): - """Setup the notify services.""" + """Set up the notify services.""" descriptions = yield from hass.loop.run_in_executor( None, load_yaml_config_file, os.path.join(os.path.dirname(__file__), 'services.yaml')) @@ -166,7 +166,7 @@ def async_setup(hass, config): @asyncio.coroutine def async_platform_discovered(platform, info): - """Callback to load a platform.""" + """Handle for discovered platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) diff --git a/homeassistant/components/notify/apns.py b/homeassistant/components/notify/apns.py index 83ae6d489a1..ac273443506 100644 --- a/homeassistant/components/notify/apns.py +++ b/homeassistant/components/notify/apns.py @@ -77,18 +77,18 @@ class ApnsDevice(object): @property def push_id(self): - """The APNS id for the device.""" + """Return the APNS id for the device.""" return self.device_push_id @property def name(self): - """The friendly name for the device.""" + """Return the friendly name for the device.""" return self.device_name @property def tracking_device_id(self): """ - Device Id. + Return the device Id. The id of a device that is tracked by the device tracking component. @@ -98,7 +98,7 @@ class ApnsDevice(object): @property def full_tracking_device_id(self): """ - Fully qualified device id. + Return the fully qualified device id. The full id of a device that is tracked by the device tracking component. @@ -107,7 +107,7 @@ class ApnsDevice(object): @property def disabled(self): - """Should receive notifications.""" + """Return the .""" return self.device_disabled def disable(self): @@ -177,9 +177,7 @@ class ApnsNotificationService(BaseNotificationService): if device.tracking_device_id is not None ] track_state_change( - hass, - tracking_ids, - self.device_state_changed_listener) + hass, tracking_ids, self.device_state_changed_listener) def device_state_changed_listener(self, entity_id, from_s, to_s): """ @@ -205,10 +203,7 @@ class ApnsNotificationService(BaseNotificationService): current_tracking_id = None if current_device is None \ else current_device.tracking_device_id - device = ApnsDevice( - push_id, - device_name, - current_tracking_id) + device = ApnsDevice(push_id, device_name, current_tracking_id) if current_device is None: self.devices[push_id] = device @@ -244,15 +239,15 @@ class ApnsNotificationService(BaseNotificationService): elif isinstance(message, template_helper.Template): rendered_message = message.render() else: - rendered_message = "" + rendered_message = '' payload = Payload( alert=rendered_message, - badge=message_data.get("badge"), - sound=message_data.get("sound"), - category=message_data.get("category"), - custom=message_data.get("custom", {}), - content_available=message_data.get("content_available", False)) + badge=message_data.get('badge'), + sound=message_data.get('sound'), + category=message_data.get('category'), + custom=message_data.get('custom', {}), + content_available=message_data.get('content_available', False)) device_update = False @@ -266,13 +261,9 @@ class ApnsNotificationService(BaseNotificationService): if device_state is None or state == str(device_state): try: apns.send_notification( - push_id, - payload, - topic=self.topic) + push_id, payload, topic=self.topic) except Unregistered: - logging.error( - "Device %s has unregistered.", - push_id) + logging.error("Device %s has unregistered", push_id) device_update = True device.disable() diff --git a/homeassistant/components/notify/aws_lambda.py b/homeassistant/components/notify/aws_lambda.py index 801537fbba6..7bdc103523d 100644 --- a/homeassistant/components/notify/aws_lambda.py +++ b/homeassistant/components/notify/aws_lambda.py @@ -17,8 +17,9 @@ from homeassistant.components.notify import ( import homeassistant.helpers.config_validation as cv from homeassistant.remote import JSONEncoder +REQUIREMENTS = ['boto3==1.4.3'] + _LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ["boto3==1.4.3"] CONF_REGION = 'region_name' CONF_ACCESS_KEY_ID = 'aws_access_key_id' @@ -28,7 +29,7 @@ CONF_CONTEXT = 'context' ATTR_CREDENTIALS = 'credentials' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_REGION, default="us-east-1"): cv.string, + vol.Optional(CONF_REGION, default='us-east-1'): cv.string, vol.Inclusive(CONF_ACCESS_KEY_ID, ATTR_CREDENTIALS): cv.string, vol.Inclusive(CONF_SECRET_ACCESS_KEY, ATTR_CREDENTIALS): cv.string, vol.Exclusive(CONF_PROFILE_NAME, ATTR_CREDENTIALS): cv.string, @@ -40,8 +41,8 @@ def get_service(hass, config, discovery_info=None): """Get the AWS Lambda notification service.""" context_str = json.dumps({'hass': hass.config.as_dict(), 'custom': config[CONF_CONTEXT]}, cls=JSONEncoder) - context_b64 = base64.b64encode(context_str.encode("utf-8")) - context = context_b64.decode("utf-8") + context_b64 = base64.b64encode(context_str.encode('utf-8')) + context = context_b64.decode('utf-8') # pylint: disable=import-error import boto3 diff --git a/homeassistant/components/notify/aws_sns.py b/homeassistant/components/notify/aws_sns.py index 9b95c486b4d..27fa7ac41c2 100644 --- a/homeassistant/components/notify/aws_sns.py +++ b/homeassistant/components/notify/aws_sns.py @@ -26,7 +26,7 @@ CONF_PROFILE_NAME = 'profile_name' ATTR_CREDENTIALS = 'credentials' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_REGION, default="us-east-1"): cv.string, + vol.Optional(CONF_REGION, default='us-east-1'): cv.string, vol.Inclusive(CONF_ACCESS_KEY_ID, ATTR_CREDENTIALS): cv.string, vol.Inclusive(CONF_SECRET_ACCESS_KEY, ATTR_CREDENTIALS): cv.string, vol.Exclusive(CONF_PROFILE_NAME, ATTR_CREDENTIALS): cv.string, diff --git a/homeassistant/components/notify/aws_sqs.py b/homeassistant/components/notify/aws_sqs.py index 76a137734d3..227dba14b43 100644 --- a/homeassistant/components/notify/aws_sqs.py +++ b/homeassistant/components/notify/aws_sqs.py @@ -25,7 +25,7 @@ CONF_PROFILE_NAME = 'profile_name' ATTR_CREDENTIALS = 'credentials' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_REGION, default="us-east-1"): cv.string, + vol.Optional(CONF_REGION, default='us-east-1'): cv.string, vol.Inclusive(CONF_ACCESS_KEY_ID, ATTR_CREDENTIALS): cv.string, vol.Inclusive(CONF_SECRET_ACCESS_KEY, ATTR_CREDENTIALS): cv.string, vol.Exclusive(CONF_PROFILE_NAME, ATTR_CREDENTIALS): cv.string, diff --git a/homeassistant/components/notify/ciscospark.py b/homeassistant/components/notify/ciscospark.py index ee6115c3f79..0bf184023d7 100644 --- a/homeassistant/components/notify/ciscospark.py +++ b/homeassistant/components/notify/ciscospark.py @@ -34,29 +34,17 @@ def get_service(hass, config, discovery_info=None): class CiscoSparkNotificationService(BaseNotificationService): - """CiscoSparkNotificationService.""" + """The Cisco Spark Notification Service.""" def __init__(self, token, default_room): - """ - Initialize the service. - - Args: - token: Cisco Spark Developer's Token - default_room: Cisco Spark Room ID - """ + """Initialize the service.""" from ciscosparkapi import CiscoSparkAPI self._default_room = default_room self._token = token self._spark = CiscoSparkAPI(access_token=self._token) def send_message(self, message="", **kwargs): - """ - Send a message to a user. - - Args: - message: notificaiton text - kwargs: attributes used - 'title' - """ + """Send a message to a user.""" from ciscosparkapi import SparkApiError try: title = "" diff --git a/homeassistant/components/notify/command_line.py b/homeassistant/components/notify/command_line.py index cd3bdfb16f3..4a7483d6e4d 100644 --- a/homeassistant/components/notify/command_line.py +++ b/homeassistant/components/notify/command_line.py @@ -43,6 +43,6 @@ class CommandLineNotificationService(BaseNotificationService): stdin=subprocess.PIPE, shell=True) proc.communicate(input=message) if proc.returncode != 0: - _LOGGER.error('Command failed: %s', self.command) + _LOGGER.error("Command failed: %s", self.command) except subprocess.SubprocessError: - _LOGGER.error('Error trying to exec Command: %s', self.command) + _LOGGER.error("Error trying to exec Command: %s", self.command) diff --git a/homeassistant/components/notify/facebook.py b/homeassistant/components/notify/facebook.py index 8f8bb98bbe1..ef85450ca63 100644 --- a/homeassistant/components/notify/facebook.py +++ b/homeassistant/components/notify/facebook.py @@ -69,6 +69,6 @@ class FacebookNotificationService(BaseNotificationService): obj = resp.json() error_message = obj['error']['message'] error_code = obj['error']['code'] - _LOGGER.error("Error %s : %s (Code %s)", resp.status_code, - error_message, - error_code) + _LOGGER.error( + "Error %s : %s (Code %s)", resp.status_code, error_message, + error_code) diff --git a/homeassistant/components/notify/free_mobile.py b/homeassistant/components/notify/free_mobile.py index 74d9a80ad86..92ea75a79dc 100644 --- a/homeassistant/components/notify/free_mobile.py +++ b/homeassistant/components/notify/free_mobile.py @@ -13,9 +13,9 @@ from homeassistant.components.notify import ( from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME import homeassistant.helpers.config_validation as cv -_LOGGER = logging.getLogger(__name__) REQUIREMENTS = ['freesms==0.1.1'] +_LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, @@ -25,8 +25,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_service(hass, config, discovery_info=None): """Get the Free Mobile SMS notification service.""" - return FreeSMSNotificationService(config[CONF_USERNAME], - config[CONF_ACCESS_TOKEN]) + return FreeSMSNotificationService( + config[CONF_USERNAME], config[CONF_ACCESS_TOKEN]) class FreeSMSNotificationService(BaseNotificationService): diff --git a/homeassistant/components/notify/gntp.py b/homeassistant/components/notify/gntp.py index 5aaaf64577c..b7e5b1b813a 100644 --- a/homeassistant/components/notify/gntp.py +++ b/homeassistant/components/notify/gntp.py @@ -73,7 +73,7 @@ class GNTPNotificationService(BaseNotificationService): try: self.gntp.register() except gntp.errors.NetworkError: - _LOGGER.error('Unable to register with the GNTP host.') + _LOGGER.error("Unable to register with the GNTP host") return def send_message(self, message="", **kwargs): diff --git a/homeassistant/components/notify/group.py b/homeassistant/components/notify/group.py index 07cc7b1146a..a98bb6c2317 100644 --- a/homeassistant/components/notify/group.py +++ b/homeassistant/components/notify/group.py @@ -17,7 +17,7 @@ import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) -CONF_SERVICES = "services" +CONF_SERVICES = 'services' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_SERVICES): vol.All(cv.ensure_list, [{ diff --git a/homeassistant/components/notify/html5.py b/homeassistant/components/notify/html5.py index 419e5aba2f8..3aa5db7faba 100644 --- a/homeassistant/components/notify/html5.py +++ b/homeassistant/components/notify/html5.py @@ -90,12 +90,10 @@ CALLBACK_EVENT_PAYLOAD_SCHEMA = vol.Schema({ NOTIFY_CALLBACK_EVENT = 'html5_notification' -# badge and timestamp are Chrome specific (not in official spec) - -HTML5_SHOWNOTIFICATION_PARAMETERS = ('actions', 'badge', 'body', 'dir', - 'icon', 'lang', 'renotify', - 'requireInteraction', 'tag', 'timestamp', - 'vibrate') +# Badge and timestamp are Chrome specific (not in official spec) +HTML5_SHOWNOTIFICATION_PARAMETERS = ( + 'actions', 'badge', 'body', 'dir', 'icon', 'lang', 'renotify', + 'requireInteraction', 'tag', 'timestamp', 'vibrate') def get_service(hass, config, discovery_info=None): @@ -115,8 +113,8 @@ def get_service(hass, config, discovery_info=None): gcm_sender_id = config.get(ATTR_GCM_SENDER_ID) if gcm_sender_id is not None: - add_manifest_json_key(ATTR_GCM_SENDER_ID, - config.get(ATTR_GCM_SENDER_ID)) + add_manifest_json_key( + ATTR_GCM_SENDER_ID, config.get(ATTR_GCM_SENDER_ID)) return HTML5NotificationService(gcm_api_key, registrations) @@ -136,7 +134,7 @@ def _load_config(filename): return json.loads(inp) except (IOError, ValueError) as error: - _LOGGER.error('Reading config file %s failed: %s', filename, error) + _LOGGER.error("Reading config file %s failed: %s", filename, error) return None @@ -158,7 +156,7 @@ def _save_config(filename, config): fdesc.write(json.dumps( config, cls=JSONBytesDecoder, indent=4, sort_keys=True)) except (IOError, TypeError) as error: - _LOGGER.error('Saving config file failed: %s', error) + _LOGGER.error("Saving config file failed: %s", error) return False return True @@ -185,17 +183,16 @@ class HTML5PushRegistrationView(HomeAssistantView): try: data = REGISTER_SCHEMA(data) except vol.Invalid as ex: - return self.json_message(humanize_error(data, ex), - HTTP_BAD_REQUEST) + return self.json_message( + humanize_error(data, ex), HTTP_BAD_REQUEST) - name = ensure_unique_string('unnamed device', - self.registrations.keys()) + name = ensure_unique_string('unnamed device', self.registrations) self.registrations[name] = data if not _save_config(self.json_path, self.registrations): - return self.json_message('Error saving registration.', - HTTP_INTERNAL_SERVER_ERROR) + return self.json_message( + 'Error saving registration.', HTTP_INTERNAL_SERVER_ERROR) return self.json_message('Push notification subscriber registered.') @@ -224,8 +221,8 @@ class HTML5PushRegistrationView(HomeAssistantView): if not _save_config(self.json_path, self.registrations): self.registrations[found] = reg - return self.json_message('Error saving registration.', - HTTP_INTERNAL_SERVER_ERROR) + return self.json_message( + 'Error saving registration.', HTTP_INTERNAL_SERVER_ERROR) return self.json_message('Push notification subscriber unregistered.') @@ -318,7 +315,7 @@ class HTML5PushCallbackView(HomeAssistantView): try: event_payload = CALLBACK_EVENT_PAYLOAD_SCHEMA(event_payload) except vol.Invalid as ex: - _LOGGER.warning('Callback event payload is not valid! %s', + _LOGGER.warning("Callback event payload is not valid: %s", humanize_error(event_payload, ex)) event_name = '{}.{}'.format(NOTIFY_CALLBACK_EVENT, @@ -390,8 +387,8 @@ class HTML5NotificationService(BaseNotificationService): for target in targets: info = self.registrations.get(target) if info is None: - _LOGGER.error('%s is not a valid HTML5 push notification' - ' target!', target) + _LOGGER.error("%s is not a valid HTML5 push notification" + " target", target) continue jwt_exp = (datetime.datetime.fromtimestamp(timestamp) + diff --git a/homeassistant/components/notify/instapush.py b/homeassistant/components/notify/instapush.py index 1058293b3b5..39cdf0fc475 100644 --- a/homeassistant/components/notify/instapush.py +++ b/homeassistant/components/notify/instapush.py @@ -48,7 +48,7 @@ def get_service(hass, config, discovery_info=None): '{}{}'.format(_RESOURCE, 'events/list'), headers=headers, timeout=DEFAULT_TIMEOUT).json() except ValueError: - _LOGGER.error('Unexpected answer from Instapush API') + _LOGGER.error("Unexpected answer from Instapush API") return None if 'error' in response: diff --git a/homeassistant/components/notify/ios.py b/homeassistant/components/notify/ios.py index 6486eed1512..469f1f3e61f 100644 --- a/homeassistant/components/notify/ios.py +++ b/homeassistant/components/notify/ios.py @@ -46,10 +46,10 @@ def get_service(hass, config, discovery_info=None): hass.config.components.add("notify.ios") if not ios.devices_with_push(): - _LOGGER.error(("The notify.ios platform was loaded but no " - "devices exist! Please check the documentation at " - "https://home-assistant.io/ecosystem/ios/notifications" - "/ for more information")) + _LOGGER.error("The notify.ios platform was loaded but no " + "devices exist! Please check the documentation at " + "https://home-assistant.io/ecosystem/ios/notifications" + "/ for more information") return None return iOSNotificationService() diff --git a/homeassistant/components/notify/joaoapps_join.py b/homeassistant/components/notify/joaoapps_join.py index f79c7186359..84b37f249a8 100644 --- a/homeassistant/components/notify/joaoapps_join.py +++ b/homeassistant/components/notify/joaoapps_join.py @@ -34,7 +34,7 @@ def get_service(hass, config, discovery_info=None): if api_key: from pyjoin import get_devices if not get_devices(api_key): - _LOGGER.error("Error connecting to Join, check API key") + _LOGGER.error("Error connecting to Join. Check theAPI key") return False return JoinNotificationService(device_id, api_key) @@ -52,9 +52,7 @@ class JoinNotificationService(BaseNotificationService): from pyjoin import send_notification title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) data = kwargs.get(ATTR_DATA) or {} - send_notification(device_id=self._device_id, - text=message, - title=title, - icon=data.get('icon'), - smallicon=data.get('smallicon'), - api_key=self._api_key) + send_notification( + device_id=self._device_id, text=message, title=title, + icon=data.get('icon'), smallicon=data.get('smallicon'), + api_key=self._api_key) diff --git a/homeassistant/components/notify/kodi.py b/homeassistant/components/notify/kodi.py index db72fff37d5..eda01c13086 100644 --- a/homeassistant/components/notify/kodi.py +++ b/homeassistant/components/notify/kodi.py @@ -100,4 +100,4 @@ class KodiNotificationService(BaseNotificationService): title, message, icon, displaytime) except jsonrpc_async.TransportError: - _LOGGER.warning('Unable to fetch Kodi data, Is Kodi online?') + _LOGGER.warning("Unable to fetch Kodi data. Is Kodi online?") diff --git a/homeassistant/components/notify/lannouncer.py b/homeassistant/components/notify/lannouncer.py index 4d038faeb9a..5677f38b06c 100644 --- a/homeassistant/components/notify/lannouncer.py +++ b/homeassistant/components/notify/lannouncer.py @@ -74,12 +74,12 @@ class LannouncerNotificationService(BaseNotificationService): # Check response buffer = sock.recv(1024) if buffer != b'LANnouncer: OK': - _LOGGER.error('Error sending data to Lannnouncer: %s', + _LOGGER.error("Error sending data to Lannnouncer: %s", buffer.decode()) # Close socket sock.close() except socket.gaierror: - _LOGGER.error('Unable to connect to host %s', self._host) + _LOGGER.error("Unable to connect to host %s", self._host) except socket.error: - _LOGGER.exception('Failed to send data to Lannnouncer') + _LOGGER.exception("Failed to send data to Lannnouncer") diff --git a/homeassistant/components/notify/llamalab_automate.py b/homeassistant/components/notify/llamalab_automate.py index bf000171c12..606c0fafc8b 100644 --- a/homeassistant/components/notify/llamalab_automate.py +++ b/homeassistant/components/notify/llamalab_automate.py @@ -8,16 +8,16 @@ import logging import requests import voluptuous as vol -from homeassistant.components.notify import (BaseNotificationService, - PLATFORM_SCHEMA) -from homeassistant.const import CONF_API_KEY +from homeassistant.components.notify import ( + BaseNotificationService, PLATFORM_SCHEMA) +from homeassistant.const import CONF_API_KEY, CONF_DEVICE from homeassistant.helpers import config_validation as cv + _LOGGER = logging.getLogger(__name__) +_RESOURCE = 'https://llamalab.com/automate/cloud/message' CONF_TO = 'to' -CONF_DEVICE = 'device' -_RESOURCE = 'https://llamalab.com/automate/cloud/message' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, diff --git a/homeassistant/components/notify/matrix.py b/homeassistant/components/notify/matrix.py index f1e59f048ba..c3bdeae0280 100644 --- a/homeassistant/components/notify/matrix.py +++ b/homeassistant/components/notify/matrix.py @@ -56,7 +56,7 @@ class MatrixNotificationService(BaseNotificationService): def __init__(self, config_file, homeserver, default_room, verify_ssl, username, password): - """Setup the client.""" + """Set up the client.""" self.session_filepath = config_file self.auth_tokens = self.get_auth_tokens() diff --git a/homeassistant/components/notify/message_bird.py b/homeassistant/components/notify/message_bird.py index 7e9ce3b093f..b20abb52efc 100644 --- a/homeassistant/components/notify/message_bird.py +++ b/homeassistant/components/notify/message_bird.py @@ -34,7 +34,7 @@ def get_service(hass, config, discovery_info=None): # validates the api key client.balance() except messagebird.client.ErrorException: - _LOGGER.error('The specified MessageBird API key is invalid.') + _LOGGER.error("The specified MessageBird API key is invalid") return None return MessageBirdNotificationService(config.get(CONF_SENDER), client) @@ -54,15 +54,13 @@ class MessageBirdNotificationService(BaseNotificationService): targets = kwargs.get(ATTR_TARGET) if not targets: - _LOGGER.error('No target specified.') + _LOGGER.error("No target specified") return for target in targets: try: - self.client.message_create(self.sender, - target, - message, - {'reference': 'HA'}) + self.client.message_create( + self.sender, target, message, {'reference': 'HA'}) except ErrorException as exception: - _LOGGER.error('Failed to notify %s: %s', target, exception) + _LOGGER.error("Failed to notify %s: %s", target, exception) continue diff --git a/homeassistant/components/notify/mysensors.py b/homeassistant/components/notify/mysensors.py index a2708a51efd..d9576767f25 100644 --- a/homeassistant/components/notify/mysensors.py +++ b/homeassistant/components/notify/mysensors.py @@ -5,8 +5,8 @@ For more details about this platform, please refer to the documentation https://home-assistant.io/components/notify.mysensors/ """ from homeassistant.components import mysensors -from homeassistant.components.notify import (ATTR_TARGET, - BaseNotificationService) +from homeassistant.components.notify import ( + ATTR_TARGET, BaseNotificationService) def get_service(hass, config, discovery_info=None): diff --git a/homeassistant/components/notify/nma.py b/homeassistant/components/notify/nma.py index 1116b5728fd..e81dc457a81 100644 --- a/homeassistant/components/notify/nma.py +++ b/homeassistant/components/notify/nma.py @@ -18,7 +18,6 @@ import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) _RESOURCE = 'https://www.notifymyandroid.com/publicapi/' - PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, }) @@ -34,7 +33,7 @@ def get_service(hass, config, discovery_info=None): tree = ET.fromstring(response.content) if tree[0].tag == 'error': - _LOGGER.error("Wrong API key supplied. %s", tree[0].text) + _LOGGER.error("Wrong API key supplied: %s", tree[0].text) return None return NmaNotificationService(config[CONF_API_KEY]) diff --git a/homeassistant/components/notify/pushbullet.py b/homeassistant/components/notify/pushbullet.py index fb6543afcb4..18f74ac01ae 100644 --- a/homeassistant/components/notify/pushbullet.py +++ b/homeassistant/components/notify/pushbullet.py @@ -14,9 +14,10 @@ from homeassistant.components.notify import ( from homeassistant.const import CONF_API_KEY import homeassistant.helpers.config_validation as cv -_LOGGER = logging.getLogger(__name__) REQUIREMENTS = ['pushbullet.py==0.10.0'] +_LOGGER = logging.getLogger(__name__) + ATTR_URL = 'url' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -33,9 +34,7 @@ def get_service(hass, config, discovery_info=None): try: pushbullet = PushBullet(config[CONF_API_KEY]) except InvalidKeyError: - _LOGGER.error( - "Wrong API key supplied. " - "Get it at https://www.pushbullet.com/account") + _LOGGER.error("Wrong API key supplied") return None return PushBulletNotificationService(pushbullet) diff --git a/homeassistant/components/notify/pushetta.py b/homeassistant/components/notify/pushetta.py index b1a71c57513..a29cd587105 100644 --- a/homeassistant/components/notify/pushetta.py +++ b/homeassistant/components/notify/pushetta.py @@ -29,9 +29,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_service(hass, config, discovery_info=None): """Get the Pushetta notification service.""" - pushetta_service = PushettaNotificationService(config[CONF_API_KEY], - config[CONF_CHANNEL_NAME], - config[CONF_SEND_TEST_MSG]) + api_key = config[CONF_API_KEY] + channel_name = config[CONF_CHANNEL_NAME] + send_test_msg = config[CONF_SEND_TEST_MSG] + + pushetta_service = PushettaNotificationService( + api_key, channel_name, send_test_msg) if pushetta_service.is_valid: return pushetta_service diff --git a/homeassistant/components/notify/pushover.py b/homeassistant/components/notify/pushover.py index afaf4e6a7e9..3d8d62230ee 100644 --- a/homeassistant/components/notify/pushover.py +++ b/homeassistant/components/notify/pushover.py @@ -32,11 +32,10 @@ def get_service(hass, config, discovery_info=None): from pushover import InitError try: - return PushoverNotificationService(config[CONF_USER_KEY], - config[CONF_API_KEY]) + return PushoverNotificationService( + config[CONF_USER_KEY], config[CONF_API_KEY]) except InitError: - _LOGGER.error( - 'Wrong API key supplied. Get it at https://pushover.net') + _LOGGER.error("Wrong API key supplied") return None @@ -74,4 +73,4 @@ class PushoverNotificationService(BaseNotificationService): except ValueError as val_err: _LOGGER.error(str(val_err)) except RequestError: - _LOGGER.exception('Could not send pushover notification') + _LOGGER.exception("Could not send pushover notification") diff --git a/homeassistant/components/notify/rest.py b/homeassistant/components/notify/rest.py index 41d100b3a09..1a40e1f1833 100644 --- a/homeassistant/components/notify/rest.py +++ b/homeassistant/components/notify/rest.py @@ -71,8 +71,8 @@ class RestNotificationService(BaseNotificationService): } if self._title_param_name is not None: - data[self._title_param_name] = kwargs.get(ATTR_TITLE, - ATTR_TITLE_DEFAULT) + data[self._title_param_name] = kwargs.get( + ATTR_TITLE, ATTR_TITLE_DEFAULT) if self._target_param_name is not None and ATTR_TARGET in kwargs: # Target is a list as of 0.29 and we don't want to break existing diff --git a/homeassistant/components/notify/sendgrid.py b/homeassistant/components/notify/sendgrid.py index 4db12a5b8d8..bb4a5078013 100644 --- a/homeassistant/components/notify/sendgrid.py +++ b/homeassistant/components/notify/sendgrid.py @@ -75,4 +75,4 @@ class SendgridNotificationService(BaseNotificationService): response = self._sg.client.mail.send.post(request_body=data) if response.status_code is not 202: - _LOGGER.error('Unable to send notification with SendGrid') + _LOGGER.error("Unable to send notification") diff --git a/homeassistant/components/notify/slack.py b/homeassistant/components/notify/slack.py index b9f33c95d43..8f63fcd7a2f 100644 --- a/homeassistant/components/notify/slack.py +++ b/homeassistant/components/notify/slack.py @@ -41,7 +41,7 @@ def get_service(hass, config, discovery_info=None): config.get(CONF_ICON, None)) except slacker.Error: - _LOGGER.exception("Slack authentication failed") + _LOGGER.exception("Authentication failed") return None @@ -77,12 +77,9 @@ class SlackNotificationService(BaseNotificationService): for target in targets: try: - self.slack.chat.post_message(target, message, - as_user=self._as_user, - username=self._username, - icon_emoji=self._icon, - attachments=attachments, - link_names=True) + self.slack.chat.post_message( + target, message, as_user=self._as_user, + username=self._username, icon_emoji=self._icon, + attachments=attachments, link_names=True) except slacker.Error as err: - _LOGGER.error("Could not send slack notification. Error: %s", - err) + _LOGGER.error("Could not send notification. Error: %s", err) diff --git a/homeassistant/components/notify/smtp.py b/homeassistant/components/notify/smtp.py index 3b76f87e91c..1a2e1bf5b4e 100644 --- a/homeassistant/components/notify/smtp.py +++ b/homeassistant/components/notify/smtp.py @@ -191,8 +191,8 @@ def _build_multipart_msg(message, images): msg.attach(attachment) attachment.add_header('Content-ID', '<{}>'.format(cid)) except TypeError: - _LOGGER.warning("Attachment %s has an unkown MIME type." - " Falling back to file", atch_name) + _LOGGER.warning("Attachment %s has an unkown MIME type. " + "Falling back to file", atch_name) attachment = MIMEApplication(file_bytes, Name=atch_name) attachment['Content-Disposition'] = ('attachment; ' 'filename="%s"' % diff --git a/homeassistant/components/notify/syslog.py b/homeassistant/components/notify/syslog.py index 31689bdc9f0..740148e28e5 100644 --- a/homeassistant/components/notify/syslog.py +++ b/homeassistant/components/notify/syslog.py @@ -11,6 +11,7 @@ import voluptuous as vol from homeassistant.components.notify import ( ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService) +_LOGGER = logging.getLogger(__name__) CONF_FACILITY = 'facility' CONF_OPTION = 'option' @@ -64,9 +65,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ }) -_LOGGER = logging.getLogger(__name__) - - def get_service(hass, config, discovery_info=None): """Get the syslog notification service.""" import syslog diff --git a/homeassistant/components/notify/telstra.py b/homeassistant/components/notify/telstra.py index efe90dc51ba..7fabb51eac8 100644 --- a/homeassistant/components/notify/telstra.py +++ b/homeassistant/components/notify/telstra.py @@ -11,7 +11,7 @@ import voluptuous as vol from homeassistant.components.notify import ( BaseNotificationService, ATTR_TITLE, PLATFORM_SCHEMA) -from homeassistant.const import CONTENT_TYPE_JSON +from homeassistant.const import CONTENT_TYPE_JSON, HTTP_HEADER_CONTENT_TYPE import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -34,7 +34,7 @@ def get_service(hass, config, discovery_info=None): phone_number = config.get(CONF_PHONE_NUMBER) if _authenticate(consumer_key, consumer_secret) is False: - _LOGGER.exception('Error obtaining authorization from Telstra API') + _LOGGER.exception("Error obtaining authorization from Telstra API") return None return TelstraNotificationService( @@ -73,7 +73,7 @@ class TelstraNotificationService(BaseNotificationService): } message_resource = 'https://api.telstra.com/v1/sms/messages' message_headers = { - 'Content-Type': CONTENT_TYPE_JSON, + HTTP_HEADER_CONTENT_TYPE: CONTENT_TYPE_JSON, 'Authorization': 'Bearer ' + token_response['access_token'], } message_response = requests.post( diff --git a/homeassistant/components/notify/twilio_call.py b/homeassistant/components/notify/twilio_call.py index f917d5cdab3..b517808d2ce 100644 --- a/homeassistant/components/notify/twilio_call.py +++ b/homeassistant/components/notify/twilio_call.py @@ -15,10 +15,10 @@ from homeassistant.components.notify import ( ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService) _LOGGER = logging.getLogger(__name__) -DEPENDENCIES = ["twilio"] +DEPENDENCIES = ['twilio'] -CONF_FROM_NUMBER = "from_number" +CONF_FROM_NUMBER = 'from_number' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_FROM_NUMBER): @@ -28,8 +28,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_service(hass, config, discovery_info=None): """Get the Twilio Call notification service.""" - return TwilioCallNotificationService(hass.data[DATA_TWILIO], - config[CONF_FROM_NUMBER]) + return TwilioCallNotificationService( + hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER]) class TwilioCallNotificationService(BaseNotificationService): @@ -58,8 +58,7 @@ class TwilioCallNotificationService(BaseNotificationService): for target in targets: try: - self.client.calls.create(to=target, - url=twimlet_url, - from_=self.from_number) + self.client.calls.create( + to=target, url=twimlet_url, from_=self.from_number) except TwilioRestException as exc: _LOGGER.error(exc) diff --git a/homeassistant/components/notify/twilio_sms.py b/homeassistant/components/notify/twilio_sms.py index 1bdfcb64407..52cfe2f436d 100644 --- a/homeassistant/components/notify/twilio_sms.py +++ b/homeassistant/components/notify/twilio_sms.py @@ -27,8 +27,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_service(hass, config, discovery_info=None): """Get the Twilio SMS notification service.""" - return TwilioSMSNotificationService(hass.data[DATA_TWILIO], - config[CONF_FROM_NUMBER]) + return TwilioSMSNotificationService( + hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER]) class TwilioSMSNotificationService(BaseNotificationService): @@ -48,5 +48,5 @@ class TwilioSMSNotificationService(BaseNotificationService): return for target in targets: - self.client.messages.create(to=target, body=message, - from_=self.from_number) + self.client.messages.create( + to=target, body=message, from_=self.from_number) diff --git a/homeassistant/components/notify/twitter.py b/homeassistant/components/notify/twitter.py index 21388c292eb..4bbe8a5d9e1 100644 --- a/homeassistant/components/notify/twitter.py +++ b/homeassistant/components/notify/twitter.py @@ -64,5 +64,4 @@ class TwitterNotificationService(BaseNotificationService): error_message = obj['errors'][0]['message'] error_code = obj['errors'][0]['code'] _LOGGER.error("Error %s : %s (Code %s)", resp.status_code, - error_message, - error_code) + error_message, error_code) diff --git a/homeassistant/components/notify/xmpp.py b/homeassistant/components/notify/xmpp.py index ee358ed069c..8faafbeab58 100644 --- a/homeassistant/components/notify/xmpp.py +++ b/homeassistant/components/notify/xmpp.py @@ -33,9 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_service(hass, config, discovery_info=None): """Get the Jabber (XMPP) notification service.""" return XmppNotificationService( - config.get('sender'), - config.get('password'), - config.get('recipient'), + config.get('sender'), config.get('password'), config.get('recipient'), config.get('tls')) @@ -86,7 +84,7 @@ def send_message(sender, password, recipient, use_tls, message): self.disconnect(wait=True) def check_credentials(self, event): - """"Disconnect from the server if credentials are invalid.""" + """Disconnect from the server if credentials are invalid.""" self.disconnect() SendNotificationBot() diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index 04322646f80..90dc34c4634 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -33,10 +33,12 @@ from . import purge, migration from .const import DATA_INSTANCE from .util import session_scope -DOMAIN = 'recorder' - REQUIREMENTS = ['sqlalchemy==1.1.9'] +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'recorder' + DEFAULT_URL = 'sqlite:///{hass_config_path}' DEFAULT_DB_FILE = 'home-assistant_v2.db' @@ -66,8 +68,6 @@ CONFIG_SCHEMA = vol.Schema({ }) }, extra=vol.ALLOW_EXTRA) -_LOGGER = logging.getLogger(__name__) - def wait_connection_ready(hass): """ @@ -101,7 +101,7 @@ def run_information(hass, point_in_time: Optional[datetime]=None): @asyncio.coroutine def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: - """Setup the recorder.""" + """Set up the recorder.""" conf = config.get(DOMAIN, {}) purge_days = conf.get(CONF_PURGE_DAYS) @@ -175,7 +175,7 @@ class Recorder(threading.Thread): if not connected: @callback def connection_failed(): - """Connection failed tasks.""" + """Connect failed tasks.""" self.async_db_ready.set_result(False) persistent_notification.async_create( self.hass, diff --git a/homeassistant/components/recorder/models.py b/homeassistant/components/recorder/models.py index ce42ba187c2..6dcb5dbd051 100644 --- a/homeassistant/components/recorder/models.py +++ b/homeassistant/components/recorder/models.py @@ -1,11 +1,11 @@ """Models for SQLAlchemy.""" - import json from datetime import datetime import logging -from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer, - String, Text, distinct) +from sqlalchemy import ( + Boolean, Column, DateTime, ForeignKey, Index, Integer, String, Text, + distinct) from sqlalchemy.ext.declarative import declarative_base import homeassistant.util.dt as dt_util diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index e4ea1af1060..63faf2633b1 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -24,7 +24,7 @@ def session_scope(*, hass=None, session=None): yield session session.commit() except Exception as err: # pylint: disable=broad-except - _LOGGER.error('Error executing query: %s', err) + _LOGGER.error("Error executing query: %s", err) session.rollback() raise finally: @@ -43,7 +43,7 @@ def commit(session, work): session.commit() return True except sqlalchemy.exc.OperationalError as err: - _LOGGER.error('Error executing query: %s', err) + _LOGGER.error("Error executing query: %s", err) session.rollback() time.sleep(QUERY_RETRY_WAIT) return False @@ -63,7 +63,7 @@ def execute(qry): (row.to_native() for row in qry) if row is not None] except SQLAlchemyError as err: - _LOGGER.error('Error executing query: %s', err) + _LOGGER.error("Error executing query: %s", err) if tryno == RETRIES - 1: raise diff --git a/homeassistant/components/remote/demo.py b/homeassistant/components/remote/demo.py index 90c691a3d3c..6976c116be9 100644 --- a/homeassistant/components/remote/demo.py +++ b/homeassistant/components/remote/demo.py @@ -10,7 +10,7 @@ from homeassistant.const import DEVICE_DEFAULT_NAME # pylint: disable=unused-argument def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the demo remotes.""" + """Set up the demo remotes.""" add_devices_callback([ DemoRemote('Remote One', False, None), DemoRemote('Remote Two', True, 'mdi:remote'), diff --git a/homeassistant/components/remote/harmony.py b/homeassistant/components/remote/harmony.py index 351b85cf902..e0c01023660 100755 --- a/homeassistant/components/remote/harmony.py +++ b/homeassistant/components/remote/harmony.py @@ -81,7 +81,7 @@ def register_services(hass): def _apply_service(service, service_func, *service_func_args): - """Internal func for applying a service.""" + """Handle services to apply.""" entity_ids = service.data.get('entity_id') if entity_ids: diff --git a/homeassistant/components/scene/__init__.py b/homeassistant/components/scene/__init__.py index 0d407ac3a9a..5b147fbb656 100644 --- a/homeassistant/components/scene/__init__.py +++ b/homeassistant/components/scene/__init__.py @@ -68,7 +68,7 @@ def activate(hass, entity_id=None): @asyncio.coroutine def async_setup(hass, config): - """Setup scenes.""" + """Set up the scenes.""" logger = logging.getLogger(__name__) component = EntityComponent(logger, DOMAIN, hass) diff --git a/homeassistant/components/scene/homeassistant.py b/homeassistant/components/scene/homeassistant.py index 39942eea301..57c56e8b2f6 100644 --- a/homeassistant/components/scene/homeassistant.py +++ b/homeassistant/components/scene/homeassistant.py @@ -37,7 +37,7 @@ SCENECONFIG = namedtuple('SceneConfig', [CONF_NAME, STATES]) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup home assistant scene entries.""" + """Set up home assistant scene entries.""" scene_config = config.get(STATES) async_add_devices(HomeAssistantScene( diff --git a/homeassistant/components/scene/hunterdouglas_powerview.py b/homeassistant/components/scene/hunterdouglas_powerview.py index c831876bf11..622acbd2583 100644 --- a/homeassistant/components/scene/hunterdouglas_powerview.py +++ b/homeassistant/components/scene/hunterdouglas_powerview.py @@ -20,7 +20,7 @@ HUB_ADDRESS = 'address' # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the powerview scenes stored in a Powerview hub.""" + """Set up the powerview scenes stored in a Powerview hub.""" from powerview_api import powerview hub_address = config.get(HUB_ADDRESS) @@ -30,7 +30,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): _scenes = _pv.get_scenes() _rooms = _pv.get_rooms() except ConnectionError: - _LOGGER.exception("error connecting to powerview " + _LOGGER.exception("Error connecting to powerview " "hub with ip address: %s", hub_address) return False add_devices(PowerViewScene(hass, scene, _rooms, _pv) @@ -49,9 +49,8 @@ class PowerViewScene(Scene): self.scene_data = scene_data self._sync_room_data(room_data) self.entity_id_format = DOMAIN + '.{}' - self.entity_id = generate_entity_id(self.entity_id_format, - str(self.scene_data["id"]), - hass=hass) + self.entity_id = generate_entity_id( + self.entity_id_format, str(self.scene_data["id"]), hass=hass) def _sync_room_data(self, room_data): """Sync the room data.""" diff --git a/homeassistant/components/scene/lifx_cloud.py b/homeassistant/components/scene/lifx_cloud.py index f600510d406..b96a56ca2bd 100644 --- a/homeassistant/components/scene/lifx_cloud.py +++ b/homeassistant/components/scene/lifx_cloud.py @@ -32,7 +32,7 @@ PLATFORM_SCHEMA = vol.Schema({ # pylint: disable=unused-argument @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the scenes stored in the LIFX Cloud.""" + """Set up the scenes stored in the LIFX Cloud.""" token = config.get(CONF_TOKEN) timeout = config.get(CONF_TIMEOUT) diff --git a/homeassistant/components/scene/wink.py b/homeassistant/components/scene/wink.py index aef7f375f0d..3906e7b5551 100644 --- a/homeassistant/components/scene/wink.py +++ b/homeassistant/components/scene/wink.py @@ -14,7 +14,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink platform.""" + """Set up the Wink platform.""" import pywink for scene in pywink.get_scenes(): diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index a3f361bdffe..92b874cf2c8 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -11,17 +11,20 @@ import logging from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa +_LOGGER = logging.getLogger(__name__) + DOMAIN = 'sensor' -SCAN_INTERVAL = timedelta(seconds=30) ENTITY_ID_FORMAT = DOMAIN + '.{}' +SCAN_INTERVAL = timedelta(seconds=30) + @asyncio.coroutine def async_setup(hass, config): """Track states and offer events for sensors.""" component = EntityComponent( - logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) + _LOGGER, DOMAIN, hass, SCAN_INTERVAL) yield from component.async_setup(config) return True diff --git a/homeassistant/components/sensor/alarmdecoder.py b/homeassistant/components/sensor/alarmdecoder.py index 88246cc0bc2..dba1697f026 100644 --- a/homeassistant/components/sensor/alarmdecoder.py +++ b/homeassistant/components/sensor/alarmdecoder.py @@ -10,19 +10,17 @@ import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity - from homeassistant.components.alarmdecoder import (SIGNAL_PANEL_MESSAGE) - from homeassistant.const import (STATE_UNKNOWN) -DEPENDENCIES = ['alarmdecoder'] - _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['alarmdecoder'] + @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Perform the setup for AlarmDecoder sensor devices.""" + """Set up for AlarmDecoder sensor devices.""" _LOGGER.debug("AlarmDecoderSensor: async_setup_platform") device = AlarmDecoderSensor(hass) @@ -40,7 +38,7 @@ class AlarmDecoderSensor(Entity): self._icon = 'mdi:alarm-check' self._name = 'Alarm Panel Display' - _LOGGER.debug("AlarmDecoderSensor: Setting up panel") + _LOGGER.debug("Setting up panel") @asyncio.coroutine def async_added_to_hass(self): diff --git a/homeassistant/components/sensor/android_ip_webcam.py b/homeassistant/components/sensor/android_ip_webcam.py index 687649e226a..c9e1238d9a3 100644 --- a/homeassistant/components/sensor/android_ip_webcam.py +++ b/homeassistant/components/sensor/android_ip_webcam.py @@ -15,7 +15,7 @@ DEPENDENCIES = ['android_ip_webcam'] @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the IP Webcam Sensor.""" + """Set up the IP Webcam Sensor.""" if discovery_info is None: return diff --git a/homeassistant/components/sensor/apcupsd.py b/homeassistant/components/sensor/apcupsd.py index 8c2cf22655d..ec4db5e2934 100644 --- a/homeassistant/components/sensor/apcupsd.py +++ b/homeassistant/components/sensor/apcupsd.py @@ -105,7 +105,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_entities, discovery_info=None): - """Setup the APCUPSd sensors.""" + """Set up the APCUPSd sensors.""" entities = [] for resource in config[CONF_RESOURCES]: @@ -117,8 +117,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None): if sensor_type.upper() not in apcupsd.DATA.status: _LOGGER.warning( - 'Sensor type: "%s" does not appear in the APCUPSd status ' - 'output', sensor_type) + "Sensor type: %s does not appear in the APCUPSd status output", + sensor_type) entities.append(APCUPSdSensor(apcupsd.DATA, sensor_type)) diff --git a/homeassistant/components/sensor/arduino.py b/homeassistant/components/sensor/arduino.py index 03307a49768..f49d8e76f6c 100644 --- a/homeassistant/components/sensor/arduino.py +++ b/homeassistant/components/sensor/arduino.py @@ -16,7 +16,6 @@ from homeassistant.const import CONF_NAME from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv - _LOGGER = logging.getLogger(__name__) CONF_PINS = 'pins' @@ -36,7 +35,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Arduino platform.""" - # Verify that the Arduino board is present if arduino.BOARD is None: _LOGGER.error("A connection has not been made to the Arduino board") return False diff --git a/homeassistant/components/sensor/arest.py b/homeassistant/components/sensor/arest.py index d99240cf0d2..6edef785280 100644 --- a/homeassistant/components/sensor/arest.py +++ b/homeassistant/components/sensor/arest.py @@ -83,7 +83,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if var_conf is not None: for variable, var_data in var_conf.items(): if variable not in response['variables']: - _LOGGER.error("Variable: '%s' does not exist", variable) + _LOGGER.error("Variable: %s does not exist", variable) continue renderer = make_renderer(var_data.get(CONF_VALUE_TEMPLATE)) diff --git a/homeassistant/components/sensor/arwn.py b/homeassistant/components/sensor/arwn.py index d2e148b8204..a63451771d6 100644 --- a/homeassistant/components/sensor/arwn.py +++ b/homeassistant/components/sensor/arwn.py @@ -135,17 +135,17 @@ class ArwnSensor(Entity): @property def unit_of_measurement(self): - """Unit this state is expressed in.""" + """Return the unit of measurement the state is expressed in.""" return self._unit_of_measurement @property def should_poll(self): - """Should we poll.""" + """Return the polling state.""" return False @property def icon(self): - """Icon of device based on its type.""" + """Return the icon of device based on its type.""" if self._icon: return self._icon else: diff --git a/homeassistant/components/sensor/bitcoin.py b/homeassistant/components/sensor/bitcoin.py index 48f3c66a4c1..371918a95d4 100644 --- a/homeassistant/components/sensor/bitcoin.py +++ b/homeassistant/components/sensor/bitcoin.py @@ -66,8 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): currency = config.get(CONF_CURRENCY) if currency not in exchangerates.get_ticker(): - _LOGGER.warning('Currency "%s" is not available. Using "USD"', - currency) + _LOGGER.warning("Currency %s is not available. Using USD", currency) currency = DEFAULT_CURRENCY data = BitcoinData() diff --git a/homeassistant/components/sensor/blink.py b/homeassistant/components/sensor/blink.py index e069dfa00f7..3805af0f2ba 100644 --- a/homeassistant/components/sensor/blink.py +++ b/homeassistant/components/sensor/blink.py @@ -53,26 +53,26 @@ class BlinkSensor(Entity): @property def name(self): - """A method to return the name of the camera.""" + """Return the name of the camera.""" return self._name @property def state(self): - """A camera's current state.""" + """Return the camera's current state.""" return self._state @property def unique_id(self): - """A unique camera sensor identifier.""" + """Return the unique camera sensor identifier.""" return "sensor_{}_{}".format(self._name, self.index) @property def unit_of_measurement(self): - """A method to determine the unit of measurement for temperature.""" + """Return the unit of measurement.""" return self._unit_of_measurement def update(self): - """A method to retrieve sensor data from the camera.""" + """Retrieve sensor data from the camera.""" camera = self.data.cameras[self._camera_name] if self._type == 'temperature': self._state = camera.temperature diff --git a/homeassistant/components/sensor/bloomsky.py b/homeassistant/components/sensor/bloomsky.py index 1026e2a92db..62769dc0494 100644 --- a/homeassistant/components/sensor/bloomsky.py +++ b/homeassistant/components/sensor/bloomsky.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available BloomSky weather sensors.""" + """Set up the available BloomSky weather sensors.""" bloomsky = get_component('bloomsky') # Default needed in case of discovery sensors = config.get(CONF_MONITORED_CONDITIONS, SENSOR_TYPES) @@ -68,7 +68,7 @@ class BloomSkySensor(Entity): @property def name(self): - """The name of the BloomSky device and this sensor.""" + """Return the name of the BloomSky device and this sensor.""" return self._name @property @@ -78,7 +78,7 @@ class BloomSkySensor(Entity): @property def state(self): - """The current state, eg. value, of this sensor.""" + """Return the current state, eg. value, of this sensor.""" return self._state @property diff --git a/homeassistant/components/sensor/bom.py b/homeassistant/components/sensor/bom.py index a83ca49c619..db92ff40cf8 100644 --- a/homeassistant/components/sensor/bom.py +++ b/homeassistant/components/sensor/bom.py @@ -102,14 +102,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if station is not None: if zone_id and wmo_id: _LOGGER.warning( - 'Using config "%s", not "%s" and "%s" for BOM sensor', + "Using config %s, not %s and %s for BOM sensor", CONF_STATION, CONF_ZONE_ID, CONF_WMO_ID) elif zone_id and wmo_id: station = '{}.{}'.format(zone_id, wmo_id) else: - station = closest_station(config.get(CONF_LATITUDE), - config.get(CONF_LONGITUDE), - hass.config.config_dir) + station = closest_station( + config.get(CONF_LATITUDE), config.get(CONF_LONGITUDE), + hass.config.config_dir) if station is None: _LOGGER.error("Could not get BOM weather station from lat/lon") return False @@ -186,7 +186,7 @@ class BOMCurrentData(object): def _build_url(self): url = _RESOURCE.format(self._zone_id, self._zone_id, self._wmo_id) - _LOGGER.info("BOM url %s", url) + _LOGGER.info("BOM URL %s", url) return url @Throttle(MIN_TIME_BETWEEN_UPDATES) diff --git a/homeassistant/components/sensor/broadlink.py b/homeassistant/components/sensor/broadlink.py index e0612c8b577..7d5018e054c 100644 --- a/homeassistant/components/sensor/broadlink.py +++ b/homeassistant/components/sensor/broadlink.py @@ -49,7 +49,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Broadlink device sensors.""" + """Set up the Broadlink device sensors.""" mac = config.get(CONF_MAC).encode().replace(b':', b'') mac_addr = binascii.unhexlify(mac) broadlink_data = BroadlinkData( diff --git a/homeassistant/components/sensor/coinmarketcap.py b/homeassistant/components/sensor/coinmarketcap.py index eee43328f29..198e3756760 100644 --- a/homeassistant/components/sensor/coinmarketcap.py +++ b/homeassistant/components/sensor/coinmarketcap.py @@ -52,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: CoinMarketCapData(currency).update() except HTTPError: - _LOGGER.warning("Currency '%s' is not available. Using 'bitcoin'", + _LOGGER.warning("Currency %s is not available. Using bitcoin", currency) currency = DEFAULT_CURRENCY diff --git a/homeassistant/components/sensor/comed_hourly_pricing.py b/homeassistant/components/sensor/comed_hourly_pricing.py index 747ea0683d8..4f6e0953e54 100644 --- a/homeassistant/components/sensor/comed_hourly_pricing.py +++ b/homeassistant/components/sensor/comed_hourly_pricing.py @@ -20,13 +20,13 @@ _RESOURCE = 'https://hourlypricing.comed.com/api' SCAN_INTERVAL = timedelta(minutes=5) -CONF_MONITORED_FEEDS = 'monitored_feeds' -CONF_SENSOR_TYPE = 'type' -CONF_OFFSET = 'offset' -CONF_NAME = 'name' - -CONF_FIVE_MINUTE = 'five_minute' +CONF_ATTRIBUTION = "Data provided by ComEd Hourly Pricing service" CONF_CURRENT_HOUR_AVERAGE = 'current_hour_average' +CONF_FIVE_MINUTE = 'five_minute' +CONF_MONITORED_FEEDS = 'monitored_feeds' +CONF_NAME = 'name' +CONF_OFFSET = 'offset' +CONF_SENSOR_TYPE = 'type' SENSOR_TYPES = { CONF_FIVE_MINUTE: ['ComEd 5 Minute Price', 'c'], @@ -47,7 +47,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ComEd Hourly Pricing sensor.""" + """Set up the ComEd Hourly Pricing sensor.""" dev = [] for variable in config[CONF_MONITORED_FEEDS]: dev.append(ComedHourlyPricingSensor( @@ -89,8 +89,7 @@ class ComedHourlyPricingSensor(Entity): @property def device_state_attributes(self): """Return the state attributes.""" - attrs = {ATTR_ATTRIBUTION: 'Data provided by ComEd Hourly ' - 'Pricing service'} + attrs = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION} return attrs def update(self): @@ -109,4 +108,4 @@ class ComedHourlyPricingSensor(Entity): else: self._state = STATE_UNKNOWN except (RequestException, ValueError, KeyError): - _LOGGER.warning('Could not update status for %s', self.name) + _LOGGER.warning("Could not update status for %s", self.name) diff --git a/homeassistant/components/sensor/command_line.py b/homeassistant/components/sensor/command_line.py index 227b133535d..f2542413abf 100644 --- a/homeassistant/components/sensor/command_line.py +++ b/homeassistant/components/sensor/command_line.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Command Sensor.""" + """Set up the Command Sensor.""" name = config.get(CONF_NAME) command = config.get(CONF_COMMAND) unit = config.get(CONF_UNIT_OF_MEASUREMENT) @@ -97,13 +97,13 @@ class CommandSensorData(object): def update(self): """Get the latest data with a shell command.""" - _LOGGER.info('Running command: %s', self.command) + _LOGGER.info("Running command: %s", self.command) try: - return_value = subprocess.check_output(self.command, shell=True, - timeout=15) + return_value = subprocess.check_output( + self.command, shell=True, timeout=15) self.value = return_value.strip().decode('utf-8') except subprocess.CalledProcessError: - _LOGGER.error('Command failed: %s', self.command) + _LOGGER.error("Command failed: %s", self.command) except subprocess.TimeoutExpired: - _LOGGER.error('Timeout for command: %s', self.command) + _LOGGER.error("Timeout for command: %s", self.command) diff --git a/homeassistant/components/sensor/crimereports.py b/homeassistant/components/sensor/crimereports.py index 8f118fc3c32..b6e5ea33216 100644 --- a/homeassistant/components/sensor/crimereports.py +++ b/homeassistant/components/sensor/crimereports.py @@ -25,11 +25,14 @@ REQUIREMENTS = ['crimereports==1.0.0'] _LOGGER = logging.getLogger(__name__) -SCAN_INTERVAL = timedelta(minutes=30) -DOMAIN = 'crimereports' -EVENT_INCIDENT = '{}_incident'.format(DOMAIN) CONF_RADIUS = 'radius' +DOMAIN = 'crimereports' + +EVENT_INCIDENT = '{}_incident'.format(DOMAIN) + +SCAN_INTERVAL = timedelta(minutes=30) + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_NAME): cv.string, vol.Required(CONF_RADIUS): vol.Coerce(float), @@ -42,14 +45,16 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Crime Reports platform.""" + """Set up the Crime Reports platform.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) - add_devices([CrimeReportsSensor(hass, config.get(CONF_NAME), - latitude, longitude, - config.get(CONF_RADIUS), - config.get(CONF_INCLUDE), - config.get(CONF_EXCLUDE))], True) + name = config.get(CONF_NAME) + radius = config.get(CONF_RADIUS) + include = config.get(CONF_INCLUDE) + exclude = config.get(CONF_EXCLUDE) + + add_devices([CrimeReportsSensor( + hass, name, latitude, longitude, radius, include, exclude)], True) class CrimeReportsSensor(Entity): @@ -64,8 +69,8 @@ class CrimeReportsSensor(Entity): self._include = include self._exclude = exclude radius_kilometers = convert(radius, LENGTH_METERS, LENGTH_KILOMETERS) - self._crimereports = crimereports.CrimeReports((latitude, longitude), - radius_kilometers) + self._crimereports = crimereports.CrimeReports( + (latitude, longitude), radius_kilometers) self._attributes = None self._state = None self._previous_incidents = set() @@ -103,9 +108,8 @@ class CrimeReportsSensor(Entity): """Update device state.""" import crimereports incident_counts = defaultdict(int) - incidents = self._crimereports.get_incidents(now().date(), - include=self._include, - exclude=self._exclude) + incidents = self._crimereports.get_incidents( + now().date(), include=self._include, exclude=self._exclude) fire_events = len(self._previous_incidents) > 0 if len(incidents) < len(self._previous_incidents): self._previous_incidents = set() diff --git a/homeassistant/components/sensor/darksky.py b/homeassistant/components/sensor/darksky.py index aa44611aec2..eaf0c474994 100644 --- a/homeassistant/components/sensor/darksky.py +++ b/homeassistant/components/sensor/darksky.py @@ -130,8 +130,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Dark Sky sensor.""" - # latitude and longitude are inclusive on config + """Set up the Dark Sky sensor.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) @@ -163,8 +162,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): sensors.append(DarkSkySensor(forecast_data, variable, name)) if forecast is not None and 'daily' in SENSOR_TYPES[variable][7]: for forecast_day in forecast: - sensors.append(DarkSkySensor(forecast_data, - variable, name, forecast_day)) + sensors.append(DarkSkySensor( + forecast_data, variable, name, forecast_day)) add_devices(sensors, True) @@ -189,8 +188,8 @@ class DarkSkySensor(Entity): if self.forecast_day == 0: return '{} {}'.format(self.client_name, self._name) else: - return '{} {} {}'.format(self.client_name, self._name, - self.forecast_day) + return '{} {} {}'.format( + self.client_name, self._name, self.forecast_day) @property def state(self): @@ -285,7 +284,7 @@ class DarkSkySensor(Entity): def get_state(self, data): """ - Helper function that returns a new state based on the type. + Return a new state based on the type. If the sensor type is unknown, the current state is returned. """ diff --git a/homeassistant/components/sensor/demo.py b/homeassistant/components/sensor/demo.py index a290a0edd53..ba7c93203df 100644 --- a/homeassistant/components/sensor/demo.py +++ b/homeassistant/components/sensor/demo.py @@ -10,7 +10,7 @@ from homeassistant.helpers.entity import Entity # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo sensors.""" + """Set up the Demo sensors.""" add_devices([ DemoSensor('Outside Temperature', 15.6, TEMP_CELSIUS, 12), DemoSensor('Outside Humidity', 54, '%', None), diff --git a/homeassistant/components/sensor/deutsche_bahn.py b/homeassistant/components/sensor/deutsche_bahn.py index 34be6ba078c..0f6e3b267ca 100644 --- a/homeassistant/components/sensor/deutsche_bahn.py +++ b/homeassistant/components/sensor/deutsche_bahn.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Deutsche Bahn Sensor.""" + """Set up the Deutsche Bahn Sensor.""" start = config.get(CONF_START) destination = config.get(CONF_DESTINATION) diff --git a/homeassistant/components/sensor/dht.py b/homeassistant/components/sensor/dht.py index 327001e67cd..a6fc9b10bee 100644 --- a/homeassistant/components/sensor/dht.py +++ b/homeassistant/components/sensor/dht.py @@ -49,7 +49,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the DHT sensor.""" + """Set up the DHT sensor.""" # pylint: disable=import-error import Adafruit_DHT @@ -139,8 +139,8 @@ class DHTClient(object): @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data the DHT sensor.""" - humidity, temperature = self.adafruit_dht.read_retry(self.sensor, - self.pin) + humidity, temperature = self.adafruit_dht.read_retry( + self.sensor, self.pin) if temperature: self.data[SENSOR_TEMPERATURE] = temperature if humidity: diff --git a/homeassistant/components/sensor/dnsip.py b/homeassistant/components/sensor/dnsip.py index 67b2e04d157..7b792d179c5 100644 --- a/homeassistant/components/sensor/dnsip.py +++ b/homeassistant/components/sensor/dnsip.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the DNS IP sensor.""" + """Set up the DNS IP sensor.""" hostname = config.get(CONF_HOSTNAME) ipv6 = config.get(CONF_IPV6) if ipv6: diff --git a/homeassistant/components/sensor/dovado.py b/homeassistant/components/sensor/dovado.py index 6b3ff58fab5..eba6596efc4 100644 --- a/homeassistant/components/sensor/dovado.py +++ b/homeassistant/components/sensor/dovado.py @@ -14,9 +14,9 @@ from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle from homeassistant.util import slugify import homeassistant.helpers.config_validation as cv -from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD, - CONF_HOST, CONF_PORT, - CONF_SENSORS, DEVICE_DEFAULT_NAME) +from homeassistant.const import ( + CONF_USERNAME, CONF_PASSWORD, CONF_HOST, CONF_PORT, CONF_SENSORS, + DEVICE_DEFAULT_NAME) from homeassistant.components.sensor import (DOMAIN, PLATFORM_SCHEMA) _LOGGER = logging.getLogger(__name__) @@ -25,23 +25,23 @@ REQUIREMENTS = ['dovado==0.4.1'] MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30) -SENSOR_UPLOAD = "upload" -SENSOR_DOWNLOAD = "download" -SENSOR_SIGNAL = "signal" -SENSOR_NETWORK = "network" -SENSOR_SMS_UNREAD = "sms" +SENSOR_UPLOAD = 'upload' +SENSOR_DOWNLOAD = 'download' +SENSOR_SIGNAL = 'signal' +SENSOR_NETWORK = 'network' +SENSOR_SMS_UNREAD = 'sms' SENSORS = { - SENSOR_NETWORK: ("signal strength", "Network", None, - "mdi:access-point-network"), - SENSOR_SIGNAL: ("signal strength", "Signal Strength", "%", - "mdi:signal"), - SENSOR_SMS_UNREAD: ("sms unread", "SMS unread", "", - "mdi:message-text-outline"), - SENSOR_UPLOAD: ("traffic modem tx", "Sent", "GB", - "mdi:cloud-upload"), - SENSOR_DOWNLOAD: ("traffic modem rx", "Received", "GB", - "mdi:cloud-download"), + SENSOR_NETWORK: ('signal strength', 'Network', None, + 'mdi:access-point-network'), + SENSOR_SIGNAL: ('signal strength', 'Signal Strength', '%', + 'mdi:signal'), + SENSOR_SMS_UNREAD: ('sms unread', 'SMS unread', '', + 'mdi:message-text-outline'), + SENSOR_UPLOAD: ('traffic modem tx', 'Sent', 'GB', + 'mdi:cloud-upload'), + SENSOR_DOWNLOAD: ('traffic modem rx', 'Received', 'GB', + 'mdi:cloud-download'), } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -55,7 +55,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the dovado platform for sensors.""" + """Set up the Dovado platform for sensors.""" return Dovado().setup(hass, config, add_devices) @@ -68,28 +68,24 @@ class Dovado: self._dovado = None def setup(self, hass, config, add_devices): - """Setup the connection.""" + """Set up the connection.""" import dovado self._dovado = dovado.Dovado( - config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - config.get(CONF_HOST), - config.get(CONF_PORT)) + config.get(CONF_USERNAME), config.get(CONF_PASSWORD), + config.get(CONF_HOST), config.get(CONF_PORT)) if not self.update(): return False def send_sms(service): """Send SMS through the router.""" - number = service.data.get("number"), - message = service.data.get("message") - _LOGGER.debug("message for %s: %s", - number, message) + number = service.data.get('number'), + message = service.data.get('message') + _LOGGER.debug("message for %s: %s", number, message) self._dovado.send_sms(number, message) - if self.state.get("sms") == "enabled": - service_name = slugify("{} {}".format(self.name, - "send_sms")) + if self.state.get('sms') == 'enabled': + service_name = slugify("{} {}".format(self.name, 'send_sms')) hass.services.register(DOMAIN, service_name, send_sms) for sensor in SENSORS: @@ -153,8 +149,7 @@ class DovadoSensor(Entity): @property def name(self): """Return the name of the sensor.""" - return "{} {}".format(self._dovado.name, - SENSORS[self._sensor][1]) + return "{} {}".format(self._dovado.name, SENSORS[self._sensor][1]) @property def state(self): @@ -175,4 +170,4 @@ class DovadoSensor(Entity): def device_state_attributes(self): """Return the state attributes.""" return {k: v for k, v in self._dovado.state.items() - if k not in ["date", "time"]} + if k not in ['date', 'time']} diff --git a/homeassistant/components/sensor/dsmr.py b/homeassistant/components/sensor/dsmr.py index 84669a57000..23324fe7360 100644 --- a/homeassistant/components/sensor/dsmr.py +++ b/homeassistant/components/sensor/dsmr.py @@ -1,4 +1,5 @@ -"""Support for Dutch Smart Meter Requirements. +""" +Support for Dutch Smart Meter Requirements. Also known as: Smartmeter or P1 port. @@ -23,7 +24,6 @@ DSMR version the Entities for this component are create during bootstrap. Another loop (DSMR class) is setup which reads the telegram queue, stores/caches the latest telegram and notifies the Entities that the telegram has been updated. - """ import asyncio from datetime import timedelta @@ -72,8 +72,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): logging.getLogger('dsmr_parser').setLevel(logging.ERROR) from dsmr_parser import obis_references as obis_ref - from dsmr_parser.clients.protocol import (create_dsmr_reader, - create_tcp_dsmr_reader) + from dsmr_parser.clients.protocol import ( + create_dsmr_reader, create_tcp_dsmr_reader) import serial dsmr_version = config[CONF_DSMR_VERSION] @@ -116,18 +116,14 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): # Creates a asyncio.Protocol factory for reading DSMR telegrams from serial # and calls update_entities_telegram to update entities on arrival if config[CONF_HOST]: - reader_factory = partial(create_tcp_dsmr_reader, - config[CONF_HOST], - config[CONF_PORT], - config[CONF_DSMR_VERSION], - update_entities_telegram, - loop=hass.loop) + reader_factory = partial( + create_tcp_dsmr_reader, config[CONF_HOST], config[CONF_PORT], + config[CONF_DSMR_VERSION], update_entities_telegram, + loop=hass.loop) else: - reader_factory = partial(create_dsmr_reader, - config[CONF_PORT], - config[CONF_DSMR_VERSION], - update_entities_telegram, - loop=hass.loop) + reader_factory = partial( + create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION], + update_entities_telegram, loop=hass.loop) @asyncio.coroutine def connect_and_reconnect(): @@ -141,7 +137,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): TimeoutError): # log any error while establishing connection and drop to retry # connection wait - _LOGGER.exception('error connecting to DSMR') + _LOGGER.exception("Error connecting to DSMR") transport = None if transport: @@ -174,7 +170,7 @@ class DSMREntity(Entity): """Entity reading values from DSMR telegram.""" def __init__(self, name, obis): - """"Initialize entity.""" + """Initialize entity.""" self._name = name self._obis = obis self.telegram = {} diff --git a/homeassistant/components/sensor/dte_energy_bridge.py b/homeassistant/components/sensor/dte_energy_bridge.py index 4a57bddfb9d..ea2739c3096 100644 --- a/homeassistant/components/sensor/dte_energy_bridge.py +++ b/homeassistant/components/sensor/dte_energy_bridge.py @@ -28,7 +28,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the DTE energy bridge sensor.""" + """Set up the DTE energy bridge sensor.""" name = config.get(CONF_NAME) ip_address = config.get(CONF_IP_ADDRESS) diff --git a/homeassistant/components/sensor/dublin_bus_transport.py b/homeassistant/components/sensor/dublin_bus_transport.py index ab921d1bbdd..337f8188847 100644 --- a/homeassistant/components/sensor/dublin_bus_transport.py +++ b/homeassistant/components/sensor/dublin_bus_transport.py @@ -58,7 +58,7 @@ def due_in_minutes(timestamp): def setup_platform(hass, config, add_devices, discovery_info=None): - """Get the Dublin public transport sensor.""" + """Set up the Dublin public transport sensor.""" name = config.get(CONF_NAME) stop = config.get(CONF_STOP_ID) route = config.get(CONF_ROUTE) diff --git a/homeassistant/components/sensor/dweet.py b/homeassistant/components/sensor/dweet.py index 0f9ea017571..e5f3d00830b 100644 --- a/homeassistant/components/sensor/dweet.py +++ b/homeassistant/components/sensor/dweet.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable, too-many-function-args def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Dweet sensor.""" + """Set up the Dweet sensor.""" import dweepy name = config.get(CONF_NAME) @@ -48,11 +48,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]['content']) except dweepy.DweepyError: - _LOGGER.error("Device/thing '%s' could not be found", device) + _LOGGER.error("Device/thing %s could not be found", device) return False if value_template.render_with_possible_json_value(content) == '': - _LOGGER.error("'%s' was not found", value_template) + _LOGGER.error("%s was not found", value_template) return False dweet = DweetData(device) @@ -115,5 +115,5 @@ class DweetData(object): try: self.data = dweepy.get_latest_dweet_for(self._device) except dweepy.DweepyError: - _LOGGER.error("Device '%s' could not be found", self._device) + _LOGGER.error("Device %s could not be found", self._device) self.data = None diff --git a/homeassistant/components/sensor/ebox.py b/homeassistant/components/sensor/ebox.py index 8357e9ad8f9..3cfa5ef9ff4 100644 --- a/homeassistant/components/sensor/ebox.py +++ b/homeassistant/components/sensor/ebox.py @@ -1,8 +1,7 @@ """ Support for EBox. -Get data from 'My Usage Page' page: -https://client.ebox.ca/myusage +Get data from 'My Usage Page' page: https://client.ebox.ca/myusage For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.ebox/ @@ -25,12 +24,12 @@ REQUIREMENTS = ['pyebox==0.1.0'] _LOGGER = logging.getLogger(__name__) -GIGABITS = "Gb" # type: str -PRICE = "CAD" # type: str -DAYS = "days" # type: str -PERCENT = "%" # type: str +GIGABITS = 'Gb' # type: str +PRICE = 'CAD' # type: str +DAYS = 'days' # type: str +PERCENT = '%' # type: str -DEFAULT_NAME = "EBox" +DEFAULT_NAME = 'EBox' REQUESTS_TIMEOUT = 15 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) diff --git a/homeassistant/components/sensor/ecobee.py b/homeassistant/components/sensor/ecobee.py index 961fb9aabe3..25a363680c4 100644 --- a/homeassistant/components/sensor/ecobee.py +++ b/homeassistant/components/sensor/ecobee.py @@ -18,7 +18,7 @@ ECOBEE_CONFIG_FILE = 'ecobee.conf' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Ecobee sensors.""" + """Set up the Ecobee sensors.""" if discovery_info is None: return data = ecobee.NETWORK diff --git a/homeassistant/components/sensor/eddystone_temperature.py b/homeassistant/components/sensor/eddystone_temperature.py index babc8ee60a6..16e9df15e5a 100644 --- a/homeassistant/components/sensor/eddystone_temperature.py +++ b/homeassistant/components/sensor/eddystone_temperature.py @@ -136,9 +136,9 @@ class Monitor(object): def callback(bt_addr, _, packet, additional_info): """Callback for new packets.""" - self.process_packet(additional_info['namespace'], - additional_info['instance'], - packet.temperature) + self.process_packet( + additional_info['namespace'], additional_info['instance'], + packet.temperature) # pylint: disable=import-error from beacontools import ( diff --git a/homeassistant/components/sensor/efergy.py b/homeassistant/components/sensor/efergy.py index 8731158cb6a..da7181972cb 100644 --- a/homeassistant/components/sensor/efergy.py +++ b/homeassistant/components/sensor/efergy.py @@ -30,6 +30,8 @@ CONF_BUDGET = 'budget' CONF_COST = 'cost' CONF_CURRENT_VALUES = 'current_values' +DEFAULT_PERIOD = 'year' + SENSOR_TYPES = { CONF_INSTANT: ['Energy Usage', 'kW'], CONF_AMOUNT: ['Energy Consumed', 'kWh'], @@ -43,7 +45,7 @@ TYPES_SCHEMA = vol.In(SENSOR_TYPES) SENSORS_SCHEMA = vol.Schema({ vol.Required(CONF_SENSOR_TYPE): TYPES_SCHEMA, vol.Optional(CONF_CURRENCY, default=''): cv.string, - vol.Optional(CONF_PERIOD, default='year'): cv.string, + vol.Optional(CONF_PERIOD, default=DEFAULT_PERIOD): cv.string, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -54,7 +56,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Efergy sensor.""" + """Set up the Efergy sensor.""" app_token = config.get(CONF_APPTOKEN) utc_offset = str(config.get(CONF_UTC_OFFSET)) dev = [] @@ -146,4 +148,4 @@ class EfergySensor(Entity): else: self._state = 'Unknown' except (RequestException, ValueError, KeyError): - _LOGGER.warning('Could not update status for %s', self.name) + _LOGGER.warning("Could not update status for %s", self.name) diff --git a/homeassistant/components/sensor/eliqonline.py b/homeassistant/components/sensor/eliqonline.py index dad15361ba4..21b259863a7 100644 --- a/homeassistant/components/sensor/eliqonline.py +++ b/homeassistant/components/sensor/eliqonline.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ELIQ Online sensor.""" + """Set up the ELIQ Online sensor.""" import eliqonline access_token = config.get(CONF_ACCESS_TOKEN) diff --git a/homeassistant/components/sensor/enocean.py b/homeassistant/components/sensor/enocean.py index 5f2f8edf872..6b0207c2488 100644 --- a/homeassistant/components/sensor/enocean.py +++ b/homeassistant/components/sensor/enocean.py @@ -26,7 +26,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup an EnOcean sensor device.""" + """Set up an EnOcean sensor device.""" dev_id = config.get(CONF_ID) devname = config.get(CONF_NAME) @@ -64,4 +64,4 @@ class EnOceanSensor(enocean.EnOceanDevice, Entity): @property def unit_of_measurement(self): """Return the unit of measurement.""" - return "W" + return 'W' diff --git a/homeassistant/components/sensor/envisalink.py b/homeassistant/components/sensor/envisalink.py index 9803f675913..7f1ee5c0d41 100644 --- a/homeassistant/components/sensor/envisalink.py +++ b/homeassistant/components/sensor/envisalink.py @@ -14,9 +14,10 @@ from homeassistant.components.envisalink import ( SIGNAL_KEYPAD_UPDATE, SIGNAL_PARTITION_UPDATE) from homeassistant.helpers.entity import Entity -DEPENDENCIES = ['envisalink'] _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['envisalink'] + @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): @@ -46,7 +47,7 @@ class EnvisalinkSensor(EnvisalinkDevice, Entity): self._icon = 'mdi:alarm' self._partition_number = partition_number - _LOGGER.debug('Setting up sensor for partition: ' + partition_name) + _LOGGER.debug("Setting up sensor for partition: %s", partition_name) super().__init__(partition_name + ' Keypad', info, controller) @asyncio.coroutine diff --git a/homeassistant/components/sensor/fastdotcom.py b/homeassistant/components/sensor/fastdotcom.py index 63ddb0663d7..61f2e000d1d 100644 --- a/homeassistant/components/sensor/fastdotcom.py +++ b/homeassistant/components/sensor/fastdotcom.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Fast.com sensor.""" + """Set up the Fast.com sensor.""" data = SpeedtestData(hass, config) sensor = SpeedtestSensor(data) add_devices([sensor]) @@ -87,7 +87,7 @@ class SpeedtestSensor(Entity): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity is about to be added to hass.""" + """Handle entity which will be added.""" state = yield from async_get_last_state(self.hass, self.entity_id) if not state: return @@ -101,14 +101,13 @@ class SpeedtestData(object): """Initialize the data object.""" self.data = None if not config.get(CONF_MANUAL): - track_time_change(hass, self.update, - second=config.get(CONF_SECOND), - minute=config.get(CONF_MINUTE), - hour=config.get(CONF_HOUR), - day=config.get(CONF_DAY)) + track_time_change( + hass, self.update, second=config.get(CONF_SECOND), + minute=config.get(CONF_MINUTE), hour=config.get(CONF_HOUR), + day=config.get(CONF_DAY)) def update(self, now): """Get the latest data from fast.com.""" from fastdotcom import fast_com - _LOGGER.info('Executing fast.com speedtest') + _LOGGER.info("Executing fast.com speedtest") self.data = {'download': fast_com()} diff --git a/homeassistant/components/sensor/fedex.py b/homeassistant/components/sensor/fedex.py index 2e1b8e6a6a0..d1626ce2974 100644 --- a/homeassistant/components/sensor/fedex.py +++ b/homeassistant/components/sensor/fedex.py @@ -23,10 +23,13 @@ REQUIREMENTS = ['fedexdeliverymanager==1.0.2'] _LOGGER = logging.getLogger(__name__) -DOMAIN = 'fedex' -COOKIE = 'fedexdeliverymanager_cookies.pickle' CONF_UPDATE_INTERVAL = 'update_interval' +COOKIE = 'fedexdeliverymanager_cookies.pickle' + +DOMAIN = 'fedex' + ICON = 'mdi:package-variant-closed' + STATUS_DELIVERED = 'delivered' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -40,19 +43,19 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Fedex platform.""" + """Set up the Fedex platform.""" import fedexdeliverymanager try: cookie = hass.config.path(COOKIE) - session = fedexdeliverymanager.get_session(config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - cookie_path=cookie) + session = fedexdeliverymanager.get_session( + config.get(CONF_USERNAME), config.get(CONF_PASSWORD), + cookie_path=cookie) except fedexdeliverymanager.FedexError: - _LOGGER.exception('Could not connect to Fedex Delivery Manager') + _LOGGER.exception("Could not connect to Fedex Delivery Manager") return False - add_devices([FedexSensor(session, config.get(CONF_NAME), - config.get(CONF_UPDATE_INTERVAL))]) + add_devices([FedexSensor( + session, config.get(CONF_NAME), config.get(CONF_UPDATE_INTERVAL))]) class FedexSensor(Entity): diff --git a/homeassistant/components/sensor/fido.py b/homeassistant/components/sensor/fido.py index 5deb00db67b..c4f4217616f 100644 --- a/homeassistant/components/sensor/fido.py +++ b/homeassistant/components/sensor/fido.py @@ -21,61 +21,44 @@ from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle import homeassistant.helpers.config_validation as cv -REQUIREMENTS = ["pyfido==1.0.1"] +REQUIREMENTS = ['pyfido==1.0.1'] _LOGGER = logging.getLogger(__name__) -KILOBITS = "Kb" # type: str -PRICE = "CAD" # type: str -MESSAGES = "messages" # type: str -MINUTES = "minutes" # type: str +KILOBITS = 'Kb' # type: str +PRICE = 'CAD' # type: str +MESSAGES = 'messages' # type: str +MINUTES = 'minutes' # type: str -DEFAULT_NAME = "Fido" +DEFAULT_NAME = 'Fido' REQUESTS_TIMEOUT = 15 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) SENSOR_TYPES = { - 'fido_dollar': ['Fido dollar', - PRICE, 'mdi:square-inc-cash'], - 'balance': ['Balance', - PRICE, 'mdi:square-inc-cash'], - 'data_used': ['Data used', - KILOBITS, 'mdi:download'], - 'data_limit': ['Data limit', - KILOBITS, 'mdi:download'], - 'data_remaining': ['Data remaining', - KILOBITS, 'mdi:download'], - 'text_used': ['Text used', - MESSAGES, 'mdi:message-text'], - 'text_limit': ['Text limit', - MESSAGES, 'mdi:message-text'], - 'text_remaining': ['Text remaining', - MESSAGES, 'mdi:message-text'], - 'mms_used': ['MMS used', - MESSAGES, 'mdi:message-image'], - 'mms_limit': ['MMS limit', - MESSAGES, 'mdi:message-image'], - 'mms_remaining': ['MMS remaining', - MESSAGES, 'mdi:message-image'], + 'fido_dollar': ['Fido dollar', PRICE, 'mdi:square-inc-cash'], + 'balance': ['Balance', PRICE, 'mdi:square-inc-cash'], + 'data_used': ['Data used', KILOBITS, 'mdi:download'], + 'data_limit': ['Data limit', KILOBITS, 'mdi:download'], + 'data_remaining': ['Data remaining', KILOBITS, 'mdi:download'], + 'text_used': ['Text used', MESSAGES, 'mdi:message-text'], + 'text_limit': ['Text limit', MESSAGES, 'mdi:message-text'], + 'text_remaining': ['Text remaining', MESSAGES, 'mdi:message-text'], + 'mms_used': ['MMS used', MESSAGES, 'mdi:message-image'], + 'mms_limit': ['MMS limit', MESSAGES, 'mdi:message-image'], + 'mms_remaining': ['MMS remaining', MESSAGES, 'mdi:message-image'], 'text_int_used': ['International text used', MESSAGES, 'mdi:message-alert'], 'text_int_limit': ['International text limit', MESSAGES, 'mdi:message-alart'], 'text_int_remaining': ['Internaltional remaining', MESSAGES, 'mdi:message-alert'], - 'talk_used': ['Talk used', - MINUTES, 'mdi:cellphone'], - 'talk_limit': ['Talk limit', - MINUTES, 'mdi:cellphone'], - 'talt_remaining': ['Talk remaining', - MINUTES, 'mdi:cellphone'], - 'other_talk_used': ['Other Talk used', - MINUTES, 'mdi:cellphone'], - 'other_talk_limit': ['Other Talk limit', - MINUTES, 'mdi:cellphone'], - 'other_talk_remaining': ['Other Talk remaining', - MINUTES, 'mdi:cellphone'], + 'talk_used': ['Talk used', MINUTES, 'mdi:cellphone'], + 'talk_limit': ['Talk limit', MINUTES, 'mdi:cellphone'], + 'talt_remaining': ['Talk remaining', MINUTES, 'mdi:cellphone'], + 'other_talk_used': ['Other Talk used', MINUTES, 'mdi:cellphone'], + 'other_talk_limit': ['Other Talk limit', MINUTES, 'mdi:cellphone'], + 'other_talk_remaining': ['Other Talk remaining', MINUTES, 'mdi:cellphone'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ diff --git a/homeassistant/components/sensor/fitbit.py b/homeassistant/components/sensor/fitbit.py index 697fecca077..d976da723d6 100644 --- a/homeassistant/components/sensor/fitbit.py +++ b/homeassistant/components/sensor/fitbit.py @@ -156,7 +156,7 @@ def request_app_setup(hass, config, add_devices, config_path, # pylint: disable=unused-argument def fitbit_configuration_callback(callback_data): - """The actions to do when our configuration callback is called.""" + """Handle configuration updates.""" config_path = hass.config.path(FITBIT_CONFIG_FILE) if os.path.isfile(config_path): config_file = config_from_file(config_path) @@ -201,7 +201,7 @@ def request_oauth_completion(hass): # pylint: disable=unused-argument def fitbit_configuration_callback(callback_data): - """The actions to do when our configuration callback is called.""" + """Handle configuration updates.""" start_url = '{}{}'.format(hass.config.api.base_url, FITBIT_AUTH_START) diff --git a/homeassistant/components/sensor/fixer.py b/homeassistant/components/sensor/fixer.py index b30b660516d..87fafe2c27c 100644 --- a/homeassistant/components/sensor/fixer.py +++ b/homeassistant/components/sensor/fixer.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Fixer.io sensor.""" + """Set up the Fixer.io sensor.""" from fixerio import (Fixerio, exceptions) name = config.get(CONF_NAME) @@ -51,7 +51,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: Fixerio(base=base, symbols=[target], secure=True).latest() except exceptions.FixerioException: - _LOGGER.error('One of the given currencies is not supported') + _LOGGER.error("One of the given currencies is not supported") return False data = ExchangeData(base, target) @@ -116,9 +116,9 @@ class ExchangeData(object): self.rate = None self.base_currency = base_currency self.target_currency = target_currency - self.exchange = Fixerio(base=self.base_currency, - symbols=[self.target_currency], - secure=True) + self.exchange = Fixerio( + base=self.base_currency, symbols=[self.target_currency], + secure=True) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): diff --git a/homeassistant/components/sensor/fritzbox_callmonitor.py b/homeassistant/components/sensor/fritzbox_callmonitor.py index 956ca3fe495..ea2fcd026b3 100644 --- a/homeassistant/components/sensor/fritzbox_callmonitor.py +++ b/homeassistant/components/sensor/fritzbox_callmonitor.py @@ -24,20 +24,22 @@ from homeassistant.util import Throttle REQUIREMENTS = ['fritzconnection==0.6.3'] _LOGGER = logging.getLogger(__name__) -DEFAULT_NAME = 'Phone' -DEFAULT_HOST = '169.254.1.1' # IP valid for all Fritz!Box routers -DEFAULT_PORT = 1012 -VALUE_DEFAULT = 'idle' -VALUE_RING = 'ringing' -VALUE_CALL = 'dialing' -VALUE_CONNECT = 'talking' -VALUE_DISCONNECT = 'idle' CONF_PHONEBOOK = 'phonebook' CONF_PREFIXES = 'prefixes' +DEFAULT_HOST = '169.254.1.1' # IP valid for all Fritz!Box routers +DEFAULT_NAME = 'Phone' +DEFAULT_PORT = 1012 + INTERVAL_RECONNECT = 60 +VALUE_CALL = 'dialing' +VALUE_CONNECT = 'talking' +VALUE_DEFAULT = 'idle' +VALUE_DISCONNECT = 'idle' +VALUE_RING = 'ringing' + # Return cached results if phonebook was downloaded less then this time ago. MIN_TIME_PHONEBOOK_UPDATE = datetime.timedelta(hours=6) SCAN_INTERVAL = datetime.timedelta(hours=3) @@ -49,13 +51,13 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_PASSWORD, default='admin'): cv.string, vol.Optional(CONF_USERNAME, default=''): cv.string, vol.Optional(CONF_PHONEBOOK, default=0): cv.positive_int, - vol.Optional(CONF_PREFIXES, default=[]): vol.All(cv.ensure_list, - [cv.string]) + vol.Optional(CONF_PREFIXES, default=[]): + vol.All(cv.ensure_list, [cv.string]) }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Fritz!Box call monitor sensor platform.""" + """Set up Fritz!Box call monitor sensor platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -65,14 +67,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): prefixes = config.get('prefixes') try: - phonebook = FritzBoxPhonebook(host=host, port=port, - username=username, password=password, - phonebook_id=phonebook_id, - prefixes=prefixes) + phonebook = FritzBoxPhonebook( + host=host, port=port, username=username, password=password, + phonebook_id=phonebook_id, prefixes=prefixes) # pylint: disable=bare-except except: phonebook = None - _LOGGER.warning('Phonebook with ID %s not found on Fritz!Box', + _LOGGER.warning("Phonebook with ID %s not found on Fritz!Box", phonebook_id) sensor = FritzBoxCallSensor(name=name, phonebook=phonebook) @@ -116,7 +117,7 @@ class FritzBoxCallSensor(Entity): @property def should_poll(self): - """Polling needed only to update phonebook, if defined.""" + """Only poll to update phonebook, if defined.""" if self.phonebook is None: return False else: @@ -250,9 +251,8 @@ class FritzBoxPhonebook(object): # pylint: disable=import-error import fritzconnection as fc # Establish a connection to the FRITZ!Box. - self.fph = fc.FritzPhonebook(address=self.host, - user=self.username, - password=self.password) + self.fph = fc.FritzPhonebook( + address=self.host, user=self.username, password=self.password) if self.phonebook_id not in self.fph.list_phonebooks: raise ValueError("Phonebook with this ID not found.") @@ -266,7 +266,7 @@ class FritzBoxPhonebook(object): self.number_dict = {re.sub(r'[^\d\+]', '', nr): name for name, nrs in self.phonebook_dict.items() for nr in nrs} - _LOGGER.info('Fritz!Box phone book successfully updated.') + _LOGGER.info("Fritz!Box phone book successfully updated") def get_name(self, number): """Return a name for a given phone number.""" diff --git a/homeassistant/components/sensor/fritzbox_netmonitor.py b/homeassistant/components/sensor/fritzbox_netmonitor.py index ba0ee8be1b9..003307fbd83 100644 --- a/homeassistant/components/sensor/fritzbox_netmonitor.py +++ b/homeassistant/components/sensor/fritzbox_netmonitor.py @@ -19,19 +19,21 @@ from requests.exceptions import RequestException REQUIREMENTS = ['fritzconnection==0.6.3'] -MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) +_LOGGER = logging.getLogger(__name__) CONF_DEFAULT_IP = '169.254.1.1' # This IP is valid for all FRITZ!Box routers. -ATTR_IS_LINKED = "is_linked" -ATTR_IS_CONNECTED = "is_connected" -ATTR_WAN_ACCESS_TYPE = "wan_access_type" -ATTR_EXTERNAL_IP = "external_ip" -ATTR_UPTIME = "uptime" -ATTR_BYTES_SENT = "bytes_sent" -ATTR_BYTES_RECEIVED = "bytes_received" -ATTR_MAX_BYTE_RATE_UP = "max_byte_rate_up" -ATTR_MAX_BYTE_RATE_DOWN = "max_byte_rate_down" +ATTR_BYTES_RECEIVED = 'bytes_received' +ATTR_BYTES_SENT = 'bytes_sent' +ATTR_EXTERNAL_IP = 'external_ip' +ATTR_IS_CONNECTED = 'is_connected' +ATTR_IS_LINKED = 'is_linked' +ATTR_MAX_BYTE_RATE_DOWN = 'max_byte_rate_down' +ATTR_MAX_BYTE_RATE_UP = 'max_byte_rate_up' +ATTR_UPTIME = 'uptime' +ATTR_WAN_ACCESS_TYPE = 'wan_access_type' + +MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) STATE_ONLINE = 'online' STATE_OFFLINE = 'offline' @@ -42,8 +44,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default=CONF_DEFAULT_IP): cv.string, }) -_LOGGER = logging.getLogger(__name__) - def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the fritzbox monitor sensors.""" diff --git a/homeassistant/components/sensor/glances.py b/homeassistant/components/sensor/glances.py index 699781d323b..ef9ea3138bd 100644 --- a/homeassistant/components/sensor/glances.py +++ b/homeassistant/components/sensor/glances.py @@ -93,7 +93,7 @@ class GlancesSensor(Entity): @property def name(self): - """The name of the sensor.""" + """Return the name of the sensor.""" if self._name is None: return SENSOR_TYPES[self.type][0] else: diff --git a/homeassistant/components/sensor/google_travel_time.py b/homeassistant/components/sensor/google_travel_time.py index 6c625ce8038..0e495c67817 100644 --- a/homeassistant/components/sensor/google_travel_time.py +++ b/homeassistant/components/sensor/google_travel_time.py @@ -73,15 +73,15 @@ TRACKABLE_DOMAINS = ['device_tracker', 'sensor', 'zone'] def convert_time_to_utc(timestr): """Take a string like 08:00:00 and convert it to a unix timestamp.""" - combined = datetime.combine(dt_util.start_of_local_day(), - dt_util.parse_time(timestr)) + combined = datetime.combine( + dt_util.start_of_local_day(), dt_util.parse_time(timestr)) if combined < datetime.now(): combined = combined + timedelta(days=1) return dt_util.as_timestamp(combined) def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the Google travel time platform.""" + """Set up the Google travel time platform.""" def run_setup(event): """Delay the setup until Home Assistant is fully initialized. @@ -225,9 +225,8 @@ class GoogleTravelTimeSensor(Entity): self._origin = self._resolve_zone(self._origin) if self._destination is not None and self._origin is not None: - self._matrix = self._client.distance_matrix(self._origin, - self._destination, - **options_copy) + self._matrix = self._client.distance_matrix( + self._origin, self._destination, **options_copy) def _get_location_from_entity(self, entity_id): """Get the location from the entity state or attributes.""" @@ -246,7 +245,7 @@ class GoogleTravelTimeSensor(Entity): zone_entity = self._hass.states.get("zone.%s" % entity.state) if location.has_location(zone_entity): _LOGGER.debug( - "%s is in %s, getting zone location.", + "%s is in %s, getting zone location", entity_id, zone_entity.entity_id ) return self._get_location_from_attributes(zone_entity) diff --git a/homeassistant/components/sensor/gpsd.py b/homeassistant/components/sensor/gpsd.py index f6f9e75df31..9027802c295 100644 --- a/homeassistant/components/sensor/gpsd.py +++ b/homeassistant/components/sensor/gpsd.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the GPSD component.""" + """Set up the GPSD component.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -57,9 +57,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: sock.connect((host, port)) sock.shutdown(2) - _LOGGER.debug('Connection to GPSD possible') + _LOGGER.debug("Connection to GPSD possible") except socket.error: - _LOGGER.error('Not able to connect to GPSD') + _LOGGER.error("Not able to connect to GPSD") return False add_devices([GpsdSensor(hass, name, host, port)]) diff --git a/homeassistant/components/sensor/gtfs.py b/homeassistant/components/sensor/gtfs.py index 2726f1f579f..961b8067009 100644 --- a/homeassistant/components/sensor/gtfs.py +++ b/homeassistant/components/sensor/gtfs.py @@ -160,7 +160,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): os.makedirs(gtfs_dir) if not os.path.exists(os.path.join(gtfs_dir, data)): - _LOGGER.error("The given GTFS data file/folder was not found!") + _LOGGER.error("The given GTFS data file/folder was not found") return False import pygtfs @@ -222,8 +222,8 @@ class GTFSDepartureSensor(Entity): def update(self): """Get the latest data from GTFS and update the states.""" with self.lock: - self._departure = get_next_departure(self._pygtfs, self.origin, - self.destination) + self._departure = get_next_departure( + self._pygtfs, self.origin, self.destination) if not self._departure: self._state = 0 self._attributes = {'Info': 'No more departures today'} diff --git a/homeassistant/components/sensor/haveibeenpwned.py b/homeassistant/components/sensor/haveibeenpwned.py index f5b6d8cfba0..1c28db9a9df 100644 --- a/homeassistant/components/sensor/haveibeenpwned.py +++ b/homeassistant/components/sensor/haveibeenpwned.py @@ -102,10 +102,9 @@ class HaveIBeenPwnedSensor(Entity): # data after hass startup once we have the data it will update as # normal using update if self._email not in self._data.data: - track_point_in_time(self._hass, - self.update_nothrottle, - dt_util.now() + - MIN_TIME_BETWEEN_FORCED_UPDATES) + track_point_in_time( + self._hass, self.update_nothrottle, + dt_util.now() + MIN_TIME_BETWEEN_FORCED_UPDATES) return if self._email in self._data.data: @@ -153,7 +152,7 @@ class HaveIBeenPwnedData(object): allow_redirects=True, timeout=5) except requests.exceptions.RequestException: - _LOGGER.error("failed fetching HaveIBeenPwned Data for '%s'", + _LOGGER.error("Failed fetching HaveIBeenPwned Data for %s", self._email) return @@ -174,6 +173,6 @@ class HaveIBeenPwnedData(object): self.set_next_email() else: - _LOGGER.error("failed fetching HaveIBeenPwned Data for '%s'" + _LOGGER.error("Failed fetching HaveIBeenPwned Data for %s" "(HTTP Status_code = %d)", self._email, req.status_code) diff --git a/homeassistant/components/sensor/hddtemp.py b/homeassistant/components/sensor/hddtemp.py index c0e3dc32d4d..b7ba91ba94a 100644 --- a/homeassistant/components/sensor/hddtemp.py +++ b/homeassistant/components/sensor/hddtemp.py @@ -38,7 +38,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the HDDTemp sensor.""" + """Set up the HDDTemp sensor.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -118,6 +118,6 @@ class HddTempData(object): host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT) self.data = connection.read_all().decode('ascii') except ConnectionRefusedError: - _LOGGER.error('HDDTemp is not available at %s:%s', self.host, - self.port) + _LOGGER.error( + "HDDTemp is not available at %s:%s", self.host, self.port) self.data = None diff --git a/homeassistant/components/sensor/history_stats.py b/homeassistant/components/sensor/history_stats.py index fe073b89fcd..7d9dfaaa48f 100644 --- a/homeassistant/components/sensor/history_stats.py +++ b/homeassistant/components/sensor/history_stats.py @@ -4,7 +4,6 @@ Component to make instant statistics about your history. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.history_stats/ """ - import datetime import logging import math @@ -152,7 +151,7 @@ class HistoryStatsSensor(Entity): @property def should_poll(self): - """Polling required.""" + """Return the polling state.""" return True @property @@ -239,8 +238,8 @@ class HistoryStatsSensor(Entity): start = dt_util.as_local(dt_util.utc_from_timestamp( math.floor(float(start_rendered)))) except ValueError: - _LOGGER.error('PARSING ERROR: start must be a datetime' - ' or a timestamp.') + _LOGGER.error("Parsing error: start must be a datetime" + "or a timestamp") return # Parse end @@ -256,8 +255,8 @@ class HistoryStatsSensor(Entity): end = dt_util.as_local(dt_util.utc_from_timestamp( math.floor(float(end_rendered)))) except ValueError: - _LOGGER.error('PARSING ERROR: end must be a datetime' - ' or a timestamp.') + _LOGGER.error("Parsing error: end must be a datetime " + "or a timestamp") return # Calculate start or end using the duration @@ -305,5 +304,5 @@ class HistoryStatsHelper: # Common during HA startup - so just a warning _LOGGER.warning(ex) return - _LOGGER.error('Error parsing template for [' + field + ']') + _LOGGER.error("Error parsing template for field %s", field) _LOGGER.error(ex) diff --git a/homeassistant/components/sensor/homematic.py b/homeassistant/components/sensor/homematic.py index 2215597f506..44ba7dfa753 100644 --- a/homeassistant/components/sensor/homematic.py +++ b/homeassistant/components/sensor/homematic.py @@ -3,11 +3,7 @@ The homematic sensor platform. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.homematic/ - -Important: For this platform to work the homematic component has to be -properly configured. """ - import logging from homeassistant.const import STATE_UNKNOWN from homeassistant.components.homematic import HMDevice, ATTR_DISCOVER_DEVICES @@ -17,45 +13,45 @@ _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['homematic'] HM_STATE_HA_CAST = { - "RotaryHandleSensor": {0: "closed", 1: "tilted", 2: "open"}, - "WaterSensor": {0: "dry", 1: "wet", 2: "water"}, - "CO2Sensor": {0: "normal", 1: "added", 2: "strong"}, + 'RotaryHandleSensor': {0: 'closed', 1: 'tilted', 2: 'open'}, + 'WaterSensor': {0: 'dry', 1: 'wet', 2: 'water'}, + 'CO2Sensor': {0: 'normal', 1: 'added', 2: 'strong'}, } HM_UNIT_HA_CAST = { - "HUMIDITY": "%", - "TEMPERATURE": "°C", - "BRIGHTNESS": "#", - "POWER": "W", - "CURRENT": "mA", - "VOLTAGE": "V", - "ENERGY_COUNTER": "Wh", - "GAS_POWER": "m3", - "GAS_ENERGY_COUNTER": "m3", - "LUX": "lux", - "RAIN_COUNTER": "mm", - "WIND_SPEED": "km/h", - "WIND_DIRECTION": "°", - "WIND_DIRECTION_RANGE": "°", - "SUNSHINEDURATION": "#", - "AIR_PRESSURE": "hPa", - "FREQUENCY": "Hz", - "VALUE": "#", + 'HUMIDITY': '%', + 'TEMPERATURE': '°C', + 'BRIGHTNESS': '#', + 'POWER': 'W', + 'CURRENT': 'mA', + 'VOLTAGE': 'V', + 'ENERGY_COUNTER': 'Wh', + 'GAS_POWER': 'm3', + 'GAS_ENERGY_COUNTER': 'm3', + 'LUX': 'lux', + 'RAIN_COUNTER': 'mm', + 'WIND_SPEED': 'km/h', + 'WIND_DIRECTION': '°', + 'WIND_DIRECTION_RANGE': '°', + 'SUNSHINEDURATION': '#', + 'AIR_PRESSURE': 'hPa', + 'FREQUENCY': 'Hz', + 'VALUE': '#', } HM_ICON_HA_CAST = { - "WIND_SPEED": 'mdi:weather-windy', - "HUMIDITY": 'mdi:water-percent', - "TEMPERATURE": 'mdi:thermometer', - "LUX": 'mdi:weather-sunny', - "BRIGHTNESS": 'mdi:invert-colors', - "POWER": 'mdi:flash-red-eye', - "CURRENT": "mdi:flash-red-eye", + 'WIND_SPEED': 'mdi:weather-windy', + 'HUMIDITY': 'mdi:water-percent', + 'TEMPERATURE': 'mdi:thermometer', + 'LUX': 'mdi:weather-sunny', + 'BRIGHTNESS': 'mdi:invert-colors', + 'POWER': 'mdi:flash-red-eye', + 'CURRENT': 'mdi:flash-red-eye', } def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the platform.""" + """Set up the Homematic platform.""" if discovery_info is None: return @@ -96,8 +92,8 @@ class HMSensor(HMDevice): """Generate a data dict (self._data) from hm metadata.""" # Add state to data dict if self._state: - _LOGGER.debug("%s init datadict with main node '%s'", self._name, + _LOGGER.debug("%s init datadict with main node %s", self._name, self._state) self._data.update({self._state: STATE_UNKNOWN}) else: - _LOGGER.critical("Can't correctly init sensor %s.", self._name) + _LOGGER.critical("Can't correctly init sensor %s", self._name) diff --git a/homeassistant/components/sensor/hp_ilo.py b/homeassistant/components/sensor/hp_ilo.py index 675db6400a0..338a6e7aff5 100644 --- a/homeassistant/components/sensor/hp_ilo.py +++ b/homeassistant/components/sensor/hp_ilo.py @@ -26,7 +26,6 @@ DEFAULT_PORT = 443 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300) -# Each sensor is defined as follows: 'Descriptive name', 'python-ilo function' SENSOR_TYPES = { 'server_name': ['Server Name', 'get_server_name'], 'server_fqdn': ['Server FQDN', 'get_server_fqdn'], @@ -74,9 +73,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): # Initialize and add all of the sensors. devices = [] for ilo_type in monitored_variables: - new_device = HpIloSensor(hp_ilo_data=hp_ilo_data, - sensor_type=SENSOR_TYPES.get(ilo_type), - client_name=name) + new_device = HpIloSensor( + hp_ilo_data=hp_ilo_data, sensor_type=SENSOR_TYPES.get(ilo_type), + client_name=name) devices.append(new_device) add_devices(devices) @@ -161,10 +160,9 @@ class HpIloData(object): import hpilo try: - self.data = hpilo.Ilo(hostname=self._host, - login=self._login, - password=self._password, - port=self._port) + self.data = hpilo.Ilo( + hostname=self._host, login=self._login, + password=self._password, port=self._port) except (hpilo.IloError, hpilo.IloCommunicationError, hpilo.IloLoginFailed) as error: raise ValueError("Unable to init HP ILO, %s", error) diff --git a/homeassistant/components/sensor/hydroquebec.py b/homeassistant/components/sensor/hydroquebec.py index 9fcabd62d76..c96909e5bc1 100644 --- a/homeassistant/components/sensor/hydroquebec.py +++ b/homeassistant/components/sensor/hydroquebec.py @@ -25,12 +25,12 @@ REQUIREMENTS = ['pyhydroquebec==1.1.0'] _LOGGER = logging.getLogger(__name__) -KILOWATT_HOUR = "kWh" # type: str -PRICE = "CAD" # type: str -DAYS = "days" # type: str -CONF_CONTRACT = "contract" # type: str +KILOWATT_HOUR = 'kWh' # type: str +PRICE = 'CAD' # type: str +DAYS = 'days' # type: str +CONF_CONTRACT = 'contract' # type: str -DEFAULT_NAME = "HydroQuebec" +DEFAULT_NAME = 'HydroQuebec' REQUESTS_TIMEOUT = 15 MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1) @@ -73,10 +73,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) -HOST = "https://www.hydroquebec.com" -HOME_URL = "{}/portail/web/clientele/authentification".format(HOST) -PROFILE_URL = ("{}/portail/fr/group/clientele/" - "portrait-de-consommation".format(HOST)) +HOST = 'https://www.hydroquebec.com' +HOME_URL = '{}/portail/web/clientele/authentification'.format(HOST) +PROFILE_URL = ('{}/portail/fr/group/clientele/' + 'portrait-de-consommation'.format(HOST)) MONTHLY_MAP = (('period_total_bill', 'montantFacturePeriode'), ('period_length', 'nbJourLecturePeriode'), ('period_total_days', 'nbJourPrevuPeriode'), @@ -163,9 +163,8 @@ class HydroquebecData(object): def __init__(self, username, password, contract=None): """Initialize the data object.""" from pyhydroquebec import HydroQuebecClient - self.client = HydroQuebecClient(username, - password, - REQUESTS_TIMEOUT) + self.client = HydroQuebecClient( + username, password, REQUESTS_TIMEOUT) self._contract = contract self.data = {} @@ -187,7 +186,5 @@ class HydroquebecData(object): @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Return the latest collected data from HydroQuebec.""" - # Fetch data self._fetch_data() - # Update data self.data = self.client.get_data(self._contract)[self._contract] diff --git a/homeassistant/components/sensor/imap.py b/homeassistant/components/sensor/imap.py index 4d7f34ef682..dc772df48c0 100644 --- a/homeassistant/components/sensor/imap.py +++ b/homeassistant/components/sensor/imap.py @@ -31,12 +31,11 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the IMAP platform.""" - sensor = ImapSensor(config.get(CONF_NAME, None), - config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - config.get(CONF_SERVER), - config.get(CONF_PORT)) + """Set up the IMAP platform.""" + sensor = ImapSensor( + config.get(CONF_NAME, None), config.get(CONF_USERNAME), + config.get(CONF_PASSWORD), config.get(CONF_SERVER), + config.get(CONF_PORT)) if sensor.connection: add_devices([sensor]) diff --git a/homeassistant/components/sensor/imap_email_content.py b/homeassistant/components/sensor/imap_email_content.py index 65ae27b4de3..99613f0f7e8 100644 --- a/homeassistant/components/sensor/imap_email_content.py +++ b/homeassistant/components/sensor/imap_email_content.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the EMail platform.""" + """Set up the Email sensor platform.""" reader = EmailReader( config.get(CONF_USERNAME), config.get(CONF_PASSWORD), config.get(CONF_SERVER), config.get(CONF_PORT)) diff --git a/homeassistant/components/sensor/influxdb.py b/homeassistant/components/sensor/influxdb.py index 035c894ba0c..b4688c77e1b 100644 --- a/homeassistant/components/sensor/influxdb.py +++ b/homeassistant/components/sensor/influxdb.py @@ -65,7 +65,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the InfluxDB component.""" + """Set up the InfluxDB component.""" influx_conf = {'host': config[CONF_HOST], 'port': config.get(CONF_PORT), 'username': config.get(CONF_USERNAME), @@ -105,13 +105,11 @@ class InfluxSensor(Entity): query.get(CONF_FIELD), query.get(CONF_MEASUREMENT_NAME), query.get(CONF_WHERE)) - influx = InfluxDBClient(host=influx_conf['host'], - port=influx_conf['port'], - username=influx_conf['username'], - password=influx_conf['password'], - database=database, - ssl=influx_conf['ssl'], - verify_ssl=influx_conf['verify_ssl']) + influx = InfluxDBClient( + host=influx_conf['host'], port=influx_conf['port'], + username=influx_conf['username'], password=influx_conf['password'], + database=database, ssl=influx_conf['ssl'], + verify_ssl=influx_conf['verify_ssl']) try: influx.query("select * from /.*/ LIMIT 1;") self.connected = True @@ -135,12 +133,12 @@ class InfluxSensor(Entity): @property def unit_of_measurement(self): - """Unit of measurement of this entity, if any.""" + """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def should_poll(self): - """Polling needed.""" + """Return the polling state.""" return True def update(self): @@ -172,11 +170,11 @@ class InfluxSensorData(object): points = list(self.influx.query(self.query).get_points()) if not points: - _LOGGER.warning("Query returned no points, sensor state set" - " to UNKNOWN : %s", self.query) + _LOGGER.warning("Query returned no points, sensor state set " + "to UNKNOWN: %s", self.query) self.value = None else: if points: - _LOGGER.warning("Query returned multiple points, only first" - " one shown : %s", self.query) + _LOGGER.warning("Query returned multiple points, only first " + "one shown: %s", self.query) self.value = points[0].get('value') diff --git a/homeassistant/components/sensor/ios.py b/homeassistant/components/sensor/ios.py index 1455431e5f7..c3bcbf60828 100644 --- a/homeassistant/components/sensor/ios.py +++ b/homeassistant/components/sensor/ios.py @@ -7,24 +7,24 @@ https://home-assistant.io/ecosystem/ios/ from homeassistant.components import ios from homeassistant.helpers.entity import Entity -DEPENDENCIES = ["ios"] +DEPENDENCIES = ['ios'] SENSOR_TYPES = { - "level": ["Battery Level", "%"], - "state": ["Battery State", None] + 'level': ['Battery Level', '%'], + 'state': ['Battery State', None] } -DEFAULT_ICON_LEVEL = "mdi:battery" -DEFAULT_ICON_STATE = "mdi:power-plug" +DEFAULT_ICON_LEVEL = 'mdi:battery' +DEFAULT_ICON_STATE = 'mdi:power-plug' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the iOS sensor.""" + """Set up the iOS sensor.""" if discovery_info is None: return dev = list() for device_name, device in ios.devices().items(): - for sensor_type in ("level", "state"): + for sensor_type in ('level', 'state'): dev.append(IOSSensor(sensor_type, device_name, device)) add_devices(dev) @@ -36,7 +36,7 @@ class IOSSensor(Entity): def __init__(self, sensor_type, device_name, device): """Initialize the sensor.""" self._device_name = device_name - self._name = device_name + " " + SENSOR_TYPES[sensor_type][0] + self._name = "{} {}".format(device_name, SENSOR_TYPES[sensor_type][0]) self._device = device self.type = sensor_type self._state = None diff --git a/homeassistant/components/sensor/knx.py b/homeassistant/components/sensor/knx.py index fef02710b9e..1178938ce49 100644 --- a/homeassistant/components/sensor/knx.py +++ b/homeassistant/components/sensor/knx.py @@ -4,19 +4,18 @@ Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ -from homeassistant.const import (TEMP_CELSIUS, TEMPERATURE, CONF_TYPE, - ILLUMINANCE, SPEED_MS, CONF_MINIMUM, - CONF_MAXIMUM) +from homeassistant.const import ( + TEMP_CELSIUS, TEMPERATURE, CONF_TYPE, ILLUMINANCE, SPEED_MS, CONF_MINIMUM, + CONF_MAXIMUM) from homeassistant.components.knx import (KNXConfig, KNXGroupAddress) - -DEPENDENCIES = ["knx"] +DEPENDENCIES = ['knx'] # Speed units -SPEED_METERPERSECOND = "m/s" # type: str +SPEED_METERPERSECOND = 'm/s' # type: str # Illuminance units -ILLUMINANCE_LUX = "lx" # type: str +ILLUMINANCE_LUX = 'lx' # type: str # Predefined Minimum, Maximum Values for Sensors # Temperature as defined in KNX Standard 3.10 - 9.001 DPT_Value_Temp @@ -33,25 +32,25 @@ KNX_SPEED_MS_MAX = 670760 def setup_platform(hass, config, add_entities, discovery_info=None): - """Setup the KNX Sensor platform.""" + """Set up the KNX Sensor platform.""" # Add KNX Temperature Sensors # KNX Datapoint 9.001 DPT_Value_Temp if config[CONF_TYPE] == TEMPERATURE: minimum_value, maximum_value = \ - update_and_define_min_max(config, KNX_TEMP_MIN, - KNX_TEMP_MAX) + update_and_define_min_max(config, KNX_TEMP_MIN, KNX_TEMP_MAX) add_entities([ - KNXSensorFloatClass(hass, KNXConfig(config), TEMP_CELSIUS, - minimum_value, maximum_value) + KNXSensorFloatClass( + hass, KNXConfig(config), TEMP_CELSIUS, minimum_value, + maximum_value) ]) # Add KNX Speed Sensors(Like Wind Speed) # KNX Datapoint 9.005 DPT_Value_Wsp elif config[CONF_TYPE] == SPEED_MS: minimum_value, maximum_value = \ - update_and_define_min_max(config, KNX_SPEED_MS_MIN, - KNX_SPEED_MS_MAX) + update_and_define_min_max( + config, KNX_SPEED_MS_MIN, KNX_SPEED_MS_MAX) add_entities([ KNXSensorFloatClass(hass, KNXConfig(config), SPEED_METERPERSECOND, @@ -70,9 +69,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None): ]) -def update_and_define_min_max(config, minimum_default, - maximum_default): - """Function help determinate a min/max value defined in config.""" +def update_and_define_min_max(config, minimum_default, maximum_default): + """Determinate a min/max value defined in the configuration.""" minimum_value = minimum_default maximum_value = maximum_default if config.get(CONF_MINIMUM): diff --git a/homeassistant/components/sensor/kwb.py b/homeassistant/components/sensor/kwb.py index 54799ccc6b4..0641917145b 100644 --- a/homeassistant/components/sensor/kwb.py +++ b/homeassistant/components/sensor/kwb.py @@ -15,7 +15,6 @@ from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv - REQUIREMENTS = ['pykwb==0.0.8'] _LOGGER = logging.getLogger(__name__) @@ -50,7 +49,7 @@ PLATFORM_SCHEMA = vol.Schema( def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the KWB component.""" + """Set up the KWB component.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) device = config.get(CONF_DEVICE) diff --git a/homeassistant/components/sensor/linux_battery.py b/homeassistant/components/sensor/linux_battery.py index ddfb12f008b..18e2250ee13 100644 --- a/homeassistant/components/sensor/linux_battery.py +++ b/homeassistant/components/sensor/linux_battery.py @@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Linux Battery sensor.""" + """Set up the Linux Battery sensor.""" name = config.get(CONF_NAME) battery_id = config.get(CONF_BATTERY) diff --git a/homeassistant/components/sensor/loopenergy.py b/homeassistant/components/sensor/loopenergy.py index ebd044343b0..a2d6b0c3a0c 100644 --- a/homeassistant/components/sensor/loopenergy.py +++ b/homeassistant/components/sensor/loopenergy.py @@ -59,7 +59,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Loop Energy sensors.""" + """Set up the Loop Energy sensors.""" import pyloopenergy elec_config = config.get(CONF_ELEC) @@ -77,7 +77,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): def stop_loopenergy(event): """Shutdown loopenergy thread on exit.""" - _LOGGER.info("Shutting down loopenergy.") + _LOGGER.info("Shutting down loopenergy") controller.terminate() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_loopenergy) diff --git a/homeassistant/components/sensor/lyft.py b/homeassistant/components/sensor/lyft.py index 8a8609f8914..c16fae9f5d5 100644 --- a/homeassistant/components/sensor/lyft.py +++ b/homeassistant/components/sensor/lyft.py @@ -79,8 +79,8 @@ class LyftSensor(Entity): self._product_id = product_id self._product = product self._sensortype = sensorType - self._name = '{} {}'.format(self._product['display_name'], - self._sensortype) + self._name = '{} {}'.format( + self._product['display_name'], self._sensortype) if 'lyft' not in self._name.lower(): self._name = 'Lyft{}'.format(self._name) if self._sensortype == 'time': diff --git a/homeassistant/components/sensor/metoffice.py b/homeassistant/components/sensor/metoffice.py index 725fca1db44..c1ffb01d212 100644 --- a/homeassistant/components/sensor/metoffice.py +++ b/homeassistant/components/sensor/metoffice.py @@ -4,7 +4,6 @@ Support for UK Met Office weather service. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.metoffice/ """ - import logging from datetime import timedelta @@ -25,17 +24,17 @@ REQUIREMENTS = ['datapoint==0.4.3'] CONF_ATTRIBUTION = "Data provided by the Met Office" CONDITION_CLASSES = { - 'cloudy': ["7", "8"], - 'fog': ["5", "6"], - 'hail': ["19", "20", "21"], - 'lightning': ["30"], - 'lightning-rainy': ["28", "29"], - 'partlycloudy': ["2", "3"], - 'pouring': ["13", "14", "15"], - 'rainy': ["9", "10", "11", "12"], - 'snowy': ["22", "23", "24", "25", "26", "27"], - 'snowy-rainy': ["16", "17", "18"], - 'sunny': ["0", "1"], + 'cloudy': ['7', '8'], + 'fog': ['5', '6'], + 'hail': ['19', '20', '21'], + 'lightning': ['30'], + 'lightning-rainy': ['28', '29'], + 'partlycloudy': ['2', '3'], + 'pouring': ['13', '14', '15'], + 'rainy': ['9', '10', '11', '12'], + 'snowy': ['22', '23', '24', '25', '26', '27'], + 'snowy-rainy': ['16', '17', '18'], + 'sunny': ['0', '1'], 'windy': [], 'windy-variant': [], 'exceptional': [], @@ -67,7 +66,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the sensor platform.""" + """Set up the Metoffice sensor platform.""" import datapoint as dp datapoint = dp.connection(api_key=config.get(CONF_API_KEY)) @@ -167,8 +166,8 @@ class MetOfficeCurrentData(object): import datapoint as dp try: - forecast = self._datapoint.get_forecast_for_site(self._site.id, - "3hourly") + forecast = self._datapoint.get_forecast_for_site( + self._site.id, "3hourly") self.data = forecast.now() except (ValueError, dp.exceptions.APIException) as err: _LOGGER.error("Check Met Office %s", err.args) diff --git a/homeassistant/components/sensor/mfi.py b/homeassistant/components/sensor/mfi.py index af2c277f2cd..9d78ffd3f1a 100644 --- a/homeassistant/components/sensor/mfi.py +++ b/homeassistant/components/sensor/mfi.py @@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup mFi sensors.""" + """Set up mFi sensors.""" host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) @@ -65,7 +65,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): client = MFiClient(host, username, password, port=port, use_tls=use_tls, verify=verify_tls) except (FailedToLogin, requests.exceptions.ConnectionError) as ex: - _LOGGER.error('Unable to connect to mFi: %s', str(ex)) + _LOGGER.error("Unable to connect to mFi: %s", str(ex)) return False add_devices(MfiSensor(port, hass) diff --git a/homeassistant/components/sensor/mhz19.py b/homeassistant/components/sensor/mhz19.py index 816b7465f8f..cd559d3bbd2 100644 --- a/homeassistant/components/sensor/mhz19.py +++ b/homeassistant/components/sensor/mhz19.py @@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available CO2 sensors.""" + """Set up the available CO2 sensors.""" from pmsensor import co2sensor try: @@ -118,7 +118,7 @@ class MHZ19Sensor(Entity): class MHZClient(object): - """Get the latest data from the DHT sensor.""" + """Get the latest data from the MH-Z sensor.""" def __init__(self, co2sensor, serial): """Initialize the sensor.""" diff --git a/homeassistant/components/sensor/min_max.py b/homeassistant/components/sensor/min_max.py index 33ffc769991..59a89fa0e3e 100644 --- a/homeassistant/components/sensor/min_max.py +++ b/homeassistant/components/sensor/min_max.py @@ -123,7 +123,7 @@ class MinMaxSensor(Entity): @callback # pylint: disable=invalid-name def async_min_max_sensor_state_listener(entity, old_state, new_state): - """Called when the sensor changes state.""" + """Handle the sensor state changes.""" if new_state.state is None or new_state.state in STATE_UNKNOWN: self.states[entity] = STATE_UNKNOWN hass.async_add_job(self.async_update_ha_state, True) diff --git a/homeassistant/components/sensor/modbus.py b/homeassistant/components/sensor/modbus.py index f1449e5df06..3ee59e5ae54 100644 --- a/homeassistant/components/sensor/modbus.py +++ b/homeassistant/components/sensor/modbus.py @@ -17,6 +17,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA _LOGGER = logging.getLogger(__name__) + DEPENDENCIES = ['modbus'] CONF_COUNT = 'count' diff --git a/homeassistant/components/sensor/modem_callerid.py b/homeassistant/components/sensor/modem_callerid.py index bb9a984c87b..e12ddb445ec 100644 --- a/homeassistant/components/sensor/modem_callerid.py +++ b/homeassistant/components/sensor/modem_callerid.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup modem caller id sensor platform.""" + """Set up modem caller ID sensor platform.""" from basicmodem.basicmodem import BasicModem as bm name = config.get(CONF_NAME) port = config.get(CONF_DEVICE) @@ -47,7 +47,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class ModemCalleridSensor(Entity): - """Implementation of USB modem callerid sensor.""" + """Implementation of USB modem caller ID sensor.""" def __init__(self, hass, name, port, modem): """Initialize the sensor.""" @@ -100,7 +100,7 @@ class ModemCalleridSensor(Entity): return def _incomingcallcallback(self, newstate): - """Callback from modem, process based on new state.""" + """Handle new states.""" if newstate == self.modem.STATE_RING: if self.state == self.modem.STATE_IDLE: att = {"cid_time": self.modem.get_cidtime, diff --git a/homeassistant/components/sensor/mold_indicator.py b/homeassistant/components/sensor/mold_indicator.py index 102b4620410..b668b68005c 100644 --- a/homeassistant/components/sensor/mold_indicator.py +++ b/homeassistant/components/sensor/mold_indicator.py @@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup MoldIndicator sensor.""" + """Set up MoldIndicator sensor.""" name = config.get(CONF_NAME, DEFAULT_NAME) indoor_temp_sensor = config.get(CONF_INDOOR_TEMP) outdoor_temp_sensor = config.get(CONF_OUTDOOR_TEMP) @@ -113,9 +113,8 @@ class MoldIndicator(Entity): elif unit == TEMP_CELSIUS: return temp else: - _LOGGER.error("Temp sensor has unsupported unit: %s" - " (allowed: %s, %s)", - unit, TEMP_CELSIUS, TEMP_FAHRENHEIT) + _LOGGER.error("Temp sensor has unsupported unit: %s (allowed: %s, " + "%s)", unit, TEMP_CELSIUS, TEMP_FAHRENHEIT) return None @@ -151,7 +150,7 @@ class MoldIndicator(Entity): self._calc_moldindicator() def _sensor_changed(self, entity_id, old_state, new_state): - """Called when sensor values change.""" + """Handle sensor state changes.""" if new_state is None: return @@ -167,7 +166,7 @@ class MoldIndicator(Entity): def _calc_dewpoint(self): """Calculate the dewpoint for the indoor air.""" - # use magnus approximation to calculate the dew point + # Use magnus approximation to calculate the dew point alpha = MAGNUS_K2 * self._indoor_temp / (MAGNUS_K3 + self._indoor_temp) beta = MAGNUS_K2 * MAGNUS_K3 / (MAGNUS_K3 + self._indoor_temp) @@ -215,11 +214,11 @@ class MoldIndicator(Entity): else: self._state = '{0:d}'.format(int(crit_humidity)) - _LOGGER.debug('Mold indicator humidity: %s ', self._state) + _LOGGER.debug("Mold indicator humidity: %s", self._state) @property def should_poll(self): - """Polling needed.""" + """Return the polling state.""" return False @property diff --git a/homeassistant/components/sensor/mqtt.py b/homeassistant/components/sensor/mqtt.py index 9fcb9298805..63b015b3dfd 100644 --- a/homeassistant/components/sensor/mqtt.py +++ b/homeassistant/components/sensor/mqtt.py @@ -75,13 +75,13 @@ class MqttSensor(Entity): self._expiration_trigger = None def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages.""" # auto-expire enabled? if self._expire_after is not None and self._expire_after > 0: # Reset old trigger @@ -94,9 +94,7 @@ class MqttSensor(Entity): dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( - self.hass, - self.value_is_expired, - expiration_at) + self.hass, self.value_is_expired, expiration_at) if self._template is not None: payload = self._template.async_render_with_possible_json_value( diff --git a/homeassistant/components/sensor/mqtt_room.py b/homeassistant/components/sensor/mqtt_room.py index 427daa1a8a2..3d0dbd68afa 100644 --- a/homeassistant/components/sensor/mqtt_room.py +++ b/homeassistant/components/sensor/mqtt_room.py @@ -58,7 +58,7 @@ MQTT_PAYLOAD = vol.Schema(vol.All(json.loads, vol.Schema({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup MQTT Sensor.""" + """Set up MQTT room Sensor.""" async_add_devices([MQTTRoomSensor( config.get(CONF_NAME), config.get(CONF_STATE_TOPIC), @@ -85,7 +85,7 @@ class MQTTRoomSensor(Entity): self._updated = None def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @@ -100,12 +100,12 @@ class MQTTRoomSensor(Entity): @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT messages.""" try: data = MQTT_PAYLOAD(payload) except vol.MultipleInvalid as error: - _LOGGER.debug('skipping update because of malformatted ' - 'data: %s', error) + _LOGGER.debug( + "Skipping update because of malformatted data: %s", error) return device = _parse_update_data(topic, data) diff --git a/homeassistant/components/sensor/mvglive.py b/homeassistant/components/sensor/mvglive.py index c2f8c2be71f..3bb027c6e7e 100644 --- a/homeassistant/components/sensor/mvglive.py +++ b/homeassistant/components/sensor/mvglive.py @@ -29,6 +29,8 @@ CONF_LINES = 'lines' CONF_PRODUCTS = 'products' CONF_TIMEOFFSET = 'timeoffset' +DEFAULT_PRODUCT = ['U-Bahn', 'Tram', 'Bus', 'S-Bahn'] + ICONS = { 'U-Bahn': 'mdi:subway', 'Tram': 'mdi:tram', @@ -47,16 +49,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_DESTINATIONS, default=['']): cv.ensure_list_csv, vol.Optional(CONF_DIRECTIONS, default=['']): cv.ensure_list_csv, vol.Optional(CONF_LINES, default=['']): cv.ensure_list_csv, - vol.Optional(CONF_PRODUCTS, - default=['U-Bahn', 'Tram', - 'Bus', 'S-Bahn']): cv.ensure_list_csv, + vol.Optional(CONF_PRODUCTS, default=DEFAULT_PRODUCT): + cv.ensure_list_csv, vol.Optional(CONF_TIMEOFFSET, default=0): cv.positive_int, vol.Optional(CONF_NAME): cv.string}] }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Get the MVGLive sensor.""" + """Set up the MVGLive sensor.""" sensors = [] for nextdeparture in config.get(CONF_NEXT_DEPARTURE): sensors.append( @@ -147,14 +148,13 @@ class MVGLiveData(object): def update(self): """Update the connection data.""" try: - _departures = self.mvg.getlivedata(station=self._station, - ubahn=self._include_ubahn, - tram=self._include_tram, - bus=self._include_bus, - sbahn=self._include_sbahn) + _departures = self.mvg.getlivedata( + station=self._station, ubahn=self._include_ubahn, + tram=self._include_tram, bus=self._include_bus, + sbahn=self._include_sbahn) except ValueError: self.departures = {} - _LOGGER.warning("Returned data not understood.") + _LOGGER.warning("Returned data not understood") return for _departure in _departures: # find the first departure meeting the criteria diff --git a/homeassistant/components/sensor/mysensors.py b/homeassistant/components/sensor/mysensors.py index 9f750e3c10b..d46680c7b66 100644 --- a/homeassistant/components/sensor/mysensors.py +++ b/homeassistant/components/sensor/mysensors.py @@ -14,7 +14,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the MySensors platform for sensors.""" + """Set up the MySensors platform for sensors.""" # Only act if loaded via mysensors by discovery event. # Otherwise gateway is not setup. if discovery_info is None: diff --git a/homeassistant/components/sensor/neato.py b/homeassistant/components/sensor/neato.py index 7c33e481069..39d77e736c5 100644 --- a/homeassistant/components/sensor/neato.py +++ b/homeassistant/components/sensor/neato.py @@ -32,12 +32,12 @@ ATTR_CLEAN_SUSP_TIME = 'clean_suspension_time' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Neato sensor platform.""" + """Set up the Neato sensor platform.""" dev = [] for robot in hass.data[NEATO_ROBOTS]: for type_name in SENSOR_TYPES: dev.append(NeatoConnectedSensor(hass, robot, type_name)) - _LOGGER.debug('Adding sensors %s', dev) + _LOGGER.debug("Adding sensors %s", dev) add_devices(dev) @@ -56,7 +56,7 @@ class NeatoConnectedSensor(Entity): except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as ex: self._state = None - _LOGGER.warning('Neato connection error: %s', ex) + _LOGGER.warning("Neato connection error: %s", ex) self._mapdata = hass.data[NEATO_MAP_DATA] self.clean_time_start = None self.clean_time_stop = None @@ -78,7 +78,7 @@ class NeatoConnectedSensor(Entity): requests.exceptions.HTTPError) as ex: self._state = None self._status_state = 'Offline' - _LOGGER.warning('Neato connection error: %s', ex) + _LOGGER.warning("Neato connection error: %s", ex) return if not self._state: return diff --git a/homeassistant/components/sensor/nest.py b/homeassistant/components/sensor/nest.py index 6305f5265b0..e2567fdf4ca 100644 --- a/homeassistant/components/sensor/nest.py +++ b/homeassistant/components/sensor/nest.py @@ -44,7 +44,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Nest Sensor.""" + """Set up the Nest Sensor.""" if discovery_info is None: return diff --git a/homeassistant/components/sensor/netatmo.py b/homeassistant/components/sensor/netatmo.py index 41fc4287f5f..a83b218ca8f 100644 --- a/homeassistant/components/sensor/netatmo.py +++ b/homeassistant/components/sensor/netatmo.py @@ -65,7 +65,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available Netatmo weather sensors.""" + """Set up the available Netatmo weather sensors.""" netatmo = get_component('netatmo') data = NetAtmoData(netatmo.NETATMO_AUTH, config.get(CONF_STATION, None)) @@ -109,9 +109,8 @@ class NetAtmoSensor(Entity): module_id = self.netatmo_data.\ station_data.moduleByName(module=module_name)['_id'] self.module_id = module_id[1] - self._unique_id = "Netatmo Sensor {0} - {1} ({2})".format(self._name, - module_id, - self.type) + self._unique_id = "Netatmo Sensor {0} - {1} ({2})".format( + self._name, module_id, self.type) self.update() @property @@ -307,7 +306,7 @@ class NetAtmoData(object): self.station_data = lnetatmo.WeatherStationData(self.auth) if self.station is not None: - self.data = self.station_data.lastData(station=self.station, - exclude=3600) + self.data = self.station_data.lastData( + station=self.station, exclude=3600) else: self.data = self.station_data.lastData(exclude=3600) diff --git a/homeassistant/components/sensor/netdata.py b/homeassistant/components/sensor/netdata.py index 5a3077350bc..e575cae8529 100644 --- a/homeassistant/components/sensor/netdata.py +++ b/homeassistant/components/sensor/netdata.py @@ -103,7 +103,7 @@ class NetdataSensor(Entity): @property def name(self): - """The name of the sensor.""" + """Return the name of the sensor.""" return self._name @property diff --git a/homeassistant/components/sensor/neurio_energy.py b/homeassistant/components/sensor/neurio_energy.py index 628e739f36f..5e3bf55dc9d 100644 --- a/homeassistant/components/sensor/neurio_energy.py +++ b/homeassistant/components/sensor/neurio_energy.py @@ -43,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Neurio sensor.""" + """Set up the Neurio sensor.""" api_key = config.get(CONF_API_KEY) api_secret = config.get(CONF_API_SECRET) sensor_id = config.get(CONF_SENSOR_ID) @@ -90,7 +90,7 @@ class NeurioData(object): if not self.sensor_id: user_info = self.neurio_client.get_user_information() - _LOGGER.warning('Sensor ID auto-detected: %s', user_info[ + _LOGGER.warning("Sensor ID auto-detected: %s", user_info[ "locations"][0]["sensors"][0]["sensorId"]) self.sensor_id = user_info[ "locations"][0]["sensors"][0]["sensorId"] @@ -111,7 +111,7 @@ class NeurioData(object): sample = self.neurio_client.get_samples_live_last(self.sensor_id) self._active_power = sample['consumptionPower'] except (requests.exceptions.RequestException, ValueError, KeyError): - _LOGGER.warning('Could not update current power usage.') + _LOGGER.warning("Could not update current power usage") return None def get_daily_usage(self): @@ -127,7 +127,7 @@ class NeurioData(object): history = self.neurio_client.get_samples_stats( self.sensor_id, start_time, 'days', end_time) except (requests.exceptions.RequestException, ValueError, KeyError): - _LOGGER.warning('Could not update daily power usage.') + _LOGGER.warning("Could not update daily power usage") return None for result in history: diff --git a/homeassistant/components/sensor/nut.py b/homeassistant/components/sensor/nut.py index 2608be8ded9..2ebc83724ba 100644 --- a/homeassistant/components/sensor/nut.py +++ b/homeassistant/components/sensor/nut.py @@ -135,7 +135,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_entities, discovery_info=None): - """Setup the NUT sensors.""" + """Set up the NUT sensors.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -146,7 +146,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): data = PyNUTData(host, port, alias, username, password) if data.status is None: - _LOGGER.error("NUT Sensor has no data, unable to setup.") + _LOGGER.error("NUT Sensor has no data, unable to setup") return False _LOGGER.debug('NUT Sensors Available: %s', data.status) @@ -160,14 +160,14 @@ def setup_platform(hass, config, add_entities, discovery_info=None): entities.append(NUTSensor(name, data, sensor_type)) else: _LOGGER.warning( - 'Sensor type: "%s" does not appear in the NUT status ' - 'output, cannot add.', sensor_type) + "Sensor type: %s does not appear in the NUT status " + "output, cannot add", sensor_type) try: data.update(no_throttle=True) except data.pynuterror as err: _LOGGER.error("Failure while testing NUT status retrieval. " - "Cannot continue setup., %s", err) + "Cannot continue setup: %s", err) return False add_entities(entities) @@ -180,7 +180,7 @@ class NUTSensor(Entity): """Initialize the sensor.""" self._data = data self.type = sensor_type - self._name = name + ' ' + SENSOR_TYPES[sensor_type][0] + self._name = "{} {}".format(name, SENSOR_TYPES[sensor_type][0]) self._unit = SENSOR_TYPES[sensor_type][1] self.update() @@ -281,8 +281,8 @@ class PyNUTData(object): try: return self._client.list_vars(self._alias) except (self.pynuterror, ConnectionResetError) as err: - _LOGGER.debug("Error getting NUT vars for host %s: %s", - self._host, err) + _LOGGER.debug( + "Error getting NUT vars for host %s: %s", self._host, err) return None @Throttle(MIN_TIME_BETWEEN_UPDATES) diff --git a/homeassistant/components/sensor/nzbget.py b/homeassistant/components/sensor/nzbget.py index f007ea034fc..7a95e445ae0 100644 --- a/homeassistant/components/sensor/nzbget.py +++ b/homeassistant/components/sensor/nzbget.py @@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the NZBGet sensors.""" + """Set up the NZBGet sensors.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) @@ -105,7 +105,7 @@ class NZBGetSensor(Entity): @property def unit_of_measurement(self): - """Unit of measurement of this entity, if any.""" + """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): diff --git a/homeassistant/components/sensor/octoprint.py b/homeassistant/components/sensor/octoprint.py index d58f55e0ab7..b029451bd5e 100644 --- a/homeassistant/components/sensor/octoprint.py +++ b/homeassistant/components/sensor/octoprint.py @@ -16,7 +16,6 @@ from homeassistant.helpers.entity import Entity from homeassistant.loader import get_component import homeassistant.helpers.config_validation as cv - _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['octoprint'] @@ -24,7 +23,6 @@ DEPENDENCIES = ['octoprint'] DEFAULT_NAME = 'OctoPrint' SENSOR_TYPES = { - # API Endpoint, Group, Key, unit 'Temperatures': ['printer', 'temperature', '*', TEMP_CELSIUS], 'Current State': ['printer', 'state', 'text', None], 'Job Percentage': ['job', 'progress', 'completion', '%'], @@ -39,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available OctoPrint sensors.""" + """Set up the available OctoPrint sensors.""" octoprint = get_component('octoprint') name = config.get(CONF_NAME) monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) @@ -50,23 +48,16 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if octo_type == "Temperatures": for tool in octoprint.OCTOPRINT.get_tools(): for temp_type in types: - new_sensor = OctoPrintSensor(octoprint.OCTOPRINT, - temp_type, - temp_type, - name, - SENSOR_TYPES[octo_type][3], - SENSOR_TYPES[octo_type][0], - SENSOR_TYPES[octo_type][1], - tool) + new_sensor = OctoPrintSensor( + octoprint.OCTOPRINT, temp_type, temp_type, name, + SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], + SENSOR_TYPES[octo_type][1], tool) devices.append(new_sensor) else: - new_sensor = OctoPrintSensor(octoprint.OCTOPRINT, - octo_type, - SENSOR_TYPES[octo_type][2], - name, - SENSOR_TYPES[octo_type][3], - SENSOR_TYPES[octo_type][0], - SENSOR_TYPES[octo_type][1]) + new_sensor = OctoPrintSensor( + octoprint.OCTOPRINT, octo_type, SENSOR_TYPES[octo_type][2], + name, SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], + SENSOR_TYPES[octo_type][1]) devices.append(new_sensor) add_devices(devices) @@ -113,16 +104,15 @@ class OctoPrintSensor(Entity): @property def unit_of_measurement(self): - """Unit of measurement of this entity, if any.""" + """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Update state of sensor.""" try: - self._state = self.api.update(self.sensor_type, - self.api_endpoint, - self.api_group, - self.api_tool) + self._state = self.api.update( + self.sensor_type, self.api_endpoint, self.api_group, + self.api_tool) except requests.exceptions.ConnectionError: # Error calling the api, already logged in api.update() return diff --git a/homeassistant/components/sensor/ohmconnect.py b/homeassistant/components/sensor/ohmconnect.py index 929fa607a4e..8a227af8ab3 100644 --- a/homeassistant/components/sensor/ohmconnect.py +++ b/homeassistant/components/sensor/ohmconnect.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the OhmConnect sensor.""" + """Set up the OhmConnect sensor.""" name = config.get(CONF_NAME) ohmid = config.get(CONF_ID) diff --git a/homeassistant/components/sensor/onewire.py b/homeassistant/components/sensor/onewire.py index c9028fc28ab..a06573fe97f 100644 --- a/homeassistant/components/sensor/onewire.py +++ b/homeassistant/components/sensor/onewire.py @@ -14,8 +14,11 @@ import homeassistant.helpers.config_validation as cv from homeassistant.const import STATE_UNKNOWN, TEMP_CELSIUS from homeassistant.components.sensor import PLATFORM_SCHEMA +_LOGGER = logging.getLogger(__name__) + CONF_MOUNT_DIR = 'mount_dir' CONF_NAMES = 'names' + DEFAULT_MOUNT_DIR = '/sys/bus/w1/devices/' DEVICE_FAMILIES = ('10', '22', '28', '3B', '42') @@ -24,12 +27,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_MOUNT_DIR, default=DEFAULT_MOUNT_DIR): cv.string, }) -_LOGGER = logging.getLogger(__name__) - # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the one wire Sensors.""" + """Set up the one wire Sensors.""" base_dir = config.get(CONF_MOUNT_DIR) sensor_ids = [] device_files = [] @@ -51,9 +52,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): os.path.split(family_file_path)[0], 'temperature')) if device_files == []: - _LOGGER.error('No onewire sensor found. Check if ' - 'dtoverlay=w1-gpio is in your /boot/config.txt. ' - 'Check the mount_dir parameter if it\'s defined.') + _LOGGER.error("No onewire sensor found. Check if dtoverlay=w1-gpio " + "is in your /boot/config.txt. " + "Check the mount_dir parameter if it's defined") return devs = [] @@ -129,11 +130,11 @@ class OneWire(Entity): if len(temp_read) == 1: temp = round(float(temp_read[0]), 1) except ValueError: - _LOGGER.warning('Invalid temperature value read from ' + + _LOGGER.warning("Invalid temperature value read from %s", self._device_file) except FileNotFoundError: - _LOGGER.warning('Cannot read from sensor: ' + - self._device_file) + _LOGGER.warning( + "Cannot read from sensor: %s", self._device_file) if temp < -55 or temp > 125: return diff --git a/homeassistant/components/sensor/openevse.py b/homeassistant/components/sensor/openevse.py index d3ac52f58bd..8751dda83fd 100644 --- a/homeassistant/components/sensor/openevse.py +++ b/homeassistant/components/sensor/openevse.py @@ -4,7 +4,6 @@ Support for monitoring an OpenEVSE Charger. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.openevse/ """ - import logging from requests import RequestException diff --git a/homeassistant/components/sensor/opensky.py b/homeassistant/components/sensor/opensky.py index 17e5f1f351c..43c9177f960 100644 --- a/homeassistant/components/sensor/opensky.py +++ b/homeassistant/components/sensor/opensky.py @@ -20,7 +20,6 @@ from homeassistant.util import distance as util_distance from homeassistant.util import location as util_location import homeassistant.helpers.config_validation as cv - _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=12) # opensky public limit is 10 seconds @@ -51,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Open Sky platform.""" + """Set up the Open Sky platform.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) add_devices([OpenSkySensor( @@ -132,10 +131,10 @@ class OpenSkySensor(Entity): @property def unit_of_measurement(self): - """Unit of measurement.""" + """Return the unit of measurement.""" return 'flights' @property def icon(self): - """Icon.""" + """Return the icon.""" return 'mdi:airplane' diff --git a/homeassistant/components/sensor/openweathermap.py b/homeassistant/components/sensor/openweathermap.py index 4c556e61ae2..f3620efdb43 100755 --- a/homeassistant/components/sensor/openweathermap.py +++ b/homeassistant/components/sensor/openweathermap.py @@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the OpenWeatherMap sensor.""" + """Set up the OpenWeatherMap sensor.""" if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False diff --git a/homeassistant/components/sensor/pi_hole.py b/homeassistant/components/sensor/pi_hole.py index 31335acc466..1d63aacff11 100644 --- a/homeassistant/components/sensor/pi_hole.py +++ b/homeassistant/components/sensor/pi_hole.py @@ -52,7 +52,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Pi-Hole sensor.""" + """Set up the Pi-Hole sensor.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) use_ssl = config.get(CONF_SSL) diff --git a/homeassistant/components/sensor/plex.py b/homeassistant/components/sensor/plex.py index 33da15ac836..eb6b5f49f6a 100644 --- a/homeassistant/components/sensor/plex.py +++ b/homeassistant/components/sensor/plex.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Plex sensor.""" + """Set up the Plex sensor.""" name = config.get(CONF_NAME) plex_user = config.get(CONF_USERNAME) plex_password = config.get(CONF_PASSWORD) diff --git a/homeassistant/components/sensor/pocketcasts.py b/homeassistant/components/sensor/pocketcasts.py index 5ccd082ef89..36e0bb88e0a 100644 --- a/homeassistant/components/sensor/pocketcasts.py +++ b/homeassistant/components/sensor/pocketcasts.py @@ -32,7 +32,7 @@ SCAN_INTERVAL = timedelta(minutes=5) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the pocketcasts platform for sensors.""" + """Set up the pocketcasts platform for sensors.""" import pocketcasts try: api = pocketcasts.Api( @@ -61,9 +61,9 @@ class PocketCastsSensor(Entity): """Update sensor values.""" try: self._state = len(self._api.new_episodes_released()) - _LOGGER.debug('Found %d new episodes', self._state) + _LOGGER.debug("Found %d new episodes", self._state) except OSError as err: - _LOGGER.warning('Failed to contact server: %s', err) + _LOGGER.warning("Failed to contact server: %s", err) @property def name(self): diff --git a/homeassistant/components/sensor/pushbullet.py b/homeassistant/components/sensor/pushbullet.py index acbe6487e9f..b81ca1beb38 100644 --- a/homeassistant/components/sensor/pushbullet.py +++ b/homeassistant/components/sensor/pushbullet.py @@ -107,7 +107,7 @@ class PushBulletNotificationProvider(): self.thread.start() def on_push(self, data): - """Method to update the current data. + """Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events. @@ -117,11 +117,11 @@ class PushBulletNotificationProvider(): @property def data(self): - """The current data stored in the provider.""" + """Return the current data stored in the provider.""" return self._data def retrieve_pushes(self): - """The method to run the daemon thread in. + """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ diff --git a/homeassistant/components/sensor/qnap.py b/homeassistant/components/sensor/qnap.py index e57c59e41d6..c72d2d65c6d 100644 --- a/homeassistant/components/sensor/qnap.py +++ b/homeassistant/components/sensor/qnap.py @@ -4,7 +4,6 @@ Support for QNAP NAS Sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.qnap/ """ - import logging from datetime import timedelta @@ -106,7 +105,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the QNAP NAS sensor.""" + """Set up the QNAP NAS sensor.""" api = QNAPStatsAPI(config) api.update() @@ -125,14 +124,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None): # Basic sensors for variable in config[CONF_MONITORED_CONDITIONS]: if variable in _SYSTEM_MON_COND: - sensors.append(QNAPSystemSensor(api, variable, - _SYSTEM_MON_COND[variable])) + sensors.append(QNAPSystemSensor( + api, variable, _SYSTEM_MON_COND[variable])) if variable in _CPU_MON_COND: - sensors.append(QNAPCPUSensor(api, variable, - _CPU_MON_COND[variable])) + sensors.append(QNAPCPUSensor( + api, variable, _CPU_MON_COND[variable])) if variable in _MEMORY_MON_COND: - sensors.append(QNAPMemorySensor(api, variable, - _MEMORY_MON_COND[variable])) + sensors.append(QNAPMemorySensor( + api, variable, _MEMORY_MON_COND[variable])) # Network sensors nics = config[CONF_NICS] @@ -210,7 +209,7 @@ class QNAPStatsAPI(object): self.data["volumes"] = self._api.get_volumes() self.data["bandwidth"] = self._api.get_bandwidth() except: - _LOGGER.exception("Failed to fetch QNAP stats from the NAS.") + _LOGGER.exception("Failed to fetch QNAP stats from the NAS") class QNAPSensor(Entity): @@ -228,19 +227,17 @@ class QNAPSensor(Entity): @property def name(self): """Return the name of the sensor, if any.""" - server_name = self._api.data["system_stats"]["system"]["name"] + server_name = self._api.data['system_stats']['system']['name'] if self.monitor_device is not None: - return "{} {} ({})".format(server_name, - self.var_name, - self.monitor_device) + return "{} {} ({})".format( + server_name, self.var_name, self.monitor_device) else: - return "{} {}".format(server_name, - self.var_name) + return "{} {}".format(server_name, self.var_name) @property def icon(self): - """Icon to use in the frontend, if any.""" + """Return the icon to use in the frontend, if any.""" return self.var_icon @property @@ -259,10 +256,10 @@ class QNAPCPUSensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - if self.var_id == "cpu_temp": - return self._api.data["system_stats"]["cpu"]["temp_c"] - elif self.var_id == "cpu_usage": - return self._api.data["system_stats"]["cpu"]["usage_percent"] + if self.var_id == 'cpu_temp': + return self._api.data['system_stats']['cpu']['temp_c'] + elif self.var_id == 'cpu_usage': + return self._api.data['system_stats']['cpu']['usage_percent'] class QNAPMemorySensor(QNAPSensor): @@ -271,27 +268,27 @@ class QNAPMemorySensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - free = float(self._api.data["system_stats"]["memory"]["free"]) / 1024 - if self.var_id == "memory_free": + free = float(self._api.data['system_stats']['memory']['free']) / 1024 + if self.var_id == 'memory_free': return round_nicely(free) - total = float(self._api.data["system_stats"]["memory"]["total"]) / 1024 + total = float(self._api.data['system_stats']['memory']['total']) / 1024 used = total - free - if self.var_id == "memory_used": + if self.var_id == 'memory_used': return round_nicely(used) - if self.var_id == "memory_percent_used": + if self.var_id == 'memory_percent_used': return round(used / total * 100) @property def device_state_attributes(self): """Return the state attributes.""" if self._api.data: - data = self._api.data["system_stats"]["memory"] - size = round_nicely(float(data["total"]) / 1024) + data = self._api.data['system_stats']['memory'] + size = round_nicely(float(data['total']) / 1024) return { - ATTR_MEMORY_SIZE: "{} GB".format(size), + ATTR_MEMORY_SIZE: '{} GB'.format(size), } @@ -301,30 +298,30 @@ class QNAPNetworkSensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - if self.var_id == "network_link_status": - nic = self._api.data["system_stats"]["nics"][self.monitor_device] - return nic["link_status"] + if self.var_id == 'network_link_status': + nic = self._api.data['system_stats']['nics'][self.monitor_device] + return nic['link_status'] - data = self._api.data["bandwidth"][self.monitor_device] - if self.var_id == "network_tx": - return round_nicely(data["tx"] / 1024 / 1024) + data = self._api.data['bandwidth'][self.monitor_device] + if self.var_id == 'network_tx': + return round_nicely(data['tx'] / 1024 / 1024) - if self.var_id == "network_rx": - return round_nicely(data["rx"] / 1024 / 1024) + if self.var_id == 'network_rx': + return round_nicely(data['rx'] / 1024 / 1024) @property def device_state_attributes(self): """Return the state attributes.""" if self._api.data: - data = self._api.data["system_stats"]["nics"][self.monitor_device] + data = self._api.data['system_stats']['nics'][self.monitor_device] return { - ATTR_IP: data["ip"], - ATTR_MASK: data["mask"], - ATTR_MAC: data["mac"], - ATTR_MAX_SPEED: data["max_speed"], - ATTR_PACKETS_TX: data["tx_packets"], - ATTR_PACKETS_RX: data["rx_packets"], - ATTR_PACKETS_ERR: data["err_packets"] + ATTR_IP: data['ip'], + ATTR_MASK: data['mask'], + ATTR_MAC: data['mac'], + ATTR_MAX_SPEED: data['max_speed'], + ATTR_PACKETS_TX: data['tx_packets'], + ATTR_PACKETS_RX: data['rx_packets'], + ATTR_PACKETS_ERR: data['err_packets'] } @@ -334,28 +331,27 @@ class QNAPSystemSensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - if self.var_id == "status": - return self._api.data["system_health"] + if self.var_id == 'status': + return self._api.data['system_health'] - if self.var_id == "system_temp": - return int(self._api.data["system_stats"]["system"]["temp_c"]) + if self.var_id == 'system_temp': + return int(self._api.data['system_stats']['system']['temp_c']) @property def device_state_attributes(self): """Return the state attributes.""" if self._api.data: - data = self._api.data["system_stats"] - days = int(data["uptime"]["days"]) - hours = int(data["uptime"]["hours"]) - minutes = int(data["uptime"]["minutes"]) + data = self._api.data['system_stats'] + days = int(data['uptime']['days']) + hours = int(data['uptime']['hours']) + minutes = int(data['uptime']['minutes']) return { - ATTR_NAME: data["system"]["name"], - ATTR_MODEL: data["system"]["model"], - ATTR_SERIAL: data["system"]["serial_number"], - ATTR_UPTIME: "{:0>2d}d {:0>2d}h {:0>2d}m".format(days, - hours, - minutes) + ATTR_NAME: data['system']['name'], + ATTR_MODEL: data['system']['model'], + ATTR_SERIAL: data['system']['serial_number'], + ATTR_UPTIME: '{:0>2d}d {:0>2d}h {:0>2d}m'.format( + days, hours, minutes) } @@ -365,18 +361,18 @@ class QNAPDriveSensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - data = self._api.data["smart_drive_health"][self.monitor_device] + data = self._api.data['smart_drive_health'][self.monitor_device] - if self.var_id == "drive_smart_status": - return data["health"] + if self.var_id == 'drive_smart_status': + return data['health'] - if self.var_id == "drive_temp": - return int(data["temp_c"]) + if self.var_id == 'drive_temp': + return int(data['temp_c']) @property def name(self): """Return the name of the sensor, if any.""" - server_name = self._api.data["system_stats"]["system"]["name"] + server_name = self._api.data['system_stats']['system']['name'] return "{} {} (Drive {})".format( server_name, @@ -388,12 +384,12 @@ class QNAPDriveSensor(QNAPSensor): def device_state_attributes(self): """Return the state attributes.""" if self._api.data: - data = self._api.data["smart_drive_health"][self.monitor_device] + data = self._api.data['smart_drive_health'][self.monitor_device] return { - ATTR_DRIVE: data["drive_number"], - ATTR_MODEL: data["model"], - ATTR_SERIAL: data["serial"], - ATTR_TYPE: data["type"], + ATTR_DRIVE: data['drive_number'], + ATTR_MODEL: data['model'], + ATTR_SERIAL: data['serial'], + ATTR_TYPE: data['type'], } @@ -403,27 +399,27 @@ class QNAPVolumeSensor(QNAPSensor): @property def state(self): """Return the state of the sensor.""" - data = self._api.data["volumes"][self.monitor_device] + data = self._api.data['volumes'][self.monitor_device] - free_gb = int(data["free_size"]) / 1024 / 1024 / 1024 - if self.var_id == "volume_size_free": + free_gb = int(data['free_size']) / 1024 / 1024 / 1024 + if self.var_id == 'volume_size_free': return round_nicely(free_gb) - total_gb = int(data["total_size"]) / 1024 / 1024 / 1024 + total_gb = int(data['total_size']) / 1024 / 1024 / 1024 used_gb = total_gb - free_gb - if self.var_id == "volume_size_used": + if self.var_id == 'volume_size_used': return round_nicely(used_gb) - if self.var_id == "volume_percentage_used": + if self.var_id == 'volume_percentage_used': return round(used_gb / total_gb * 100) @property def device_state_attributes(self): """Return the state attributes.""" if self._api.data: - data = self._api.data["volumes"][self.monitor_device] - total_gb = int(data["total_size"]) / 1024 / 1024 / 1024 + data = self._api.data['volumes'][self.monitor_device] + total_gb = int(data['total_size']) / 1024 / 1024 / 1024 return { ATTR_VOLUME_SIZE: "{} GB".format(round_nicely(total_gb)), diff --git a/homeassistant/components/sensor/random.py b/homeassistant/components/sensor/random.py index 0b0761d7076..b9083245218 100644 --- a/homeassistant/components/sensor/random.py +++ b/homeassistant/components/sensor/random.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Random number sensor.""" + """Set up the Random number sensor.""" name = config.get(CONF_NAME) minimum = config.get(CONF_MINIMUM) maximum = config.get(CONF_MAXIMUM) @@ -66,7 +66,7 @@ class RandomSensor(Entity): @property def icon(self): - """Icon to use in the frontend, if any.""" + """Return the icon to use in the frontend, if any.""" return ICON @property diff --git a/homeassistant/components/sensor/rest.py b/homeassistant/components/sensor/rest.py index 16b50f8b901..cbb649892f5 100644 --- a/homeassistant/components/sensor/rest.py +++ b/homeassistant/components/sensor/rest.py @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the RESTful sensor.""" + """Set up the RESTful sensor.""" name = config.get(CONF_NAME) resource = config.get(CONF_RESOURCE) method = config.get(CONF_METHOD) @@ -67,7 +67,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): rest.update() if rest.data is None: - _LOGGER.error('Unable to fetch REST data') + _LOGGER.error("Unable to fetch REST data") return False add_devices([RestSensor(hass, rest, name, unit, value_template)]) diff --git a/homeassistant/components/sensor/rfxtrx.py b/homeassistant/components/sensor/rfxtrx.py index 5f7eb8e5577..e01dbc83422 100644 --- a/homeassistant/components/sensor/rfxtrx.py +++ b/homeassistant/components/sensor/rfxtrx.py @@ -56,7 +56,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): add_devices_callback(sensors) def sensor_update(event): - """Callback for sensor updates from the RFXtrx gateway.""" + """Handle sensor updates from the RFXtrx gateway.""" if not isinstance(event, SensorEvent): return @@ -82,8 +82,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): return pkt_id = "".join("{0:02x}".format(x) for x in event.data) - _LOGGER.info("Automatic add rfxtrx.sensor: %s", - pkt_id) + _LOGGER.info("Automatic add rfxtrx.sensor: %s", pkt_id) data_type = '' for _data_type in DATA_TYPES: diff --git a/homeassistant/components/sensor/ring.py b/homeassistant/components/sensor/ring.py index dfe791c4c41..bfe8b2ec1cd 100644 --- a/homeassistant/components/sensor/ring.py +++ b/homeassistant/components/sensor/ring.py @@ -49,15 +49,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None): for sensor_type in config.get(CONF_MONITORED_CONDITIONS): for device in ring.chimes: if 'chime' in SENSOR_TYPES[sensor_type][1]: - sensors.append(RingSensor(hass, - device, - sensor_type)) + sensors.append(RingSensor(hass, device, sensor_type)) for device in ring.doorbells: if 'doorbell' in SENSOR_TYPES[sensor_type][1]: - sensors.append(RingSensor(hass, - device, - sensor_type)) + sensors.append(RingSensor(hass, device, sensor_type)) add_devices(sensors, True) return True @@ -74,8 +70,8 @@ class RingSensor(Entity): self._extra = None self._icon = 'mdi:{}'.format(SENSOR_TYPES.get(self._sensor_type)[3]) self._kind = SENSOR_TYPES.get(self._sensor_type)[4] - self._name = "{0} {1}".format(self._data.name, - SENSOR_TYPES.get(self._sensor_type)[0]) + self._name = "{0} {1}".format( + self._data.name, SENSOR_TYPES.get(self._sensor_type)[0]) self._state = STATE_UNKNOWN self._tz = str(hass.config.time_zone) @@ -121,7 +117,7 @@ class RingSensor(Entity): def update(self): """Get the latest data and updates the state.""" - _LOGGER.debug("Pulling data from %s sensor.", self._name) + _LOGGER.debug("Pulling data from %s sensor", self._name) self._data.update() @@ -137,5 +133,5 @@ class RingSensor(Entity): if history: self._extra = history[0] created_at = self._extra['created_at'] - self._state = '{0:0>2}:{1:0>2}'.format(created_at.hour, - created_at.minute) + self._state = '{0:0>2}:{1:0>2}'.format( + created_at.hour, created_at.minute) diff --git a/homeassistant/components/sensor/sabnzbd.py b/homeassistant/components/sensor/sabnzbd.py index d27f7945e55..9caa0b08374 100644 --- a/homeassistant/components/sensor/sabnzbd.py +++ b/homeassistant/components/sensor/sabnzbd.py @@ -51,7 +51,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the SABnzbd sensors.""" + """Set up the SABnzbd sensors.""" from pysabnzbd import SabnzbdApi, SabnzbdApiException host = config.get(CONF_HOST) diff --git a/homeassistant/components/sensor/sensehat.py b/homeassistant/components/sensor/sensehat.py index f421fe79ff9..7a759351b35 100644 --- a/homeassistant/components/sensor/sensehat.py +++ b/homeassistant/components/sensor/sensehat.py @@ -59,7 +59,7 @@ def get_average(temp_base): def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Sense HAT sensor platform.""" + """Set up the Sense HAT sensor platform.""" data = SenseHatData(config.get(CONF_IS_HAT_ATTACHED)) dev = [] for variable in config[CONF_DISPLAY_OPTIONS]: diff --git a/homeassistant/components/sensor/sleepiq.py b/homeassistant/components/sensor/sleepiq.py index ff6fb945e83..cf35a400e47 100644 --- a/homeassistant/components/sensor/sleepiq.py +++ b/homeassistant/components/sensor/sleepiq.py @@ -11,7 +11,7 @@ ICON = 'mdi:hotel' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the SleepIQ sensors.""" + """Set up the SleepIQ sensors.""" if discovery_info is None: return diff --git a/homeassistant/components/sensor/sma.py b/homeassistant/components/sensor/sma.py index 27ab20ab67d..2f3a29efbc0 100644 --- a/homeassistant/components/sensor/sma.py +++ b/homeassistant/components/sensor/sma.py @@ -1,4 +1,5 @@ -"""SMA Solar Webconnect interface. +""" +SMA Solar Webconnect interface. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.sma/ @@ -65,14 +66,14 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up SMA WebConnect sensor.""" import pysma - # sensor_defs from the library + # Sensor_defs from the library sensor_defs = dict(zip(SENSOR_OPTIONS, [ (pysma.KEY_CURRENT_CONSUMPTION_W, 'W', 1), (pysma.KEY_CURRENT_POWER_W, 'W', 1), (pysma.KEY_TOTAL_CONSUMPTION_KWH, 'kWh', 1000), (pysma.KEY_TOTAL_YIELD_KWH, 'kWh', 1000)])) - # sensor_defs from the custom config + # Sensor_defs from the custom config for name, prop in config[CONF_CUSTOM].items(): if name in sensor_defs: _LOGGER.warning("Custom sensor %s replace built-in sensor", name) diff --git a/homeassistant/components/sensor/speedtest.py b/homeassistant/components/sensor/speedtest.py index 600ef10cd80..bf3af95d515 100644 --- a/homeassistant/components/sensor/speedtest.py +++ b/homeassistant/components/sensor/speedtest.py @@ -125,7 +125,7 @@ class SpeedtestSensor(Entity): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity is about to be added to hass.""" + """Handle all entity which are about to be added.""" state = yield from async_get_last_state(self.hass, self.entity_id) if not state: return @@ -140,11 +140,10 @@ class SpeedtestData(object): self.data = None self._server_id = config.get(CONF_SERVER_ID) if not config.get(CONF_MANUAL): - track_time_change(hass, self.update, - second=config.get(CONF_SECOND), - minute=config.get(CONF_MINUTE), - hour=config.get(CONF_HOUR), - day=config.get(CONF_DAY)) + track_time_change( + hass, self.update, second=config.get(CONF_SECOND), + minute=config.get(CONF_MINUTE), hour=config.get(CONF_HOUR), + day=config.get(CONF_DAY)) def update(self, now): """Get the latest data from speedtest.net.""" diff --git a/homeassistant/components/sensor/statistics.py b/homeassistant/components/sensor/statistics.py index 342724830e3..67850957388 100644 --- a/homeassistant/components/sensor/statistics.py +++ b/homeassistant/components/sensor/statistics.py @@ -80,7 +80,7 @@ class StatisticsSensor(Entity): @callback # pylint: disable=invalid-name def async_stats_sensor_state_listener(entity, old_state, new_state): - """Called when the sensor changes state.""" + """Handle the sensor state changes.""" self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT) diff --git a/homeassistant/components/sensor/steam_online.py b/homeassistant/components/sensor/steam_online.py index 679b798a24b..9fd5ab7dd7d 100644 --- a/homeassistant/components/sensor/steam_online.py +++ b/homeassistant/components/sensor/steam_online.py @@ -37,7 +37,7 @@ STATE_PLAY = 'Play' # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Steam platform.""" + """Set up the Steam platform.""" import steam as steamod steamod.api.key.set(config.get(CONF_API_KEY)) add_devices( diff --git a/homeassistant/components/sensor/supervisord.py b/homeassistant/components/sensor/supervisord.py index fae7032ea58..b2d8c32d9a0 100644 --- a/homeassistant/components/sensor/supervisord.py +++ b/homeassistant/components/sensor/supervisord.py @@ -25,12 +25,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Supervisord platform.""" + """Set up the Supervisord platform.""" url = config.get(CONF_URL) try: supervisor_server = xmlrpc.client.ServerProxy(url) except ConnectionRefusedError: - _LOGGER.error('Could not connect to Supervisord') + _LOGGER.error("Could not connect to Supervisord") return False processes = supervisor_server.supervisor.getAllProcessInfo() diff --git a/homeassistant/components/sensor/swiss_hydrological_data.py b/homeassistant/components/sensor/swiss_hydrological_data.py index ebd932c267c..0df63956f2e 100644 --- a/homeassistant/components/sensor/swiss_hydrological_data.py +++ b/homeassistant/components/sensor/swiss_hydrological_data.py @@ -41,17 +41,16 @@ ATTR_DISCHARGE_MAX = 'discharge_max' ATTR_WATERLEVEL_MAX = 'level_max' ATTR_TEMPERATURE_MAX = 'temperature_max' +MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=30) + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_STATION): vol.Coerce(int), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) -# Return cached results if last scan was less then this time ago. -MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=30) - def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Swiss hydrological sensor.""" + """Set up the Swiss hydrological sensor.""" import xmltodict name = config.get(CONF_NAME) @@ -61,10 +60,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): response = requests.get(_RESOURCE, timeout=5) if any(str(station) == location.get('@StrNr') for location in xmltodict.parse(response.text)['AKT_Data']['MesPar']) is False: - _LOGGER.error('The given station does not exist: %s', station) + _LOGGER.error("The given station does not exist: %s", station) return False except requests.exceptions.ConnectionError: - _LOGGER.error('The URL is not accessible') + _LOGGER.error("The URL is not accessible") return False data = HydrologicalData(station) @@ -164,7 +163,7 @@ class HydrologicalData(object): try: response = requests.get(_RESOURCE, timeout=5) except requests.exceptions.ConnectionError: - _LOGGER.error('Unable to retrieve data from %s', _RESOURCE) + _LOGGER.error("Unable to retrieve data from %s", _RESOURCE) try: stations = xmltodict.parse(response.text)['AKT_Data']['MesPar'] diff --git a/homeassistant/components/sensor/swiss_public_transport.py b/homeassistant/components/sensor/swiss_public_transport.py index a730e5d16cf..3ca8c4cb8e1 100644 --- a/homeassistant/components/sensor/swiss_public_transport.py +++ b/homeassistant/components/sensor/swiss_public_transport.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Get the Swiss public transport sensor.""" + """Set up the Swiss public transport sensor.""" name = config.get(CONF_NAME) # journal contains [0] Station ID start, [1] Station ID destination # [2] Station name start, and [3] Station name destination @@ -52,8 +52,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: for location in [config.get(CONF_START), config.get(CONF_DESTINATION)]: # transport.opendata.ch doesn't play nice with requests.Session - result = requests.get(_RESOURCE + 'locations?query=%s' % location, - timeout=10) + result = requests.get( + '{}locations?query={}'.format(_RESOURCE, location), timeout=10) journey.append(result.json()['stations'][0]['name']) except KeyError: _LOGGER.exception( diff --git a/homeassistant/components/sensor/synologydsm.py b/homeassistant/components/sensor/synologydsm.py index 8ee0d6eae18..b2bcea02c00 100644 --- a/homeassistant/components/sensor/synologydsm.py +++ b/homeassistant/components/sensor/synologydsm.py @@ -4,7 +4,6 @@ Support for Synology NAS Sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.synologydsm/ """ - import logging from datetime import timedelta @@ -86,7 +85,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the Synology NAS Sensor.""" + """Set up the Synology NAS Sensor.""" # pylint: disable=too-many-locals def run_setup(event): """Wait until HASS is fully initialized before creating. @@ -139,7 +138,7 @@ class SynoApi(): # pylint: disable=too-many-arguments, bare-except def __init__(self, host, port, username, password, temp_unit): - """Constructor of the API wrapper class.""" + """Initialize the API wrapper class.""" from SynologyDSM import SynologyDSM self.temp_unit = temp_unit diff --git a/homeassistant/components/sensor/tado.py b/homeassistant/components/sensor/tado.py index 371d7e3e1c9..b654a4444c4 100644 --- a/homeassistant/components/sensor/tado.py +++ b/homeassistant/components/sensor/tado.py @@ -84,7 +84,7 @@ class TadoSensor(Entity): """Representation of a tado Sensor.""" def __init__(self, store, zone_name, zone_id, zone_variable, data_id): - """Initialization of TadoSensor class.""" + """Initialize of the Tado Sensor.""" self._store = store self.zone_name = zone_name diff --git a/homeassistant/components/sensor/ted5000.py b/homeassistant/components/sensor/ted5000.py index f01e7909e52..08681fd37f2 100644 --- a/homeassistant/components/sensor/ted5000.py +++ b/homeassistant/components/sensor/ted5000.py @@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Ted5000 sensor.""" + """Set up the Ted5000 sensor.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) @@ -68,7 +68,7 @@ class Ted5000Sensor(Entity): @property def name(self): - """The name of the sensor.""" + """Return the name of the sensor.""" return self._name @property diff --git a/homeassistant/components/sensor/tellduslive.py b/homeassistant/components/sensor/tellduslive.py index 9bebbe6e3dc..68d0bb6535f 100644 --- a/homeassistant/components/sensor/tellduslive.py +++ b/homeassistant/components/sensor/tellduslive.py @@ -3,7 +3,6 @@ Support for Tellstick Net/Telstick Live. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.tellduslive/ - """ import logging @@ -36,7 +35,7 @@ SENSOR_TYPES = { def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Tellstick sensors.""" + """Set up the Tellstick sensors.""" if discovery_info is None: return add_devices(TelldusLiveSensor(hass, sensor) for sensor in discovery_info) diff --git a/homeassistant/components/sensor/tellstick.py b/homeassistant/components/sensor/tellstick.py index d16bb28f4f4..c9f922207e5 100644 --- a/homeassistant/components/sensor/tellstick.py +++ b/homeassistant/components/sensor/tellstick.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Tellstick sensors.""" + """Set up the Tellstick sensors.""" import tellcore.telldus as telldus import tellcore.constants as tellcore_constants diff --git a/homeassistant/components/sensor/temper.py b/homeassistant/components/sensor/temper.py index 4ccd1be7d76..ce9d974d927 100644 --- a/homeassistant/components/sensor/temper.py +++ b/homeassistant/components/sensor/temper.py @@ -35,7 +35,7 @@ def get_temper_devices(): # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Temper sensors.""" + """Setu p the Temper sensors.""" temp_unit = hass.config.units.temperature_unit name = config.get(CONF_NAME) scaling = { @@ -107,6 +107,6 @@ class TemperSensor(Entity): sensor_value = self.temper_device.get_temperature(format_str) self.current_value = round(sensor_value, 1) except IOError: - _LOGGER.error('Failed to get temperature. The device address may' - 'have changed - attempting to reset device') + _LOGGER.error("Failed to get temperature. The device address may" + "have changed. Attempting to reset device") reset_devices() diff --git a/homeassistant/components/sensor/template.py b/homeassistant/components/sensor/template.py index 51a7bc82a85..8cf3083d7ed 100644 --- a/homeassistant/components/sensor/template.py +++ b/homeassistant/components/sensor/template.py @@ -40,7 +40,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine # pylint: disable=unused-argument def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the template sensors.""" + """Set up the template sensors.""" sensors = [] for device, device_config in config[CONF_SENSORS].items(): @@ -100,7 +100,7 @@ class SensorTemplate(Entity): @callback def template_sensor_state_listener(entity, old_state, new_state): - """Called when the target device changes state.""" + """Handle device state changes.""" self.hass.async_add_job(self.async_update_ha_state(True)) @callback diff --git a/homeassistant/components/sensor/time_date.py b/homeassistant/components/sensor/time_date.py index 9182145dc95..97e6bfd4b3a 100644 --- a/homeassistant/components/sensor/time_date.py +++ b/homeassistant/components/sensor/time_date.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Time and Date sensor.""" + """Set up the Time and Date sensor.""" if hass.config.time_zone is None: _LOGGER.error("Timezone is not set in Home Assistant configuration") return False diff --git a/homeassistant/components/sensor/torque.py b/homeassistant/components/sensor/torque.py index 219275aee52..acc7958ea7f 100644 --- a/homeassistant/components/sensor/torque.py +++ b/homeassistant/components/sensor/torque.py @@ -48,7 +48,7 @@ def convert_pid(value): # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Torque platform.""" + """Set up the Torque platform.""" vehicle = config.get(CONF_NAME) email = config.get(CONF_EMAIL) sensors = {} diff --git a/homeassistant/components/sensor/transmission.py b/homeassistant/components/sensor/transmission.py index 3c9aad05626..add9cb1aca6 100644 --- a/homeassistant/components/sensor/transmission.py +++ b/homeassistant/components/sensor/transmission.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Transmission sensors.""" + """Set up the Transmission sensors.""" import transmissionrpc from transmissionrpc.error import TransmissionError diff --git a/homeassistant/components/sensor/twitch.py b/homeassistant/components/sensor/twitch.py index 249d18ce6cb..6d075049b74 100644 --- a/homeassistant/components/sensor/twitch.py +++ b/homeassistant/components/sensor/twitch.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Twitch platform.""" + """Set up the Twitch platform.""" channels = config.get(CONF_CHANNELS, []) add_devices([TwitchSensor(channel) for channel in channels]) diff --git a/homeassistant/components/sensor/ups.py b/homeassistant/components/sensor/ups.py index 415ff1f8745..905cdab566e 100644 --- a/homeassistant/components/sensor/ups.py +++ b/homeassistant/components/sensor/ups.py @@ -40,15 +40,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the UPS platform.""" + """Set up the UPS platform.""" import upsmychoice try: cookie = hass.config.path(COOKIE) - session = upsmychoice.get_session(config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - cookie_path=cookie) + session = upsmychoice.get_session( + config.get(CONF_USERNAME), config.get(CONF_PASSWORD), + cookie_path=cookie) except upsmychoice.UPSError: - _LOGGER.exception('Could not connect to UPS My Choice') + _LOGGER.exception("Could not connect to UPS My Choice") return False add_devices([UPSSensor(session, config.get(CONF_NAME), diff --git a/homeassistant/components/sensor/usps.py b/homeassistant/components/sensor/usps.py index c0fc3d9cfe4..ec1b2f5575e 100644 --- a/homeassistant/components/sensor/usps.py +++ b/homeassistant/components/sensor/usps.py @@ -39,15 +39,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the USPS platform.""" + """Set up the USPS platform.""" import myusps try: cookie = hass.config.path(COOKIE) - session = myusps.get_session(config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - cookie_path=cookie) + session = myusps.get_session( + config.get(CONF_USERNAME), config.get(CONF_PASSWORD), + cookie_path=cookie) except myusps.USPSError: - _LOGGER.exception('Could not connect to My USPS') + _LOGGER.exception("Could not connect to My USPS") return False add_devices([USPSSensor(session, config.get(CONF_NAME), diff --git a/homeassistant/components/sensor/vasttrafik.py b/homeassistant/components/sensor/vasttrafik.py index 9f62c8620de..c78d352e626 100644 --- a/homeassistant/components/sensor/vasttrafik.py +++ b/homeassistant/components/sensor/vasttrafik.py @@ -42,11 +42,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the departure sensor.""" + """Set up the departure sensor.""" import vasttrafik planner = vasttrafik.JournyPlanner( - config.get(CONF_KEY), - config.get(CONF_SECRET)) + config.get(CONF_KEY), config.get(CONF_SECRET)) sensors = [] for departure in config.get(CONF_DEPARTURES): sensors.append( @@ -104,7 +103,7 @@ class VasttrafikDepartureSensor(Entity): """Return the next departure time.""" if not self._departureboard: _LOGGER.warning( - 'No departures from "%s" heading "%s"', + "No departures from %s heading %s", self._departure['name'], self._heading['name'] if self._heading else 'ANY') return @@ -121,5 +120,5 @@ class VasttrafikDepartureSensor(Entity): direction=self._heading['id'] if self._heading else None, date=datetime.now()+self._delay) except self._vasttrafik.Error: - _LOGGER.warning('Unable to read departure board, updating token') + _LOGGER.warning("Unable to read departure board, updating token") self._planner.update_token() diff --git a/homeassistant/components/sensor/vera.py b/homeassistant/components/sensor/vera.py index f6ae00f02a6..5cb528219a5 100644 --- a/homeassistant/components/sensor/vera.py +++ b/homeassistant/components/sensor/vera.py @@ -23,7 +23,7 @@ SCAN_INTERVAL = timedelta(seconds=5) def setup_platform(hass, config, add_devices, discovery_info=None): - """Perform the setup for Vera controller devices.""" + """Set up the Vera controller devices.""" add_devices( VeraSensor(device, VERA_CONTROLLER) for device in VERA_DEVICES['sensor']) diff --git a/homeassistant/components/sensor/verisure.py b/homeassistant/components/sensor/verisure.py index 932da40bc9f..4b22512fd4d 100644 --- a/homeassistant/components/sensor/verisure.py +++ b/homeassistant/components/sensor/verisure.py @@ -16,7 +16,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Verisure platform.""" + """Set up the Verisure platform.""" sensors = [] if int(hub.config.get(CONF_THERMOMETERS, 1)): diff --git a/homeassistant/components/sensor/volvooncall.py b/homeassistant/components/sensor/volvooncall.py index 9554d8c5b02..703315c478c 100644 --- a/homeassistant/components/sensor/volvooncall.py +++ b/homeassistant/components/sensor/volvooncall.py @@ -13,7 +13,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Volvo sensors.""" + """Set up the Volvo sensors.""" if discovery_info is None: return add_devices([VolvoSensor(hass, *discovery_info)]) diff --git a/homeassistant/components/sensor/wunderground.py b/homeassistant/components/sensor/wunderground.py index 93e747cd16f..d50f6b0897c 100644 --- a/homeassistant/components/sensor/wunderground.py +++ b/homeassistant/components/sensor/wunderground.py @@ -112,11 +112,10 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the WUnderground sensor.""" - rest = WUndergroundData(hass, - config.get(CONF_API_KEY), - config.get(CONF_PWS_ID), - config.get(CONF_LANG)) + """Set up the WUnderground sensor.""" + rest = WUndergroundData( + hass, config.get(CONF_API_KEY), config.get(CONF_PWS_ID), + config.get(CONF_LANG)) sensors = [] for variable in config[CONF_MONITORED_CONDITIONS]: sensors.append(WUndergroundSensor(rest, variable)) diff --git a/homeassistant/components/sensor/yr.py b/homeassistant/components/sensor/yr.py index 0e2c07e24bb..16951f21c5d 100644 --- a/homeassistant/components/sensor/yr.py +++ b/homeassistant/components/sensor/yr.py @@ -25,7 +25,6 @@ from homeassistant.helpers.event import ( async_track_point_in_utc_time, async_track_utc_time_change) from homeassistant.util import dt as dt_util - REQUIREMENTS = ['xmltodict==0.11.0'] _LOGGER = logging.getLogger(__name__) @@ -62,7 +61,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Yr.no sensor.""" + """Set up the Yr.no sensor.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0) @@ -82,9 +81,9 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): weather = YrData(hass, coordinates, dev) # Update weather on the hour, spread seconds - async_track_utc_time_change(hass, weather.async_update, - minute=randrange(1, 10), - second=randrange(0, 59)) + async_track_utc_time_change( + hass, weather.async_update, minute=randrange(1, 10), + second=randrange(0, 59)) yield from weather.async_update() @@ -166,8 +165,8 @@ class YrData(object): try: websession = async_get_clientsession(self.hass) with async_timeout.timeout(10, loop=self.hass.loop): - resp = yield from websession.get(self._url, - params=self._urlparams) + resp = yield from websession.get( + self._url, params=self._urlparams) if resp.status != 200: try_again('{} returned {}'.format(resp.url, resp.status)) return diff --git a/homeassistant/components/sensor/yweather.py b/homeassistant/components/sensor/yweather.py index b45da4121bb..3144e812870 100644 --- a/homeassistant/components/sensor/yweather.py +++ b/homeassistant/components/sensor/yweather.py @@ -52,7 +52,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Yahoo! weather sensor.""" + """Setnup the Yahoo! weather sensor.""" from yahooweather import get_woeid, UNIT_C, UNIT_F unit = hass.config.units.temperature_unit @@ -60,15 +60,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): forecast = config.get(CONF_FORECAST) name = config.get(CONF_NAME) - # convert unit yunit = UNIT_C if unit == TEMP_CELSIUS else UNIT_F - # for print HA style temp SENSOR_TYPES["temperature"][1] = unit SENSOR_TYPES["temp_min"][1] = unit SENSOR_TYPES["temp_max"][1] = unit - # if not exists a customer woeid / calc from HA + # If not exists a customer woeid / calc from HA if woeid is None: woeid = get_woeid(hass.config.latitude, hass.config.longitude) # receive a error? @@ -76,15 +74,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None): _LOGGER.critical("Can't retrieve WOEID from yahoo!") return False - # create api object yahoo_api = YahooWeatherData(woeid, yunit) - # if update is false, it will never work... if not yahoo_api.update(): _LOGGER.critical("Can't retrieve weather data from yahoo!") return False - # check if forecast support by API if forecast >= len(yahoo_api.yahoo.Forecast): _LOGGER.error("Yahoo! only support %d days forcast!", len(yahoo_api.yahoo.Forecast)) @@ -152,30 +147,30 @@ class YahooWeatherSensor(Entity): return # default code for weather image - self._code = self._data.yahoo.Now["code"] + self._code = self._data.yahoo.Now['code'] # read data - if self._type == "weather_current": - self._state = self._data.yahoo.Now["text"] - elif self._type == "weather": - self._code = self._data.yahoo.Forecast[self._forecast]["code"] - self._state = self._data.yahoo.Forecast[self._forecast]["text"] - elif self._type == "temperature": - self._state = self._data.yahoo.Now["temp"] - elif self._type == "temp_min": - self._code = self._data.yahoo.Forecast[self._forecast]["code"] - self._state = self._data.yahoo.Forecast[self._forecast]["low"] - elif self._type == "temp_max": - self._code = self._data.yahoo.Forecast[self._forecast]["code"] - self._state = self._data.yahoo.Forecast[self._forecast]["high"] - elif self._type == "wind_speed": - self._state = self._data.yahoo.Wind["speed"] - elif self._type == "humidity": - self._state = self._data.yahoo.Atmosphere["humidity"] - elif self._type == "pressure": - self._state = self._data.yahoo.Atmosphere["pressure"] - elif self._type == "visibility": - self._state = self._data.yahoo.Atmosphere["visibility"] + if self._type == 'weather_current': + self._state = self._data.yahoo.Now['text'] + elif self._type == 'weather': + self._code = self._data.yahoo.Forecast[self._forecast]['code'] + self._state = self._data.yahoo.Forecast[self._forecast]['text'] + elif self._type == 'temperature': + self._state = self._data.yahoo.Now['temp'] + elif self._type == 'temp_min': + self._code = self._data.yahoo.Forecast[self._forecast]['code'] + self._state = self._data.yahoo.Forecast[self._forecast]['low'] + elif self._type == 'temp_max': + self._code = self._data.yahoo.Forecast[self._forecast]['code'] + self._state = self._data.yahoo.Forecast[self._forecast]['high'] + elif self._type == 'wind_speed': + self._state = self._data.yahoo.Wind['speed'] + elif self._type == 'humidity': + self._state = self._data.yahoo.Atmosphere['humidity'] + elif self._type == 'pressure': + self._state = self._data.yahoo.Atmosphere['pressure'] + elif self._type == 'visibility': + self._state = self._data.yahoo.Atmosphere['visibility'] class YahooWeatherData(object): diff --git a/homeassistant/components/sensor/zabbix.py b/homeassistant/components/sensor/zabbix.py index 6c3d0a3d653..9f46159b1a2 100644 --- a/homeassistant/components/sensor/zabbix.py +++ b/homeassistant/components/sensor/zabbix.py @@ -5,28 +5,28 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.zabbix/ """ import logging + import voluptuous as vol -from homeassistant.helpers.entity import Entity import homeassistant.components.zabbix as zabbix -from homeassistant.components.sensor import PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv - +from homeassistant.components.sensor import PLATFORM_SCHEMA +from homeassistant.const import CONF_NAME +from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['zabbix'] -_CONF_TRIGGERS = "triggers" -_CONF_HOSTIDS = "hostids" -_CONF_INDIVIDUAL = "individual" -_CONF_NAME = "name" +_CONF_TRIGGERS = 'triggers' +_CONF_HOSTIDS = 'hostids' +_CONF_INDIVIDUAL = 'individual' _ZABBIX_ID_LIST_SCHEMA = vol.Schema([int]) _ZABBIX_TRIGGER_SCHEMA = vol.Schema({ vol.Optional(_CONF_HOSTIDS, default=[]): _ZABBIX_ID_LIST_SCHEMA, vol.Optional(_CONF_INDIVIDUAL, default=False): cv.boolean(True), - vol.Optional(_CONF_NAME, default=None): cv.string, + vol.Optional(CONF_NAME, default=None): cv.string, }) # SCAN_INTERVAL = 30 @@ -42,18 +42,17 @@ def setup_platform(hass, config, add_devices, discovery_info=None): zapi = hass.data[zabbix.DOMAIN] if not zapi: - _LOGGER.error("zapi is None. Zabbix component hasn't been loaded?") + _LOGGER.error("zapi is None. Zabbix component hasn't been loaded?") return False - _LOGGER.info("Connected to Zabbix API Version %s", - zapi.api_version()) + _LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version()) trigger_conf = config.get(_CONF_TRIGGERS) # The following code seems overly complex. Need to think about this... if trigger_conf: hostids = trigger_conf.get(_CONF_HOSTIDS) individual = trigger_conf.get(_CONF_INDIVIDUAL) - name = trigger_conf.get(_CONF_NAME) + name = trigger_conf.get(CONF_NAME) if individual: # Individual sensor per host @@ -63,10 +62,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): return False for hostid in hostids: - _LOGGER.debug("Creating Zabbix Sensor: " + str(hostid)) - sensor = ZabbixSingleHostTriggerCountSensor(zapi, - [hostid], - name) + _LOGGER.debug("Creating Zabbix Sensor: %s", str(hostid)) + sensor = ZabbixSingleHostTriggerCountSensor( + zapi, [hostid], name) sensors.append(sensor) else: if not hostids: @@ -75,10 +73,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): sensor = ZabbixTriggerCountSensor(zapi, name) else: # Single sensor that sums total issues for all hosts - _LOGGER.debug("Creating Zabbix Sensor group: " + str(hostids)) - sensor = ZabbixMultipleHostTriggerCountSensor(zapi, - hostids, - name) + _LOGGER.debug("Creating Zabbix Sensor group: %s", str(hostids)) + sensor = ZabbixMultipleHostTriggerCountSensor( + zapi, hostids, name) sensors.append(sensor) else: # Single sensor that provides the total count of triggers. @@ -115,14 +112,12 @@ class ZabbixTriggerCountSensor(Entity): return 'issues' def _call_zabbix_api(self): - return self._zapi.trigger.get(output="extend", - only_true=1, - monitored=1, - filter={"value": 1}) + return self._zapi.trigger.get( + output="extend", only_true=1, monitored=1, filter={"value": 1}) def update(self): """Update the sensor.""" - _LOGGER.debug("Updating ZabbixTriggerCountSensor: " + str(self._name)) + _LOGGER.debug("Updating ZabbixTriggerCountSensor: %s", str(self._name)) triggers = self._call_zabbix_api() self._state = len(triggers) @@ -140,35 +135,31 @@ class ZabbixSingleHostTriggerCountSensor(ZabbixTriggerCountSensor): super().__init__(zApi, name) self._hostid = hostid if not name: - self._name = self._zapi.host.get(hostids=self._hostid, - output="extend")[0]["name"] + self._name = self._zapi.host.get( + hostids=self._hostid, output="extend")[0]["name"] self._attributes["Host ID"] = self._hostid def _call_zabbix_api(self): - return self._zapi.trigger.get(hostids=self._hostid, - output="extend", - only_true=1, - monitored=1, - filter={"value": 1}) + return self._zapi.trigger.get( + hostids=self._hostid, output="extend", only_true=1, monitored=1, + filter={"value": 1}) class ZabbixMultipleHostTriggerCountSensor(ZabbixTriggerCountSensor): """Get the active trigger count for specified Zabbix monitored hosts.""" def __init__(self, zApi, hostids, name=None): - """Initiate Zabbix sensor.""" + """Initialize Zabbix sensor.""" super().__init__(zApi, name) self._hostids = hostids if not name: - host_names = self._zapi.host.get(hostids=self._hostids, - output="extend") + host_names = self._zapi.host.get( + hostids=self._hostids, output="extend") self._name = " ".join(name["name"] for name in host_names) self._attributes["Host IDs"] = self._hostids def _call_zabbix_api(self): - return self._zapi.trigger.get(hostids=self._hostids, - output="extend", - only_true=1, - monitored=1, - filter={"value": 1}) + return self._zapi.trigger.get( + hostids=self._hostids, output="extend", only_true=1, + monitored=1, filter={"value": 1}) diff --git a/homeassistant/components/sensor/zamg.py b/homeassistant/components/sensor/zamg.py index 3d5f6146a39..ef4ebe373e7 100644 --- a/homeassistant/components/sensor/zamg.py +++ b/homeassistant/components/sensor/zamg.py @@ -185,7 +185,7 @@ class ZamgData(object): .format(self._station_id)) def get_data(self, variable): - """Generic accessor for data.""" + """Get the data.""" return self.data.get(variable) @@ -231,7 +231,7 @@ def closest_station(lat, lon, cache_dir): stations = zamg_stations(cache_dir) def comparable_dist(zamg_id): - """A fast key function for psudeo-distance from lat/lon.""" + """Calculater psudeo-distance from lat/lon.""" station_lat, station_lon = stations[zamg_id] return (lat - station_lat) ** 2 + (lon - station_lon) ** 2 diff --git a/homeassistant/components/sensor/zha.py b/homeassistant/components/sensor/zha.py index ef1fe36873b..dd176a9119b 100644 --- a/homeassistant/components/sensor/zha.py +++ b/homeassistant/components/sensor/zha.py @@ -19,7 +19,7 @@ DEPENDENCIES = ['zha'] @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup Zigbee Home Automation sensors.""" + """Set up Zigbee Home Automation sensors.""" discovery_info = zha.get_discovery_info(hass, discovery_info) if discovery_info is None: return @@ -44,10 +44,7 @@ def make_sensor(discovery_info): cluster = clusters[0] yield from cluster.bind() yield from cluster.configure_reporting( - attr, - 300, - 600, - sensor.min_reportable_change, + attr, 300, 600, sensor.min_reportable_change, ) return sensor @@ -95,5 +92,5 @@ class TemperatureSensor(Sensor): if self._state == 'unknown': return 'unknown' celsius = round(float(self._state) / 100, 1) - return convert_temperature(celsius, TEMP_CELSIUS, - self.unit_of_measurement) + return convert_temperature( + celsius, TEMP_CELSIUS, self.unit_of_measurement) diff --git a/homeassistant/components/sensor/zigbee.py b/homeassistant/components/sensor/zigbee.py index f3e8d5480a8..176c0fd51aa 100644 --- a/homeassistant/components/sensor/zigbee.py +++ b/homeassistant/components/sensor/zigbee.py @@ -31,7 +31,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ZigBee platform. + """Set up the ZigBee platform. Uses the 'type' config value to work out which type of ZigBee sensor we're dealing with and instantiates the relevant classes to handle it. diff --git a/homeassistant/components/sensor/zoneminder.py b/homeassistant/components/sensor/zoneminder.py index 388c12641c5..8ef5266790c 100644 --- a/homeassistant/components/sensor/zoneminder.py +++ b/homeassistant/components/sensor/zoneminder.py @@ -81,7 +81,7 @@ class ZMSensorEvents(Entity): """Get the number of events for each monitor.""" def __init__(self, monitor_id, monitor_name, include_archived): - """Initiate event sensor.""" + """Initialize event sensor.""" self._monitor_id = monitor_id self._monitor_name = monitor_name self._include_archived = include_archived diff --git a/homeassistant/components/sensor/zwave.py b/homeassistant/components/sensor/zwave.py index 92ea3966b0f..e9ea0e7512d 100644 --- a/homeassistant/components/sensor/zwave.py +++ b/homeassistant/components/sensor/zwave.py @@ -16,7 +16,7 @@ _LOGGER = logging.getLogger(__name__) def get_device(node, values, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" # Generic Device mappings if node.has_command_class(zwave.const.COMMAND_CLASS_SENSOR_MULTILEVEL): return ZWaveMultilevelSensor(values) @@ -38,7 +38,7 @@ class ZWaveSensor(zwave.ZWaveDeviceEntity): self.update_properties() def update_properties(self): - """Callback on data changes for node values.""" + """Handle the data changes for node values.""" self._state = self.values.primary.data self._units = self.values.primary.units diff --git a/homeassistant/components/switch/anel_pwrctrl.py b/homeassistant/components/switch/anel_pwrctrl.py index ff3eaf387ab..fccb43a08f2 100644 --- a/homeassistant/components/switch/anel_pwrctrl.py +++ b/homeassistant/components/switch/anel_pwrctrl.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup PwrCtrl devices/switches.""" + """Set up PwrCtrl devices/switches.""" host = config.get(CONF_HOST, None) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) diff --git a/homeassistant/components/switch/broadlink.py b/homeassistant/components/switch/broadlink.py index e97745cc0c6..8e4bacf7f99 100644 --- a/homeassistant/components/switch/broadlink.py +++ b/homeassistant/components/switch/broadlink.py @@ -10,33 +10,33 @@ import asyncio import binascii import logging import socket + import voluptuous as vol import homeassistant.loader as loader from homeassistant.util.dt import utcnow from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) -from homeassistant.const import (CONF_FRIENDLY_NAME, CONF_SWITCHES, - CONF_COMMAND_OFF, CONF_COMMAND_ON, - CONF_TIMEOUT, CONF_HOST, CONF_MAC, - CONF_TYPE) +from homeassistant.const import ( + CONF_FRIENDLY_NAME, CONF_SWITCHES, CONF_COMMAND_OFF, CONF_COMMAND_ON, + CONF_TIMEOUT, CONF_HOST, CONF_MAC, CONF_TYPE) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['broadlink==0.3'] _LOGGER = logging.getLogger(__name__) -DOMAIN = "broadlink" +DOMAIN = 'broadlink' DEFAULT_NAME = 'Broadlink switch' DEFAULT_TIMEOUT = 10 DEFAULT_RETRY = 3 -SERVICE_LEARN = "learn_command" -SERVICE_SEND = "send_packet" +SERVICE_LEARN = 'learn_command' +SERVICE_SEND = 'send_packet' -RM_TYPES = ["rm", "rm2", "rm_mini", "rm_pro_phicomm", "rm2_home_plus", - "rm2_home_plus_gdt", "rm2_pro_plus", "rm2_pro_plus2", - "rm2_pro_plus_bl", "rm_mini_shate"] -SP1_TYPES = ["sp1"] -SP2_TYPES = ["sp2", "honeywell_sp2", "sp3", "spmini2", "spminiplus"] +RM_TYPES = ['rm', 'rm2', 'rm_mini', 'rm_pro_phicomm', 'rm2_home_plus', + 'rm2_home_plus_gdt', 'rm2_pro_plus', 'rm2_pro_plus2', + 'rm2_pro_plus_bl', 'rm_mini_shate'] +SP1_TYPES = ['sp1'] +SP2_TYPES = ['sp2', 'honeywell_sp2', 'sp3', 'spmini2', 'spminiplus'] SWITCH_TYPES = RM_TYPES + SP1_TYPES + SP2_TYPES @@ -58,7 +58,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Broadlink switches.""" + """Set up Broadlink switches.""" import broadlink devices = config.get(CONF_SWITCHES, {}) ip_addr = config.get(CONF_HOST) @@ -75,33 +75,31 @@ def setup_platform(hass, config, add_devices, discovery_info=None): auth = yield from hass.loop.run_in_executor(None, broadlink_device.auth) except socket.timeout: - _LOGGER.error("Failed to connect to device, timeout.") + _LOGGER.error("Failed to connect to device, timeout") return if not auth: - _LOGGER.error("Failed to connect to device.") + _LOGGER.error("Failed to connect to device") return - yield from hass.loop.run_in_executor(None, - broadlink_device.enter_learning) + yield from hass.loop.run_in_executor( + None, broadlink_device.enter_learning) _LOGGER.info("Press the key you want HASS to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=20): - packet = yield from hass.loop.run_in_executor(None, - broadlink_device. - check_data) + packet = yield from hass.loop.run_in_executor( + None, broadlink_device.check_data) if packet: - log_msg = 'Recieved packet is: {}'.\ + log_msg = "Recieved packet is: {}".\ format(b64encode(packet).decode('utf8')) _LOGGER.info(log_msg) - persistent_notification.async_create(hass, log_msg, - title='Broadlink switch') + persistent_notification.async_create( + hass, log_msg, title='Broadlink switch') return yield from asyncio.sleep(1, loop=hass.loop) - _LOGGER.error('Did not received any signal.') - persistent_notification.async_create(hass, - "Did not received any signal", - title='Broadlink switch') + _LOGGER.error("Did not received any signal") + persistent_notification.async_create( + hass, "Did not received any signal", title='Broadlink switch') @asyncio.coroutine def _send_packet(call): @@ -119,7 +117,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): None, broadlink_device.auth) except socket.timeout: if retry == DEFAULT_RETRY-1: - _LOGGER.error("Failed to send packet to device.") + _LOGGER.error("Failed to send packet to device") if switch_type in RM_TYPES: broadlink_device = broadlink.rm((ip_addr, 80), mac_addr) @@ -148,7 +146,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: broadlink_device.auth() except socket.timeout: - _LOGGER.error("Failed to connect to device.") + _LOGGER.error("Failed to connect to device") add_devices(switches) @@ -199,7 +197,7 @@ class BroadlinkRMSwitch(SwitchDevice): def _sendpacket(self, packet, retry=2): """Send packet to device.""" if packet is None: - _LOGGER.debug("Empty packet.") + _LOGGER.debug("Empty packet") return True try: self._device.send_data(packet) diff --git a/homeassistant/components/switch/demo.py b/homeassistant/components/switch/demo.py index 54277d3ab39..83b8ae796bb 100644 --- a/homeassistant/components/switch/demo.py +++ b/homeassistant/components/switch/demo.py @@ -10,7 +10,7 @@ from homeassistant.const import DEVICE_DEFAULT_NAME # pylint: disable=unused-argument def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the demo switches.""" + """Set up the demo switches.""" add_devices_callback([ DemoSwitch('Decorative Lights', True, None, True), DemoSwitch('AC', False, 'mdi:air-conditioner', False) diff --git a/homeassistant/components/switch/digital_ocean.py b/homeassistant/components/switch/digital_ocean.py index 066a356ba7b..c873439dd58 100644 --- a/homeassistant/components/switch/digital_ocean.py +++ b/homeassistant/components/switch/digital_ocean.py @@ -28,7 +28,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Digital Ocean droplet switch.""" + """Set up the Digital Ocean droplet switch.""" digital_ocean = get_component('digital_ocean') droplets = config.get(CONF_DROPLETS) diff --git a/homeassistant/components/switch/dlink.py b/homeassistant/components/switch/dlink.py index 11aff81a0d5..d5036f9cb06 100644 --- a/homeassistant/components/switch/dlink.py +++ b/homeassistant/components/switch/dlink.py @@ -39,7 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup a D-Link Smart Plug.""" + """Set up a D-Link Smart Plug.""" from pyW215.pyW215 import SmartPlug host = config.get(CONF_HOST) diff --git a/homeassistant/components/switch/enocean.py b/homeassistant/components/switch/enocean.py index ead5d789bbd..abe197485d4 100644 --- a/homeassistant/components/switch/enocean.py +++ b/homeassistant/components/switch/enocean.py @@ -26,7 +26,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the EnOcean switch platform.""" + """Set up the EnOcean switch platform.""" dev_id = config.get(CONF_ID) devname = config.get(CONF_NAME) diff --git a/homeassistant/components/switch/flux.py b/homeassistant/components/switch/flux.py index 034fb7a4262..2052ffc4c15 100644 --- a/homeassistant/components/switch/flux.py +++ b/homeassistant/components/switch/flux.py @@ -81,7 +81,7 @@ def set_lights_temp(hass, lights, mired, brightness): # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Flux switches.""" + """Set up the Flux switches.""" name = config.get(CONF_NAME) lights = config.get(CONF_LIGHTS) start_time = config.get(CONF_START_TIME) @@ -139,11 +139,11 @@ class FluxSwitch(SwitchDevice): if self.is_on: return - # make initial update + # Make initial update self.flux_update() - self.unsub_tracker = track_time_change(self.hass, self.flux_update, - second=[0, 30]) + self.unsub_tracker = track_time_change( + self.hass, self.flux_update, second=[0, 30]) self.schedule_update_ha_state() @@ -159,13 +159,12 @@ class FluxSwitch(SwitchDevice): """Update all the lights using flux.""" if now is None: now = dt_now() - sunset = next_setting(self.hass, SUN).replace(day=now.day, - month=now.month, - year=now.year) + sunset = next_setting(self.hass, SUN).replace( + day=now.day, month=now.month, year=now.year) start_time = self.find_start_time(now) - stop_time = now.replace(hour=self._stop_time.hour, - minute=self._stop_time.minute, - second=0) + stop_time = now.replace( + hour=self._stop_time.hour, minute=self._stop_time.minute, + second=0) if start_time < now < sunset: # Daytime @@ -203,26 +202,25 @@ class FluxSwitch(SwitchDevice): if self._mode == MODE_XY: set_lights_xy(self.hass, self._lights, x_val, y_val, brightness) - _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%" - " of %s cycle complete at %s", x_val, y_val, + _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%% " + "of %s cycle complete at %s", x_val, y_val, brightness, round( percentage_complete * 100), time_state, now) else: # Convert to mired and clamp to allowed values mired = color_temperature_kelvin_to_mired(temp) set_lights_temp(self.hass, self._lights, mired, brightness) - _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%%" - " of %s cycle complete at %s", mired, brightness, + _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%% " + "of %s cycle complete at %s", mired, brightness, round(percentage_complete * 100), time_state, now) def find_start_time(self, now): """Return sunrise or start_time if given.""" if self._start_time: - sunrise = now.replace(hour=self._start_time.hour, - minute=self._start_time.minute, - second=0) + sunrise = now.replace( + hour=self._start_time.hour, minute=self._start_time.minute, + second=0) else: - sunrise = next_rising(self.hass, SUN).replace(day=now.day, - month=now.month, - year=now.year) + sunrise = next_rising(self.hass, SUN).replace( + day=now.day, month=now.month, year=now.year) return sunrise diff --git a/homeassistant/components/switch/hikvisioncam.py b/homeassistant/components/switch/hikvisioncam.py index 220011b2fb0..74d3a2429eb 100644 --- a/homeassistant/components/switch/hikvisioncam.py +++ b/homeassistant/components/switch/hikvisioncam.py @@ -34,7 +34,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Hikvision camera.""" + """Set up Hikvision camera.""" import hikvision.api from hikvision.error import HikvisionError, MissingParamError diff --git a/homeassistant/components/switch/homematic.py b/homeassistant/components/switch/homematic.py index bbacfdb1db9..a95f414bb1b 100644 --- a/homeassistant/components/switch/homematic.py +++ b/homeassistant/components/switch/homematic.py @@ -15,7 +15,7 @@ DEPENDENCIES = ['homematic'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Homematic switch platform.""" + """Set up the Homematic switch platform.""" if discovery_info is None: return diff --git a/homeassistant/components/switch/knx.py b/homeassistant/components/switch/knx.py index 5141e26cdf3..d07df08ed5c 100644 --- a/homeassistant/components/switch/knx.py +++ b/homeassistant/components/switch/knx.py @@ -25,7 +25,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the KNX switch platform.""" + """Set up the KNX switch platform.""" add_devices([KNXSwitch(hass, KNXConfig(config))]) diff --git a/homeassistant/components/switch/lutron_caseta.py b/homeassistant/components/switch/lutron_caseta.py index a8fca67e91a..01d8e063db9 100644 --- a/homeassistant/components/switch/lutron_caseta.py +++ b/homeassistant/components/switch/lutron_caseta.py @@ -1,11 +1,15 @@ -"""Support for Lutron Caseta switches.""" +""" +Support for Lutron Caseta switches. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sitch.lutron_caseta/ +""" import logging from homeassistant.components.lutron_caseta import ( LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice) from homeassistant.components.switch import SwitchDevice - _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['lutron_caseta'] @@ -13,7 +17,7 @@ DEPENDENCIES = ['lutron_caseta'] # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Lutron switch.""" + """Set up Lutron switch.""" devs = [] bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE] switch_devices = bridge.get_devices_by_type("WallSwitch") diff --git a/homeassistant/components/switch/mfi.py b/homeassistant/components/switch/mfi.py index da74d189c6f..76c3df5c98c 100644 --- a/homeassistant/components/switch/mfi.py +++ b/homeassistant/components/switch/mfi.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup mFi sensors.""" + """Set up mFi sensors.""" host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) diff --git a/homeassistant/components/switch/mochad.py b/homeassistant/components/switch/mochad.py index b7ebcabeb86..21df1898fd2 100644 --- a/homeassistant/components/switch/mochad.py +++ b/homeassistant/components/switch/mochad.py @@ -31,7 +31,7 @@ PLATFORM_SCHEMA = vol.Schema({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup X10 switches over a mochad controller.""" + """Set up X10 switches over a mochad controller.""" devs = config.get(CONF_DEVICES) add_devices([MochadSwitch( hass, mochad.CONTROLLER.ctrl, dev) for dev in devs]) diff --git a/homeassistant/components/switch/mysensors.py b/homeassistant/components/switch/mysensors.py index 968166d4d65..c72ea1e4cfe 100644 --- a/homeassistant/components/switch/mysensors.py +++ b/homeassistant/components/switch/mysensors.py @@ -28,7 +28,7 @@ SEND_IR_CODE_SERVICE_SCHEMA = vol.Schema({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors platform for switches.""" + """Set up the mysensors platform for switches.""" # Only act if loaded via mysensors by discovery event. # Otherwise gateway is not setup. if discovery_info is None: @@ -158,7 +158,7 @@ class MySensorsIRSwitch(MySensorsSwitch): """IR switch child class to MySensorsSwitch.""" def __init__(self, *args): - """Setup instance attributes.""" + """Set up instance attributes.""" MySensorsSwitch.__init__(self, *args) self._ir_code = None diff --git a/homeassistant/components/switch/orvibo.py b/homeassistant/components/switch/orvibo.py index 0ce1426dd1f..8acf398968d 100644 --- a/homeassistant/components/switch/orvibo.py +++ b/homeassistant/components/switch/orvibo.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup S20 switches.""" + """Set up S20 switches.""" from orvibo.s20 import discover, S20, S20Exception switch_data = {} diff --git a/homeassistant/components/switch/rfxtrx.py b/homeassistant/components/switch/rfxtrx.py index 959bab5fe40..4679ea19f4d 100644 --- a/homeassistant/components/switch/rfxtrx.py +++ b/homeassistant/components/switch/rfxtrx.py @@ -17,7 +17,7 @@ PLATFORM_SCHEMA = rfxtrx.DEFAULT_SCHEMA def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the RFXtrx platform.""" + """Set up the RFXtrx platform.""" import RFXtrx as rfxtrxmod # Add switch from config file diff --git a/homeassistant/components/switch/rpi_gpio.py b/homeassistant/components/switch/rpi_gpio.py index cc761250be4..18d05db2f28 100644 --- a/homeassistant/components/switch/rpi_gpio.py +++ b/homeassistant/components/switch/rpi_gpio.py @@ -36,7 +36,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Raspberry PI GPIO devices.""" + """Set up the Raspberry PI GPIO devices.""" invert_logic = config.get(CONF_INVERT_LOGIC) switches = [] diff --git a/homeassistant/components/switch/scsgate.py b/homeassistant/components/switch/scsgate.py index 965011d12ea..7c22e0d5a88 100644 --- a/homeassistant/components/switch/scsgate.py +++ b/homeassistant/components/switch/scsgate.py @@ -31,7 +31,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the SCSGate switches.""" + """Set up the SCSGate switches.""" logger = logging.getLogger(__name__) _setup_traditional_switches( diff --git a/homeassistant/components/switch/tellduslive.py b/homeassistant/components/switch/tellduslive.py index 5f3901d79b8..eec63ebaa5c 100644 --- a/homeassistant/components/switch/tellduslive.py +++ b/homeassistant/components/switch/tellduslive.py @@ -16,7 +16,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Tellstick switches.""" + """Set up Tellstick switches.""" if discovery_info is None: return add_devices(TelldusLiveSwitch(hass, switch) for switch in discovery_info) diff --git a/homeassistant/components/switch/tellstick.py b/homeassistant/components/switch/tellstick.py index 094db06c49f..c631eedc050 100644 --- a/homeassistant/components/switch/tellstick.py +++ b/homeassistant/components/switch/tellstick.py @@ -17,7 +17,7 @@ PLATFORM_SCHEMA = vol.Schema({vol.Required("platform"): DOMAIN}) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Tellstick switches.""" + """Set up Tellstick switches.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None): return diff --git a/homeassistant/components/switch/template.py b/homeassistant/components/switch/template.py index 4ea2d82388d..b88b9ea590d 100644 --- a/homeassistant/components/switch/template.py +++ b/homeassistant/components/switch/template.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine # pylint: disable=unused-argument def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Template switch.""" + """Set up the Template switch.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): diff --git a/homeassistant/components/switch/thinkingcleaner.py b/homeassistant/components/switch/thinkingcleaner.py index c088667a044..37c2f52e228 100644 --- a/homeassistant/components/switch/thinkingcleaner.py +++ b/homeassistant/components/switch/thinkingcleaner.py @@ -31,7 +31,7 @@ SWITCH_TYPES = { def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ThinkingCleaner platform.""" + """Set up the ThinkingCleaner platform.""" from pythinkingcleaner import Discovery discovery = Discovery() diff --git a/homeassistant/components/switch/tplink.py b/homeassistant/components/switch/tplink.py index cc00a3691ee..1b8ef585557 100644 --- a/homeassistant/components/switch/tplink.py +++ b/homeassistant/components/switch/tplink.py @@ -32,7 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the TPLink switch platform.""" + """Set up the TPLink switch platform.""" from pyHS100 import SmartPlug host = config.get(CONF_HOST) name = config.get(CONF_NAME) diff --git a/homeassistant/components/switch/transmission.py b/homeassistant/components/switch/transmission.py index 6b8f89838d5..656a6227358 100644 --- a/homeassistant/components/switch/transmission.py +++ b/homeassistant/components/switch/transmission.py @@ -33,7 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Transmission switch.""" + """Set up the Transmission switch.""" import transmissionrpc from transmissionrpc.error import TransmissionError diff --git a/homeassistant/components/switch/verisure.py b/homeassistant/components/switch/verisure.py index d7974335811..3aeb092f35b 100644 --- a/homeassistant/components/switch/verisure.py +++ b/homeassistant/components/switch/verisure.py @@ -14,7 +14,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Verisure switch platform.""" + """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False diff --git a/homeassistant/components/switch/volvooncall.py b/homeassistant/components/switch/volvooncall.py index 46cfd667951..9e20ddb5e7e 100644 --- a/homeassistant/components/switch/volvooncall.py +++ b/homeassistant/components/switch/volvooncall.py @@ -15,7 +15,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Tellstick switches.""" + """Set up Tellstick switches.""" if discovery_info is None: return add_devices([VolvoSwitch(hass, *discovery_info)]) diff --git a/homeassistant/components/switch/wemo.py b/homeassistant/components/switch/wemo.py index 700d9d25b5a..ba47ed7cb04 100644 --- a/homeassistant/components/switch/wemo.py +++ b/homeassistant/components/switch/wemo.py @@ -32,7 +32,7 @@ WEMO_STANDBY = 8 # pylint: disable=unused-argument, too-many-function-args def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup discovered WeMo switches.""" + """Set up discovered WeMo switches.""" import pywemo.discovery as discovery if discovery_info is not None: diff --git a/homeassistant/components/switch/wink.py b/homeassistant/components/switch/wink.py index 5d5b477be99..6783f2201c1 100644 --- a/homeassistant/components/switch/wink.py +++ b/homeassistant/components/switch/wink.py @@ -12,7 +12,7 @@ DEPENDENCIES = ['wink'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink platform.""" + """Set up the Wink platform.""" import pywink for switch in pywink.get_switches(): diff --git a/homeassistant/components/switch/zha.py b/homeassistant/components/switch/zha.py index fb327d3ddd9..c98db2e894e 100644 --- a/homeassistant/components/switch/zha.py +++ b/homeassistant/components/switch/zha.py @@ -16,7 +16,7 @@ DEPENDENCIES = ['zha'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Zigbee Home Automation switches.""" + """Set up Zigbee Home Automation switches.""" discovery_info = zha.get_discovery_info(hass, discovery_info) if discovery_info is None: return diff --git a/homeassistant/components/switch/zigbee.py b/homeassistant/components/switch/zigbee.py index 7a58b0867c1..a0db5685a90 100644 --- a/homeassistant/components/switch/zigbee.py +++ b/homeassistant/components/switch/zigbee.py @@ -25,7 +25,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ZigBee switch platform.""" + """Set up the ZigBee switch platform.""" add_devices([ZigBeeSwitch(hass, ZigBeeDigitalOutConfig(config))]) diff --git a/homeassistant/components/telegram_bot/__init__.py b/homeassistant/components/telegram_bot/__init__.py index e0adff19731..1a79109f17d 100644 --- a/homeassistant/components/telegram_bot/__init__.py +++ b/homeassistant/components/telegram_bot/__init__.py @@ -39,10 +39,10 @@ PLATFORM_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Setup the telegram bot component.""" + """Set up the telegram bot component.""" @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): - """Setup a telegram bot platform.""" + """Set up a telegram bot platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) diff --git a/homeassistant/components/telegram_bot/polling.py b/homeassistant/components/telegram_bot/polling.py index d46c3f539d2..c9891e884f0 100644 --- a/homeassistant/components/telegram_bot/polling.py +++ b/homeassistant/components/telegram_bot/polling.py @@ -1,5 +1,9 @@ -"""Telegram bot polling implementation.""" +""" +Telegram bot polling implementation. +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/telegram_bot.polling/ +""" import asyncio from asyncio.futures import CancelledError import logging @@ -23,7 +27,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the polling platform.""" + """Set up the Telegram polling platform.""" import telegram bot = telegram.Bot(config[CONF_API_KEY]) pol = TelegramPoll(bot, hass, config[CONF_ALLOWED_CHAT_IDS]) diff --git a/homeassistant/components/telegram_bot/webhooks.py b/homeassistant/components/telegram_bot/webhooks.py index 3444c58809a..4c9f7684d36 100644 --- a/homeassistant/components/telegram_bot/webhooks.py +++ b/homeassistant/components/telegram_bot/webhooks.py @@ -1,9 +1,8 @@ """ Allows utilizing telegram webhooks. -See https://core.telegram.org/bots/webhooks for details - about webhooks. - +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/telegram_bot.webhooks/ """ import asyncio import logging @@ -45,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the polling platform.""" + """Set up the Telegram webhooks platform.""" import telegram bot = telegram.Bot(config[CONF_API_KEY]) @@ -54,9 +53,9 @@ def setup_platform(hass, config, async_add_devices, discovery_info=None): hass.config.api.base_url, TELEGRAM_HANDLER_URL) if current_status and current_status['url'] != handler_url: if bot.setWebhook(handler_url): - _LOGGER.info("set new telegram webhook %s", handler_url) + _LOGGER.info("Set new telegram webhook %s", handler_url) else: - _LOGGER.error("set telegram webhook failed %s", handler_url) + _LOGGER.error("Set telegram webhook failed %s", handler_url) return False hass.bus.listen_once( diff --git a/homeassistant/components/tts/amazon_polly.py b/homeassistant/components/tts/amazon_polly.py index 7dab49482ed..e3c90f4778c 100644 --- a/homeassistant/components/tts/amazon_polly.py +++ b/homeassistant/components/tts/amazon_polly.py @@ -81,7 +81,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_engine(hass, config): - """Setup Amazon Polly speech component.""" + """Set up Amazon Polly speech component.""" # pylint: disable=import-error output_format = config.get(CONF_OUTPUT_FORMAT) sample_rate = config.get(CONF_SAMPLE_RATE, diff --git a/homeassistant/components/tts/demo.py b/homeassistant/components/tts/demo.py index d9d1eccec8d..ea169e9f1a5 100644 --- a/homeassistant/components/tts/demo.py +++ b/homeassistant/components/tts/demo.py @@ -22,7 +22,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def get_engine(hass, config): - """Setup Demo speech component.""" + """Set up Demo speech component.""" return DemoProvider(config[CONF_LANG]) diff --git a/homeassistant/components/tts/marytts.py b/homeassistant/components/tts/marytts.py index ffb6950d79b..e0e7e1d0f88 100644 --- a/homeassistant/components/tts/marytts.py +++ b/homeassistant/components/tts/marytts.py @@ -51,7 +51,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_get_engine(hass, config): - """Setup MaryTTS speech component.""" + """Set up MaryTTS speech component.""" return MaryTTSProvider(hass, config) diff --git a/homeassistant/components/tts/yandextts.py b/homeassistant/components/tts/yandextts.py index fb95faf1ecf..0f8ec88f87b 100644 --- a/homeassistant/components/tts/yandextts.py +++ b/homeassistant/components/tts/yandextts.py @@ -66,7 +66,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_get_engine(hass, config): - """Setup VoiceRSS speech component.""" + """Set up VoiceRSS speech component.""" return YandexSpeechKitProvider(hass, config) diff --git a/homeassistant/components/weather/__init__.py b/homeassistant/components/weather/__init__.py index d67af26f560..9b0daf10efb 100644 --- a/homeassistant/components/weather/__init__.py +++ b/homeassistant/components/weather/__init__.py @@ -36,7 +36,7 @@ ATTR_FORECAST_TIME = 'datetime' @asyncio.coroutine def async_setup(hass, config): - """Setup the weather component.""" + """Set up the weather component.""" component = EntityComponent(_LOGGER, DOMAIN, hass) yield from component.async_setup(config) diff --git a/homeassistant/components/weather/demo.py b/homeassistant/components/weather/demo.py index 00470e86e1b..0a404447346 100644 --- a/homeassistant/components/weather/demo.py +++ b/homeassistant/components/weather/demo.py @@ -29,7 +29,7 @@ CONDITION_CLASSES = { def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo weather.""" + """Set up the Demo weather.""" add_devices([ DemoWeather('South', 'Sunshine', 21, 92, 1099, 0.5, TEMP_CELSIUS, [22, 19, 15, 12, 14, 18, 21]), diff --git a/homeassistant/components/weather/openweathermap.py b/homeassistant/components/weather/openweathermap.py index aa3213c3832..088ca359cc1 100644 --- a/homeassistant/components/weather/openweathermap.py +++ b/homeassistant/components/weather/openweathermap.py @@ -53,7 +53,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the OpenWeatherMap weather platform.""" + """Set up the OpenWeatherMap weather platform.""" import pyowm longitude = config.get(CONF_LONGITUDE, round(hass.config.longitude, 5)) diff --git a/homeassistant/components/zwave/__init__.py b/homeassistant/components/zwave/__init__.py index bf7eaa87e68..dad7a55d14c 100755 --- a/homeassistant/components/zwave/__init__.py +++ b/homeassistant/components/zwave/__init__.py @@ -214,7 +214,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): # pylint: disable=R0914 def setup(hass, config): - """Setup Z-Wave. + """Set up Z-Wave. Will automatically load components to support devices found on the network. """ diff --git a/homeassistant/helpers/__init__.py b/homeassistant/helpers/__init__.py index 47a7627b5ce..91ec5051552 100644 --- a/homeassistant/helpers/__init__.py +++ b/homeassistant/helpers/__init__.py @@ -17,7 +17,7 @@ ConfigType = Dict[str, Any] # pylint: disable=invalid-sequence-index def config_per_platform(config: ConfigType, domain: str) -> Iterable[Tuple[Any, Any]]: - """Generator to break a component config into different platforms. + """Break a component config into different platforms. For example, will find 'switch', 'switch 2', 'switch 3', .. etc Async friendly. diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index 24af8a26351..bbfb19f7806 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -30,7 +30,7 @@ _LOGGER = logging.getLogger(__name__) def _threaded_factory(async_factory): - """Helper method to create threaded versions of async factories.""" + """Create threaded versions of async factories.""" @ft.wraps(async_factory) def factory(config, config_validation=True): """Threaded factory.""" @@ -90,7 +90,7 @@ def async_and_from_config(config: ConfigType, config_validation: bool=True): if not check(hass, variables): return False except Exception as ex: # pylint: disable=broad-except - _LOGGER.warning('Error during and-condition: %s', ex) + _LOGGER.warning("Error during and-condition: %s", ex) return False return True @@ -121,7 +121,7 @@ def async_or_from_config(config: ConfigType, config_validation: bool=True): if check(hass, variables): return True except Exception as ex: # pylint: disable=broad-except - _LOGGER.warning('Error during or-condition: %s', ex) + _LOGGER.warning("Error during or-condition: %s", ex) return False @@ -285,7 +285,7 @@ def async_template(hass, value_template, variables=None): try: value = value_template.async_render(variables) except TemplateError as ex: - _LOGGER.error('Error during template condition: %s', ex) + _LOGGER.error("Error during template condition: %s", ex) return False return value.lower() == 'true' diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index 32eeeaff5ab..3378116163f 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -43,7 +43,7 @@ T = TypeVar('T') # Adapted from: # https://github.com/alecthomas/voluptuous/issues/115#issuecomment-144464666 def has_at_least_one_key(*keys: str) -> Callable: - """Validator that at least one key exists.""" + """Validate that at least one key exists.""" def validate(obj: Dict) -> Dict: """Test keys exist in dict.""" if not isinstance(obj, dict): @@ -192,7 +192,7 @@ time_period = vol.Any(time_period_str, time_period_seconds, timedelta, def match_all(value): - """Validator that matches all values.""" + """Validate that matches all values.""" return value diff --git a/homeassistant/helpers/deprecation.py b/homeassistant/helpers/deprecation.py index a2396b9d30f..88de3a48aa0 100644 --- a/homeassistant/helpers/deprecation.py +++ b/homeassistant/helpers/deprecation.py @@ -1,5 +1,4 @@ """Deprecation helpers for Home Assistant.""" - import inspect import logging @@ -13,9 +12,9 @@ def deprecated_substitute(substitute_name): warning will be issued alerting the user of the impending change. """ def decorator(func): - """Decorator function.""" + """Decorate function as deprecated.""" def func_wrapper(self): - """Wrapper for original function.""" + """Wrap for the original function.""" if hasattr(self, substitute_name): # If this platform is still using the old property, issue # a logger warning once with instructions on how to fix it. diff --git a/homeassistant/helpers/discovery.py b/homeassistant/helpers/discovery.py index 67fa71ece29..7d3d7d0e823 100644 --- a/homeassistant/helpers/discovery.py +++ b/homeassistant/helpers/discovery.py @@ -19,7 +19,7 @@ ATTR_PLATFORM = 'platform' def listen(hass, service, callback): - """Setup listener for discovery of specific service. + """Set up listener for discovery of specific service. Service can be a string or a list/tuple. """ @@ -29,7 +29,7 @@ def listen(hass, service, callback): @core.callback def async_listen(hass, service, callback): - """Setup listener for discovery of specific service. + """Set up listener for discovery of specific service. Service can be a string or a list/tuple. """ diff --git a/homeassistant/helpers/dispatcher.py b/homeassistant/helpers/dispatcher.py index c4c5ea59d6b..d5fbadec883 100644 --- a/homeassistant/helpers/dispatcher.py +++ b/homeassistant/helpers/dispatcher.py @@ -1,4 +1,4 @@ -"""Helpers for hass dispatcher & internal component / platform.""" +"""Helpers for Home Assistant dispatcher & internal component/platform.""" import logging from homeassistant.core import callback diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index 6a625ee9e3e..f687d1e808f 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -206,13 +206,13 @@ class Entity(object): # update entity data if force_refresh: if self._update_warn: - _LOGGER.warning('Update for %s is already in progress', + _LOGGER.warning("Update for %s is already in progress", self.entity_id) return self._update_warn = self.hass.loop.call_later( SLOW_UPDATE_WARNING, _LOGGER.warning, - 'Update of %s is taking over %s seconds.', self.entity_id, + "Update of %s is taking over %s seconds", self.entity_id, SLOW_UPDATE_WARNING ) @@ -224,7 +224,7 @@ class Entity(object): yield from self.hass.loop.run_in_executor( None, self.update) except Exception: # pylint: disable=broad-except - _LOGGER.exception('Update for %s fails', self.entity_id) + _LOGGER.exception("Update for %s fails", self.entity_id) return finally: self._update_warn.cancel() @@ -264,9 +264,9 @@ class Entity(object): if not self._slow_reported and end - start > 0.4: self._slow_reported = True - _LOGGER.warning('Updating state for %s took %.3f seconds. ' - 'Please report platform to the developers at ' - 'https://goo.gl/Nvioub', self.entity_id, + _LOGGER.warning("Updating state for %s took %.3f seconds. " + "Please report platform to the developers at " + "https://goo.gl/Nvioub", self.entity_id, end - start) # Overwrite properties that have been set in the config file. @@ -316,7 +316,7 @@ class Entity(object): self.hass.states.async_remove(self.entity_id) def _attr_setter(self, name, typ, attr, attrs): - """Helper method to populate attributes based on properties.""" + """Populate attributes based on properties.""" if attr in attrs: return diff --git a/homeassistant/helpers/entity_component.py b/homeassistant/helpers/entity_component.py index 9e059528619..6e69f772d1e 100644 --- a/homeassistant/helpers/entity_component.py +++ b/homeassistant/helpers/entity_component.py @@ -76,7 +76,7 @@ class EntityComponent(object): # Refer to: homeassistant.components.discovery.load_platform() @callback def component_platform_discovered(platform, info): - """Callback to load a platform.""" + """Handle the loading of a platform.""" self.hass.async_add_job( self._async_setup_platform(platform, {}, info)) @@ -114,7 +114,7 @@ class EntityComponent(object): @asyncio.coroutine def _async_setup_platform(self, platform_type, platform_config, discovery_info=None): - """Setup a platform for this component. + """Set up a platform for this component. This method must be run in the event loop. """ @@ -140,7 +140,7 @@ class EntityComponent(object): self.logger.info("Setting up %s.%s", self.domain, platform_type) warn_task = self.hass.loop.call_later( SLOW_SETUP_WARNING, self.logger.warning, - 'Setup of platform %s is taking over %s seconds.', platform_type, + "Setup of platform %s is taking over %s seconds.", platform_type, SLOW_SETUP_WARNING) try: @@ -161,7 +161,7 @@ class EntityComponent(object): '{}.{}'.format(self.domain, platform_type)) except Exception: # pylint: disable=broad-except self.logger.exception( - 'Error while setting up platform %s', platform_type) + "Error while setting up platform %s", platform_type) finally: warn_task.cancel() @@ -297,7 +297,7 @@ class EntityPlatform(object): """Keep track of entities for a single platform and stay in loop.""" def __init__(self, component, platform, scan_interval, entity_namespace): - """Initalize the entity platform.""" + """Initialize the entity platform.""" self.component = component self.platform = platform self.scan_interval = scan_interval @@ -430,7 +430,7 @@ class EntityPlatform(object): yield from update_coro except Exception: # pylint: disable=broad-except self.component.logger.exception( - 'Error while update entity from %s in %s', + "Error while update entity from %s in %s", self.platform, self.component.domain) if tasks: diff --git a/homeassistant/helpers/event.py b/homeassistant/helpers/event.py index 12e031bfc3e..0cdcca42eca 100644 --- a/homeassistant/helpers/event.py +++ b/homeassistant/helpers/event.py @@ -59,7 +59,7 @@ def async_track_state_change(hass, entity_ids, action, from_state=None, @callback def state_change_listener(event): - """The listener that listens for specific state changes.""" + """Handle specific state changes.""" if entity_ids != MATCH_ALL and \ event.data.get('entity_id') not in entity_ids: return @@ -175,7 +175,7 @@ def async_track_time_interval(hass, action, interval): @callback def interval_listener(now): - """Called when when the interval has elapsed.""" + """Handle elaspsed intervals.""" nonlocal remove remove = async_track_point_in_utc_time( hass, interval_listener, next_interval()) @@ -212,7 +212,7 @@ def async_track_sunrise(hass, action, offset=None): @callback def sunrise_automation_listener(now): - """Called when it's time for action.""" + """Handle points in time to execute actions.""" nonlocal remove remove = async_track_point_in_utc_time( hass, sunrise_automation_listener, next_rise()) @@ -249,7 +249,7 @@ def async_track_sunset(hass, action, offset=None): @callback def sunset_automation_listener(now): - """Called when it's time for action.""" + """Handle points in time to execute actions.""" nonlocal remove remove = async_track_point_in_utc_time( hass, sunset_automation_listener, next_set()) diff --git a/homeassistant/helpers/restore_state.py b/homeassistant/helpers/restore_state.py index c022d5ae8f3..08e7a91397a 100644 --- a/homeassistant/helpers/restore_state.py +++ b/homeassistant/helpers/restore_state.py @@ -50,7 +50,7 @@ def _load_restore_cache(hass: HomeAssistant): @asyncio.coroutine def async_get_last_state(hass, entity_id: str): - """Helper to restore state.""" + """Restore state.""" if DATA_RESTORE_CACHE in hass.data: return hass.data[DATA_RESTORE_CACHE].get(entity_id) @@ -84,7 +84,7 @@ def async_get_last_state(hass, entity_id: str): @asyncio.coroutine def async_restore_state(entity, extract_info): - """Helper to call entity.async_restore_state with cached info.""" + """Call entity.async_restore_state with cached info.""" if entity.hass.state not in (CoreState.starting, CoreState.not_running): _LOGGER.debug("Not restoring state for %s: Hass is not starting: %s", entity.entity_id, entity.hass.state) diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index 03a01ece768..b44905a3141 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -19,14 +19,14 @@ from homeassistant.util.async import ( _LOGGER = logging.getLogger(__name__) -CONF_ALIAS = "alias" -CONF_SERVICE = "service" -CONF_SERVICE_DATA = "data" -CONF_SEQUENCE = "sequence" -CONF_EVENT = "event" -CONF_EVENT_DATA = "event_data" -CONF_DELAY = "delay" -CONF_WAIT_TEMPLATE = "wait_template" +CONF_ALIAS = 'alias' +CONF_SERVICE = 'service' +CONF_SERVICE_DATA = 'data' +CONF_SEQUENCE = 'sequence' +CONF_EVENT = 'event' +CONF_EVENT_DATA = 'event_data' +CONF_DELAY = 'delay' +CONF_WAIT_TEMPLATE = 'wait_template' def call_from_config(hass: HomeAssistant, config: ConfigType, @@ -88,7 +88,7 @@ class Script(): @callback def async_script_delay(now): - """Called after delay is done.""" + """Handle delay.""" # pylint: disable=cell-var-from-loop self._async_listener.remove(unsub) self.hass.async_add_job(self.async_run(variables)) @@ -124,7 +124,7 @@ class Script(): @callback def async_script_wait(entity_id, from_s, to_s): - """Called after template condition is true.""" + """Handle script after template condition is true.""" self._async_remove_listener() self.hass.async_add_job(self.async_run(variables)) diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index ce0d4f6c8a3..af6aa0f2195 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -81,7 +81,7 @@ def async_call_from_config(hass, config, blocking=False, variables=None, def extract_entity_ids(hass, service_call, expand_group=True): - """Helper method to extract a list of entity ids from a service call. + """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. diff --git a/homeassistant/helpers/state.py b/homeassistant/helpers/state.py index dbc32d1c37e..7715e49880d 100644 --- a/homeassistant/helpers/state.py +++ b/homeassistant/helpers/state.py @@ -133,7 +133,7 @@ def async_reproduce_state(hass, states, blocking=False): for state in states: if hass.states.get(state.entity_id) is None: - _LOGGER.warning('reproduce_state: Unable to find entity %s', + _LOGGER.warning("reproduce_state: Unable to find entity %s", state.entity_id) continue diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index ce5cc9e918d..7c2aeff71aa 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -131,7 +131,7 @@ class Template(object): try: return self._compiled.render(variables).strip() except jinja2.TemplateError as ex: - _LOGGER.error('Error parsing value: %s (value: %s, template: %s)', + _LOGGER.error("Error parsing value: %s (value: %s, template: %s)", ex, value, self.template) return value if error_value is _SENTINEL else error_value @@ -238,11 +238,11 @@ class LocationMethods(object): point_state = self._resolve_state(args[0]) if point_state is None: - _LOGGER.warning('Closest:Unable to find state %s', args[0]) + _LOGGER.warning("Closest:Unable to find state %s", args[0]) return None elif not loc_helper.has_location(point_state): _LOGGER.warning( - 'Closest:State does not contain valid location: %s', + "Closest:State does not contain valid location: %s", point_state) return None @@ -257,7 +257,7 @@ class LocationMethods(object): if latitude is None or longitude is None: _LOGGER.warning( - 'Closest:Received invalid coordinates: %s, %s', + "Closest:Received invalid coordinates: %s, %s", args[0], args[1]) return None @@ -297,7 +297,7 @@ class LocationMethods(object): if latitude is None or longitude is None: _LOGGER.warning( - 'Distance:State does not contains a location: %s', + "Distance:State does not contains a location: %s", value) return None @@ -305,7 +305,7 @@ class LocationMethods(object): # We expect this and next value to be lat&lng if not to_process: _LOGGER.warning( - 'Distance:Expected latitude and longitude, got %s', + "Distance:Expected latitude and longitude, got %s", value) return None @@ -314,8 +314,8 @@ class LocationMethods(object): longitude = convert(value_2, float) if latitude is None or longitude is None: - _LOGGER.warning('Distance:Unable to process latitude and ' - 'longitude: %s, %s', value, value_2) + _LOGGER.warning("Distance:Unable to process latitude and " + "longitude: %s, %s", value, value_2) return None locations.append((latitude, longitude)) diff --git a/homeassistant/helpers/typing.py b/homeassistant/helpers/typing.py index 24774ac29da..d0feab414da 100644 --- a/homeassistant/helpers/typing.py +++ b/homeassistant/helpers/typing.py @@ -1,4 +1,4 @@ -"""Typing Helpers for Home-Assistant.""" +"""Typing Helpers for Home Assistant.""" from typing import Dict, Any, Tuple import homeassistant.core diff --git a/homeassistant/scripts/db_migrator.py b/homeassistant/scripts/db_migrator.py index ee3ee253b65..bf4dddc94fe 100644 --- a/homeassistant/scripts/db_migrator.py +++ b/homeassistant/scripts/db_migrator.py @@ -47,7 +47,7 @@ def print_progress(iteration: int, total: int, prefix: str='', suffix: str='', def run(script_args: List) -> int: - """The actual script body.""" + """Run the actual script.""" # pylint: disable=invalid-name from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker diff --git a/homeassistant/scripts/influxdb_import.py b/homeassistant/scripts/influxdb_import.py index 2d9af4c7529..c21ac4adad9 100644 --- a/homeassistant/scripts/influxdb_import.py +++ b/homeassistant/scripts/influxdb_import.py @@ -9,7 +9,7 @@ import homeassistant.config as config_util def run(script_args: List) -> int: - """The actual script body.""" + """Run the actual script.""" from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from influxdb import InfluxDBClient diff --git a/homeassistant/scripts/influxdb_migrator.py b/homeassistant/scripts/influxdb_migrator.py index 6f643c592de..6f130d18757 100644 --- a/homeassistant/scripts/influxdb_migrator.py +++ b/homeassistant/scripts/influxdb_migrator.py @@ -32,7 +32,7 @@ def print_progress(iteration: int, total: int, prefix: str='', suffix: str='', def run(script_args: List) -> int: - """The actual script body.""" + """Run the actual script.""" from influxdb import InfluxDBClient parser = argparse.ArgumentParser( diff --git a/homeassistant/scripts/macos/__init__.py b/homeassistant/scripts/macos/__init__.py index a37275e715f..275a33627a9 100644 --- a/homeassistant/scripts/macos/__init__.py +++ b/homeassistant/scripts/macos/__init__.py @@ -4,7 +4,7 @@ import time def install_osx(): - """Setup to run via launchd on OS X.""" + """Set up to run via launchd on OS X.""" with os.popen('which hass') as inp: hass_path = inp.read().strip() diff --git a/homeassistant/util/__init__.py b/homeassistant/util/__init__.py index 1186892b512..616b9100815 100644 --- a/homeassistant/util/__init__.py +++ b/homeassistant/util/__init__.py @@ -185,7 +185,7 @@ class OrderedSet(MutableSet): next_item[1] = prev_item def __iter__(self): - """Iteration of the set.""" + """Iterate of the set.""" end = self.end curr = end[2] while curr is not end: @@ -273,7 +273,7 @@ class Throttle(object): @wraps(method) def wrapper(*args, **kwargs): - """Wrapper that allows wrapped to be called only once per min_time. + """Wrap that allows wrapped to be called only once per min_time. If we cannot acquire the lock, it is running so return None. """ diff --git a/homeassistant/util/async.py b/homeassistant/util/async.py index 58aaa4b0338..ea8e5e3c874 100644 --- a/homeassistant/util/async.py +++ b/homeassistant/util/async.py @@ -19,7 +19,7 @@ _LOGGER = logging.getLogger(__name__) def _set_result_unless_cancelled(fut, result): - """Helper setting the result only if the future was not cancelled.""" + """Set the result only if the Future was not cancelled.""" if fut.cancelled(): return fut.set_result(result) @@ -41,7 +41,7 @@ def _set_concurrent_future_state(concurr, source): def _copy_future_state(source, dest): - """Internal helper to copy state from another Future. + """Copy state from another Future. The other Future may be a concurrent.futures.Future. """ @@ -112,7 +112,7 @@ def run_coroutine_threadsafe(coro, loop): future = concurrent.futures.Future() def callback(): - """Callback to call the coroutine.""" + """Handle the call to the coroutine.""" try: # pylint: disable=deprecated-method _chain_future(ensure_future(coro, loop=loop), future) @@ -142,7 +142,7 @@ def fire_coroutine_threadsafe(coro, loop): raise TypeError('A coroutine object is required: %s' % coro) def callback(): - """Callback to fire coroutine.""" + """Handle the firing of a coroutine.""" # pylint: disable=deprecated-method ensure_future(coro, loop=loop) diff --git a/homeassistant/util/logging.py b/homeassistant/util/logging.py index 095e906efe1..16d5c750172 100644 --- a/homeassistant/util/logging.py +++ b/homeassistant/util/logging.py @@ -73,7 +73,7 @@ class AsyncHandler(object): self.loop.call_soon_threadsafe(self._queue.put_nowait, record) def __repr__(self): - """String name of this.""" + """Return the string names.""" return str(self.handler) def _process(self): diff --git a/tests/common.py b/tests/common.py index 1dc6e9ffdba..0a2ea951c91 100644 --- a/tests/common.py +++ b/tests/common.py @@ -78,7 +78,7 @@ def get_test_home_assistant(): orig_stop = hass.stop def start_hass(*mocks): - """Helper to start hass.""" + """Start hass.""" run_coroutine_threadsafe(hass.async_start(), loop=hass.loop).result() def stop_hass(): @@ -167,12 +167,12 @@ def get_test_instance_port(): def mock_service(hass, domain, service): - """Setup a fake service & return a list that logs calls to this service.""" + """Set up a fake service & return a calls log list to this service.""" calls = [] @asyncio.coroutine def mock_service_log(call): # pylint: disable=unnecessary-lambda - """"Mocked service call.""" + """Mocked service call.""" calls.append(call) if hass.loop.__dict__.get("_thread_ident", 0) == threading.get_ident(): @@ -228,7 +228,7 @@ def ensure_sun_set(hass): def load_fixture(filename): - """Helper to load a fixture.""" + """Load a fixture.""" path = os.path.join(os.path.dirname(__file__), 'fixtures', filename) with open(path) as fptr: return fptr.read() @@ -320,7 +320,7 @@ class MockModule(object): self.async_setup = async_setup def setup(self, hass, config): - """Setup the component. + """Set up the component. We always define this mock because MagicMock setups will be seen by the executor as a coroutine, raising an exception. @@ -344,7 +344,7 @@ class MockPlatform(object): self.PLATFORM_SCHEMA = platform_schema def setup_platform(self, hass, config, add_devices, discovery_info=None): - """Setup the platform.""" + """Set up the platform.""" if self._setup_platform is not None: self._setup_platform(hass, config, add_devices, discovery_info) @@ -409,7 +409,7 @@ def patch_yaml_files(files_dict, endswith=True): """Mock open() in the yaml module, used by load_yaml.""" # Return the mocked file on full match if fname in files_dict: - _LOGGER.debug('patch_yaml_files match %s', fname) + _LOGGER.debug("patch_yaml_files match %s", fname) res = StringIO(files_dict[fname]) setattr(res, 'name', fname) return res @@ -417,29 +417,29 @@ def patch_yaml_files(files_dict, endswith=True): # Match using endswith for ends in matchlist: if fname.endswith(ends): - _LOGGER.debug('patch_yaml_files end match %s: %s', ends, fname) + _LOGGER.debug("patch_yaml_files end match %s: %s", ends, fname) res = StringIO(files_dict[ends]) setattr(res, 'name', fname) return res # Fallback for hass.components (i.e. services.yaml) if 'homeassistant/components' in fname: - _LOGGER.debug('patch_yaml_files using real file: %s', fname) + _LOGGER.debug("patch_yaml_files using real file: %s", fname) return open(fname, encoding='utf-8') # Not found - raise FileNotFoundError('File not found: {}'.format(fname)) + raise FileNotFoundError("File not found: {}".format(fname)) return patch.object(yaml, 'open', mock_open_f, create=True) def mock_coro(return_value=None): - """Helper method to return a coro that returns a value.""" + """Return a coro that returns a value.""" return mock_coro_func(return_value)() def mock_coro_func(return_value=None): - """Helper method to create a coro function that returns a value.""" + """Return a method to create a coro function that returns a value.""" @asyncio.coroutine def coro(*args, **kwargs): """Fake coroutine.""" @@ -469,7 +469,7 @@ def assert_setup_component(count, domain=None): res = async_process_component_config( hass, config_input, domain) config[domain] = None if res is None else res.get(domain) - _LOGGER.debug('Configuration for %s, Validated: %s, Original %s', + _LOGGER.debug("Configuration for %s, Validated: %s, Original %s", domain, config[domain], config_input.get(domain)) return res diff --git a/tests/components/fan/__init__.py b/tests/components/fan/__init__.py index 463e96a4319..54ed1fcc505 100644 --- a/tests/components/fan/__init__.py +++ b/tests/components/fan/__init__.py @@ -17,7 +17,7 @@ class TestFanEntity(unittest.TestCase): """Test coverage for base fan entity class.""" def setUp(self): - """Setup test data.""" + """Set up test data.""" self.fan = BaseFan() def tearDown(self): diff --git a/tests/test_util/aiohttp.py b/tests/test_util/aiohttp.py index 39e926ab7e7..0af5321c65f 100644 --- a/tests/test_util/aiohttp.py +++ b/tests/test_util/aiohttp.py @@ -63,7 +63,7 @@ class AiohttpClientMocker: @property def call_count(self): - """Number of requests made.""" + """Return the number of requests made.""" return len(self.mock_calls) def clear_requests(self): diff --git a/tests/testing_config/custom_components/image_processing/test.py b/tests/testing_config/custom_components/image_processing/test.py index 0c538bc6781..29d362699f5 100644 --- a/tests/testing_config/custom_components/image_processing/test.py +++ b/tests/testing_config/custom_components/image_processing/test.py @@ -4,7 +4,7 @@ from homeassistant.components.image_processing import ImageProcessingEntity def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the test image_processing platform.""" + """Set up the test image_processing platform.""" add_devices([TestImageProcessing('camera.demo_camera', "Test")]) diff --git a/tests/testing_config/custom_components/light/test.py b/tests/testing_config/custom_components/light/test.py index 07a856d42bc..fafe88eecbe 100644 --- a/tests/testing_config/custom_components/light/test.py +++ b/tests/testing_config/custom_components/light/test.py @@ -11,7 +11,7 @@ DEVICES = [] def init(empty=False): - """Initalize the platform with devices.""" + """Initialize the platform with devices.""" global DEVICES DEVICES = [] if empty else [ diff --git a/tests/testing_config/custom_components/switch/test.py b/tests/testing_config/custom_components/switch/test.py index ca027e9e906..2819f2f2951 100644 --- a/tests/testing_config/custom_components/switch/test.py +++ b/tests/testing_config/custom_components/switch/test.py @@ -11,7 +11,7 @@ DEVICES = [] def init(empty=False): - """Initalize the platform with devices.""" + """Initialize the platform with devices.""" global DEVICES DEVICES = [] if empty else [