From 3ee4d1060fdbe067c19f7d4ce4777a7eb9dbb412 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Sun, 30 Apr 2017 07:04:49 +0200 Subject: [PATCH] Update docstrings (#7361) * Update docstrings * Update docstrings * Update docstrings * Update docstrings * update docstrings * Update docstrings * Update docstrings * Update docstrings * Update docstrings * Update docstrings * Update tomato.py * Update isy994.py * Lint + fix tests * Lint --- homeassistant/__main__.py | 4 +- homeassistant/bootstrap.py | 14 +-- homeassistant/components/__init__.py | 2 +- .../alarm_control_panel/alarmdecoder.py | 17 ++- .../alarm_control_panel/alarmdotcom.py | 3 +- .../alarm_control_panel/concord232.py | 4 +- .../components/alarm_control_panel/demo.py | 2 +- .../alarm_control_panel/envisalink.py | 2 +- .../components/alarm_control_panel/manual.py | 10 +- .../components/alarm_control_panel/mqtt.py | 8 +- .../components/alarm_control_panel/nx584.py | 17 ++- .../alarm_control_panel/simplisafe.py | 8 +- .../alarm_control_panel/totalconnect.py | 17 ++- .../alarm_control_panel/verisure.py | 17 ++- .../components/alarm_control_panel/wink.py | 3 +- homeassistant/components/alarmdecoder.py | 38 +++--- .../components/automation/__init__.py | 6 +- homeassistant/components/automation/event.py | 4 +- .../components/automation/homeassistant.py | 2 +- homeassistant/components/automation/state.py | 10 +- homeassistant/components/automation/time.py | 8 +- homeassistant/components/automation/zone.py | 4 +- homeassistant/components/bbb_gpio.py | 4 +- .../components/binary_sensor/__init__.py | 2 +- .../components/binary_sensor/alarmdecoder.py | 10 +- .../binary_sensor/android_ip_webcam.py | 6 +- .../components/binary_sensor/apcupsd.py | 2 +- .../components/binary_sensor/bbb_gpio.py | 4 +- .../components/binary_sensor/blink.py | 2 +- .../components/binary_sensor/bloomsky.py | 7 +- .../components/binary_sensor/command_line.py | 4 +- .../components/binary_sensor/concord232.py | 9 +- .../components/binary_sensor/demo.py | 4 +- .../components/binary_sensor/ecobee.py | 2 +- .../components/binary_sensor/enocean.py | 8 +- .../components/binary_sensor/envisalink.py | 5 +- .../components/binary_sensor/ffmpeg_motion.py | 16 ++- .../components/binary_sensor/ffmpeg_noise.py | 12 +- .../components/binary_sensor/flic.py | 2 +- .../components/binary_sensor/hikvision.py | 16 +-- .../components/binary_sensor/homematic.py | 28 ++--- .../components/binary_sensor/insteon_plm.py | 4 +- .../components/binary_sensor/isy994.py | 3 +- homeassistant/components/binary_sensor/knx.py | 2 +- .../components/binary_sensor/maxcube.py | 2 +- .../components/binary_sensor/modbus.py | 8 +- .../components/binary_sensor/mqtt.py | 4 +- .../components/binary_sensor/mysensors.py | 2 +- .../components/binary_sensor/nest.py | 20 +-- .../components/binary_sensor/netatmo.py | 89 ++++++-------- .../components/binary_sensor/nx584.py | 4 +- .../components/binary_sensor/octoprint.py | 26 ++-- .../components/binary_sensor/rest.py | 6 +- .../components/binary_sensor/rpi_gpio.py | 8 +- .../components/binary_sensor/sleepiq.py | 2 +- homeassistant/components/binary_sensor/tcp.py | 2 +- .../components/binary_sensor/template.py | 22 ++-- .../components/binary_sensor/threshold.py | 2 +- .../components/binary_sensor/trend.py | 29 ++--- .../components/binary_sensor/volvooncall.py | 3 +- .../components/binary_sensor/wemo.py | 16 ++- .../components/binary_sensor/wink.py | 28 ++--- homeassistant/components/binary_sensor/zha.py | 6 +- .../components/binary_sensor/zigbee.py | 2 +- .../components/binary_sensor/zwave.py | 10 +- homeassistant/components/bloomsky.py | 7 +- homeassistant/components/calendar/__init__.py | 20 +-- homeassistant/components/calendar/demo.py | 14 +-- homeassistant/components/calendar/google.py | 13 +- homeassistant/components/camera/__init__.py | 22 ++-- homeassistant/components/camera/blink.py | 8 +- homeassistant/components/camera/bloomsky.py | 6 +- homeassistant/components/camera/demo.py | 6 +- homeassistant/components/camera/ffmpeg.py | 4 +- homeassistant/components/camera/foscam.py | 4 +- homeassistant/components/camera/generic.py | 12 +- homeassistant/components/camera/local_file.py | 4 +- homeassistant/components/camera/mjpeg.py | 6 +- homeassistant/components/camera/mqtt.py | 10 +- homeassistant/components/camera/neato.py | 10 +- homeassistant/components/camera/netatmo.py | 18 +-- homeassistant/components/camera/rpi_camera.py | 2 +- homeassistant/components/camera/synology.py | 14 +-- homeassistant/components/camera/uvc.py | 23 ++-- homeassistant/components/camera/verisure.py | 37 +++--- homeassistant/components/camera/zoneminder.py | 16 +-- homeassistant/components/climate/__init__.py | 84 ++++++------- homeassistant/components/climate/demo.py | 26 ++-- homeassistant/components/climate/ecobee.py | 31 +++-- .../components/climate/eq3btsmart.py | 22 ++-- .../components/climate/generic_thermostat.py | 16 +-- homeassistant/components/climate/heatmiser.py | 2 +- homeassistant/components/climate/homematic.py | 25 ++-- homeassistant/components/climate/honeywell.py | 37 +++--- homeassistant/components/climate/knx.py | 2 +- homeassistant/components/climate/maxcube.py | 14 +-- homeassistant/components/climate/mysensors.py | 38 +++--- homeassistant/components/climate/nest.py | 4 +- homeassistant/components/climate/netatmo.py | 3 +- homeassistant/components/climate/oem.py | 22 ++-- homeassistant/components/climate/proliphix.py | 3 +- .../components/climate/radiotherm.py | 2 +- homeassistant/components/climate/tado.py | 8 +- homeassistant/components/climate/vera.py | 24 ++-- homeassistant/components/climate/wink.py | 4 +- homeassistant/components/climate/zwave.py | 14 +-- homeassistant/components/config/__init__.py | 8 +- homeassistant/components/config/core.py | 4 +- homeassistant/components/config/group.py | 5 +- homeassistant/components/config/hassbian.py | 6 +- homeassistant/components/config/zwave.py | 2 +- homeassistant/components/configurator.py | 4 +- homeassistant/components/cover/__init__.py | 3 +- .../components/cover/command_line.py | 12 +- homeassistant/components/cover/demo.py | 2 +- homeassistant/components/cover/homematic.py | 8 +- homeassistant/components/cover/isy994.py | 18 ++- homeassistant/components/cover/mqtt.py | 6 +- homeassistant/components/cover/myq.py | 10 +- homeassistant/components/cover/mysensors.py | 3 +- homeassistant/components/cover/rfxtrx.py | 15 +-- homeassistant/components/cover/rpi_gpio.py | 4 +- homeassistant/components/cover/scsgate.py | 2 +- homeassistant/components/cover/tellduslive.py | 4 +- homeassistant/components/cover/vera.py | 4 +- homeassistant/components/cover/wink.py | 3 +- homeassistant/components/cover/zwave.py | 10 +- homeassistant/components/demo.py | 18 +-- .../components/device_sun_light_trigger.py | 12 +- .../components/device_tracker/__init__.py | 71 ++++++----- .../components/device_tracker/actiontec.py | 10 +- .../components/device_tracker/aruba.py | 16 +-- .../components/device_tracker/asuswrt.py | 50 ++++---- .../components/device_tracker/automatic.py | 2 +- .../components/device_tracker/bbox.py | 6 +- .../device_tracker/bluetooth_le_tracker.py | 19 +-- .../device_tracker/bluetooth_tracker.py | 28 +++-- .../device_tracker/bt_home_hub_5.py | 12 +- .../components/device_tracker/cisco_ios.py | 7 +- .../components/device_tracker/ddwrt.py | 14 +-- .../components/device_tracker/demo.py | 9 +- .../components/device_tracker/fritz.py | 14 +-- .../components/device_tracker/gpslogger.py | 13 +- .../components/device_tracker/icloud.py | 53 ++++---- .../components/device_tracker/linksys_ap.py | 9 +- .../components/device_tracker/luci.py | 21 ++-- .../components/device_tracker/mqtt.py | 4 +- .../components/device_tracker/mqtt_json.py | 10 +- .../components/device_tracker/mysensors.py | 8 +- .../components/device_tracker/netgear.py | 14 +-- .../components/device_tracker/nmap_tracker.py | 2 +- .../components/device_tracker/owntracks.py | 47 ++++--- .../components/device_tracker/ping.py | 6 +- .../components/device_tracker/swisscom.py | 1 - .../components/device_tracker/tado.py | 10 +- .../components/device_tracker/thomson.py | 9 +- .../components/device_tracker/tomato.py | 24 ++-- .../components/device_tracker/tplink.py | 30 ++--- .../components/device_tracker/trackr.py | 10 +- .../components/device_tracker/ubus.py | 20 +-- .../components/device_tracker/unifi.py | 16 +-- .../components/device_tracker/upc_connect.py | 4 +- .../components/device_tracker/volvooncall.py | 4 +- .../components/device_tracker/xiaomi.py | 35 +++--- homeassistant/components/dweet.py | 2 +- homeassistant/components/ecobee.py | 10 +- .../components/emulated_hue/__init__.py | 24 ++-- homeassistant/components/enocean.py | 13 +- homeassistant/components/envisalink.py | 44 +++---- homeassistant/components/fan/__init__.py | 4 +- homeassistant/components/fan/demo.py | 4 +- homeassistant/components/fan/isy994.py | 10 +- homeassistant/components/fan/mqtt.py | 10 +- homeassistant/components/fan/wink.py | 4 +- homeassistant/components/ffmpeg.py | 29 ++--- homeassistant/components/foursquare.py | 6 +- homeassistant/components/frontend/__init__.py | 51 ++++---- homeassistant/components/google.py | 22 ++-- homeassistant/components/graphite.py | 30 ++--- homeassistant/components/group.py | 4 +- homeassistant/components/hassio.py | 8 +- homeassistant/components/hdmi_cec.py | 6 +- homeassistant/components/history.py | 4 +- homeassistant/components/homematic.py | 10 +- homeassistant/components/http/__init__.py | 15 ++- homeassistant/components/http/auth.py | 10 +- homeassistant/components/http/ban.py | 10 +- homeassistant/components/ifttt.py | 2 +- .../components/image_processing/__init__.py | 3 +- .../components/image_processing/demo.py | 2 +- .../image_processing/microsoft_face_detect.py | 6 +- .../microsoft_face_identify.py | 6 +- .../image_processing/openalpr_cloud.py | 10 +- .../image_processing/openalpr_local.py | 10 +- homeassistant/components/influxdb.py | 2 +- homeassistant/components/input_boolean.py | 4 +- homeassistant/components/input_select.py | 6 +- homeassistant/components/input_slider.py | 24 ++-- homeassistant/components/insteon_hub.py | 6 +- homeassistant/components/insteon_local.py | 4 +- homeassistant/components/insteon_plm.py | 8 +- homeassistant/components/introduction.py | 2 +- homeassistant/components/ios.py | 116 +++++++++--------- homeassistant/components/isy994.py | 43 ++++--- homeassistant/components/joaoapps_join.py | 6 +- homeassistant/components/keyboard_remote.py | 45 +++---- homeassistant/components/knx.py | 22 ++-- homeassistant/components/lirc.py | 4 +- homeassistant/components/litejet.py | 4 +- homeassistant/components/logbook.py | 23 ++-- homeassistant/components/logentries.py | 12 +- homeassistant/components/logger.py | 4 +- homeassistant/components/lutron.py | 4 +- homeassistant/components/lutron_caseta.py | 11 +- homeassistant/components/microsoft_face.py | 4 +- homeassistant/components/mochad.py | 9 +- homeassistant/components/modbus.py | 28 ++--- homeassistant/components/mqtt_eventstream.py | 4 +- homeassistant/components/mysensors.py | 82 +++++++------ homeassistant/components/neato.py | 14 +-- homeassistant/components/nest.py | 22 ++-- homeassistant/components/nuimo_controller.py | 32 ++--- homeassistant/components/octoprint.py | 11 +- homeassistant/components/panel_iframe.py | 9 +- .../components/persistent_notification.py | 10 +- homeassistant/components/pilight.py | 12 +- homeassistant/components/proximity.py | 6 +- homeassistant/components/qwikswitch.py | 2 +- homeassistant/components/rest_command.py | 2 +- homeassistant/components/rfxtrx.py | 6 +- homeassistant/components/ring.py | 2 +- homeassistant/components/rpi_gpio.py | 6 +- homeassistant/components/rss_feed_template.py | 8 +- homeassistant/components/script.py | 18 +-- homeassistant/components/scsgate.py | 8 +- homeassistant/components/shell_command.py | 10 +- homeassistant/components/sleepiq.py | 10 +- homeassistant/components/splunk.py | 12 +- homeassistant/components/statsd.py | 2 +- homeassistant/components/sun.py | 2 +- homeassistant/components/tado.py | 10 +- homeassistant/components/tellduslive.py | 21 ++-- homeassistant/components/tellstick.py | 14 +-- homeassistant/components/tradfri.py | 4 +- homeassistant/components/vera.py | 5 +- homeassistant/components/verisure.py | 15 ++- homeassistant/components/volvooncall.py | 17 ++- homeassistant/components/weblink.py | 2 +- homeassistant/components/websocket_api.py | 61 ++++----- homeassistant/components/wemo.py | 2 +- homeassistant/components/wink.py | 4 +- homeassistant/components/zha/__init__.py | 14 +-- homeassistant/components/zha/const.py | 3 +- homeassistant/components/zigbee.py | 32 ++--- homeassistant/components/zone.py | 6 +- homeassistant/config.py | 2 +- homeassistant/core.py | 30 ++--- homeassistant/exceptions.py | 4 +- homeassistant/remote.py | 12 +- homeassistant/setup.py | 60 +++++---- homeassistant/util/temperature.py | 18 ++- homeassistant/util/yaml.py | 12 +- tests/components/device_tracker/test_ddwrt.py | 2 +- tests/components/test_splunk.py | 3 +- 264 files changed, 1686 insertions(+), 1768 deletions(-) diff --git a/homeassistant/__main__.py b/homeassistant/__main__.py index 7035b26f670..0b07e5aa6f6 100644 --- a/homeassistant/__main__.py +++ b/homeassistant/__main__.py @@ -1,4 +1,4 @@ -"""Starts home assistant.""" +"""Start Home Assistant.""" from __future__ import print_function import argparse @@ -277,7 +277,7 @@ def cmdline() -> List[str]: def setup_and_run_hass(config_dir: str, args: argparse.Namespace) -> Optional[int]: - """Setup HASS and run.""" + """Set up HASS and run.""" from homeassistant import bootstrap # Run a simple daemon runner process on Windows to handle restarts diff --git a/homeassistant/bootstrap.py b/homeassistant/bootstrap.py index 8bf03597b9b..eeda1db51fc 100644 --- a/homeassistant/bootstrap.py +++ b/homeassistant/bootstrap.py @@ -1,4 +1,4 @@ -"""Provides methods to bootstrap a home assistant instance.""" +"""Provide methods to bootstrap a Home Assistant instance.""" import asyncio import logging import logging.handlers @@ -206,7 +206,7 @@ def async_from_config_file(config_path: str, @core.callback def async_enable_logging(hass: core.HomeAssistant, verbose: bool=False, log_rotate_days=None) -> None: - """Setup the logging. + """Set up the logging. This method must be run in the event loop. """ @@ -216,10 +216,10 @@ def async_enable_logging(hass: core.HomeAssistant, verbose: bool=False, colorfmt = "%(log_color)s{}%(reset)s".format(fmt) datefmt = '%Y-%m-%d %H:%M:%S' - # suppress overly verbose logs from libraries that aren't helpful - logging.getLogger("requests").setLevel(logging.WARNING) - logging.getLogger("urllib3").setLevel(logging.WARNING) - logging.getLogger("aiohttp.access").setLevel(logging.WARNING) + # Suppress overly verbose logs from libraries that aren't helpful + logging.getLogger('requests').setLevel(logging.WARNING) + logging.getLogger('urllib3').setLevel(logging.WARNING) + logging.getLogger('aiohttp.access').setLevel(logging.WARNING) try: from colorlog import ColoredFormatter @@ -274,7 +274,7 @@ def async_enable_logging(hass: core.HomeAssistant, verbose: bool=False, else: _LOGGER.error( - 'Unable to setup error log %s (access denied)', err_log_path) + "Unable to setup error log %s (access denied)", err_log_path) def mount_local_lib_path(config_dir: str) -> str: diff --git a/homeassistant/components/__init__.py b/homeassistant/components/__init__.py index 2bb7af23662..2abbf6c86ed 100644 --- a/homeassistant/components/__init__.py +++ b/homeassistant/components/__init__.py @@ -102,7 +102,7 @@ def reload_core_config(hass): @asyncio.coroutine def async_setup(hass, config): - """Setup general services related to Home Assistant.""" + """Set up general services related to Home Assistant.""" @asyncio.coroutine def async_handle_turn_service(service): """Method to handle calls to homeassistant.turn_on/off.""" diff --git a/homeassistant/components/alarm_control_panel/alarmdecoder.py b/homeassistant/components/alarm_control_panel/alarmdecoder.py index f176a87827b..40084eb1351 100644 --- a/homeassistant/components/alarm_control_panel/alarmdecoder.py +++ b/homeassistant/components/alarm_control_panel/alarmdecoder.py @@ -44,7 +44,7 @@ class AlarmDecoderAlarmPanel(alarm.AlarmControlPanel): self._name = name self._state = STATE_UNKNOWN - _LOGGER.debug("AlarmDecoderAlarm: Setting up panel") + _LOGGER.debug("Setting up panel") @asyncio.coroutine def async_added_to_hass(self): @@ -94,26 +94,23 @@ class AlarmDecoderAlarmPanel(alarm.AlarmControlPanel): @asyncio.coroutine def async_alarm_disarm(self, code=None): """Send disarm command.""" - _LOGGER.debug("AlarmDecoderAlarm::alarm_disarm: %s", code) + _LOGGER.debug("alarm_disarm: %s", code) if code: - _LOGGER.debug("AlarmDecoderAlarm::alarm_disarm: sending %s1", - str(code)) + _LOGGER.debug("alarm_disarm: sending %s1", str(code)) self.hass.data[DATA_AD].send("{!s}1".format(code)) @asyncio.coroutine def async_alarm_arm_away(self, code=None): """Send arm away command.""" - _LOGGER.debug("AlarmDecoderAlarm::alarm_arm_away: %s", code) + _LOGGER.debug("alarm_arm_away: %s", code) if code: - _LOGGER.debug("AlarmDecoderAlarm::alarm_arm_away: sending %s2", - str(code)) + _LOGGER.debug("alarm_arm_away: sending %s2", str(code)) self.hass.data[DATA_AD].send("{!s}2".format(code)) @asyncio.coroutine def async_alarm_arm_home(self, code=None): """Send arm home command.""" - _LOGGER.debug("AlarmDecoderAlarm::alarm_arm_home: %s", code) + _LOGGER.debug("alarm_arm_home: %s", code) if code: - _LOGGER.debug("AlarmDecoderAlarm::alarm_arm_home: sending %s3", - str(code)) + _LOGGER.debug("alarm_arm_home: sending %s3", str(code)) self.hass.data[DATA_AD].send("{!s}3".format(code)) diff --git a/homeassistant/components/alarm_control_panel/alarmdotcom.py b/homeassistant/components/alarm_control_panel/alarmdotcom.py index 6e99ba67257..75d3bc9922d 100644 --- a/homeassistant/components/alarm_control_panel/alarmdotcom.py +++ b/homeassistant/components/alarm_control_panel/alarmdotcom.py @@ -1,5 +1,4 @@ """ - Interfaces with Alarm.com alarm control panels. For more details about this platform, please refer to the documentation at @@ -33,7 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup a Alarm.com control panel.""" + """Set up a Alarm.com control panel.""" name = config.get(CONF_NAME) code = config.get(CONF_CODE) username = config.get(CONF_USERNAME) diff --git a/homeassistant/components/alarm_control_panel/concord232.py b/homeassistant/components/alarm_control_panel/concord232.py index 18a492d6c12..167b7909fe6 100755 --- a/homeassistant/components/alarm_control_panel/concord232.py +++ b/homeassistant/components/alarm_control_panel/concord232.py @@ -51,7 +51,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class Concord232Alarm(alarm.AlarmControlPanel): - """Represents the Concord232-based alarm panel.""" + """Representation of the Concord232-based alarm panel.""" def __init__(self, hass, url, name): """Initialize the Concord232 alarm panel.""" @@ -79,7 +79,7 @@ class Concord232Alarm(alarm.AlarmControlPanel): @property def code_format(self): - """The characters if code is defined.""" + """Return the characters if code is defined.""" return '[0-9]{4}([0-9]{2})?' @property diff --git a/homeassistant/components/alarm_control_panel/demo.py b/homeassistant/components/alarm_control_panel/demo.py index ccbe3e72e3c..8ebf0a93c38 100644 --- a/homeassistant/components/alarm_control_panel/demo.py +++ b/homeassistant/components/alarm_control_panel/demo.py @@ -8,7 +8,7 @@ import homeassistant.components.alarm_control_panel.manual as manual def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo alarm control panel platform.""" + """Set up the Demo alarm control panel platform.""" add_devices([ manual.ManualAlarm(hass, 'Alarm', '1234', 5, 10, False), ]) diff --git a/homeassistant/components/alarm_control_panel/envisalink.py b/homeassistant/components/alarm_control_panel/envisalink.py index 25f9257f393..34919a9db79 100644 --- a/homeassistant/components/alarm_control_panel/envisalink.py +++ b/homeassistant/components/alarm_control_panel/envisalink.py @@ -104,7 +104,7 @@ class EnvisalinkAlarm(EnvisalinkDevice, alarm.AlarmControlPanel): @callback def _update_callback(self, partition): - """Update HA state, if needed.""" + """Update Home Assistant state, if needed.""" if partition is None or int(partition) == self._partition_number: self.hass.async_add_job(self.async_update_ha_state()) diff --git a/homeassistant/components/alarm_control_panel/manual.py b/homeassistant/components/alarm_control_panel/manual.py index cc67795d713..ba932a1c372 100644 --- a/homeassistant/components/alarm_control_panel/manual.py +++ b/homeassistant/components/alarm_control_panel/manual.py @@ -39,7 +39,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the manual alarm platform.""" + """Set up the manual alarm platform.""" add_devices([ManualAlarm( hass, config[CONF_NAME], @@ -52,7 +52,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class ManualAlarm(alarm.AlarmControlPanel): """ - Represents an alarm status. + Representation of an alarm status. When armed, will be pending for 'pending_time', after that armed. When triggered, will be pending for 'trigger_time'. After that will be @@ -62,7 +62,7 @@ class ManualAlarm(alarm.AlarmControlPanel): def __init__(self, hass, name, code, pending_time, trigger_time, disarm_after_trigger): - """Initalize the manual alarm panel.""" + """Init the manual alarm panel.""" self._state = STATE_ALARM_DISARMED self._hass = hass self._name = name @@ -75,7 +75,7 @@ class ManualAlarm(alarm.AlarmControlPanel): @property def should_poll(self): - """No polling needed.""" + """Return the plling state.""" return False @property @@ -166,5 +166,5 @@ class ManualAlarm(alarm.AlarmControlPanel): """Validate given code.""" check = self._code is None or code == self._code if not check: - _LOGGER.warning('Invalid code given for %s', state) + _LOGGER.warning("Invalid code given for %s", state) return check diff --git a/homeassistant/components/alarm_control_panel/mqtt.py b/homeassistant/components/alarm_control_panel/mqtt.py index b22f50b6575..33bfe464eea 100644 --- a/homeassistant/components/alarm_control_panel/mqtt.py +++ b/homeassistant/components/alarm_control_panel/mqtt.py @@ -45,7 +45,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the MQTT platform.""" + """Set up the MQTT Alarm Control Panel platform.""" async_add_devices([MqttAlarm( config.get(CONF_NAME), config.get(CONF_STATE_TOPIC), @@ -62,7 +62,7 @@ class MqttAlarm(alarm.AlarmControlPanel): def __init__(self, name, state_topic, command_topic, qos, payload_disarm, payload_arm_home, payload_arm_away, code): - """Initalize the MQTT alarm panel.""" + """Init the MQTT Alarm Control Panel.""" self._state = STATE_UNKNOWN self._name = name self._state_topic = state_topic @@ -80,11 +80,11 @@ class MqttAlarm(alarm.AlarmControlPanel): """ @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Run when new MQTT message has been received.""" if payload not in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED): - _LOGGER.warning('Received unexpected payload: %s', payload) + _LOGGER.warning("Received unexpected payload: %s", payload) return self._state = payload self.hass.async_add_job(self.async_update_ha_state()) diff --git a/homeassistant/components/alarm_control_panel/nx584.py b/homeassistant/components/alarm_control_panel/nx584.py index b7b3beec72d..81a8b02cc64 100644 --- a/homeassistant/components/alarm_control_panel/nx584.py +++ b/homeassistant/components/alarm_control_panel/nx584.py @@ -32,7 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup nx584 platform.""" + """Set up the nx584 platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -42,15 +42,15 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: add_devices([NX584Alarm(hass, url, name)]) except requests.exceptions.ConnectionError as ex: - _LOGGER.error('Unable to connect to NX584: %s', str(ex)) + _LOGGER.error("Unable to connect to NX584: %s", str(ex)) return False class NX584Alarm(alarm.AlarmControlPanel): - """Represents the NX584-based alarm panel.""" + """Representation of a NX584-based alarm panel.""" def __init__(self, hass, url, name): - """Initalize the nx584 alarm panel.""" + """Init the nx584 alarm panel.""" from nx584 import client self._hass = hass self._name = name @@ -69,7 +69,7 @@ class NX584Alarm(alarm.AlarmControlPanel): @property def code_format(self): - """The characters if code is defined.""" + """Return che characters if code is defined.""" return '[0-9]{4}([0-9]{2})?' @property @@ -83,20 +83,19 @@ class NX584Alarm(alarm.AlarmControlPanel): part = self._alarm.list_partitions()[0] zones = self._alarm.list_zones() except requests.exceptions.ConnectionError as ex: - _LOGGER.error('Unable to connect to %(host)s: %(reason)s', + _LOGGER.error("Unable to connect to %(host)s: %(reason)s", dict(host=self._url, reason=ex)) self._state = STATE_UNKNOWN zones = [] except IndexError: - _LOGGER.error('nx584 reports no partitions') + _LOGGER.error("nx584 reports no partitions") self._state = STATE_UNKNOWN zones = [] bypassed = False for zone in zones: if zone['bypassed']: - _LOGGER.debug('Zone %(zone)s is bypassed, ' - 'assuming HOME', + _LOGGER.debug("Zone %(zone)s is bypassed, assuming HOME", dict(zone=zone['number'])) bypassed = True break diff --git a/homeassistant/components/alarm_control_panel/simplisafe.py b/homeassistant/components/alarm_control_panel/simplisafe.py index 6d8e6be1f5c..985d219865d 100644 --- a/homeassistant/components/alarm_control_panel/simplisafe.py +++ b/homeassistant/components/alarm_control_panel/simplisafe.py @@ -123,25 +123,25 @@ class SimpliSafeAlarm(alarm.AlarmControlPanel): if not self._validate_code(code, 'disarming'): return self.simplisafe.set_state('off') - _LOGGER.info('SimpliSafe alarm disarming') + _LOGGER.info("SimpliSafe alarm disarming") def alarm_arm_home(self, code=None): """Send arm home command.""" if not self._validate_code(code, 'arming home'): return self.simplisafe.set_state('home') - _LOGGER.info('SimpliSafe alarm arming home') + _LOGGER.info("SimpliSafe alarm arming home") def alarm_arm_away(self, code=None): """Send arm away command.""" if not self._validate_code(code, 'arming away'): return self.simplisafe.set_state('away') - _LOGGER.info('SimpliSafe alarm arming away') + _LOGGER.info("SimpliSafe alarm arming away") def _validate_code(self, code, state): """Validate given code.""" check = self._code is None or code == self._code if not check: - _LOGGER.warning('Wrong code entered for %s', state) + _LOGGER.warning("Wrong code entered for %s", state) return check diff --git a/homeassistant/components/alarm_control_panel/totalconnect.py b/homeassistant/components/alarm_control_panel/totalconnect.py index a69e260c053..13925d7bd02 100644 --- a/homeassistant/components/alarm_control_panel/totalconnect.py +++ b/homeassistant/components/alarm_control_panel/totalconnect.py @@ -1,15 +1,20 @@ -"""Interfaces with TotalConnect alarm control panels.""" +""" +Interfaces with TotalConnect alarm control panels. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/alarm_control_panel.totalconnect/ +""" import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv import homeassistant.components.alarm_control_panel as alarm from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_UNKNOWN, CONF_NAME) -import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['total_connect_client==0.7'] @@ -25,7 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup a TotalConnect control panel.""" + """Set up a TotalConnect control panel.""" name = config.get(CONF_NAME) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) @@ -41,13 +46,13 @@ class TotalConnect(alarm.AlarmControlPanel): """Initialize the TotalConnect status.""" from total_connect_client import TotalConnectClient - _LOGGER.debug('Setting up TotalConnect...') + _LOGGER.debug("Setting up TotalConnect...") self._name = name self._username = username self._password = password self._state = STATE_UNKNOWN - self._client = TotalConnectClient.TotalConnectClient(username, - password) + self._client = TotalConnectClient.TotalConnectClient( + username, password) @property def name(self): diff --git a/homeassistant/components/alarm_control_panel/verisure.py b/homeassistant/components/alarm_control_panel/verisure.py index c1a394fe462..83a6ef44b76 100644 --- a/homeassistant/components/alarm_control_panel/verisure.py +++ b/homeassistant/components/alarm_control_panel/verisure.py @@ -17,7 +17,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Verisure platform.""" + """Set up the Verisure platform.""" alarms = [] if int(hub.config.get(CONF_ALARM, 1)): hub.update_alarms() @@ -29,7 +29,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class VerisureAlarm(alarm.AlarmControlPanel): - """Represent a Verisure alarm status.""" + """Representation of a Verisure alarm status.""" def __init__(self, device_id): """Initalize the Verisure alarm panel.""" @@ -55,12 +55,12 @@ class VerisureAlarm(alarm.AlarmControlPanel): @property def code_format(self): - """The code format as regex.""" + """Return the code format as regex.""" return '^\\d{%s}$' % self._digits @property def changed_by(self): - """Last change triggered by.""" + """Return the last change triggered by.""" return self._changed_by def update(self): @@ -75,24 +75,23 @@ class VerisureAlarm(alarm.AlarmControlPanel): self._state = STATE_ALARM_ARMED_AWAY elif hub.alarm_status[self._id].status != 'pending': _LOGGER.error( - 'Unknown alarm state %s', - hub.alarm_status[self._id].status) + 'Unknown alarm state %s', hub.alarm_status[self._id].status) self._changed_by = hub.alarm_status[self._id].name def alarm_disarm(self, code=None): """Send disarm command.""" hub.my_pages.alarm.set(code, 'DISARMED') - _LOGGER.info('verisure alarm disarming') + _LOGGER.info("verisure alarm disarming") hub.my_pages.alarm.wait_while_pending() def alarm_arm_home(self, code=None): """Send arm home command.""" hub.my_pages.alarm.set(code, 'ARMED_HOME') - _LOGGER.info('verisure alarm arming home') + _LOGGER.info("verisure alarm arming home") hub.my_pages.alarm.wait_while_pending() def alarm_arm_away(self, code=None): """Send arm away command.""" hub.my_pages.alarm.set(code, 'ARMED_AWAY') - _LOGGER.info('verisure alarm arming away') + _LOGGER.info("verisure alarm arming away") hub.my_pages.alarm.wait_while_pending() diff --git a/homeassistant/components/alarm_control_panel/wink.py b/homeassistant/components/alarm_control_panel/wink.py index c489b53c9c0..12dca97dd81 100644 --- a/homeassistant/components/alarm_control_panel/wink.py +++ b/homeassistant/components/alarm_control_panel/wink.py @@ -16,11 +16,12 @@ from homeassistant.components.wink import WinkDevice, DOMAIN _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['wink'] + STATE_ALARM_PRIVACY = 'Private' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink platform.""" + """Set up the Wink platform.""" import pywink for camera in pywink.get_cameras(): diff --git a/homeassistant/components/alarmdecoder.py b/homeassistant/components/alarmdecoder.py index ec99f2381e5..186526c7758 100644 --- a/homeassistant/components/alarmdecoder.py +++ b/homeassistant/components/alarmdecoder.py @@ -24,19 +24,16 @@ DOMAIN = 'alarmdecoder' DATA_AD = 'alarmdecoder' - CONF_DEVICE = 'device' -CONF_DEVICE_TYPE = 'type' -CONF_DEVICE_HOST = 'host' -CONF_DEVICE_PORT = 'port' -CONF_DEVICE_PATH = 'path' CONF_DEVICE_BAUD = 'baudrate' - -CONF_ZONES = 'zones' +CONF_DEVICE_HOST = 'host' +CONF_DEVICE_PATH = 'path' +CONF_DEVICE_PORT = 'port' +CONF_DEVICE_TYPE = 'type' +CONF_PANEL_DISPLAY = 'panel_display' CONF_ZONE_NAME = 'name' CONF_ZONE_TYPE = 'type' - -CONF_PANEL_DISPLAY = 'panel_display' +CONF_ZONES = 'zones' DEFAULT_DEVICE_TYPE = 'socket' DEFAULT_DEVICE_HOST = 'localhost' @@ -87,7 +84,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Common setup for AlarmDecoder devices.""" + """Set up for the AlarmDecoder devices.""" from alarmdecoder import AlarmDecoder from alarmdecoder.devices import (SocketDevice, SerialDevice, USBDevice) @@ -106,28 +103,28 @@ def async_setup(hass, config): sync_connect = asyncio.Future(loop=hass.loop) def handle_open(device): - """Callback for a successful connection.""" - _LOGGER.info("Established a connection with the alarmdecoder.") + """Handle the successful connection.""" + _LOGGER.info("Established a connection with the alarmdecoder") hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder) sync_connect.set_result(True) @callback def stop_alarmdecoder(event): - """Callback to handle shutdown alarmdecoder.""" + """The callback to handle shutdown AlarmDecoder.""" _LOGGER.debug("Shutting down alarmdecoder.") controller.close() @callback def handle_message(sender, message): - """Callback to handle message from alarmdecoder.""" + """The callback to handle message from AlarmDecoder.""" async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message) def zone_fault_callback(sender, zone): - """Callback to handle zone fault from alarmdecoder.""" + """The callback to handle zone fault from AlarmDecoder.""" async_dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone) def zone_restore_callback(sender, zone): - """Callback to handle zone restore from alarmdecoder.""" + """The callback to handle zone restore from AlarmDecoder.""" async_dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone) controller = False @@ -157,15 +154,16 @@ def async_setup(hass, config): if not result: return False - hass.async_add_job(async_load_platform(hass, 'alarm_control_panel', DOMAIN, - conf, config)) + hass.async_add_job( + async_load_platform(hass, 'alarm_control_panel', DOMAIN, conf, + config)) if zones: hass.async_add_job(async_load_platform( hass, 'binary_sensor', DOMAIN, {CONF_ZONES: zones}, config)) if display: - hass.async_add_job(async_load_platform(hass, 'sensor', DOMAIN, - conf, config)) + hass.async_add_job(async_load_platform( + hass, 'sensor', DOMAIN, conf, config)) return True diff --git a/homeassistant/components/automation/__init__.py b/homeassistant/components/automation/__init__.py index 5c3d944aad4..5f59f760d0b 100644 --- a/homeassistant/components/automation/__init__.py +++ b/homeassistant/components/automation/__init__.py @@ -141,7 +141,7 @@ def reload(hass): @asyncio.coroutine def async_setup(hass, config): - """Setup the automation.""" + """Set up the automation.""" component = EntityComponent(_LOGGER, DOMAIN, hass, group_name=GROUP_NAME_ALL_AUTOMATIONS) @@ -400,7 +400,7 @@ def _async_get_action(hass, config, name): @asyncio.coroutine def action(entity_id, variables): - """Action to be executed.""" + """Execute an action.""" _LOGGER.info('Executing %s', name) logbook.async_log_entry( hass, name, 'has been triggered', DOMAIN, entity_id) @@ -430,7 +430,7 @@ def _async_process_if(hass, config, p_config): @asyncio.coroutine def _async_process_trigger(hass, config, trigger_configs, name, action): - """Setup the triggers. + """Set up the triggers. This method is a coroutine. """ diff --git a/homeassistant/components/automation/event.py b/homeassistant/components/automation/event.py index 0ff10665eb3..ba8e67e9213 100644 --- a/homeassistant/components/automation/event.py +++ b/homeassistant/components/automation/event.py @@ -13,8 +13,8 @@ from homeassistant.core import callback, CoreState from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_START from homeassistant.helpers import config_validation as cv -CONF_EVENT_TYPE = "event_type" -CONF_EVENT_DATA = "event_data" +CONF_EVENT_TYPE = 'event_type' +CONF_EVENT_DATA = 'event_data' _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/automation/homeassistant.py b/homeassistant/components/automation/homeassistant.py index 0222ef02c26..6b8ee577a09 100644 --- a/homeassistant/components/automation/homeassistant.py +++ b/homeassistant/components/automation/homeassistant.py @@ -31,7 +31,7 @@ def async_trigger(hass, config, action): if event == EVENT_SHUTDOWN: @callback def hass_shutdown(event): - """Called when Home Assistant is shutting down.""" + """Execute when Home Assistant is shutting down.""" hass.async_run_job(action, { 'trigger': { 'platform': 'homeassistant', diff --git a/homeassistant/components/automation/state.py b/homeassistant/components/automation/state.py index 1f55ef67f25..576e9e60186 100644 --- a/homeassistant/components/automation/state.py +++ b/homeassistant/components/automation/state.py @@ -14,11 +14,11 @@ from homeassistant.helpers.event import ( async_track_state_change, async_track_point_in_utc_time) import homeassistant.helpers.config_validation as cv -CONF_ENTITY_ID = "entity_id" -CONF_FROM = "from" -CONF_TO = "to" -CONF_STATE = "state" -CONF_FOR = "for" +CONF_ENTITY_ID = 'entity_id' +CONF_FROM = 'from' +CONF_TO = 'to' +CONF_STATE = 'state' +CONF_FOR = 'for' TRIGGER_SCHEMA = vol.All( vol.Schema({ diff --git a/homeassistant/components/automation/time.py b/homeassistant/components/automation/time.py index 0adcd5f8272..9045cb7b1b6 100644 --- a/homeassistant/components/automation/time.py +++ b/homeassistant/components/automation/time.py @@ -14,9 +14,9 @@ from homeassistant.const import CONF_AFTER, CONF_PLATFORM from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import async_track_time_change -CONF_HOURS = "hours" -CONF_MINUTES = "minutes" -CONF_SECONDS = "seconds" +CONF_HOURS = 'hours' +CONF_MINUTES = 'minutes' +CONF_SECONDS = 'seconds' _LOGGER = logging.getLogger(__name__) @@ -32,7 +32,7 @@ TRIGGER_SCHEMA = vol.All(vol.Schema({ @asyncio.coroutine def async_trigger(hass, config, action): - """Listen for state changes based on configuration.""" + """"Listen for state changes based on configuration.""" if CONF_AFTER in config: after = config.get(CONF_AFTER) hours, minutes, seconds = after.hour, after.minute, after.second diff --git a/homeassistant/components/automation/zone.py b/homeassistant/components/automation/zone.py index c2a0e4d094d..61d846582cb 100644 --- a/homeassistant/components/automation/zone.py +++ b/homeassistant/components/automation/zone.py @@ -14,8 +14,8 @@ from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers import ( condition, config_validation as cv, location) -EVENT_ENTER = "enter" -EVENT_LEAVE = "leave" +EVENT_ENTER = 'enter' +EVENT_LEAVE = 'leave' DEFAULT_EVENT = EVENT_ENTER TRIGGER_SCHEMA = vol.Schema({ diff --git a/homeassistant/components/bbb_gpio.py b/homeassistant/components/bbb_gpio.py index 89692a1e1e1..5d3954b4c87 100644 --- a/homeassistant/components/bbb_gpio.py +++ b/homeassistant/components/bbb_gpio.py @@ -37,14 +37,14 @@ def setup(hass, config): # noqa: F821 def setup_output(pin): - """Setup a GPIO as output.""" + """Set up a GPIO as output.""" # pylint: disable=import-error,undefined-variable import Adafruit_BBIO.GPIO as GPIO GPIO.setup(pin, GPIO.OUT) def setup_input(pin, pull_mode): - """Setup a GPIO as input.""" + """Set up a GPIO as input.""" # pylint: disable=import-error,undefined-variable import Adafruit_BBIO.GPIO as GPIO GPIO.setup(pin, GPIO.IN, # noqa: F821 diff --git a/homeassistant/components/binary_sensor/__init__.py b/homeassistant/components/binary_sensor/__init__.py index ab49c13770a..8f2b6bc59b3 100644 --- a/homeassistant/components/binary_sensor/__init__.py +++ b/homeassistant/components/binary_sensor/__init__.py @@ -57,7 +57,7 @@ class BinarySensorDevice(Entity): @property def is_on(self): - """Return True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return None @property diff --git a/homeassistant/components/binary_sensor/alarmdecoder.py b/homeassistant/components/binary_sensor/alarmdecoder.py index 21d33a4d303..495feaf64ab 100644 --- a/homeassistant/components/binary_sensor/alarmdecoder.py +++ b/homeassistant/components/binary_sensor/alarmdecoder.py @@ -26,7 +26,7 @@ _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup AlarmDecoder binary sensor devices.""" + """Set up the AlarmDecoder binary sensor devices.""" configured_zones = discovery_info[CONF_ZONES] devices = [] @@ -35,10 +35,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): device_config_data = ZONE_SCHEMA(configured_zones[zone_num]) zone_type = device_config_data[CONF_ZONE_TYPE] zone_name = device_config_data[CONF_ZONE_NAME] - device = AlarmDecoderBinarySensor(hass, - zone_num, - zone_name, - zone_type) + device = AlarmDecoderBinarySensor( + hass, zone_num, zone_name, zone_type) devices.append(device) async_add_devices(devices) @@ -57,7 +55,7 @@ class AlarmDecoderBinarySensor(BinarySensorDevice): self._name = zone_name self._type = zone_type - _LOGGER.debug('AlarmDecoderBinarySensor: Setup up zone: ' + zone_name) + _LOGGER.debug("Setup up zone: %s", self._name) @asyncio.coroutine def async_added_to_hass(self): diff --git a/homeassistant/components/binary_sensor/android_ip_webcam.py b/homeassistant/components/binary_sensor/android_ip_webcam.py index 4b9b4af24af..b1940f432ae 100644 --- a/homeassistant/components/binary_sensor/android_ip_webcam.py +++ b/homeassistant/components/binary_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 IP Webcam binary sensors.""" + """Set up the IP Webcam binary sensors.""" if discovery_info is None: return @@ -28,7 +28,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class IPWebcamBinarySensor(AndroidIPCamEntity, BinarySensorDevice): - """Represents an IP Webcam binary sensor.""" + """Representation of an IP Webcam binary sensor.""" def __init__(self, name, host, ipcam, sensor): """Initialize the binary sensor.""" @@ -47,7 +47,7 @@ class IPWebcamBinarySensor(AndroidIPCamEntity, BinarySensorDevice): @property def is_on(self): - """True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return self._state @asyncio.coroutine diff --git a/homeassistant/components/binary_sensor/apcupsd.py b/homeassistant/components/binary_sensor/apcupsd.py index 05d0749b9ef..620b7fcc5de 100644 --- a/homeassistant/components/binary_sensor/apcupsd.py +++ b/homeassistant/components/binary_sensor/apcupsd.py @@ -21,7 +21,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_entities, discovery_info=None): - """Setup an Online Status binary sensor.""" + """Set up an Online Status binary sensor.""" add_entities((OnlineStatus(config, apcupsd.DATA),)) diff --git a/homeassistant/components/binary_sensor/bbb_gpio.py b/homeassistant/components/binary_sensor/bbb_gpio.py index dd960defaa8..785b178969f 100644 --- a/homeassistant/components/binary_sensor/bbb_gpio.py +++ b/homeassistant/components/binary_sensor/bbb_gpio.py @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Beaglebone Black GPIO devices.""" + """Set up the Beaglebone Black GPIO devices.""" pins = config.get(CONF_PINS) binary_sensors = [] @@ -53,7 +53,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class BBBGPIOBinarySensor(BinarySensorDevice): - """Represent a binary sensor that uses Beaglebone Black GPIO.""" + """Representation of a binary sensor that uses Beaglebone Black GPIO.""" def __init__(self, pin, params): """Initialize the Beaglebone Black binary sensor.""" diff --git a/homeassistant/components/binary_sensor/blink.py b/homeassistant/components/binary_sensor/blink.py index 1e95d4d466b..4d8617b3811 100644 --- a/homeassistant/components/binary_sensor/blink.py +++ b/homeassistant/components/binary_sensor/blink.py @@ -24,7 +24,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class BlinkCameraMotionSensor(BinarySensorDevice): - """A representation of a Blink binary sensor.""" + """Representation of a Blink binary sensor.""" def __init__(self, name, data): """Initialize the sensor.""" diff --git a/homeassistant/components/binary_sensor/bloomsky.py b/homeassistant/components/binary_sensor/bloomsky.py index 845a58ee918..38f362fb1bb 100644 --- a/homeassistant/components/binary_sensor/bloomsky.py +++ b/homeassistant/components/binary_sensor/bloomsky.py @@ -18,7 +18,6 @@ _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['bloomsky'] -# These are the available sensors mapped to binary_sensor class SENSOR_TYPES = { 'Rain': 'moisture', 'Night': None, @@ -31,7 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available BloomSky weather binary sensors.""" + """Set up the available BloomSky weather binary sensors.""" bloomsky = get_component('bloomsky') # Default needed in case of discovery sensors = config.get(CONF_MONITORED_CONDITIONS, SENSOR_TYPES) @@ -42,7 +41,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class BloomSkySensor(BinarySensorDevice): - """Represent a single binary sensor in a BloomSky device.""" + """Representation of a single binary sensor in a BloomSky device.""" def __init__(self, bs, device, sensor_name): """Initialize a BloomSky binary sensor.""" @@ -55,7 +54,7 @@ class BloomSkySensor(BinarySensorDevice): @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 diff --git a/homeassistant/components/binary_sensor/command_line.py b/homeassistant/components/binary_sensor/command_line.py index e08ebbe18f8..6ed0e40409a 100644 --- a/homeassistant/components/binary_sensor/command_line.py +++ b/homeassistant/components/binary_sensor/command_line.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 Command line Binary Sensor.""" + """Set up the Command line Binary Sensor.""" name = config.get(CONF_NAME) command = config.get(CONF_COMMAND) payload_off = config.get(CONF_PAYLOAD_OFF) @@ -56,7 +56,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class CommandBinarySensor(BinarySensorDevice): - """Represent a command line binary sensor.""" + """Representation of a command line binary sensor.""" def __init__(self, hass, data, name, device_class, payload_on, payload_off, value_template): diff --git a/homeassistant/components/binary_sensor/concord232.py b/homeassistant/components/binary_sensor/concord232.py index 38ec0a74f97..fc8c0b81edf 100755 --- a/homeassistant/components/binary_sensor/concord232.py +++ b/homeassistant/components/binary_sensor/concord232.py @@ -67,8 +67,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if zone['number'] not in exclude: sensors.append( Concord232ZoneSensor( - hass, client, zone, zone_types.get(zone['number'], - get_opening_type(zone))) + hass, client, zone, zone_types.get( + zone['number'], get_opening_type(zone)) + ) ) add_devices(sensors) @@ -77,7 +78,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): def get_opening_type(zone): - """Helper function to try to guess sensor type from name.""" + """Return the result of the type guessing from name.""" if 'MOTION' in zone['name']: return 'motion' if 'KEY' in zone['name']: @@ -123,7 +124,7 @@ class Concord232ZoneSensor(BinarySensorDevice): return bool(self._zone['state'] == 'Normal') def update(self): - """"Get updated stats from API.""" + """Get updated stats from API.""" last_update = datetime.datetime.now() - self._client.last_zone_update _LOGGER.debug("Zone: %s ", self._zone) if last_update > datetime.timedelta(seconds=1): diff --git a/homeassistant/components/binary_sensor/demo.py b/homeassistant/components/binary_sensor/demo.py index 9dbae2fdb49..10077c60ed1 100644 --- a/homeassistant/components/binary_sensor/demo.py +++ b/homeassistant/components/binary_sensor/demo.py @@ -8,7 +8,7 @@ from homeassistant.components.binary_sensor import BinarySensorDevice def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo binary sensor platform.""" + """Set up the Demo binary sensor platform.""" add_devices([ DemoBinarySensor('Basement Floor Wet', False, 'moisture'), DemoBinarySensor('Movement Backyard', True, 'motion'), @@ -16,7 +16,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class DemoBinarySensor(BinarySensorDevice): - """A Demo binary sensor.""" + """representation of a Demo binary sensor.""" def __init__(self, name, state, device_class): """Initialize the demo sensor.""" diff --git a/homeassistant/components/binary_sensor/ecobee.py b/homeassistant/components/binary_sensor/ecobee.py index b2a5d21386b..d14a1124390 100644 --- a/homeassistant/components/binary_sensor/ecobee.py +++ b/homeassistant/components/binary_sensor/ecobee.py @@ -13,7 +13,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/binary_sensor/enocean.py b/homeassistant/components/binary_sensor/enocean.py index be01f63e657..358abb434fd 100644 --- a/homeassistant/components/binary_sensor/enocean.py +++ b/homeassistant/components/binary_sensor/enocean.py @@ -30,7 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Binary Sensor platform fo EnOcean.""" + """Set up the Binary Sensor platform for EnOcean.""" dev_id = config.get(CONF_ID) devname = config.get(CONF_NAME) device_class = get_deprecated(config, CONF_DEVICE_CLASS, CONF_SENSOR_CLASS) @@ -44,7 +44,7 @@ class EnOceanBinarySensor(enocean.EnOceanDevice, BinarySensorDevice): def __init__(self, dev_id, devname, device_class): """Initialize the EnOcean binary sensor.""" enocean.EnOceanDevice.__init__(self) - self.stype = "listener" + self.stype = 'listener' self.dev_id = dev_id self.which = -1 self.onoff = -1 @@ -53,7 +53,7 @@ class EnOceanBinarySensor(enocean.EnOceanDevice, BinarySensorDevice): @property def name(self): - """The default name for the binary sensor.""" + """Return the default name for the binary sensor.""" return self.devname @property @@ -80,7 +80,7 @@ class EnOceanBinarySensor(enocean.EnOceanDevice, BinarySensorDevice): elif value2 == 0x10: self.which = 1 self.onoff = 1 - self.hass.bus.fire('button_pressed', {"id": self.dev_id, + self.hass.bus.fire('button_pressed', {'id': self.dev_id, 'pushed': value, 'which': self.which, 'onoff': self.onoff}) diff --git a/homeassistant/components/binary_sensor/envisalink.py b/homeassistant/components/binary_sensor/envisalink.py index 22a3256f9fe..5fbc1eb90a1 100644 --- a/homeassistant/components/binary_sensor/envisalink.py +++ b/homeassistant/components/binary_sensor/envisalink.py @@ -15,13 +15,14 @@ from homeassistant.components.envisalink import ( SIGNAL_ZONE_UPDATE) from homeassistant.const import ATTR_LAST_TRIP_TIME -DEPENDENCIES = ['envisalink'] _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['envisalink'] + @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup Envisalink binary sensor devices.""" + """Set up the Envisalink binary sensor devices.""" configured_zones = discovery_info['zones'] devices = [] diff --git a/homeassistant/components/binary_sensor/ffmpeg_motion.py b/homeassistant/components/binary_sensor/ffmpeg_motion.py index 418a6342172..1bbf39dd6e0 100644 --- a/homeassistant/components/binary_sensor/ffmpeg_motion.py +++ b/homeassistant/components/binary_sensor/ffmpeg_motion.py @@ -48,23 +48,21 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Create the binary sensor.""" + """Set up the FFmpeg binary moition sensor.""" manager = hass.data[DATA_FFMPEG] - # check source if not manager.async_run_test(config.get(CONF_INPUT)): return - # generate sensor object entity = FFmpegMotion(hass, manager, config) async_add_devices([entity]) class FFmpegBinarySensor(FFmpegBase, BinarySensorDevice): - """A binary sensor which use ffmpeg for noise detection.""" + """A binary sensor which use FFmpeg for noise detection.""" def __init__(self, config): - """Constructor for binary sensor noise detection.""" + """Init for the binary sensor noise detection.""" super().__init__(config.get(CONF_INITIAL_STATE)) self._state = False @@ -79,7 +77,7 @@ class FFmpegBinarySensor(FFmpegBase, BinarySensorDevice): @property def is_on(self): - """True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return self._state @property @@ -89,10 +87,10 @@ class FFmpegBinarySensor(FFmpegBase, BinarySensorDevice): class FFmpegMotion(FFmpegBinarySensor): - """A binary sensor which use ffmpeg for noise detection.""" + """A binary sensor which use FFmpeg for noise detection.""" def __init__(self, hass, manager, config): - """Initialize ffmpeg motion binary sensor.""" + """Initialize FFmpeg motion binary sensor.""" from haffmpeg import SensorMotion super().__init__(config) @@ -125,4 +123,4 @@ class FFmpegMotion(FFmpegBinarySensor): @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" - return "motion" + return 'motion' diff --git a/homeassistant/components/binary_sensor/ffmpeg_noise.py b/homeassistant/components/binary_sensor/ffmpeg_noise.py index c3400150f74..db7647d9b2c 100644 --- a/homeassistant/components/binary_sensor/ffmpeg_noise.py +++ b/homeassistant/components/binary_sensor/ffmpeg_noise.py @@ -45,23 +45,21 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Create the binary sensor.""" + """Set up the FFmpeg noise binary sensor.""" manager = hass.data[DATA_FFMPEG] - # check source if not manager.async_run_test(config.get(CONF_INPUT)): return - # generate sensor object entity = FFmpegNoise(hass, manager, config) async_add_devices([entity]) class FFmpegNoise(FFmpegBinarySensor): - """A binary sensor which use ffmpeg for noise detection.""" + """A binary sensor which use FFmpeg for noise detection.""" def __init__(self, hass, manager, config): - """Initialize ffmpeg noise binary sensor.""" + """Initialize FFmpeg noise binary sensor.""" from haffmpeg import SensorNoise super().__init__(config) @@ -77,14 +75,12 @@ class FFmpegNoise(FFmpegBinarySensor): if entity_ids is not None and self.entity_id not in entity_ids: return - # init config self.ffmpeg.set_options( time_duration=self._config.get(CONF_DURATION), time_reset=self._config.get(CONF_RESET), peak=self._config.get(CONF_PEAK), ) - # run yield from self.ffmpeg.open_sensor( input_source=self._config.get(CONF_INPUT), output_dest=self._config.get(CONF_OUTPUT), @@ -94,4 +90,4 @@ class FFmpegNoise(FFmpegBinarySensor): @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" - return "sound" + return 'sound' diff --git a/homeassistant/components/binary_sensor/flic.py b/homeassistant/components/binary_sensor/flic.py index 2079d6a1ce8..f78ee75ae25 100644 --- a/homeassistant/components/binary_sensor/flic.py +++ b/homeassistant/components/binary_sensor/flic.py @@ -110,7 +110,7 @@ def start_scanning(config, add_entities, client): def setup_button(hass, config, add_entities, client, address): - """Setup single button device.""" + """Set up a single button device.""" timeout = config.get(CONF_TIMEOUT) ignored_click_types = config.get(CONF_IGNORED_CLICK_TYPES) button = FlicButton(hass, client, address, timeout, ignored_click_types) diff --git a/homeassistant/components/binary_sensor/hikvision.py b/homeassistant/components/binary_sensor/hikvision.py index 9a7a1dcf546..61e69e991b3 100644 --- a/homeassistant/components/binary_sensor/hikvision.py +++ b/homeassistant/components/binary_sensor/hikvision.py @@ -67,7 +67,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_entities, discovery_info=None): - """Setup Hikvision binary sensor devices.""" + """Set up the Hikvision binary sensor devices.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -77,16 +77,16 @@ def setup_platform(hass, config, add_entities, discovery_info=None): customize = config.get(CONF_CUSTOMIZE) if config.get(CONF_SSL): - protocol = "https" + protocol = 'https' else: - protocol = "http" + protocol = 'http' url = '{}://{}'.format(protocol, host) data = HikvisionData(hass, url, port, name, username, password) if data.sensors is None: - _LOGGER.error('Hikvision event stream has no data, unable to setup.') + _LOGGER.error("Hikvision event stream has no data, unable to setup") return False entities = [] @@ -104,7 +104,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): ignore = custom.get(CONF_IGNORED) delay = custom.get(CONF_DELAY) - _LOGGER.debug('Entity: %s - %s, Options - Ignore: %s, Delay: %s', + _LOGGER.debug("Entity: %s - %s, Options - Ignore: %s, Delay: %s", data.name, sensor_name, ignore, delay) if not ignore: entities.append(HikvisionBinarySensor( @@ -126,8 +126,8 @@ class HikvisionData(object): self._password = password # Establish camera - self.camdata = HikCamera(self._url, self._port, - self._username, self._password) + self.camdata = HikCamera( + self._url, self._port, self._username, self._password) if self._name is None: self._name = self.camdata.get_name @@ -251,7 +251,7 @@ class HikvisionBinarySensor(BinarySensorDevice): # Set timer to wait until updating the state def _delay_update(now): """Timer callback for sensor update.""" - _LOGGER.debug('%s Called delayed (%ssec) update.', + _LOGGER.debug("%s Called delayed (%ssec) update", self._name, self._delay) self.schedule_update_ha_state() self._timer = None diff --git a/homeassistant/components/binary_sensor/homematic.py b/homeassistant/components/binary_sensor/homematic.py index 1ae7fde706a..17d08265a5b 100644 --- a/homeassistant/components/binary_sensor/homematic.py +++ b/homeassistant/components/binary_sensor/homematic.py @@ -14,22 +14,22 @@ _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['homematic'] SENSOR_TYPES_CLASS = { - "Remote": None, - "ShutterContact": "opening", - "MaxShutterContact": "opening", - "IPShutterContact": "opening", - "Smoke": "smoke", - "SmokeV2": "smoke", - "Motion": "motion", - "MotionV2": "motion", - "RemoteMotion": None, - "WeatherSensor": None, - "TiltSensor": None, + 'Remote': None, + 'ShutterContact': 'opening', + 'MaxShutterContact': 'opening', + 'IPShutterContact': 'opening', + 'Smoke': 'smoke', + 'SmokeV2': 'smoke', + 'Motion': 'motion', + 'MotionV2': 'motion', + 'RemoteMotion': None, + 'WeatherSensor': None, + 'TiltSensor': None, } def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Homematic binary sensor platform.""" + """Set up the Homematic binary sensor platform.""" if discovery_info is None: return @@ -56,8 +56,8 @@ class HMBinarySensor(HMDevice, BinarySensorDevice): def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" # If state is MOTION (RemoteMotion works only) - if self._state == "MOTION": - return "motion" + if self._state == 'MOTION': + return 'motion' return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__, None) def _init_data_struct(self): diff --git a/homeassistant/components/binary_sensor/insteon_plm.py b/homeassistant/components/binary_sensor/insteon_plm.py index 03cc7e6bd9b..448ceae8636 100644 --- a/homeassistant/components/binary_sensor/insteon_plm.py +++ b/homeassistant/components/binary_sensor/insteon_plm.py @@ -67,7 +67,7 @@ class InsteonPLMBinarySensorDevice(BinarySensorDevice): def is_on(self): """Return the boolean response if the node is on.""" sensorstate = self._plm.get_device_attr(self._address, 'sensorstate') - _LOGGER.info('sensor state for %s is %s', self._address, sensorstate) + _LOGGER.info("Sensor state for %s is %s", self._address, sensorstate) return bool(sensorstate) @property @@ -83,5 +83,5 @@ class InsteonPLMBinarySensorDevice(BinarySensorDevice): @callback def async_binarysensor_update(self, message): """Receive notification from transport that new data exists.""" - _LOGGER.info('Received update calback from PLM for %s', self._address) + _LOGGER.info("Received update calback from PLM for %s", self._address) self._hass.async_add_job(self.async_update_ha_state()) diff --git a/homeassistant/components/binary_sensor/isy994.py b/homeassistant/components/binary_sensor/isy994.py index 8f4cb1637b4..2c4b9e0b97f 100644 --- a/homeassistant/components/binary_sensor/isy994.py +++ b/homeassistant/components/binary_sensor/isy994.py @@ -12,7 +12,6 @@ import homeassistant.components.isy994 as isy from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.helpers.typing import ConfigType - _LOGGER = logging.getLogger(__name__) VALUE_TO_STATE = { @@ -29,7 +28,7 @@ def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): """Setup 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.') + _LOGGER.error("A connection has not been made to the ISY controller") return False devices = [] diff --git a/homeassistant/components/binary_sensor/knx.py b/homeassistant/components/binary_sensor/knx.py index 304dad9d71b..87f8a30d78c 100644 --- a/homeassistant/components/binary_sensor/knx.py +++ b/homeassistant/components/binary_sensor/knx.py @@ -11,7 +11,7 @@ DEPENDENCIES = ['knx'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the KNX binary sensor platform.""" + """Set up the KNX binary sensor platform.""" add_devices([KNXSwitch(hass, KNXConfig(config))]) diff --git a/homeassistant/components/binary_sensor/maxcube.py b/homeassistant/components/binary_sensor/maxcube.py index 13610939a5d..cf2be6baed5 100644 --- a/homeassistant/components/binary_sensor/maxcube.py +++ b/homeassistant/components/binary_sensor/maxcube.py @@ -43,7 +43,7 @@ class MaxCubeShutter(BinarySensorDevice): @property def should_poll(self): - """Polling is required.""" + """Return the polling state.""" return True @property diff --git a/homeassistant/components/binary_sensor/modbus.py b/homeassistant/components/binary_sensor/modbus.py index d43c348f116..54e4cefb230 100644 --- a/homeassistant/components/binary_sensor/modbus.py +++ b/homeassistant/components/binary_sensor/modbus.py @@ -16,9 +16,9 @@ from homeassistant.components.sensor import PLATFORM_SCHEMA _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['modbus'] -CONF_COIL = "coil" -CONF_COILS = "coils" -CONF_SLAVE = "slave" +CONF_COIL = 'coil' +CONF_COILS = 'coils' +CONF_SLAVE = 'slave' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_COILS): [{ @@ -30,7 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Modbus binary sensors.""" + """Set up the Modbus binary sensors.""" sensors = [] for coil in config.get(CONF_COILS): sensors.append(ModbusCoilSensor( diff --git a/homeassistant/components/binary_sensor/mqtt.py b/homeassistant/components/binary_sensor/mqtt.py index d8467a6cbfe..fe19523c5b2 100644 --- a/homeassistant/components/binary_sensor/mqtt.py +++ b/homeassistant/components/binary_sensor/mqtt.py @@ -79,7 +79,7 @@ class MqttBinarySensor(BinarySensorDevice): """ @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle a new received MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) @@ -95,7 +95,7 @@ class MqttBinarySensor(BinarySensorDevice): @property def should_poll(self): - """No polling needed.""" + """Return the polling state.""" return False @property diff --git a/homeassistant/components/binary_sensor/mysensors.py b/homeassistant/components/binary_sensor/mysensors.py index 3a0b09c0074..767ed858ec7 100644 --- a/homeassistant/components/binary_sensor/mysensors.py +++ b/homeassistant/components/binary_sensor/mysensors.py @@ -16,7 +16,7 @@ DEPENDENCIES = [] 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/binary_sensor/nest.py b/homeassistant/components/binary_sensor/nest.py index 4689bc59082..4089f3a2eaf 100644 --- a/homeassistant/components/binary_sensor/nest.py +++ b/homeassistant/components/binary_sensor/nest.py @@ -16,15 +16,18 @@ DEPENDENCIES = ['nest'] BINARY_TYPES = ['online'] -CLIMATE_BINARY_TYPES = ['fan', - 'is_using_emergency_heat', - 'is_locked', - 'has_leaf'] +CLIMATE_BINARY_TYPES = [ + 'fan', + 'is_using_emergency_heat', + 'is_locked', + 'has_leaf', +] CAMERA_BINARY_TYPES = [ 'motion_detected', 'sound_detected', - 'person_detected'] + 'person_detected', +] _BINARY_TYPES_DEPRECATED = [ 'hvac_ac_state', @@ -34,7 +37,8 @@ _BINARY_TYPES_DEPRECATED = [ 'hvac_heat_x3_state', 'hvac_alt_heat_state', 'hvac_alt_heat_x2_state', - 'hvac_emer_heat_state'] + 'hvac_emer_heat_state', +] _VALID_BINARY_SENSOR_TYPES = BINARY_TYPES + CLIMATE_BINARY_TYPES \ + CAMERA_BINARY_TYPES @@ -43,7 +47,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Nest binary sensors.""" + """Set up the Nest binary sensors.""" if discovery_info is None: return @@ -93,7 +97,7 @@ class NestBinarySensor(NestSensor, BinarySensorDevice): @property def is_on(self): - """True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return self._state def update(self): diff --git a/homeassistant/components/binary_sensor/netatmo.py b/homeassistant/components/binary_sensor/netatmo.py index ee7bc53c4cb..e0841e2e286 100644 --- a/homeassistant/components/binary_sensor/netatmo.py +++ b/homeassistant/components/binary_sensor/netatmo.py @@ -7,6 +7,7 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.netatmo/. """ import logging + import voluptuous as vol from homeassistant.components.binary_sensor import ( @@ -16,10 +17,9 @@ from homeassistant.loader import get_component from homeassistant.const import CONF_TIMEOUT, CONF_OFFSET from homeassistant.helpers import config_validation as cv -DEPENDENCIES = ["netatmo"] - _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['netatmo'] # These are the available sensors mapped to binary_sensor class WELCOME_SENSOR_TYPES = { @@ -61,7 +61,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup access to Netatmo binary sensor.""" + """Set up the access to Netatmo binary sensor.""" netatmo = get_component('netatmo') home = config.get(CONF_HOME, None) timeout = config.get(CONF_TIMEOUT, 15) @@ -85,35 +85,31 @@ def setup_platform(hass, config, add_devices, discovery_info=None): for camera_name in data.get_camera_names(): camera_type = data.get_camera_type(camera=camera_name, home=home) - if camera_type == "NACamera": + if camera_type == 'NACamera': if CONF_CAMERAS in config: if config[CONF_CAMERAS] != [] and \ camera_name not in config[CONF_CAMERAS]: continue for variable in welcome_sensors: - add_devices([NetatmoBinarySensor(data, camera_name, - module_name, home, timeout, - offset, camera_type, - variable)]) - if camera_type == "NOC": + add_devices([NetatmoBinarySensor( + data, camera_name, module_name, home, timeout, + offset, camera_type, variable)]) + if camera_type == 'NOC': if CONF_CAMERAS in config: if config[CONF_CAMERAS] != [] and \ camera_name not in config[CONF_CAMERAS]: continue for variable in presence_sensors: - add_devices([NetatmoBinarySensor(data, camera_name, - module_name, home, timeout, - offset, camera_type, - variable)]) + add_devices([NetatmoBinarySensor( + data, camera_name, module_name, home, timeout, offset, + camera_type, variable)]) for module_name in data.get_module_names(camera_name): for variable in tag_sensors: camera_type = None - add_devices([NetatmoBinarySensor(data, camera_name, - module_name, home, - timeout, offset, - camera_type, - variable)]) + add_devices([NetatmoBinarySensor( + data, camera_name, module_name, home, timeout, offset, + camera_type, variable)]) class NetatmoBinarySensor(BinarySensorDevice): @@ -129,23 +125,23 @@ class NetatmoBinarySensor(BinarySensorDevice): self._timeout = timeout self._offset = offset if home: - self._name = home + ' / ' + camera_name + self._name = '{} / {}'.format(home, camera_name) else: self._name = camera_name if module_name: self._name += ' / ' + module_name self._sensor_name = sensor self._name += ' ' + sensor - camera_id = data.camera_data.cameraByName(camera=camera_name, - home=home)['id'] - self._unique_id = "Netatmo_binary_sensor {0} - {1}".format(self._name, - camera_id) + camera_id = data.camera_data.cameraByName( + camera=camera_name, home=home)['id'] + self._unique_id = "Netatmo_binary_sensor {0} - {1}".format( + self._name, camera_id) self._cameratype = camera_type self.update() @property def name(self): - """The name of the Netatmo device and this sensor.""" + """Return the name of the Netatmo device and this sensor.""" return self._name @property @@ -156,9 +152,9 @@ class NetatmoBinarySensor(BinarySensorDevice): @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" - if self._cameratype == "NACamera": + if self._cameratype == 'NACamera': return WELCOME_SENSOR_TYPES.get(self._sensor_name) - elif self._cameratype == "NOC": + elif self._cameratype == 'NOC': return PRESENCE_SENSOR_TYPES.get(self._sensor_name) else: return TAG_SENSOR_TYPES.get(self._sensor_name) @@ -173,51 +169,44 @@ class NetatmoBinarySensor(BinarySensorDevice): self._data.update() self._data.update_event() - if self._cameratype == "NACamera": + if self._cameratype == 'NACamera': if self._sensor_name == "Someone known": self._state =\ - self._data.camera_data.someoneKnownSeen(self._home, - self._camera_name, - self._timeout*60) + self._data.camera_data.someoneKnownSeen( + self._home, self._camera_name, self._timeout*60) elif self._sensor_name == "Someone unknown": self._state =\ self._data.camera_data.someoneUnknownSeen( self._home, self._camera_name, self._timeout*60) elif self._sensor_name == "Motion": self._state =\ - self._data.camera_data.motionDetected(self._home, - self._camera_name, - self._timeout*60) - elif self._cameratype == "NOC": + self._data.camera_data.motionDetected( + self._home, self._camera_name, self._timeout*60) + elif self._cameratype == 'NOC': if self._sensor_name == "Outdoor motion": self._state =\ self._data.camera_data.outdoormotionDetected( self._home, self._camera_name, self._offset) elif self._sensor_name == "Outdoor human": self._state =\ - self._data.camera_data.humanDetected(self._home, - self._camera_name, - self._offset) + self._data.camera_data.humanDetected( + self._home, self._camera_name, self._offset) elif self._sensor_name == "Outdoor animal": self._state =\ - self._data.camera_data.animalDetected(self._home, - self._camera_name, - self._offset) + self._data.camera_data.animalDetected( + self._home, self._camera_name, self._offset) elif self._sensor_name == "Outdoor vehicle": self._state =\ - self._data.camera_data.carDetected(self._home, - self._camera_name, - self._offset) + self._data.camera_data.carDetected( + self._home, self._camera_name, self._offset) if self._sensor_name == "Tag Vibration": self._state =\ - self._data.camera_data.moduleMotionDetected(self._home, - self._module_name, - self._camera_name, - self._timeout*60) + self._data.camera_data.moduleMotionDetected( + self._home, self._module_name, self._camera_name, + self._timeout*60) elif self._sensor_name == "Tag Open": self._state =\ - self._data.camera_data.moduleOpened(self._home, - self._module_name, - self._camera_name) + self._data.camera_data.moduleOpened( + self._home, self._module_name, self._camera_name) else: return None diff --git a/homeassistant/components/binary_sensor/nx584.py b/homeassistant/components/binary_sensor/nx584.py index 6ffcb7b0cf3..4dff263f79a 100644 --- a/homeassistant/components/binary_sensor/nx584.py +++ b/homeassistant/components/binary_sensor/nx584.py @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the NX584 binary sensor platform.""" + """Set up the NX584 binary sensor platform.""" from nx584 import client as nx584_client host = config.get(CONF_HOST) @@ -53,7 +53,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): client = nx584_client.Client('http://{}:{}'.format(host, port)) zones = client.list_zones() except requests.exceptions.ConnectionError as ex: - _LOGGER.error('Unable to connect to NX584: %s', str(ex)) + _LOGGER.error("Unable to connect to NX584: %s", str(ex)) return False version = [int(v) for v in client.get_version().split('.')] diff --git a/homeassistant/components/binary_sensor/octoprint.py b/homeassistant/components/binary_sensor/octoprint.py index d1cc1d8e8a4..6e278ccfccf 100644 --- a/homeassistant/components/binary_sensor/octoprint.py +++ b/homeassistant/components/binary_sensor/octoprint.py @@ -15,7 +15,6 @@ from homeassistant.components.binary_sensor import ( from homeassistant.loader import get_component import homeassistant.helpers.config_validation as cv - _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['octoprint'] @@ -37,22 +36,18 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the available OctoPrint binary sensors.""" + """Set up the available OctoPrint binary sensors.""" octoprint = get_component('octoprint') name = config.get(CONF_NAME) - monitored_conditions = config.get(CONF_MONITORED_CONDITIONS, - SENSOR_TYPES.keys()) + monitored_conditions = config.get( + CONF_MONITORED_CONDITIONS, SENSOR_TYPES.keys()) devices = [] for octo_type in monitored_conditions: - new_sensor = OctoPrintBinarySensor(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], - 'flags') + new_sensor = OctoPrintBinarySensor( + 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], 'flags') devices.append(new_sensor) add_devices(devices) @@ -97,10 +92,9 @@ class OctoPrintBinarySensor(BinarySensorDevice): 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/binary_sensor/rest.py b/homeassistant/components/binary_sensor/rest.py index 2e5de7e2f27..abdbc8251c7 100644 --- a/homeassistant/components/binary_sensor/rest.py +++ b/homeassistant/components/binary_sensor/rest.py @@ -44,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the REST binary sensor.""" + """Set up the REST binary sensor.""" name = config.get(CONF_NAME) resource = config.get(CONF_RESOURCE) method = config.get(CONF_METHOD) @@ -114,8 +114,8 @@ class RestBinarySensor(BinarySensorDevice): try: return bool(int(response)) except ValueError: - return {"true": True, "on": True, "open": True, - "yes": True}.get(response.lower(), False) + return {'true': True, 'on': True, 'open': True, + 'yes': True}.get(response.lower(), False) def update(self): """Get the latest data from REST API and updates the state.""" diff --git a/homeassistant/components/binary_sensor/rpi_gpio.py b/homeassistant/components/binary_sensor/rpi_gpio.py index eaf9ee737e5..2322b1bf498 100644 --- a/homeassistant/components/binary_sensor/rpi_gpio.py +++ b/homeassistant/components/binary_sensor/rpi_gpio.py @@ -41,10 +41,10 @@ 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.""" - pull_mode = config.get('pull_mode', DEFAULT_PULL_MODE) - bouncetime = config.get('bouncetime', DEFAULT_BOUNCETIME) - invert_logic = config.get('invert_logic', DEFAULT_INVERT_LOGIC) + """Set up the Raspberry PI GPIO devices.""" + pull_mode = config.get(CONF_PULL_MODE) + bouncetime = config.get(CONF_BOUNCETIME) + invert_logic = config.get(CONF_INVERT_LOGIC) binary_sensors = [] ports = config.get('ports') diff --git a/homeassistant/components/binary_sensor/sleepiq.py b/homeassistant/components/binary_sensor/sleepiq.py index f55eba82dbe..3a6c27db386 100644 --- a/homeassistant/components/binary_sensor/sleepiq.py +++ b/homeassistant/components/binary_sensor/sleepiq.py @@ -11,7 +11,7 @@ DEPENDENCIES = ['sleepiq'] 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/binary_sensor/tcp.py b/homeassistant/components/binary_sensor/tcp.py index 12a96a5492f..cfaa8057798 100644 --- a/homeassistant/components/binary_sensor/tcp.py +++ b/homeassistant/components/binary_sensor/tcp.py @@ -27,5 +27,5 @@ class TcpBinarySensor(BinarySensorDevice, TcpSensor): @property def is_on(self): - """True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return self._state == self._config[CONF_VALUE_ON] diff --git a/homeassistant/components/binary_sensor/template.py b/homeassistant/components/binary_sensor/template.py index 396f591923b..989f8b358af 100644 --- a/homeassistant/components/binary_sensor/template.py +++ b/homeassistant/components/binary_sensor/template.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 template binary sensors.""" + """Set up template binary sensors.""" sensors = [] for device, device_config in config[CONF_SENSORS].items(): @@ -57,15 +57,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): sensors.append( BinarySensorTemplate( - hass, - device, - friendly_name, - device_class, - value_template, + hass, device, friendly_name, device_class, value_template, entity_ids) ) if not sensors: - _LOGGER.error('No sensors added') + _LOGGER.error("No sensors added") return False async_add_devices(sensors, True) @@ -79,8 +75,8 @@ class BinarySensorTemplate(BinarySensorDevice): value_template, entity_ids): """Initialize the Template binary sensor.""" self.hass = hass - self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device, - hass=hass) + self.entity_id = async_generate_entity_id( + ENTITY_ID_FORMAT, device, hass=hass) self._name = friendly_name self._device_class = device_class self._template = value_template @@ -96,7 +92,7 @@ class BinarySensorTemplate(BinarySensorDevice): @callback def template_bsensor_state_listener(entity, old_state, new_state): - """Called when the target device changes state.""" + """Handle the target device state changes.""" self.hass.async_add_job(self.async_update_ha_state(True)) @callback @@ -139,8 +135,8 @@ class BinarySensorTemplate(BinarySensorDevice): if ex.args and ex.args[0].startswith( "UndefinedError: 'None' has no attribute"): # Common during HA startup - so just a warning - _LOGGER.warning('Could not render template %s,' - ' the state is unknown.', self._name) + _LOGGER.warning("Could not render template %s, " + "the state is unknown", self._name) return - _LOGGER.error('Could not render template %s: %s', self._name, ex) + _LOGGER.error("Could not render template %s: %s", self._name, ex) self._state = False diff --git a/homeassistant/components/binary_sensor/threshold.py b/homeassistant/components/binary_sensor/threshold.py index c97ba17b874..b4891906a01 100644 --- a/homeassistant/components/binary_sensor/threshold.py +++ b/homeassistant/components/binary_sensor/threshold.py @@ -77,7 +77,7 @@ class ThresholdSensor(BinarySensorDevice): # pylint: disable=invalid-name def async_threshold_sensor_state_listener( entity, old_state, new_state): - """Called when the sensor changes state.""" + """Handle sensor state changes.""" if new_state.state == STATE_UNKNOWN: return diff --git a/homeassistant/components/binary_sensor/trend.py b/homeassistant/components/binary_sensor/trend.py index 2c2a0563452..82585acfc38 100644 --- a/homeassistant/components/binary_sensor/trend.py +++ b/homeassistant/components/binary_sensor/trend.py @@ -6,22 +6,18 @@ https://home-assistant.io/components/sensor.trend/ """ import asyncio import logging + import voluptuous as vol from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.components.binary_sensor import ( - BinarySensorDevice, - ENTITY_ID_FORMAT, - PLATFORM_SCHEMA, + BinarySensorDevice, ENTITY_ID_FORMAT, PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA) from homeassistant.const import ( - ATTR_FRIENDLY_NAME, - ATTR_ENTITY_ID, - CONF_SENSOR_CLASS, - CONF_DEVICE_CLASS, - STATE_UNKNOWN,) + ATTR_FRIENDLY_NAME, ATTR_ENTITY_ID, CONF_SENSOR_CLASS, + CONF_DEVICE_CLASS, STATE_UNKNOWN,) from homeassistant.helpers.deprecation import get_deprecated from homeassistant.helpers.entity import generate_entity_id from homeassistant.helpers.event import track_state_change @@ -47,7 +43,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the trend sensors.""" + """Set up the trend sensors.""" sensors = [] for device, device_config in config[CONF_SENSORS].items(): @@ -60,13 +56,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): sensors.append( SensorTrend( - hass, - device, - friendly_name, - entity_id, - attribute, - device_class, - invert) + hass, device, friendly_name, entity_id, attribute, + device_class, invert) ) if not sensors: _LOGGER.error("No sensors added") @@ -82,8 +73,8 @@ class SensorTrend(BinarySensorDevice): target_entity, attribute, device_class, invert): """Initialize the sensor.""" self._hass = hass - self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, device_id, - hass=hass) + self.entity_id = generate_entity_id( + ENTITY_ID_FORMAT, device_id, hass=hass) self._name = friendly_name self._target_entity = target_entity self._attribute = attribute @@ -95,7 +86,7 @@ class SensorTrend(BinarySensorDevice): @callback def trend_sensor_state_listener(entity, old_state, new_state): - """Called when the target device changes state.""" + """Handle the target device state changes.""" self.from_state = old_state self.to_state = new_state hass.async_add_job(self.async_update_ha_state(True)) diff --git a/homeassistant/components/binary_sensor/volvooncall.py b/homeassistant/components/binary_sensor/volvooncall.py index f97c670270d..2c7c398d91a 100644 --- a/homeassistant/components/binary_sensor/volvooncall.py +++ b/homeassistant/components/binary_sensor/volvooncall.py @@ -3,7 +3,6 @@ Support for VOC. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.volvooncall/ - """ import logging @@ -14,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/binary_sensor/wemo.py b/homeassistant/components/binary_sensor/wemo.py index 58bd411d758..1ec9e703eab 100644 --- a/homeassistant/components/binary_sensor/wemo.py +++ b/homeassistant/components/binary_sensor/wemo.py @@ -29,7 +29,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): class WemoBinarySensor(BinarySensorDevice): - """Represents a WeMo binary sensor.""" + """Representation a WeMo binary sensor.""" def __init__(self, device): """Initialize the WeMo sensor.""" @@ -41,10 +41,8 @@ class WemoBinarySensor(BinarySensorDevice): wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback) def _update_callback(self, _device, _type, _params): - """Called by the Wemo device callback to update state.""" - _LOGGER.info( - 'Subscription update for %s', - _device) + """Handle state changes.""" + _LOGGER.info("Subscription update for %s", _device) updated = self.wemo.subscription_update(_type, _params) self._update(force_update=(not updated)) @@ -60,7 +58,7 @@ class WemoBinarySensor(BinarySensorDevice): @property def unique_id(self): """Return the id of this WeMo device.""" - return "{}.{}".format(self.__class__, self.wemo.serialnumber) + return '{}.{}'.format(self.__class__, self.wemo.serialnumber) @property def name(self): @@ -69,7 +67,7 @@ class WemoBinarySensor(BinarySensorDevice): @property def is_on(self): - """True if sensor is on.""" + """Return true if sensor is on.""" return self._state def update(self): @@ -80,5 +78,5 @@ class WemoBinarySensor(BinarySensorDevice): try: self._state = self.wemo.get_state(force_update) except AttributeError as err: - _LOGGER.warning('Could not update status for %s (%s)', - self.name, err) + _LOGGER.warning( + "Could not update status for %s (%s)", self.name, err) diff --git a/homeassistant/components/binary_sensor/wink.py b/homeassistant/components/binary_sensor/wink.py index 797ef9649b6..3f77d1d6081 100644 --- a/homeassistant/components/binary_sensor/wink.py +++ b/homeassistant/components/binary_sensor/wink.py @@ -16,23 +16,23 @@ DEPENDENCIES = ['wink'] # These are the available sensors mapped to binary_sensor class SENSOR_TYPES = { - "opened": "opening", - "brightness": "light", - "vibration": "vibration", - "loudness": "sound", - "noise": "sound", - "capturing_audio": "sound", - "liquid_detected": "moisture", - "motion": "motion", - "presence": "occupancy", - "co_detected": "gas", - "smoke_detected": "smoke", - "capturing_video": None + 'opened': 'opening', + 'brightness': 'light', + 'vibration': 'vibration', + 'loudness': 'sound', + 'noise': 'sound', + 'capturing_audio': 'sound', + 'liquid_detected': 'moisture', + 'motion': 'motion', + 'presence': 'occupancy', + 'co_detected': 'gas', + 'smoke_detected': 'smoke', + 'capturing_video': None } def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink binary sensor platform.""" + """Set up the Wink binary sensor platform.""" import pywink for sensor in pywink.get_sensors(): @@ -83,7 +83,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if camera_sensor.capability() in SENSOR_TYPES: add_devices([WinkBinarySensorDevice(camera_sensor, hass)]) except AttributeError: - _LOGGER.info("Device isn't a sensor, skipping.") + _LOGGER.info("Device isn't a sensor, skipping") class WinkBinarySensorDevice(WinkDevice, BinarySensorDevice, Entity): diff --git a/homeassistant/components/binary_sensor/zha.py b/homeassistant/components/binary_sensor/zha.py index c12aa38bc24..1d895fbf3a7 100644 --- a/homeassistant/components/binary_sensor/zha.py +++ b/homeassistant/components/binary_sensor/zha.py @@ -27,7 +27,7 @@ CLASS_MAPPING = { @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup Zigbee Home Automation binary sensors.""" + """Set up the Zigbee Home Automation binary sensors.""" discovery_info = zha.get_discovery_info(hass, discovery_info) if discovery_info is None: return @@ -55,12 +55,12 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class BinarySensor(zha.Entity, BinarySensorDevice): - """ZHA Binary Sensor.""" + """THe ZHA Binary Sensor.""" _domain = DOMAIN def __init__(self, device_class, **kwargs): - """Initialize ZHA binary sensor.""" + """Initialize the ZHA binary sensor.""" super().__init__(**kwargs) self._device_class = device_class from bellows.zigbee.zcl.clusters.security import IasZone diff --git a/homeassistant/components/binary_sensor/zigbee.py b/homeassistant/components/binary_sensor/zigbee.py index 935d4b4bb3f..659d82f809b 100644 --- a/homeassistant/components/binary_sensor/zigbee.py +++ b/homeassistant/components/binary_sensor/zigbee.py @@ -23,7 +23,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the ZigBee binary sensor platform.""" + """Set up the ZigBee binary sensor platform.""" add_devices( [ZigBeeBinarySensor(hass, ZigBeeDigitalInConfig(config))], True) diff --git a/homeassistant/components/binary_sensor/zwave.py b/homeassistant/components/binary_sensor/zwave.py index 5fd9c39ef2a..cc5fb3ed572 100644 --- a/homeassistant/components/binary_sensor/zwave.py +++ b/homeassistant/components/binary_sensor/zwave.py @@ -20,7 +20,7 @@ DEPENDENCIES = [] def get_device(values, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" device_mapping = workaround.get_device_mapping(values.primary) if device_mapping == workaround.WORKAROUND_NO_OFF_EVENT: # Default the multiplier to 4 @@ -45,12 +45,12 @@ class ZWaveBinarySensor(BinarySensorDevice, zwave.ZWaveDeviceEntity): self._state = self.values.primary.data def update_properties(self): - """Callback on data changes for node values.""" + """Handle data changes for node values.""" self._state = self.values.primary.data @property def is_on(self): - """Return True if the binary sensor is on.""" + """Return true if the binary sensor is on.""" return self._state @property @@ -69,7 +69,7 @@ class ZWaveTriggerSensor(ZWaveBinarySensor): self.invalidate_after = None def update_properties(self): - """Called when a value for this entity's node has changed.""" + """Handle value changes for this entity's node.""" self._state = self.values.primary.data # only allow this value to be true for re_arm secs if not self.hass: @@ -83,7 +83,7 @@ class ZWaveTriggerSensor(ZWaveBinarySensor): @property def is_on(self): - """Return True if movement has happened within the rearm time.""" + """Return true if movement has happened within the rearm time.""" return self._state and \ (self.invalidate_after is None or self.invalidate_after > dt_util.utcnow()) diff --git a/homeassistant/components/bloomsky.py b/homeassistant/components/bloomsky.py index 13225773b3a..aff1c14b252 100644 --- a/homeassistant/components/bloomsky.py +++ b/homeassistant/components/bloomsky.py @@ -35,7 +35,7 @@ CONFIG_SCHEMA = vol.Schema({ # pylint: disable=unused-argument def setup(hass, config): - """Setup BloomSky component.""" + """Set up the BloomSky component.""" api_key = config[DOMAIN][CONF_API_KEY] global BLOOMSKY @@ -67,9 +67,8 @@ class BloomSky(object): def refresh_devices(self): """Use the API to retrieve a list of devices.""" _LOGGER.debug("Fetching BloomSky update") - response = requests.get(self.API_URL, - headers={"Authorization": self._api_key}, - timeout=10) + response = requests.get( + self.API_URL, headers={"Authorization": self._api_key}, timeout=10) if response.status_code == 401: raise RuntimeError("Invalid API_KEY") elif response.status_code != 200: diff --git a/homeassistant/components/calendar/__init__.py b/homeassistant/components/calendar/__init__.py index 70477198ea0..6bc8cc3029b 100644 --- a/homeassistant/components/calendar/__init__.py +++ b/homeassistant/components/calendar/__init__.py @@ -7,12 +7,10 @@ https://home-assistant.io/components/calendar/ import asyncio import logging from datetime import timedelta - import re -from homeassistant.components.google import (CONF_OFFSET, - CONF_DEVICE_ID, - CONF_NAME) +from homeassistant.components.google import ( + CONF_OFFSET, CONF_DEVICE_ID, CONF_NAME) from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.helpers.config_validation import time_period_str from homeassistant.helpers.entity import Entity, generate_entity_id @@ -20,18 +18,21 @@ from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.template import DATE_STR_FORMAT from homeassistant.util import dt + _LOGGER = logging.getLogger(__name__) -SCAN_INTERVAL = timedelta(seconds=60) DOMAIN = 'calendar' + ENTITY_ID_FORMAT = DOMAIN + '.{}' +SCAN_INTERVAL = timedelta(seconds=60) + @asyncio.coroutine def async_setup(hass, config): """Track states and offer events for calendars.""" component = EntityComponent( - logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, DOMAIN) + _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DOMAIN) yield from component.async_setup(config) return True @@ -55,9 +56,8 @@ class CalendarEventDevice(Entity): self._name = data.get(CONF_NAME) self.dev_id = data.get(CONF_DEVICE_ID) self._offset = data.get(CONF_OFFSET, DEFAULT_CONF_OFFSET) - self.entity_id = generate_entity_id(ENTITY_ID_FORMAT, - self.dev_id, - hass=hass) + self.entity_id = generate_entity_id( + ENTITY_ID_FORMAT, self.dev_id, hass=hass) self._cal_data = { 'all_day': False, @@ -87,7 +87,7 @@ class CalendarEventDevice(Entity): @property def device_state_attributes(self): - """State Attributes for HA.""" + """Return the device state attributes.""" start = self._cal_data.get('start', None) end = self._cal_data.get('end', None) start = start.strftime(DATE_STR_FORMAT) if start is not None else None diff --git a/homeassistant/components/calendar/demo.py b/homeassistant/components/calendar/demo.py index 279119a1ff5..3dc11b6773f 100755 --- a/homeassistant/components/calendar/demo.py +++ b/homeassistant/components/calendar/demo.py @@ -10,7 +10,7 @@ from homeassistant.components.google import CONF_DEVICE_ID, CONF_NAME def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo binary sensor platform.""" + """Set up the Demo Calendar platform.""" calendar_data_future = DemoGoogleCalendarDataFuture() calendar_data_current = DemoGoogleCalendarDataCurrent() add_devices([ @@ -27,8 +27,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class DemoGoogleCalendarData(object): - """Setup base class for data.""" - + """Representation of a Demo Calendar element.""" + # pylint: disable=no-self-use def update(self): """Return true so entity knows we have new data.""" @@ -36,7 +36,7 @@ class DemoGoogleCalendarData(object): class DemoGoogleCalendarDataFuture(DemoGoogleCalendarData): - """Setup future data event.""" + """Representation of a Demo Calendar for a future event.""" def __init__(self): """Set the event to a future event.""" @@ -55,7 +55,7 @@ class DemoGoogleCalendarDataFuture(DemoGoogleCalendarData): class DemoGoogleCalendarDataCurrent(DemoGoogleCalendarData): - """Create a current event we're in the middle of.""" + """Representation of a Demo Calendar for a current event.""" def __init__(self): """Set the event data.""" @@ -74,9 +74,9 @@ class DemoGoogleCalendarDataCurrent(DemoGoogleCalendarData): class DemoGoogleCalendar(CalendarEventDevice): - """A Demo binary sensor.""" + """Representation of a Demo Calendar element.""" def __init__(self, hass, calendar_data, data): - """The same as a google calendar but without the api calls.""" + """The same as a google calendar but without the API calls.""" self.data = calendar_data super().__init__(hass, data) diff --git a/homeassistant/components/calendar/google.py b/homeassistant/components/calendar/google.py index 8f9de90a1b1..8a2e77d1915 100644 --- a/homeassistant/components/calendar/google.py +++ b/homeassistant/components/calendar/google.py @@ -9,25 +9,24 @@ import logging from datetime import timedelta from homeassistant.components.calendar import CalendarEventDevice -from homeassistant.components.google import (CONF_CAL_ID, CONF_ENTITIES, - CONF_TRACK, TOKEN_FILE, - GoogleCalendarService) +from homeassistant.components.google import ( + CONF_CAL_ID, CONF_ENTITIES, CONF_TRACK, TOKEN_FILE, + GoogleCalendarService) from homeassistant.util import Throttle, dt +_LOGGER = logging.getLogger(__name__) + DEFAULT_GOOGLE_SEARCH_PARAMS = { 'orderBy': 'startTime', 'maxResults': 1, 'singleEvents': True, } -# Return cached results if last scan was less then this time ago MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) -_LOGGER = logging.getLogger(__name__) - def setup_platform(hass, config, add_devices, disc_info=None): - """Setup the calendar platform for event devices.""" + """Set up the calendar platform for event devices.""" if disc_info is None: return diff --git a/homeassistant/components/camera/__init__.py b/homeassistant/components/camera/__init__.py index 388a9fce39b..f6238d6ae23 100644 --- a/homeassistant/components/camera/__init__.py +++ b/homeassistant/components/camera/__init__.py @@ -76,7 +76,7 @@ def async_get_image(hass, entity_id, timeout=10): @asyncio.coroutine def async_setup(hass, config): - """Setup the camera component.""" + """Set up the camera component.""" component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL) hass.http.register_view(CameraImageView(component.entities)) @@ -121,12 +121,12 @@ class Camera(Entity): @property def brand(self): - """Camera brand.""" + """Return the camera brand.""" return None @property def model(self): - """Camera model.""" + """Return the camera model.""" return None def camera_image(self): @@ -191,7 +191,7 @@ class Camera(Entity): @property def state(self): - """Camera state.""" + """Return the camera state.""" if self.is_recording: return STATE_RECORDING elif self.is_streaming: @@ -201,7 +201,7 @@ class Camera(Entity): @property def state_attributes(self): - """Camera state attributes.""" + """Return the camera state attributes.""" attr = { 'access_token': self.access_tokens[-1], } @@ -233,7 +233,7 @@ class CameraView(HomeAssistantView): @asyncio.coroutine def get(self, request, entity_id): - """Start a get request.""" + """Start a GET request.""" camera = self.entities.get(entity_id) if camera is None: @@ -251,15 +251,15 @@ class CameraView(HomeAssistantView): @asyncio.coroutine def handle(self, request, camera): - """Hanlde the camera request.""" + """Handle the camera request.""" raise NotImplementedError() class CameraImageView(CameraView): """Camera view to serve an image.""" - url = "/api/camera_proxy/{entity_id}" - name = "api:camera:image" + url = '/api/camera_proxy/{entity_id}' + name = 'api:camera:image' @asyncio.coroutine def handle(self, request, camera): @@ -277,8 +277,8 @@ class CameraImageView(CameraView): class CameraMjpegStream(CameraView): """Camera View to serve an MJPEG stream.""" - url = "/api/camera_proxy_stream/{entity_id}" - name = "api:camera:stream" + url = '/api/camera_proxy_stream/{entity_id}' + name = 'api:camera:stream' @asyncio.coroutine def handle(self, request, camera): diff --git a/homeassistant/components/camera/blink.py b/homeassistant/components/camera/blink.py index 59616b0ded2..bca4fafec4f 100644 --- a/homeassistant/components/camera/blink.py +++ b/homeassistant/components/camera/blink.py @@ -21,7 +21,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup a Blink Camera.""" + """Set up a Blink Camera.""" if discovery_info is None: return @@ -49,19 +49,19 @@ class BlinkCamera(Camera): @property def name(self): - """A camera name.""" + """Return the camera name.""" return self._name @Throttle(MIN_TIME_BETWEEN_UPDATES) def request_image(self): - """An image request from Blink servers.""" + """Request a new image from Blink servers.""" _LOGGER.info("Requesting new image from blink servers") image_url = self.check_for_motion() header = self.data.cameras[self._name].header self.response = requests.get(image_url, headers=header, stream=True) def check_for_motion(self): - """A method to check if motion has been detected since last update.""" + """Check if motion has been detected since last update.""" self.data.refresh() notifs = self.data.cameras[self._name].notifications if notifs > self.notifications: diff --git a/homeassistant/components/camera/bloomsky.py b/homeassistant/components/camera/bloomsky.py index 7137c73c299..c3b4775b593 100644 --- a/homeassistant/components/camera/bloomsky.py +++ b/homeassistant/components/camera/bloomsky.py @@ -16,7 +16,7 @@ DEPENDENCIES = ['bloomsky'] # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup access to BloomSky cameras.""" + """Set up access to BloomSky cameras.""" bloomsky = get_component('bloomsky') for device in bloomsky.BLOOMSKY.devices.values(): add_devices([BloomSkyCamera(bloomsky.BLOOMSKY, device)]) @@ -26,14 +26,14 @@ class BloomSkyCamera(Camera): """Representation of the images published from the BloomSky's camera.""" def __init__(self, bs, device): - """Setup for access to the BloomSky camera images.""" + """Initialize access to the BloomSky camera images.""" super(BloomSkyCamera, self).__init__() self._name = device['DeviceName'] self._id = device['DeviceID'] self._bloomsky = bs self._url = "" self._last_url = "" - # _last_image will store images as they are downloaded so that the + # last_image will store images as they are downloaded so that the # frequent updates in home-assistant don't keep poking the server # to download the same image over and over. self._last_image = "" diff --git a/homeassistant/components/camera/demo.py b/homeassistant/components/camera/demo.py index 5e451c48b40..158f6c11751 100644 --- a/homeassistant/components/camera/demo.py +++ b/homeassistant/components/camera/demo.py @@ -11,7 +11,7 @@ from homeassistant.components.camera import Camera def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo camera platform.""" + """Set up the Demo camera platform.""" add_devices([ DemoCamera('Demo camera') ]) @@ -29,8 +29,8 @@ class DemoCamera(Camera): """Return a faked still image response.""" now = dt_util.utcnow() - image_path = os.path.join(os.path.dirname(__file__), - 'demo_{}.jpg'.format(now.second % 4)) + image_path = os.path.join( + os.path.dirname(__file__), 'demo_{}.jpg'.format(now.second % 4)) with open(image_path, 'rb') as file: return file.read() diff --git a/homeassistant/components/camera/ffmpeg.py b/homeassistant/components/camera/ffmpeg.py index d4c7b54fc7f..8ca72a09261 100644 --- a/homeassistant/components/camera/ffmpeg.py +++ b/homeassistant/components/camera/ffmpeg.py @@ -16,10 +16,10 @@ from homeassistant.components.ffmpeg import ( import homeassistant.helpers.config_validation as cv from homeassistant.helpers.aiohttp_client import ( async_aiohttp_proxy_stream) -DEPENDENCIES = ['ffmpeg'] _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['ffmpeg'] DEFAULT_NAME = 'FFmpeg' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -31,7 +31,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup a FFmpeg Camera.""" + """Set up a FFmpeg camera.""" if not hass.data[DATA_FFMPEG].async_run_test(config.get(CONF_INPUT)): return async_add_devices([FFmpegCamera(hass, config)]) diff --git a/homeassistant/components/camera/foscam.py b/homeassistant/components/camera/foscam.py index c1f9513d2c6..86061aa3d1d 100644 --- a/homeassistant/components/camera/foscam.py +++ b/homeassistant/components/camera/foscam.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 a Foscam IP Camera.""" + """Set up a Foscam IP Camera.""" add_devices([FoscamCamera(config)]) @@ -60,7 +60,7 @@ class FoscamCamera(Camera): ) self._name = device_info.get(CONF_NAME) - _LOGGER.info('Using the following URL for %s: %s', + _LOGGER.info("Using the following URL for %s: %s", self._name, uri_template.format('***', '***')) def camera_image(self): diff --git a/homeassistant/components/camera/generic.py b/homeassistant/components/camera/generic.py index a330836f32b..83164c55230 100644 --- a/homeassistant/components/camera/generic.py +++ b/homeassistant/components/camera/generic.py @@ -43,7 +43,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 a generic IP Camera.""" + """Set up a generic IP Camera.""" async_add_devices([GenericCamera(hass, config)]) @@ -85,8 +85,8 @@ class GenericCamera(Camera): try: url = self._still_image_url.async_render() except TemplateError as err: - _LOGGER.error('Error parsing template %s: %s', - self._still_image_url, err) + _LOGGER.error( + "Error parsing template %s: %s", self._still_image_url, err) return self._last_image if url == self._last_url and self._limit_refetch: @@ -100,7 +100,7 @@ class GenericCamera(Camera): response = requests.get(url, timeout=10, auth=self._auth) return response.content except requests.exceptions.RequestException as error: - _LOGGER.error('Error getting camera image: %s', error) + _LOGGER.error("Error getting camera image: %s", error) return self._last_image self._last_image = yield from self.hass.loop.run_in_executor( @@ -114,10 +114,10 @@ class GenericCamera(Camera): url, auth=self._auth) self._last_image = yield from response.read() except asyncio.TimeoutError: - _LOGGER.error('Timeout getting camera image') + _LOGGER.error("Timeout getting camera image") return self._last_image except aiohttp.ClientError as err: - _LOGGER.error('Error getting new camera image: %s', err) + _LOGGER.error("Error getting new camera image: %s", err) return self._last_image self._last_url = url diff --git a/homeassistant/components/camera/local_file.py b/homeassistant/components/camera/local_file.py index 85438820393..1f3a71c9d05 100644 --- a/homeassistant/components/camera/local_file.py +++ b/homeassistant/components/camera/local_file.py @@ -26,7 +26,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Camera.""" + """Set up the Camera that works with local files.""" file_path = config[CONF_FILE_PATH] # check filepath given is readable @@ -38,7 +38,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class LocalFile(Camera): - """Local camera.""" + """Representation of a local file camera.""" def __init__(self, name, file_path): """Initialize Local File Camera component.""" diff --git a/homeassistant/components/camera/mjpeg.py b/homeassistant/components/camera/mjpeg.py index a158c36152e..1e9859fe7c2 100644 --- a/homeassistant/components/camera/mjpeg.py +++ b/homeassistant/components/camera/mjpeg.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 a MJPEG IP Camera.""" + """Set up a MJPEG IP Camera.""" if discovery_info: config = PLATFORM_SCHEMA(discovery_info) async_add_devices([MjpegCamera(hass, config)]) @@ -102,10 +102,10 @@ class MjpegCamera(Camera): return image except asyncio.TimeoutError: - _LOGGER.error('Timeout getting camera image') + _LOGGER.error("Timeout getting camera image") except aiohttp.ClientError as err: - _LOGGER.error('Error getting new camera image: %s', err) + _LOGGER.error("Error getting new camera image: %s", err) def camera_image(self): """Return a still image response from the camera.""" diff --git a/homeassistant/components/camera/mqtt.py b/homeassistant/components/camera/mqtt.py index 39fbdc7fd9f..8d72ec35a28 100755 --- a/homeassistant/components/camera/mqtt.py +++ b/homeassistant/components/camera/mqtt.py @@ -32,17 +32,17 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Camera.""" + """Set up the MQTT Camera.""" topic = config[CONF_TOPIC] async_add_devices([MqttCamera(config[CONF_NAME], topic)]) class MqttCamera(Camera): - """MQTT camera.""" + """representation of a MQTT camera.""" def __init__(self, name, topic): - """Initialize Local File Camera component.""" + """Initialize the MQTT Camera.""" super().__init__() self._name = name @@ -61,13 +61,13 @@ class MqttCamera(Camera): return self._name def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe 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.""" self._last_image = payload return mqtt.async_subscribe( diff --git a/homeassistant/components/camera/neato.py b/homeassistant/components/camera/neato.py index d6eafc36859..33bd00caa6b 100644 --- a/homeassistant/components/camera/neato.py +++ b/homeassistant/components/camera/neato.py @@ -1,5 +1,5 @@ """ -Camera that loads a picture from a local file. +Camera that loads a picture from Neato. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/camera.neato/ @@ -18,12 +18,12 @@ DEPENDENCIES = ['neato'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Camera.""" + """Set up the Neato Camera.""" dev = [] for robot in hass.data[NEATO_ROBOTS]: if 'maps' in robot.traits: dev.append(NeatoCleaningMap(hass, robot)) - _LOGGER.debug('Adding robots for cleaning maps %s', dev) + _LOGGER.debug("Adding robots for cleaning maps %s", dev) add_devices(dev, True) @@ -34,7 +34,7 @@ class NeatoCleaningMap(Camera): """Initialize Neato cleaning map.""" super().__init__() self.robot = robot - self._robot_name = self.robot.name + ' Cleaning Map' + self._robot_name = '{} {}'.format(self.robot.name, 'Cleaning Map') self._robot_serial = self.robot.serial self.neato = hass.data[NEATO_LOGIN] self._image_url = None @@ -53,7 +53,7 @@ class NeatoCleaningMap(Camera): map_data = self.hass.data[NEATO_MAP_DATA] image_url = map_data[self._robot_serial]['maps'][0]['url'] if image_url == self._image_url: - _LOGGER.debug('The map image_url is the same as old') + _LOGGER.debug("The map image_url is the same as old") return image = self.neato.download_map(image_url) self._image = image.read() diff --git a/homeassistant/components/camera/netatmo.py b/homeassistant/components/camera/netatmo.py index 6ede7c5a162..7185d14e54d 100644 --- a/homeassistant/components/camera/netatmo.py +++ b/homeassistant/components/camera/netatmo.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 access to Netatmo cameras.""" + """Set up access to Netatmo cameras.""" netatmo = get_component('netatmo') home = config.get(CONF_HOME) verify_ssl = config.get(CONF_VERIFY_SSL, True) @@ -64,10 +64,10 @@ class NetatmoCamera(Camera): self._name = home + ' / ' + camera_name else: self._name = camera_name - camera_id = data.camera_data.cameraByName(camera=camera_name, - home=home)['id'] - self._unique_id = "Welcome_camera {0} - {1}".format(self._name, - camera_id) + camera_id = data.camera_data.cameraByName( + camera=camera_name, home=home)['id'] + self._unique_id = "Welcome_camera {0} - {1}".format( + self._name, camera_id) self._vpnurl, self._localurl = self._data.camera_data.cameraUrls( camera=camera_name ) @@ -83,13 +83,13 @@ class NetatmoCamera(Camera): response = requests.get('{0}/live/snapshot_720.jpg'.format( self._vpnurl), timeout=10, verify=self._verify_ssl) else: - _LOGGER.error('Welcome VPN url is None') + _LOGGER.error("Welcome VPN URL is None") self._data.update() (self._vpnurl, self._localurl) = \ self._data.camera_data.cameraUrls(camera=self._camera_name) return None except requests.exceptions.RequestException as error: - _LOGGER.error('Welcome url changed: %s', error) + _LOGGER.error("Welcome URL changed: %s", error) self._data.update() (self._vpnurl, self._localurl) = \ self._data.camera_data.cameraUrls(camera=self._camera_name) @@ -103,12 +103,12 @@ class NetatmoCamera(Camera): @property def brand(self): - """Camera brand.""" + """Return the camera brand.""" return "Netatmo" @property def model(self): - """Camera model.""" + """Return the camera model.""" if self._cameratype == "NOC": return "Presence" elif self._cameratype == "NACamera": diff --git a/homeassistant/components/camera/rpi_camera.py b/homeassistant/components/camera/rpi_camera.py index b42c62e56d0..6e3d3622a3f 100644 --- a/homeassistant/components/camera/rpi_camera.py +++ b/homeassistant/components/camera/rpi_camera.py @@ -62,7 +62,7 @@ def kill_raspistill(*args): def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Raspberry Camera.""" + """Set up the Raspberry Camera.""" if shutil.which("raspistill") is None: _LOGGER.error("'raspistill' was not found") return False diff --git a/homeassistant/components/camera/synology.py b/homeassistant/components/camera/synology.py index 378d75ac26d..de61535b336 100644 --- a/homeassistant/components/camera/synology.py +++ b/homeassistant/components/camera/synology.py @@ -59,7 +59,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup a Synology IP Camera.""" + """Set up a Synology IP Camera.""" verify_ssl = config.get(CONF_VERIFY_SSL) timeout = config.get(CONF_TIMEOUT) websession_init = async_get_clientsession(hass, verify_ssl) @@ -140,16 +140,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): snapshot_path = camera['snapshot_path'] device = SynologyCamera( - hass, - websession, - config, - camera_id, - camera['name'], - snapshot_path, - streaming_path, - camera_path, - auth_path, - timeout + hass, websession, config, camera_id, camera['name'], + snapshot_path, streaming_path, camera_path, auth_path, timeout ) devices.append(device) diff --git a/homeassistant/components/camera/uvc.py b/homeassistant/components/camera/uvc.py index c5252209996..3840a8a90b1 100644 --- a/homeassistant/components/camera/uvc.py +++ b/homeassistant/components/camera/uvc.py @@ -41,13 +41,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: cameras = nvrconn.index() except nvr.NotAuthorized: - _LOGGER.error('Authorization failure while connecting to NVR') + _LOGGER.error("Authorization failure while connecting to NVR") return False except nvr.NvrError: - _LOGGER.error('NVR refuses to talk to me') + _LOGGER.error("NVR refuses to talk to me") return False except requests.exceptions.ConnectionError as ex: - _LOGGER.error('Unable to connect to NVR: %s', str(ex)) + _LOGGER.error("Unable to connect to NVR: %s", str(ex)) return False identifier = nvrconn.server_version >= (3, 2, 0) and 'id' or 'uuid' @@ -113,7 +113,7 @@ class UnifiVideoCamera(Camera): store = uvc_store.get_info_store() password = store.get_camera_password(self._uuid) if password is None: - _LOGGER.debug('Logging into camera %(name)s with default password', + _LOGGER.debug("Logging into camera %(name)s with default password", dict(name=self._name)) password = 'ubnt' @@ -125,11 +125,10 @@ class UnifiVideoCamera(Camera): camera = None for addr in addrs: try: - camera = client_cls(addr, - caminfo['username'], - password) + camera = client_cls( + addr, caminfo['username'], password) camera.login() - _LOGGER.debug('Logged into UVC camera %(name)s via %(addr)s', + _LOGGER.debug("Logged into UVC camera %(name)s via %(addr)s", dict(name=self._name, addr=addr)) self._connect_addr = addr break @@ -140,7 +139,7 @@ class UnifiVideoCamera(Camera): except uvc_camera.CameraAuthError: pass if not self._connect_addr: - _LOGGER.error('Unable to login to camera') + _LOGGER.error("Unable to login to camera") return None self._camera = camera @@ -157,14 +156,14 @@ class UnifiVideoCamera(Camera): try: return self._camera.get_snapshot() except uvc_camera.CameraConnectError: - _LOGGER.error('Unable to contact camera') + _LOGGER.error("Unable to contact camera") except uvc_camera.CameraAuthError: if retry: self._login() return _get_image(retry=False) else: - _LOGGER.error('Unable to log into camera, unable ' - 'to get snapshot') + _LOGGER.error( + "Unable to log into camera, unable to get snapshot") raise return _get_image() diff --git a/homeassistant/components/camera/verisure.py b/homeassistant/components/camera/verisure.py index 6e613b72298..1c2e7e382fe 100644 --- a/homeassistant/components/camera/verisure.py +++ b/homeassistant/components/camera/verisure.py @@ -17,7 +17,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Camera.""" + """Set up the Verisure Camera.""" if not int(hub.config.get(CONF_SMARTCAM, 1)): return False directory_path = hass.config.config_dir @@ -33,7 +33,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class VerisureSmartcam(Camera): - """Local camera.""" + """Representation of a Verisure camera.""" def __init__(self, hass, device_id, directory_path): """Initialize Verisure File Camera component.""" @@ -50,9 +50,9 @@ class VerisureSmartcam(Camera): """Return image response.""" self.check_imagelist() if not self._image: - _LOGGER.debug('No image to display') + _LOGGER.debug("No image to display") return - _LOGGER.debug('Trying to open %s', self._image) + _LOGGER.debug("Trying to open %s", self._image) with open(self._image, 'rb') as file: return file.read() @@ -64,35 +64,30 @@ class VerisureSmartcam(Camera): return images = hub.smartcam_dict[self._device_id] new_image_id = images[0] - _LOGGER.debug('self._device_id=%s, self._images=%s, ' - 'self._new_image_id=%s', self._device_id, + _LOGGER.debug("self._device_id=%s, self._images=%s, " + "self._new_image_id=%s", self._device_id, images, new_image_id) if (new_image_id == '-1' or self._image_id == new_image_id): - _LOGGER.debug('The image is the same, or loading image_id') + _LOGGER.debug("The image is the same, or loading image_id") return - _LOGGER.debug('Download new image %s', new_image_id) - hub.my_pages.smartcam.download_image(self._device_id, - new_image_id, - self._directory_path) - _LOGGER.debug('Old image_id=%s', self._image_id) + _LOGGER.debug("Download new image %s", new_image_id) + hub.my_pages.smartcam.download_image( + self._device_id, new_image_id, self._directory_path) + _LOGGER.debug("Old image_id=%s", self._image_id) self.delete_image(self) self._image_id = new_image_id - self._image = os.path.join(self._directory_path, - '{}{}'.format( - self._image_id, - '.jpg')) + self._image = os.path.join( + self._directory_path, '{}{}'.format(self._image_id, '.jpg')) def delete_image(self, event): """Delete an old image.""" - remove_image = os.path.join(self._directory_path, - '{}{}'.format( - self._image_id, - '.jpg')) + remove_image = os.path.join( + self._directory_path, '{}{}'.format(self._image_id, '.jpg')) try: os.remove(remove_image) - _LOGGER.debug('Deleting old image %s', remove_image) + _LOGGER.debug("Deleting old image %s", remove_image) except OSError as error: if error.errno != errno.ENOENT: raise diff --git a/homeassistant/components/camera/zoneminder.py b/homeassistant/components/camera/zoneminder.py index e419564a887..62d895d3922 100644 --- a/homeassistant/components/camera/zoneminder.py +++ b/homeassistant/components/camera/zoneminder.py @@ -51,21 +51,21 @@ def _get_image_url(hass, monitor, mode): @asyncio.coroutine # pylint: disable=unused-argument def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup ZoneMinder cameras.""" + """Set up the ZoneMinder cameras.""" cameras = [] monitors = zoneminder.get_state('api/monitors.json') if not monitors: - _LOGGER.warning('Could not fetch monitors from ZoneMinder') + _LOGGER.warning("Could not fetch monitors from ZoneMinder") return for i in monitors['monitors']: monitor = i['Monitor'] if monitor['Function'] == 'None': - _LOGGER.info('Skipping camera %s', monitor['Id']) + _LOGGER.info("Skipping camera %s", monitor['Id']) continue - _LOGGER.info('Initializing camera %s', monitor['Id']) + _LOGGER.info("Initializing camera %s", monitor['Id']) device_info = { CONF_NAME: monitor['Name'], @@ -75,7 +75,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): cameras.append(ZoneMinderCamera(hass, device_info, monitor)) if not cameras: - _LOGGER.warning('No active cameras found') + _LOGGER.warning("No active cameras found") return async_add_devices(cameras) @@ -97,18 +97,18 @@ class ZoneMinderCamera(MjpegCamera): def update(self): """Update our recording state from the ZM API.""" - _LOGGER.debug('Updating camera state for monitor %i', self._monitor_id) + _LOGGER.debug("Updating camera state for monitor %i", self._monitor_id) status_response = zoneminder.get_state( 'api/monitors/alarm/id:%i/command:status.json' % self._monitor_id ) if not status_response: - _LOGGER.warning('Could not get status for monitor %i', + _LOGGER.warning("Could not get status for monitor %i", self._monitor_id) return if status_response['success'] is False: - _LOGGER.warning('Alarm status API call failed for monitor %i', + _LOGGER.warning("Alarm status API call failed for monitor %i", self._monitor_id) return diff --git a/homeassistant/components/climate/__init__.py b/homeassistant/components/climate/__init__.py index 2a0bd2eb5c1..44cbdc99c04 100644 --- a/homeassistant/components/climate/__init__.py +++ b/homeassistant/components/climate/__init__.py @@ -23,45 +23,45 @@ from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_ON, STATE_OFF, STATE_UNKNOWN, TEMP_CELSIUS) -DOMAIN = "climate" +DOMAIN = 'climate' -ENTITY_ID_FORMAT = DOMAIN + ".{}" +ENTITY_ID_FORMAT = DOMAIN + '.{}' SCAN_INTERVAL = timedelta(seconds=60) -SERVICE_SET_AWAY_MODE = "set_away_mode" -SERVICE_SET_AUX_HEAT = "set_aux_heat" -SERVICE_SET_TEMPERATURE = "set_temperature" -SERVICE_SET_FAN_MODE = "set_fan_mode" -SERVICE_SET_HOLD_MODE = "set_hold_mode" -SERVICE_SET_OPERATION_MODE = "set_operation_mode" -SERVICE_SET_SWING_MODE = "set_swing_mode" -SERVICE_SET_HUMIDITY = "set_humidity" +SERVICE_SET_AWAY_MODE = 'set_away_mode' +SERVICE_SET_AUX_HEAT = 'set_aux_heat' +SERVICE_SET_TEMPERATURE = 'set_temperature' +SERVICE_SET_FAN_MODE = 'set_fan_mode' +SERVICE_SET_HOLD_MODE = 'set_hold_mode' +SERVICE_SET_OPERATION_MODE = 'set_operation_mode' +SERVICE_SET_SWING_MODE = 'set_swing_mode' +SERVICE_SET_HUMIDITY = 'set_humidity' -STATE_HEAT = "heat" -STATE_COOL = "cool" -STATE_IDLE = "idle" -STATE_AUTO = "auto" -STATE_DRY = "dry" -STATE_FAN_ONLY = "fan_only" +STATE_HEAT = 'heat' +STATE_COOL = 'cool' +STATE_IDLE = 'idle' +STATE_AUTO = 'auto' +STATE_DRY = 'dry' +STATE_FAN_ONLY = 'fan_only' -ATTR_CURRENT_TEMPERATURE = "current_temperature" -ATTR_MAX_TEMP = "max_temp" -ATTR_MIN_TEMP = "min_temp" -ATTR_TARGET_TEMP_HIGH = "target_temp_high" -ATTR_TARGET_TEMP_LOW = "target_temp_low" -ATTR_AWAY_MODE = "away_mode" -ATTR_AUX_HEAT = "aux_heat" -ATTR_FAN_MODE = "fan_mode" -ATTR_FAN_LIST = "fan_list" -ATTR_CURRENT_HUMIDITY = "current_humidity" -ATTR_HUMIDITY = "humidity" -ATTR_MAX_HUMIDITY = "max_humidity" -ATTR_MIN_HUMIDITY = "min_humidity" -ATTR_HOLD_MODE = "hold_mode" -ATTR_OPERATION_MODE = "operation_mode" -ATTR_OPERATION_LIST = "operation_list" -ATTR_SWING_MODE = "swing_mode" -ATTR_SWING_LIST = "swing_list" +ATTR_CURRENT_TEMPERATURE = 'current_temperature' +ATTR_MAX_TEMP = 'max_temp' +ATTR_MIN_TEMP = 'min_temp' +ATTR_TARGET_TEMP_HIGH = 'target_temp_high' +ATTR_TARGET_TEMP_LOW = 'target_temp_low' +ATTR_AWAY_MODE = 'away_mode' +ATTR_AUX_HEAT = 'aux_heat' +ATTR_FAN_MODE = 'fan_mode' +ATTR_FAN_LIST = 'fan_list' +ATTR_CURRENT_HUMIDITY = 'current_humidity' +ATTR_HUMIDITY = 'humidity' +ATTR_MAX_HUMIDITY = 'max_humidity' +ATTR_MIN_HUMIDITY = 'min_humidity' +ATTR_HOLD_MODE = 'hold_mode' +ATTR_OPERATION_MODE = 'operation_mode' +ATTR_OPERATION_LIST = 'operation_list' +ATTR_SWING_MODE = 'swing_mode' +ATTR_SWING_LIST = 'swing_list' # The degree of precision for each platform PRECISION_WHOLE = 1 @@ -273,7 +273,7 @@ def async_setup(hass, config): @asyncio.coroutine def async_aux_heat_set_service(service): - """Set auxillary heater on target climate devices.""" + """Set auxiliary heater on target climate devices.""" target_climate = component.async_extract_from_service(service) aux_heat = service.data.get(ATTR_AUX_HEAT) @@ -467,12 +467,12 @@ class ClimateDevice(Entity): @property def unit_of_measurement(self): - """The unit of measurement to display.""" + """Return the unit of measurement to display.""" return self.hass.config.units.temperature_unit @property def temperature_unit(self): - """The unit of measurement used by the platform.""" + """Return the unit of measurement used by the platform.""" raise NotImplementedError @property @@ -492,7 +492,7 @@ class ClimateDevice(Entity): @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" return None @property @@ -537,7 +537,7 @@ class ClimateDevice(Entity): @property def fan_list(self): - """List of available fan modes.""" + """Return the list of available fan modes.""" return None @property @@ -547,7 +547,7 @@ class ClimateDevice(Entity): @property def swing_list(self): - """List of available swing modes.""" + """Return the list of available swing modes.""" return None def set_temperature(self, **kwargs): @@ -695,8 +695,8 @@ class ClimateDevice(Entity): if temp is None or not isinstance(temp, Number): return temp if self.temperature_unit != self.unit_of_measurement: - temp = convert_temperature(temp, self.temperature_unit, - self.unit_of_measurement) + temp = convert_temperature( + temp, self.temperature_unit, self.unit_of_measurement) # Round in the units appropriate if self.precision == PRECISION_HALVES: return round(temp * 2) / 2.0 diff --git a/homeassistant/components/climate/demo.py b/homeassistant/components/climate/demo.py index 9830daff69c..24b40af7eb1 100644 --- a/homeassistant/components/climate/demo.py +++ b/homeassistant/components/climate/demo.py @@ -10,14 +10,14 @@ from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo climate devices.""" + """Set up the Demo climate devices.""" add_devices([ - DemoClimate("HeatPump", 68, TEMP_FAHRENHEIT, None, None, 77, - "Auto Low", None, None, "Auto", "heat", None, None, None), - DemoClimate("Hvac", 21, TEMP_CELSIUS, True, None, 22, "On High", - 67, 54, "Off", "cool", False, None, None), - DemoClimate("Ecobee", None, TEMP_CELSIUS, None, None, 23, "Auto Low", - None, None, "Auto", "auto", None, 24, 21) + DemoClimate('HeatPump', 68, TEMP_FAHRENHEIT, None, None, 77, + 'Auto Low', None, None, 'Auto', 'heat', None, None, None), + DemoClimate('Hvac', 21, TEMP_CELSIUS, True, None, 22, 'On High', + 67, 54, 'Off', 'cool', False, None, None), + DemoClimate('Ecobee', None, TEMP_CELSIUS, None, None, 23, 'Auto Low', + None, None, 'Auto', 'auto', None, 24, 21) ]) @@ -41,15 +41,15 @@ class DemoClimate(ClimateDevice): self._current_operation = current_operation self._aux = aux self._current_swing_mode = current_swing_mode - self._fan_list = ["On Low", "On High", "Auto Low", "Auto High", "Off"] - self._operation_list = ["heat", "cool", "auto", "off"] - self._swing_list = ["Auto", "1", "2", "3", "Off"] + self._fan_list = ['On Low', 'On High', 'Auto Low', 'Auto High', 'Off'] + self._operation_list = ['heat', 'cool', 'auto', 'off'] + self._swing_list = ['Auto', '1', '2', '3', 'Off'] self._target_temperature_high = target_temp_high self._target_temperature_low = target_temp_low @property def should_poll(self): - """Polling not needed for a demo climate device.""" + """Return the polling state.""" return False @property @@ -99,7 +99,7 @@ class DemoClimate(ClimateDevice): @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" return self._operation_list @property @@ -124,7 +124,7 @@ class DemoClimate(ClimateDevice): @property def fan_list(self): - """List of available fan modes.""" + """Return the list of available fan modes.""" return self._fan_list def set_temperature(self, **kwargs): diff --git a/homeassistant/components/climate/ecobee.py b/homeassistant/components/climate/ecobee.py index 17155ffa791..9e04013d53f 100644 --- a/homeassistant/components/climate/ecobee.py +++ b/homeassistant/components/climate/ecobee.py @@ -45,7 +45,7 @@ RESUME_PROGRAM_SCHEMA = vol.Schema({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Ecobee Thermostat Platform.""" + """Set up the Ecobee Thermostat Platform.""" if discovery_info is None: return data = ecobee.NETWORK @@ -197,19 +197,19 @@ class Thermostat(ClimateDevice): if event['holdClimateRef'] == 'away': if int(event['endDate'][0:4]) - \ int(event['startDate'][0:4]) <= 1: - # a temporary hold from away climate is a hold + # A temporary hold from away climate is a hold return 'away' else: - # a premanent hold from away climate is away_mode + # A permanent hold from away climate is away_mode return None elif event['holdClimateRef'] != "": - # any other hold based on climate + # Any other hold based on climate return event['holdClimateRef'] else: - # any hold not based on a climate is a temp hold + # Any hold not based on a climate is a temp hold return TEMPERATURE_HOLD elif event['type'].startswith('auto'): - # all auto modes are treated as holds + # All auto modes are treated as holds return event['type'][4:].lower() elif event['type'] == 'vacation': self.vacation = event['name'] @@ -300,17 +300,16 @@ class Thermostat(ClimateDevice): return elif hold_mode == 'None' or hold_mode is None: if hold == VACATION_HOLD: - self.data.ecobee.delete_vacation(self.thermostat_index, - self.vacation) + self.data.ecobee.delete_vacation( + self.thermostat_index, self.vacation) else: self.data.ecobee.resume_program(self.thermostat_index) else: if hold_mode == TEMPERATURE_HOLD: self.set_temp_hold(int(self.current_temperature)) else: - self.data.ecobee.set_climate_hold(self.thermostat_index, - hold_mode, - self.hold_preference()) + self.data.ecobee.set_climate_hold( + self.thermostat_index, hold_mode, self.hold_preference()) self.update_without_throttle = True def set_auto_temp_hold(self, heat_temp, cool_temp): @@ -356,7 +355,7 @@ class Thermostat(ClimateDevice): self.set_temp_hold(int(temp)) else: _LOGGER.error( - 'Missing valid arguments for set_temperature in %s', kwargs) + "Missing valid arguments for set_temperature in %s", kwargs) def set_operation_mode(self, operation_mode): """Set HVAC mode (auto, auxHeatOnly, cool, heat, off).""" @@ -365,14 +364,14 @@ class Thermostat(ClimateDevice): def set_fan_min_on_time(self, fan_min_on_time): """Set the minimum fan on time.""" - self.data.ecobee.set_fan_min_on_time(self.thermostat_index, - fan_min_on_time) + self.data.ecobee.set_fan_min_on_time( + self.thermostat_index, fan_min_on_time) self.update_without_throttle = True def resume_program(self, resume_all): """Resume the thermostat schedule program.""" - self.data.ecobee.resume_program(self.thermostat_index, - str(resume_all).lower()) + self.data.ecobee.resume_program( + self.thermostat_index, str(resume_all).lower()) self.update_without_throttle = True def hold_preference(self): diff --git a/homeassistant/components/climate/eq3btsmart.py b/homeassistant/components/climate/eq3btsmart.py index 7e0712647ea..ff13dd48cac 100644 --- a/homeassistant/components/climate/eq3btsmart.py +++ b/homeassistant/components/climate/eq3btsmart.py @@ -21,15 +21,15 @@ REQUIREMENTS = ['python-eq3bt==0.1.5'] _LOGGER = logging.getLogger(__name__) -STATE_BOOST = "boost" -STATE_AWAY = "away" -STATE_MANUAL = "manual" +STATE_BOOST = 'boost' +STATE_AWAY = 'away' +STATE_MANUAL = 'manual' -ATTR_STATE_WINDOW_OPEN = "window_open" -ATTR_STATE_VALVE = "valve" -ATTR_STATE_LOCKED = "is_locked" -ATTR_STATE_LOW_BAT = "low_battery" -ATTR_STATE_AWAY_END = "away_end" +ATTR_STATE_WINDOW_OPEN = 'window_open' +ATTR_STATE_VALVE = 'valve' +ATTR_STATE_LOCKED = 'is_locked' +ATTR_STATE_LOW_BAT = 'low_battery' +ATTR_STATE_AWAY_END = 'away_end' DEVICE_SCHEMA = vol.Schema({ vol.Required(CONF_MAC): cv.string, @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the eQ-3 BLE thermostats.""" + """Set up the eQ-3 BLE thermostats.""" devices = [] for name, device_cfg in config[CONF_DEVICES].items(): @@ -112,14 +112,14 @@ class EQ3BTSmartThermostat(ClimateDevice): @property def current_operation(self): - """Current mode.""" + """Return the current operation mode.""" if self._thermostat.mode < 0: return None return self.modes[self._thermostat.mode] @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" return [x for x in self.modes.values()] def set_operation_mode(self, operation_mode): diff --git a/homeassistant/components/climate/generic_thermostat.py b/homeassistant/components/climate/generic_thermostat.py index 4fc667a5326..11400466c4f 100644 --- a/homeassistant/components/climate/generic_thermostat.py +++ b/homeassistant/components/climate/generic_thermostat.py @@ -14,7 +14,8 @@ from homeassistant.components import switch from homeassistant.components.climate import ( STATE_HEAT, STATE_COOL, STATE_IDLE, ClimateDevice, PLATFORM_SCHEMA) from homeassistant.const import ( - ATTR_UNIT_OF_MEASUREMENT, STATE_ON, STATE_OFF, ATTR_TEMPERATURE) + ATTR_UNIT_OF_MEASUREMENT, STATE_ON, STATE_OFF, ATTR_TEMPERATURE, + CONF_NAME) from homeassistant.helpers import condition from homeassistant.helpers.event import ( async_track_state_change, async_track_time_interval) @@ -27,7 +28,6 @@ DEPENDENCIES = ['switch', 'sensor'] DEFAULT_TOLERANCE = 0.3 DEFAULT_NAME = 'Generic Thermostat' -CONF_NAME = 'name' CONF_HEATER = 'heater' CONF_SENSOR = 'target_sensor' CONF_MIN_TEMP = 'min_temp' @@ -56,7 +56,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the generic thermostat.""" + """Set up the generic thermostat platform.""" name = config.get(CONF_NAME) heater_entity_id = config.get(CONF_HEATER) sensor_entity_id = config.get(CONF_SENSOR) @@ -74,7 +74,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class GenericThermostat(ClimateDevice): - """Representation of a GenericThermostat device.""" + """Representation of a Generic Thermostat device.""" def __init__(self, hass, name, heater_entity_id, sensor_entity_id, min_temp, max_temp, target_temp, ac_mode, min_cycle_duration, @@ -110,7 +110,7 @@ class GenericThermostat(ClimateDevice): @property def should_poll(self): - """No polling needed.""" + """Return the polling state.""" return False @property @@ -175,7 +175,7 @@ class GenericThermostat(ClimateDevice): @asyncio.coroutine def _async_sensor_changed(self, entity_id, old_state, new_state): - """Called when temperature changes.""" + """Handle temperature changes.""" if new_state is None: return @@ -185,14 +185,14 @@ class GenericThermostat(ClimateDevice): @callback def _async_switch_changed(self, entity_id, old_state, new_state): - """Called when heater switch changes state.""" + """Handle heater switch state changes.""" if new_state is None: return self.hass.async_add_job(self.async_update_ha_state()) @callback def _async_keep_alive(self, time): - """Called at constant intervals for keep-alive purposes.""" + """Call at constant intervals for keep-alive purposes.""" if self.current_operation in [STATE_COOL, STATE_HEAT]: switch.async_turn_on(self.hass, self.heater_entity_id) else: diff --git a/homeassistant/components/climate/heatmiser.py b/homeassistant/components/climate/heatmiser.py index 28d419597d3..56015ebeb5a 100644 --- a/homeassistant/components/climate/heatmiser.py +++ b/homeassistant/components/climate/heatmiser.py @@ -35,7 +35,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-variable def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the heatmiser thermostat.""" + """Set up the heatmiser thermostat.""" from heatmiserV3 import heatmiser, connection ipaddress = config.get(CONF_IPADDRESS) diff --git a/homeassistant/components/climate/homematic.py b/homeassistant/components/climate/homematic.py index 7385eeac98a..1f9ca7c1abf 100644 --- a/homeassistant/components/climate/homematic.py +++ b/homeassistant/components/climate/homematic.py @@ -14,17 +14,17 @@ DEPENDENCIES = ['homematic'] _LOGGER = logging.getLogger(__name__) -STATE_MANUAL = "manual" -STATE_BOOST = "boost" -STATE_COMFORT = "comfort" -STATE_LOWERING = "lowering" +STATE_MANUAL = 'manual' +STATE_BOOST = 'boost' +STATE_COMFORT = 'comfort' +STATE_LOWERING = 'lowering' HM_STATE_MAP = { - "AUTO_MODE": STATE_AUTO, - "MANU_MODE": STATE_MANUAL, - "BOOST_MODE": STATE_BOOST, - "COMFORT_MODE": STATE_COMFORT, - "LOWERING_MODE": STATE_LOWERING + 'AUTO_MODE': STATE_AUTO, + 'MANU_MODE': STATE_MANUAL, + 'BOOST_MODE': STATE_BOOST, + 'COMFORT_MODE': STATE_COMFORT, + 'LOWERING_MODE': STATE_LOWERING } HM_TEMP_MAP = [ @@ -41,7 +41,7 @@ HM_CONTROL_MODE = 'CONTROL_MODE' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Homematic thermostat platform.""" + """Set up the Homematic thermostat platform.""" if discovery_info is None: return @@ -76,10 +76,9 @@ class HMThermostat(HMDevice, ClimateDevice): @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" op_list = [] - # generate list for mode in self._hmdevice.ACTIONNODE: if mode in HM_STATE_MAP: op_list.append(HM_STATE_MAP.get(mode)) @@ -132,11 +131,9 @@ class HMThermostat(HMDevice, ClimateDevice): def _init_data_struct(self): """Generate a data dict (self._data) from the Homematic metadata.""" - # Add state to data dict self._state = next(iter(self._hmdevice.WRITENODE.keys())) self._data[self._state] = STATE_UNKNOWN - # support state if HM_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE: self._data[HM_CONTROL_MODE] = STATE_UNKNOWN diff --git a/homeassistant/components/climate/honeywell.py b/homeassistant/components/climate/honeywell.py index 5152519459b..94c48258bf5 100644 --- a/homeassistant/components/climate/honeywell.py +++ b/homeassistant/components/climate/honeywell.py @@ -8,13 +8,12 @@ import logging import socket import datetime -import voluptuous as vol import requests +import voluptuous as vol -from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA, - ATTR_FAN_MODE, ATTR_FAN_LIST, - ATTR_OPERATION_MODE, - ATTR_OPERATION_LIST) +from homeassistant.components.climate import ( + ClimateDevice, PLATFORM_SCHEMA, ATTR_FAN_MODE, ATTR_FAN_LIST, + ATTR_OPERATION_MODE, ATTR_OPERATION_LIST) from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE) @@ -54,7 +53,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Honeywell thermostat.""" + """Set up the Honeywell thermostat.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) region = config.get(CONF_REGION) @@ -66,7 +65,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): def _setup_round(username, password, config, add_devices): - """Setup rounding function.""" + """Set up the rounding function.""" from evohomeclient import EvohomeClient away_temp = config.get(CONF_AWAY_TEMPERATURE) @@ -87,16 +86,16 @@ def _setup_round(username, password, config, add_devices): # config will be used later def _setup_us(username, password, config, add_devices): - """Setup user.""" + """Set up the user.""" import somecomfort try: client = somecomfort.SomeComfort(username, password) except somecomfort.AuthError: - _LOGGER.error('Failed to login to honeywell account %s', username) + _LOGGER.error("Failed to login to honeywell account %s", username) return False except somecomfort.SomeComfortError as ex: - _LOGGER.error('Failed to initialize honeywell client: %s', str(ex)) + _LOGGER.error("Failed to initialize honeywell client: %s", str(ex)) return False dev_id = config.get('thermostat') @@ -199,7 +198,7 @@ class RoundThermostat(ClimateDevice): except StopIteration: _LOGGER.error("Did not receive any temperature data from the " - "evohomeclient API.") + "evohomeclient API") return self._current_temperature = data['temp'] @@ -289,7 +288,7 @@ class HoneywellUSThermostat(ClimateDevice): "setpoint_{}".format(mode), temperature) except somecomfort.SomeComfortError: - _LOGGER.error('Temperature %.1f out of range', temperature) + _LOGGER.error("Temperature %.1f out of range", temperature) @property def device_state_attributes(self): @@ -369,8 +368,8 @@ class HoneywellUSThermostat(ClimateDevice): raise exp if not self._retry(): raise exp - _LOGGER.error("SomeComfort update failed, Retrying " - "- Error: %s", exp) + _LOGGER.error( + "SomeComfort update failed, Retrying - Error: %s", exp) def _retry(self): """Recreate a new somecomfort client. @@ -380,14 +379,14 @@ class HoneywellUSThermostat(ClimateDevice): """ import somecomfort try: - self._client = somecomfort.SomeComfort(self._username, - self._password) + self._client = somecomfort.SomeComfort( + self._username, self._password) except somecomfort.AuthError: - _LOGGER.error('Failed to login to honeywell account %s', + _LOGGER.error("Failed to login to honeywell account %s", self._username) return False except somecomfort.SomeComfortError as ex: - _LOGGER.error('Failed to initialize honeywell client: %s', + _LOGGER.error("Failed to initialize honeywell client: %s", str(ex)) return False @@ -397,7 +396,7 @@ class HoneywellUSThermostat(ClimateDevice): if device.name == self._device.name] if len(devices) != 1: - _LOGGER.error('Failed to find device %s', self._device.name) + _LOGGER.error("Failed to find device %s", self._device.name) return False self._device = devices[0] diff --git a/homeassistant/components/climate/knx.py b/homeassistant/components/climate/knx.py index 888a217d90c..e399e2f3dca 100644 --- a/homeassistant/components/climate/knx.py +++ b/homeassistant/components/climate/knx.py @@ -61,7 +61,7 @@ class KNXThermostat(KNXMultiAddressDevice, ClimateDevice): @property def should_poll(self): - """Polling is needed for the KNX thermostat.""" + """Return the polling state, is needed for the KNX thermostat.""" return True @property diff --git a/homeassistant/components/climate/maxcube.py b/homeassistant/components/climate/maxcube.py index 210d159a250..9d6c1bbab5b 100644 --- a/homeassistant/components/climate/maxcube.py +++ b/homeassistant/components/climate/maxcube.py @@ -20,7 +20,7 @@ STATE_VACATION = 'vacation' def setup_platform(hass, config, add_devices, discovery_info=None): - """Iterate through all MAX! Devices and add thermostats to HASS.""" + """Iterate through all MAX! Devices and add thermostats.""" cube = hass.data[MAXCUBE_HANDLE].cube devices = [] @@ -29,9 +29,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): name = '{} {}'.format( cube.room_by_id(device.room_id).name, device.name) - # Only add thermostats and wallthermostats if cube.is_thermostat(device) or cube.is_wallthermostat(device): - # Add device to HASS devices.append(MaxCubeClimate(hass, name, device.rf_address)) if devices: @@ -52,12 +50,12 @@ class MaxCubeClimate(ClimateDevice): @property def should_poll(self): - """Polling is required.""" + """Return the polling state.""" return True @property def name(self): - """Return the name of the ClimateDevice.""" + """Return the name of the climate device.""" return self._name @property @@ -93,7 +91,7 @@ class MaxCubeClimate(ClimateDevice): @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" return self._operation_list @property @@ -148,7 +146,7 @@ class MaxCubeClimate(ClimateDevice): @staticmethod def map_mode_hass_max(operation_mode): - """Map HASS Operation Modes to MAX! Operation Modes.""" + """Map Home Assistant Operation Modes to MAX! Operation Modes.""" from maxcube.device import \ MAX_DEVICE_MODE_AUTOMATIC, \ MAX_DEVICE_MODE_MANUAL, \ @@ -170,7 +168,7 @@ class MaxCubeClimate(ClimateDevice): @staticmethod def map_mode_max_hass(mode): - """Map MAX! Operation Modes to HASS Operation Modes.""" + """Map MAX! Operation Modes to Home Assistant Operation Modes.""" from maxcube.device import \ MAX_DEVICE_MODE_AUTOMATIC, \ MAX_DEVICE_MODE_MANUAL, \ diff --git a/homeassistant/components/climate/mysensors.py b/homeassistant/components/climate/mysensors.py index 02979e75f5f..adf44a81829 100755 --- a/homeassistant/components/climate/mysensors.py +++ b/homeassistant/components/climate/mysensors.py @@ -1,8 +1,8 @@ """ -mysensors platform that offers a Climate(MySensors-HVAC) component. +MySensors platform that offers a Climate (MySensors-HVAC) component. For more details about this platform, please refer to the documentation -https://home-assistant.io/components/climate.mysensors +https://home-assistant.io/components/climate.mysensors/ """ import logging @@ -14,14 +14,22 @@ from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE _LOGGER = logging.getLogger(__name__) -DICT_HA_TO_MYS = {STATE_COOL: "CoolOn", STATE_HEAT: "HeatOn", - STATE_AUTO: "AutoChangeOver", STATE_OFF: "Off"} -DICT_MYS_TO_HA = {"CoolOn": STATE_COOL, "HeatOn": STATE_HEAT, - "AutoChangeOver": STATE_AUTO, "Off": STATE_OFF} +DICT_HA_TO_MYS = { + STATE_AUTO: 'AutoChangeOver', + STATE_COOL: 'CoolOn', + STATE_HEAT: 'HeatOn', + STATE_OFF: 'Off', +} +DICT_MYS_TO_HA = { + 'AutoChangeOver': STATE_AUTO, + 'CoolOn': STATE_COOL, + 'HeatOn': STATE_HEAT, + 'Off': STATE_OFF, +} def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors climate.""" + """Set up the mysensors climate.""" if discovery_info is None: return @@ -43,7 +51,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): - """Representation of a MySensorsHVAC hvac.""" + """Representation of a MySensors HVAC.""" @property def assumed_state(self): @@ -105,7 +113,7 @@ class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): @property def fan_list(self): """List of available fan modes.""" - return ["Auto", "Min", "Normal", "Max"] + return ['Auto', 'Min', 'Normal', 'Max'] def set_temperature(self, **kwargs): """Set new target temperature.""" @@ -140,8 +148,8 @@ class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): def set_fan_mode(self, fan): """Set new target temperature.""" set_req = self.gateway.const.SetReq - self.gateway.set_child_value(self.node_id, self.child_id, - set_req.V_HVAC_SPEED, fan) + self.gateway.set_child_value( + self.node_id, self.child_id, set_req.V_HVAC_SPEED, fan) if self.gateway.optimistic: # optimistically assume that switch has changed state self._values[set_req.V_HVAC_SPEED] = fan @@ -150,9 +158,9 @@ class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): def set_operation_mode(self, operation_mode): """Set new target temperature.""" set_req = self.gateway.const.SetReq - self.gateway.set_child_value(self.node_id, self.child_id, - set_req.V_HVAC_FLOW_STATE, - DICT_HA_TO_MYS[operation_mode]) + self.gateway.set_child_value( + self.node_id, self.child_id, set_req.V_HVAC_FLOW_STATE, + DICT_HA_TO_MYS[operation_mode]) if self.gateway.optimistic: # optimistically assume that switch has changed state self._values[set_req.V_HVAC_FLOW_STATE] = operation_mode @@ -165,7 +173,7 @@ class MySensorsHVAC(mysensors.MySensorsDeviceEntity, ClimateDevice): 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) if value_type == set_req.V_HVAC_FLOW_STATE: self._values[value_type] = DICT_MYS_TO_HA[value] else: diff --git a/homeassistant/components/climate/nest.py b/homeassistant/components/climate/nest.py index 32cae5c4cec..522a1bebb16 100644 --- a/homeassistant/components/climate/nest.py +++ b/homeassistant/components/climate/nest.py @@ -30,12 +30,10 @@ STATE_HEAT_COOL = 'heat-cool' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Nest thermostat.""" + """Set up the Nest thermostat.""" if discovery_info is None: return - _LOGGER.debug("Setting up nest thermostat") - temp_unit = hass.config.units.temperature_unit add_devices( diff --git a/homeassistant/components/climate/netatmo.py b/homeassistant/components/climate/netatmo.py index 0afc8c29bd9..cea1a41ec9f 100755 --- a/homeassistant/components/climate/netatmo.py +++ b/homeassistant/components/climate/netatmo.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_callback_devices, discovery_info=None): - """Setup the NetAtmo Thermostat.""" + """Set up the NetAtmo Thermostat.""" netatmo = get_component('netatmo') device = config.get(CONF_RELAY) @@ -150,7 +150,6 @@ class ThermostatData(object): self.current_temperature = None self.target_temperature = None self.setpoint_mode = None - # self.operation = def get_module_names(self): """Return all module available on the API as a list.""" diff --git a/homeassistant/components/climate/oem.py b/homeassistant/components/climate/oem.py index 0280f116f1e..fd43ff799db 100644 --- a/homeassistant/components/climate/oem.py +++ b/homeassistant/components/climate/oem.py @@ -19,15 +19,12 @@ from homeassistant.const import (CONF_HOST, CONF_USERNAME, CONF_PASSWORD, CONF_PORT, TEMP_CELSIUS, CONF_NAME) import homeassistant.helpers.config_validation as cv -# Home Assistant depends on 3rd party packages for API specific code. REQUIREMENTS = ['oemthermostat==1.1'] _LOGGER = logging.getLogger(__name__) -# Local configs CONF_AWAY_TEMP = 'away_temp' -# Validation of the user's configuration PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default="Thermostat"): cv.string, @@ -39,11 +36,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup oemthermostat.""" + """Set up the oemthermostat platform.""" from oemthermostat import Thermostat - # Assign configuration variables. The configuration check takes care they - # are present. name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -51,20 +46,17 @@ def setup_platform(hass, config, add_devices, discovery_info=None): password = config.get(CONF_PASSWORD) away_temp = config.get(CONF_AWAY_TEMP) - # If creating the class raises an exception, it failed to connect or - # something else went wrong. try: - therm = Thermostat(host, port=port, - username=username, password=password) + therm = Thermostat( + host, port=port, username=username, password=password) except (ValueError, AssertionError, requests.RequestException): return False - # Add devices add_devices((ThermostatDevice(hass, therm, name, away_temp), ), True) class ThermostatDevice(ClimateDevice): - """Interface class for the oemthermostat module and HA.""" + """Interface class for the oemthermostat modul.""" def __init__(self, hass, thermostat, name, away_temp): """Initialize the device.""" @@ -87,12 +79,12 @@ class ThermostatDevice(ClimateDevice): @property def name(self): - """Name of this Thermostat.""" + """Return the name of this Thermostat.""" return self._name @property def temperature_unit(self): - """The unit of measurement used by the platform.""" + """Return the unit of measurement used by the platform.""" return TEMP_CELSIUS @property @@ -114,7 +106,7 @@ class ThermostatDevice(ClimateDevice): return self._setpoint def set_temperature(self, **kwargs): - """Change the setpoint of the thermostat.""" + """Set the temperature.""" # If we are setting the temp, then we don't want away mode anymore. self.turn_away_mode_off() diff --git a/homeassistant/components/climate/proliphix.py b/homeassistant/components/climate/proliphix.py index ef6553cc062..7f7e8af6d0a 100644 --- a/homeassistant/components/climate/proliphix.py +++ b/homeassistant/components/climate/proliphix.py @@ -25,7 +25,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Proliphix thermostats.""" + """Set up the Proliphix thermostats.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) host = config.get(CONF_HOST) @@ -43,7 +43,6 @@ class ProliphixThermostat(ClimateDevice): def __init__(self, pdp): """Initialize the thermostat.""" self._pdp = pdp - # initial data self._pdp.update() self._name = self._pdp.name diff --git a/homeassistant/components/climate/radiotherm.py b/homeassistant/components/climate/radiotherm.py index 9a0e5666036..5bbed953047 100644 --- a/homeassistant/components/climate/radiotherm.py +++ b/homeassistant/components/climate/radiotherm.py @@ -40,7 +40,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Radio Thermostat.""" + """Set up the Radio Thermostat.""" import radiotherm hosts = [] diff --git a/homeassistant/components/climate/tado.py b/homeassistant/components/climate/tado.py index 600ea41e603..7bc99de26f9 100644 --- a/homeassistant/components/climate/tado.py +++ b/homeassistant/components/climate/tado.py @@ -87,7 +87,7 @@ class TadoClimate(ClimateDevice): def __init__(self, store, zone_name, zone_id, data_id, min_temp, max_temp, ac_mode, tolerance=0.3): - """Initialization of Tado climate device.""" + """Initialize of Tado climate device.""" self._store = store self._data_id = data_id @@ -113,7 +113,7 @@ class TadoClimate(ClimateDevice): @property def name(self): - """Return the name of the sensor.""" + """Return the name of the device.""" return self.zone_name @property @@ -133,12 +133,12 @@ class TadoClimate(ClimateDevice): @property def operation_list(self): - """List of available operation modes (readable).""" + """Return the list of available operation modes (readable).""" return list(OPERATION_LIST.values()) @property def temperature_unit(self): - """The unit of measurement used by the platform.""" + """Return the unit of measurement used by the platform.""" return self._unit @property diff --git a/homeassistant/components/climate/vera.py b/homeassistant/components/climate/vera.py index 79f10bc0421..06325ae0561 100644 --- a/homeassistant/components/climate/vera.py +++ b/homeassistant/components/climate/vera.py @@ -20,12 +20,12 @@ DEPENDENCIES = ['vera'] _LOGGER = logging.getLogger(__name__) -OPERATION_LIST = ["Heat", "Cool", "Auto Changeover", "Off"] -FAN_OPERATION_LIST = ["On", "Auto", "Cycle"] +OPERATION_LIST = ['Heat', 'Cool', 'Auto Changeover', 'Off'] +FAN_OPERATION_LIST = ['On', 'Auto', 'Cycle'] def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Find and return Vera thermostats.""" + """Set up of Vera thermostats.""" add_devices_callback( VeraThermostat(device, VERA_CONTROLLER) for device in VERA_DEVICES['climate']) @@ -43,19 +43,19 @@ class VeraThermostat(VeraDevice, ClimateDevice): def current_operation(self): """Return current operation ie. heat, cool, idle.""" mode = self.vera_device.get_hvac_mode() - if mode == "HeatOn": + if mode == 'HeatOn': return OPERATION_LIST[0] # heat - elif mode == "CoolOn": + elif mode == 'CoolOn': return OPERATION_LIST[1] # cool - elif mode == "AutoChangeOver": + elif mode == 'AutoChangeOver': return OPERATION_LIST[2] # auto - elif mode == "Off": + elif mode == 'Off': return OPERATION_LIST[3] # off - return "Off" + return 'Off' @property def operation_list(self): - """List of available operation modes.""" + """Return the list of available operation modes.""" return OPERATION_LIST @property @@ -72,7 +72,7 @@ class VeraThermostat(VeraDevice, ClimateDevice): @property def fan_list(self): - """List of available fan modes.""" + """Return a list of available fan modes.""" return FAN_OPERATION_LIST def set_fan_mode(self, mode): @@ -86,13 +86,13 @@ class VeraThermostat(VeraDevice, ClimateDevice): @property def current_power_w(self): - """Current power usage in W.""" + """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) def update(self): - """Called by the vera device callback to update state.""" + """Handle state updates.""" self._state = self.vera_device.get_hvac_mode() @property diff --git a/homeassistant/components/climate/wink.py b/homeassistant/components/climate/wink.py index df29768b3ff..256af2d013c 100644 --- a/homeassistant/components/climate/wink.py +++ b/homeassistant/components/climate/wink.py @@ -30,7 +30,7 @@ ATTR_OCCUPIED = "occupied" def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Wink thermostat.""" + """Set up the Wink thermostat.""" import pywink temp_unit = hass.config.units.temperature_unit for climate in pywink.get_thermostats(): @@ -449,7 +449,7 @@ class WinkAC(WinkDevice, ClimateDevice): @property def fan_list(self): - """List of available fan modes.""" + """Return a list of available fan modes.""" return [SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH] def set_fan_mode(self, mode): diff --git a/homeassistant/components/climate/zwave.py b/homeassistant/components/climate/zwave.py index a0fe3ce4c11..949bd10e0c2 100755 --- a/homeassistant/components/climate/zwave.py +++ b/homeassistant/components/climate/zwave.py @@ -33,7 +33,7 @@ DEVICE_MAPPINGS = { def get_device(hass, values, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" temp_unit = hass.config.units.temperature_unit return ZWaveClimate(values, temp_unit) @@ -65,13 +65,13 @@ class ZWaveClimate(ZWaveDeviceEntity, ClimateDevice): int(self.node.product_id, 16)) if specific_sensor_key in DEVICE_MAPPINGS: if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZXT_120: - _LOGGER.debug("Remotec ZXT-120 Zwave Thermostat" - " workaround") + _LOGGER.debug( + "Remotec ZXT-120 Zwave Thermostat workaround") self._zxt_120 = 1 self.update_properties() def update_properties(self): - """Callback on data changes for node values.""" + """Handle the data changes for node values.""" # Operation Mode if self.values.mode: self._current_operation = self.values.mode.data @@ -134,7 +134,7 @@ class ZWaveClimate(ZWaveDeviceEntity, ClimateDevice): @property def fan_list(self): - """List of available fan modes.""" + """Return a list of available fan modes.""" return self._fan_list @property @@ -144,7 +144,7 @@ class ZWaveClimate(ZWaveDeviceEntity, ClimateDevice): @property def swing_list(self): - """List of available swing modes.""" + """Return a list of available swing modes.""" return self._swing_list @property @@ -169,7 +169,7 @@ class ZWaveClimate(ZWaveDeviceEntity, ClimateDevice): @property def operation_list(self): - """List of available operation modes.""" + """Return a list of available operation modes.""" return self._operation_list @property diff --git a/homeassistant/components/config/__init__.py b/homeassistant/components/config/__init__.py index ab175d1d56f..1255043b6b5 100644 --- a/homeassistant/components/config/__init__.py +++ b/homeassistant/components/config/__init__.py @@ -20,14 +20,14 @@ ON_DEMAND = ('zwave', ) @asyncio.coroutine def async_setup(hass, config): - """Setup the config component.""" + """Set up the config component.""" register_built_in_panel(hass, 'config', 'Configuration', 'mdi:settings') @asyncio.coroutine def setup_panel(panel_name): - """Setup a panel.""" - panel = yield from async_prepare_setup_platform(hass, config, DOMAIN, - panel_name) + """Set up a panel.""" + panel = yield from async_prepare_setup_platform( + hass, config, DOMAIN, panel_name) if not panel: return diff --git a/homeassistant/components/config/core.py b/homeassistant/components/config/core.py index 15456ee74ad..4ff530ad2bc 100644 --- a/homeassistant/components/config/core.py +++ b/homeassistant/components/config/core.py @@ -7,7 +7,7 @@ from homeassistant.config import async_check_ha_config_file @asyncio.coroutine def async_setup(hass): - """Setup the hassbian config.""" + """Set up the Hassbian config.""" hass.http.register_view(CheckConfigView) return True @@ -20,7 +20,7 @@ class CheckConfigView(HomeAssistantView): @asyncio.coroutine def post(self, request): - """Validate config and return results.""" + """Validate configuration and return results.""" errors = yield from async_check_ha_config_file(request.app['hass']) state = 'invalid' if errors else 'valid' diff --git a/homeassistant/components/config/group.py b/homeassistant/components/config/group.py index 5c0fd23300e..16e1900c645 100644 --- a/homeassistant/components/config/group.py +++ b/homeassistant/components/config/group.py @@ -11,9 +11,8 @@ CONFIG_PATH = 'groups.yaml' @asyncio.coroutine def async_setup(hass): - """Setup the Group config API.""" + """Set up the Group config API.""" hass.http.register_view(EditKeyBasedConfigView( - 'group', 'config', CONFIG_PATH, cv.slug, - GROUP_SCHEMA + 'group', 'config', CONFIG_PATH, cv.slug, GROUP_SCHEMA )) return True diff --git a/homeassistant/components/config/hassbian.py b/homeassistant/components/config/hassbian.py index e94d6d25b90..8de5f62d915 100644 --- a/homeassistant/components/config/hassbian.py +++ b/homeassistant/components/config/hassbian.py @@ -32,8 +32,8 @@ _TEST_OUTPUT = """ @asyncio.coroutine def async_setup(hass): - """Setup the hassbian config.""" - # Test if is hassbian + """Set up the Hassbian config.""" + # Test if is Hassbian test_mode = 'FORCE_HASSBIAN' in os.environ is_hassbian = test_mode @@ -49,7 +49,7 @@ def async_setup(hass): @asyncio.coroutine def hassbian_status(hass, test_mode=False): """Query for the Hassbian status.""" - # fetch real output when not in test mode + # Fetch real output when not in test mode if test_mode: return json.loads(_TEST_OUTPUT) diff --git a/homeassistant/components/config/zwave.py b/homeassistant/components/config/zwave.py index 5eca596c8f4..576ff09bf2b 100644 --- a/homeassistant/components/config/zwave.py +++ b/homeassistant/components/config/zwave.py @@ -11,7 +11,7 @@ CONFIG_PATH = 'zwave_device_config.yaml' @asyncio.coroutine def async_setup(hass): - """Setup the Z-Wave config API.""" + """Set up the Z-Wave config API.""" hass.http.register_view(EditKeyBasedConfigView( 'zwave', 'device_config', CONFIG_PATH, cv.entity_id, DEVICE_CONFIG_SCHEMA_ENTRY diff --git a/homeassistant/components/configurator.py b/homeassistant/components/configurator.py index 3376815b9d5..c37f07956e4 100644 --- a/homeassistant/components/configurator.py +++ b/homeassistant/components/configurator.py @@ -75,7 +75,7 @@ def request_done(request_id): @asyncio.coroutine def async_setup(hass, config): - """Setup the configurator component.""" + """Set up the configurator component.""" return True @@ -104,7 +104,7 @@ class Configurator(object): self, name, callback, description, description_image, submit_caption, fields, link_name, link_url, entity_picture): - """Setup a request for configuration.""" + """Set up a request for configuration.""" entity_id = generate_entity_id(ENTITY_ID_FORMAT, name, hass=self.hass) if fields is None: diff --git a/homeassistant/components/cover/__init__.py b/homeassistant/components/cover/__init__.py index c857793f579..bbee0e836a3 100644 --- a/homeassistant/components/cover/__init__.py +++ b/homeassistant/components/cover/__init__.py @@ -24,6 +24,7 @@ from homeassistant.const import ( SERVICE_STOP_COVER_TILT, SERVICE_SET_COVER_TILT_POSITION, STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN, ATTR_ENTITY_ID) +_LOGGER = logging.getLogger(__name__) DOMAIN = 'cover' SCAN_INTERVAL = timedelta(seconds=15) @@ -47,8 +48,6 @@ SUPPORT_CLOSE_TILT = 32 SUPPORT_STOP_TILT = 64 SUPPORT_SET_TILT_POSITION = 128 -_LOGGER = logging.getLogger(__name__) - ATTR_CURRENT_POSITION = 'current_position' ATTR_CURRENT_TILT_POSITION = 'current_tilt_position' ATTR_POSITION = 'position' diff --git a/homeassistant/components/cover/command_line.py b/homeassistant/components/cover/command_line.py index 778496ec6fc..cd48238cae9 100644 --- a/homeassistant/components/cover/command_line.py +++ b/homeassistant/components/cover/command_line.py @@ -32,7 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup cover controlled by shell commands.""" + """Set up cover controlled by shell commands.""" devices = config.get(CONF_COVERS, {}) covers = [] @@ -78,25 +78,25 @@ class CommandCover(CoverDevice): @staticmethod def _move_cover(command): """Execute the actual commands.""" - _LOGGER.info('Running command: %s', command) + _LOGGER.info("Running command: %s", command) success = (subprocess.call(command, shell=True) == 0) if not success: - _LOGGER.error('Command failed: %s', command) + _LOGGER.error("Command failed: %s", command) return success @staticmethod def _query_state_value(command): """Execute state command for return value.""" - _LOGGER.info('Running state command: %s', command) + _LOGGER.info("Running state command: %s", command) try: return_value = subprocess.check_output(command, shell=True) return return_value.strip().decode('utf-8') except subprocess.CalledProcessError: - _LOGGER.error('Command failed: %s', command) + _LOGGER.error("Command failed: %s", command) @property def should_poll(self): @@ -128,7 +128,7 @@ class CommandCover(CoverDevice): def _query_state(self): """Query for the state.""" if not self._command_state: - _LOGGER.error('No state command specified') + _LOGGER.error("No state command specified") return return self._query_state_value(self._command_state) diff --git a/homeassistant/components/cover/demo.py b/homeassistant/components/cover/demo.py index 8a8a675703a..35574150596 100644 --- a/homeassistant/components/cover/demo.py +++ b/homeassistant/components/cover/demo.py @@ -10,7 +10,7 @@ from homeassistant.helpers.event import track_utc_time_change def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Demo covers.""" + """Set up the Demo covers.""" add_devices([ DemoCover(hass, 'Kitchen Window'), DemoCover(hass, 'Hall Window', 10), diff --git a/homeassistant/components/cover/homematic.py b/homeassistant/components/cover/homematic.py index 8420b8b47e3..ace08f53e3c 100644 --- a/homeassistant/components/cover/homematic.py +++ b/homeassistant/components/cover/homematic.py @@ -3,11 +3,7 @@ The homematic cover platform. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.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.cover import CoverDevice, ATTR_POSITION @@ -19,7 +15,7 @@ DEPENDENCIES = ['homematic'] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the platform.""" + """Set up the platform.""" if discovery_info is None: return @@ -33,7 +29,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class HMCover(HMDevice, CoverDevice): - """Represents a Homematic Cover in Home Assistant.""" + """Representation a Homematic Cover.""" @property def current_cover_position(self): diff --git a/homeassistant/components/cover/isy994.py b/homeassistant/components/cover/isy994.py index 27619de738d..1e83038278c 100644 --- a/homeassistant/components/cover/isy994.py +++ b/homeassistant/components/cover/isy994.py @@ -12,7 +12,6 @@ import homeassistant.components.isy994 as isy from homeassistant.const import STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN from homeassistant.helpers.typing import ConfigType - _LOGGER = logging.getLogger(__name__) VALUE_TO_STATE = { @@ -27,15 +26,14 @@ STATES = [STATE_OPEN, STATE_CLOSED, 'closing', 'opening', 'stopped'] # pylint: disable=unused-argument def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): - """Setup the ISY994 cover platform.""" + """Set up the ISY994 cover 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 = [] - for node in isy.filter_nodes(isy.NODES, units=UOM, - states=STATES): + for node in isy.filter_nodes(isy.NODES, units=UOM, states=STATES): devices.append(ISYCoverDevice(node)) for program in isy.PROGRAMS.get(DOMAIN, []): @@ -60,7 +58,7 @@ class ISYCoverDevice(isy.ISYDevice, CoverDevice): @property def current_cover_position(self) -> int: - """Get the current cover position.""" + """Return the current cover position.""" return sorted((0, self.value, 100))[1] @property @@ -76,12 +74,12 @@ class ISYCoverDevice(isy.ISYDevice, CoverDevice): def open_cover(self, **kwargs) -> None: """Send the open cover command to the ISY994 cover device.""" if not self._node.on(val=100): - _LOGGER.error('Unable to open the cover') + _LOGGER.error("Unable to open the cover") def close_cover(self, **kwargs) -> None: """Send the close cover command to the ISY994 cover device.""" if not self._node.off(): - _LOGGER.error('Unable to close the cover') + _LOGGER.error("Unable to close the cover") class ISYCoverProgram(ISYCoverDevice): @@ -101,9 +99,9 @@ class ISYCoverProgram(ISYCoverDevice): def open_cover(self, **kwargs) -> None: """Send the open cover command to the ISY994 cover program.""" if not self._actions.runThen(): - _LOGGER.error('Unable to open the cover') + _LOGGER.error("Unable to open the cover") def close_cover(self, **kwargs) -> None: """Send the close cover command to the ISY994 cover program.""" if not self._actions.runElse(): - _LOGGER.error('Unable to close the cover') + _LOGGER.error("Unable to close the cover") diff --git a/homeassistant/components/cover/mqtt.py b/homeassistant/components/cover/mqtt.py index 6403e0bbc85..575dc4cb345 100644 --- a/homeassistant/components/cover/mqtt.py +++ b/homeassistant/components/cover/mqtt.py @@ -49,7 +49,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 Cover.""" + """Set up the MQTT Cover.""" value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass @@ -94,13 +94,13 @@ class MqttCover(CoverDevice): @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe MQTT events. This method is a coroutine. """ @callback def message_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new MQTT message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) diff --git a/homeassistant/components/cover/myq.py b/homeassistant/components/cover/myq.py index b749fde465f..06ec7ca6211 100644 --- a/homeassistant/components/cover/myq.py +++ b/homeassistant/components/cover/myq.py @@ -27,7 +27,7 @@ DEFAULT_NAME = 'myq' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the MyQ component.""" + """Set up the MyQ component.""" from pymyq import MyQAPI as pymyq username = config.get(CONF_USERNAME) @@ -39,17 +39,17 @@ def setup_platform(hass, config, add_devices, discovery_info=None): myq = pymyq(username, password, brand) if not myq.is_supported_brand(): - logger.error('MyQ Cover - Unsupported Type. See documentation') + logger.error("Unsupported type. See documentation") return if not myq.is_login_valid(): - logger.error('MyQ Cover - Username or Password is incorrect') + logger.error("Username or Password is incorrect") return try: add_devices(MyQDevice(myq, door) for door in myq.get_garage_doors()) except (TypeError, KeyError, NameError) as ex: - logger.error("MyQ Cover - %s", ex) + logger.error("%s", ex) class MyQDevice(CoverDevice): @@ -74,7 +74,7 @@ class MyQDevice(CoverDevice): @property def is_closed(self): - """Return True if cover is closed, else False.""" + """Return true if cover is closed, else False.""" return self._status == STATE_CLOSED def close_cover(self): diff --git a/homeassistant/components/cover/mysensors.py b/homeassistant/components/cover/mysensors.py index 7daadebadad..43942dacd05 100644 --- a/homeassistant/components/cover/mysensors.py +++ b/homeassistant/components/cover/mysensors.py @@ -11,11 +11,12 @@ from homeassistant.components.cover import CoverDevice, ATTR_POSITION from homeassistant.const import STATE_ON, STATE_OFF _LOGGER = logging.getLogger(__name__) + DEPENDENCIES = [] def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors platform for covers.""" + """Set up the MySensors platform for covers.""" if discovery_info is None: return diff --git a/homeassistant/components/cover/rfxtrx.py b/homeassistant/components/cover/rfxtrx.py index a016103a8fd..0e28d3ef701 100644 --- a/homeassistant/components/cover/rfxtrx.py +++ b/homeassistant/components/cover/rfxtrx.py @@ -4,7 +4,6 @@ Support for RFXtrx cover components. For more details about this platform, please refer to the documentation https://home-assistant.io/components/cover.rfxtrx/ """ - import homeassistant.components.rfxtrx as rfxtrx from homeassistant.components.cover import CoverDevice @@ -14,16 +13,14 @@ PLATFORM_SCHEMA = rfxtrx.DEFAULT_SCHEMA def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the RFXtrx cover.""" + """Set up the RFXtrx cover.""" import RFXtrx as rfxtrxmod - # Add cover from config file - covers = rfxtrx.get_devices_from_config(config, - RfxtrxCover) + covers = rfxtrx.get_devices_from_config(config, RfxtrxCover) add_devices_callback(covers) def cover_update(event): - """Callback for cover updates from the RFXtrx gateway.""" + """Handle cover updates from the RFXtrx gateway.""" if not isinstance(event.device, rfxtrxmod.LightingDevice) or \ event.device.known_to_be_dimmable or \ not event.device.known_to_be_rollershutter: @@ -35,17 +32,17 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): rfxtrx.apply_received_command(event) - # Subscribe to main rfxtrx events + # Subscribe to main RFXtrx events if cover_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(cover_update) class RfxtrxCover(rfxtrx.RfxtrxDevice, CoverDevice): - """Representation of an rfxtrx cover.""" + """Representation of a RFXtrx cover.""" @property def should_poll(self): - """No polling available in rfxtrx cover.""" + """No polling available in RFXtrx cover.""" return False @property diff --git a/homeassistant/components/cover/rpi_gpio.py b/homeassistant/components/cover/rpi_gpio.py index 4cd4e74be06..07be998035c 100644 --- a/homeassistant/components/cover/rpi_gpio.py +++ b/homeassistant/components/cover/rpi_gpio.py @@ -1,5 +1,5 @@ """ -Support for building a Raspberry Pi cover in HA. +Support for controlling a Raspberry Pi cover. Instructions for building the controller can be found here https://github.com/andrewshilliday/garage-door-controller @@ -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 RPi cover platform.""" + """Set up the RPi cover platform.""" relay_time = config.get(CONF_RELAY_TIME) state_pull_mode = config.get(CONF_STATE_PULL_MODE) covers = [] diff --git a/homeassistant/components/cover/scsgate.py b/homeassistant/components/cover/scsgate.py index f2047b03230..ac4fddf98bb 100644 --- a/homeassistant/components/cover/scsgate.py +++ b/homeassistant/components/cover/scsgate.py @@ -23,7 +23,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the SCSGate cover.""" + """Set up the SCSGate cover.""" devices = config.get(CONF_DEVICES) covers = [] logger = logging.getLogger(__name__) diff --git a/homeassistant/components/cover/tellduslive.py b/homeassistant/components/cover/tellduslive.py index c48a14e9133..4a78cb96d06 100644 --- a/homeassistant/components/cover/tellduslive.py +++ b/homeassistant/components/cover/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/cover.tellduslive/ - """ import logging @@ -16,9 +15,10 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup covers.""" + """Set up the Telldus Live covers.""" if discovery_info is None: return + add_devices(TelldusLiveCover(hass, cover) for cover in discovery_info) diff --git a/homeassistant/components/cover/vera.py b/homeassistant/components/cover/vera.py index 033cea4a828..bcccf17da8a 100644 --- a/homeassistant/components/cover/vera.py +++ b/homeassistant/components/cover/vera.py @@ -16,14 +16,14 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Find and return Vera covers.""" + """Set up the Vera covers.""" add_devices( VeraCover(device, VERA_CONTROLLER) for device in VERA_DEVICES['cover']) class VeraCover(VeraDevice, CoverDevice): - """Represents a Vera Cover in Home Assistant.""" + """Representation a Vera Cover.""" def __init__(self, vera_device, controller): """Initialize the Vera device.""" diff --git a/homeassistant/components/cover/wink.py b/homeassistant/components/cover/wink.py index 79e2ee334dc..5472180db62 100644 --- a/homeassistant/components/cover/wink.py +++ b/homeassistant/components/cover/wink.py @@ -4,7 +4,6 @@ Support for Wink Covers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.wink/ """ - from homeassistant.components.cover import CoverDevice 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 cover platform.""" + """Set up the Wink cover platform.""" import pywink for shade in pywink.get_shades(): diff --git a/homeassistant/components/cover/zwave.py b/homeassistant/components/cover/zwave.py index f860e52de95..71194d12bba 100644 --- a/homeassistant/components/cover/zwave.py +++ b/homeassistant/components/cover/zwave.py @@ -1,5 +1,5 @@ """ -Support for Zwave cover components. +Support for Z-Wave cover components. For more details about this platform, please refer to the documentation https://home-assistant.io/components/cover.zwave/ @@ -21,7 +21,7 @@ SUPPORT_GARAGE = SUPPORT_OPEN | SUPPORT_CLOSE def get_device(hass, values, node_config, **kwargs): - """Create zwave entity device.""" + """Create Z-Wave entity device.""" invert_buttons = node_config.get(zwave.CONF_INVERT_OPENCLOSE_BUTTONS) if (values.primary.command_class == zwave.const.COMMAND_CLASS_SWITCH_MULTILEVEL @@ -35,10 +35,10 @@ def get_device(hass, values, node_config, **kwargs): class ZwaveRollershutter(zwave.ZWaveDeviceEntity, CoverDevice): - """Representation of an Zwave roller shutter.""" + """Representation of an Z-Wave cover.""" def __init__(self, hass, values, invert_buttons): - """Initialize the zwave rollershutter.""" + """Initialize the Z-Wave rollershutter.""" ZWaveDeviceEntity.__init__(self, values, DOMAIN) # pylint: disable=no-member self._network = hass.data[zwave.ZWAVE_NETWORK] @@ -53,7 +53,7 @@ class ZwaveRollershutter(zwave.ZWaveDeviceEntity, CoverDevice): self.update_properties() def update_properties(self): - """Callback on data changes for node values.""" + """Handle data changes for node values.""" # Position value self._current_position = self.values.primary.data diff --git a/homeassistant/components/demo.py b/homeassistant/components/demo.py index 6212567f3d7..f926d059db2 100644 --- a/homeassistant/components/demo.py +++ b/homeassistant/components/demo.py @@ -1,5 +1,5 @@ """ -Sets up a demo environment that mimics interaction with devices. +Set up the demo environment that mimics interaction with devices. For more details about this component, please refer to the documentation https://home-assistant.io/components/demo/ @@ -37,7 +37,7 @@ COMPONENTS_WITH_DEMO_PLATFORM = [ @asyncio.coroutine def async_setup(hass, config): - """Setup a demo environment.""" + """Set up the demo environment.""" group = loader.get_component('group') configurator = loader.get_component('configurator') persistent_notification = loader.get_component('persistent_notification') @@ -59,7 +59,7 @@ def async_setup(hass, config): bootstrap.async_setup_component(hass, 'sun') ] - # Setup demo platforms + # Set up demo platforms demo_config = config.copy() for component in COMPONENTS_WITH_DEMO_PLATFORM: demo_config[component] = {CONF_PLATFORM: 'demo'} @@ -106,19 +106,19 @@ def async_setup(hass, config): if any(not result for result in results): return False - # Setup example persistent notification + # Set up example persistent notification persistent_notification.async_create( hass, 'This is an example of a persistent notification.', title='Example Notification') - # Setup room groups + # Set up room groups lights = sorted(hass.states.async_entity_ids('light')) switches = sorted(hass.states.async_entity_ids('switch')) media_players = sorted(hass.states.async_entity_ids('media_player')) tasks2 = [] - # Setup scripts + # Set up scripts tasks2.append(bootstrap.async_setup_component( hass, 'script', {'script': { @@ -140,7 +140,7 @@ def async_setup(hass, config): }] }}})) - # Setup scenes + # Set up scenes tasks2.append(bootstrap.async_setup_component( hass, 'scene', {'scene': [ @@ -186,7 +186,7 @@ def async_setup(hass, config): if any(not result for result in results): return False - # Setup configurator + # Set up configurator configurator_ids = [] def hue_configuration_callback(data): @@ -204,7 +204,7 @@ def async_setup(hass, config): configurator.request_done(configurator_ids[0]) def setup_configurator(): - """Setup configurator.""" + """Set up a configurator.""" request_id = configurator.request_config( hass, "Philips Hue", hue_configuration_callback, description=("Press the button on the bridge to register Philips " diff --git a/homeassistant/components/device_sun_light_trigger.py b/homeassistant/components/device_sun_light_trigger.py index 0a4d7173c20..8831008e0ab 100644 --- a/homeassistant/components/device_sun_light_trigger.py +++ b/homeassistant/components/device_sun_light_trigger.py @@ -45,7 +45,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """The triggers to turn lights on or off based on device presence.""" + """Set up the triggers to control lights based on device presence.""" logger = logging.getLogger(__name__) device_tracker = get_component('device_tracker') group = get_component('group') @@ -55,10 +55,10 @@ def async_setup(hass, config): disable_turn_off = conf.get(CONF_DISABLE_TURN_OFF) light_group = conf.get(CONF_LIGHT_GROUP, light.ENTITY_ID_ALL_LIGHTS) light_profile = conf.get(CONF_LIGHT_PROFILE) - device_group = conf.get(CONF_DEVICE_GROUP, - device_tracker.ENTITY_ID_ALL_DEVICES) - device_entity_ids = group.get_entity_ids(hass, device_group, - device_tracker.DOMAIN) + device_group = conf.get( + CONF_DEVICE_GROUP, device_tracker.ENTITY_ID_ALL_DEVICES) + device_entity_ids = group.get_entity_ids( + hass, device_group, device_tracker.DOMAIN) if not device_entity_ids: logger.error("No devices found to track") @@ -84,7 +84,7 @@ def async_setup(hass, config): return next_setting - LIGHT_TRANSITION_TIME * len(light_ids) def async_turn_on_before_sunset(light_id): - """Helper function to turn on lights.""" + """Function to turn on lights.""" if not device_tracker.is_on(hass) or light.is_on(hass, light_id): return light.async_turn_on(hass, light_id, diff --git a/homeassistant/components/device_tracker/__init__.py b/homeassistant/components/device_tracker/__init__.py index c654ab05266..6582ba3f57e 100644 --- a/homeassistant/components/device_tracker/__init__.py +++ b/homeassistant/components/device_tracker/__init__.py @@ -34,7 +34,7 @@ from homeassistant.util.yaml import dump from homeassistant.helpers.event import async_track_utc_time_change from homeassistant.const import ( - ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE, + ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_MAC, DEVICE_DEFAULT_NAME, STATE_HOME, STATE_NOT_HOME, ATTR_ENTITY_ID) _LOGGER = logging.getLogger(__name__) @@ -65,13 +65,14 @@ EVENT_NEW_DEVICE = 'device_tracker_new_device' SERVICE_SEE = 'see' -ATTR_MAC = 'mac' +ATTR_ATTRIBUTES = 'attributes' +ATTR_BATTERY = 'battery' ATTR_DEV_ID = 'dev_id' +ATTR_GPS = 'gps' ATTR_HOST_NAME = 'host_name' ATTR_LOCATION_NAME = 'location_name' -ATTR_GPS = 'gps' -ATTR_BATTERY = 'battery' -ATTR_ATTRIBUTES = 'attributes' +ATTR_MAC = 'mac' +ATTR_NAME = 'name' ATTR_SOURCE_TYPE = 'source_type' SOURCE_TYPE_GPS = 'gps' @@ -117,7 +118,7 @@ def see(hass: HomeAssistantType, mac: str=None, dev_id: str=None, @asyncio.coroutine def async_setup(hass: HomeAssistantType, config: ConfigType): - """Setup device tracker.""" + """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) try: @@ -135,7 +136,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType): @asyncio.coroutine def async_setup_platform(p_type, p_config, disc_info=None): - """Setup a device tracker platform.""" + """Set up a device tracker platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: @@ -167,11 +168,11 @@ def async_setup(hass: HomeAssistantType, config: ConfigType): return if not setup: - _LOGGER.error('Error setting up platform %s', p_type) + _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except - _LOGGER.exception('Error setting up platform %s', p_type) + _LOGGER.exception("Error setting up platform %s", p_type) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] @@ -182,7 +183,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType): @callback def async_device_tracker_discovered(service, info): - """Called when a device tracker platform is discovered.""" + """Handle the discovery of device tracker platforms.""" hass.async_add_job( async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info)) @@ -191,7 +192,7 @@ def async_setup(hass: HomeAssistantType, config: ConfigType): @asyncio.coroutine def async_platform_discovered(platform, info): - """Callback to load a platform.""" + """Load a platform.""" yield from async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) @@ -272,9 +273,9 @@ class DeviceTracker(object): device = self.devices.get(dev_id) if device: - yield from device.async_seen(host_name, location_name, gps, - gps_accuracy, battery, attributes, - source_type) + yield from device.async_seen( + host_name, location_name, gps, gps_accuracy, battery, + attributes, source_type) if device.track: yield from device.async_update_ha_state() return @@ -288,9 +289,9 @@ class DeviceTracker(object): if mac is not None: self.mac_to_dev[mac] = device - yield from device.async_seen(host_name, location_name, gps, - gps_accuracy, battery, attributes, - source_type) + yield from device.async_seen( + host_name, location_name, gps, gps_accuracy, battery, attributes, + source_type) if device.track: yield from device.async_update_ha_state() @@ -310,8 +311,8 @@ class DeviceTracker(object): # update known_devices.yaml self.hass.async_add_job( - self.async_update_config(self.hass.config.path(YAML_DEVICES), - dev_id, device) + self.async_update_config( + self.hass.config.path(YAML_DEVICES), dev_id, device) ) @asyncio.coroutine @@ -349,7 +350,7 @@ class DeviceTracker(object): @asyncio.coroutine def async_setup_tracked_device(self): - """Setup all not exists tracked devices. + """Set up all not exists tracked devices. This method is a coroutine. """ @@ -486,8 +487,8 @@ class Device(Entity): except (ValueError, TypeError, IndexError): self.gps = None self.gps_accuracy = 0 - _LOGGER.warning('Could not parse gps value for %s: %s', - self.dev_id, gps) + _LOGGER.warning( + "Could not parse gps value for %s: %s", self.dev_id, gps) # pylint: disable=not-an-iterable yield from self.async_update() @@ -535,7 +536,6 @@ class Device(Entity): @asyncio.coroutine def get_vendor_for_mac(self): """Try to find the vendor string for a given MAC address.""" - # can't continue without a mac if not self.mac: return None @@ -544,11 +544,10 @@ class Device(Entity): else: mac = self.mac - # prevent lookup of invalid macs if not len(mac.split(':')) == 6: return 'unknown' - # we only need the first 3 bytes of the mac for a lookup + # We only need the first 3 bytes of the MAC for a lookup # this improves somewhat on privacy oui_bytes = mac.split(':')[0:3] # bytes like 00 get truncates to 0, API needs full bytes @@ -563,7 +562,7 @@ class Device(Entity): if resp.status == 200: vendor_string = yield from resp.text() return vendor_string - # if vendor is not known to the API (404) or there + # If vendor is not known to the API (404) or there # was a failure during the lookup (500); set vendor # to something other then None to prevent retry # as the value is only relevant when it is to be stored @@ -571,12 +570,12 @@ class Device(Entity): # the first time the device is seen. return 'unknown' except (asyncio.TimeoutError, aiohttp.ClientError): - # same as above + # Same as above return 'unknown' @asyncio.coroutine def async_added_to_hass(self): - """Called when entity about to be added to hass.""" + """Add an entity.""" state = yield from async_get_last_state(self.hass, self.entity_id) if not state: return @@ -637,10 +636,10 @@ def async_load_config(path: str, hass: HomeAssistantType, This method is a coroutine. """ dev_schema = vol.Schema({ - vol.Required('name'): cv.string, + vol.Required(CONF_NAME): cv.string, vol.Optional('track', default=False): cv.boolean, - vol.Optional('mac', default=None): vol.Any(None, vol.All(cv.string, - vol.Upper)), + vol.Optional(CONF_MAC, default=None): + vol.Any(None, vol.All(cv.string, vol.Upper)), vol.Optional(CONF_AWAY_HIDE, default=DEFAULT_AWAY_HIDE): cv.boolean, vol.Optional('gravatar', default=None): vol.Any(None, cv.string), vol.Optional('picture', default=None): vol.Any(None, cv.string), @@ -654,7 +653,7 @@ def async_load_config(path: str, hass: HomeAssistantType, devices = yield from hass.loop.run_in_executor( None, load_yaml_config_file, path) except HomeAssistantError as err: - _LOGGER.error('Unable to load %s: %s', path, str(err)) + _LOGGER.error("Unable to load %s: %s", path, str(err)) return [] for dev_id, device in devices.items(): @@ -675,7 +674,7 @@ def async_load_config(path: str, hass: HomeAssistantType, def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType, scanner: Any, async_see_device: Callable, platform: str): - """Helper method to connect scanner-based platform to device tracker. + """Set up the connect scanner-based platform to device tracker. This method must be run in the event loop. """ @@ -688,7 +687,7 @@ def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType, @asyncio.coroutine def async_device_tracker_scan(now: dt_util.dt.datetime): - """Called when interval matches.""" + """Handle interval matches.""" if update_lock.locked(): _LOGGER.warning( "Updating device list from %s took longer than the scheduled " @@ -727,8 +726,8 @@ def update_config(path: str, dev_id: str, device: Device): """Add device to YAML configuration file.""" with open(path, 'a') as out: device = {device.dev_id: { - 'name': device.name, - 'mac': device.mac, + ATTR_NAME: device.name, + ATTR_MAC: device.mac, 'picture': device.config_picture, 'track': device.track, CONF_AWAY_HIDE: device.away_hide, diff --git a/homeassistant/components/device_tracker/actiontec.py b/homeassistant/components/device_tracker/actiontec.py index 95286800b3c..882df575385 100644 --- a/homeassistant/components/device_tracker/actiontec.py +++ b/homeassistant/components/device_tracker/actiontec.py @@ -19,7 +19,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -44,7 +43,7 @@ def get_scanner(hass, config): return scanner if scanner.success_init else None -Device = namedtuple("Device", ["mac", "ip", "last_update"]) +Device = namedtuple('Device', ['mac', 'ip', 'last_update']) class ActiontecDeviceScanner(DeviceScanner): @@ -59,7 +58,7 @@ class ActiontecDeviceScanner(DeviceScanner): self.last_results = [] data = self.get_actiontec_data() self.success_init = data is not None - _LOGGER.info("actiontec scanner initialized") + _LOGGER.info("canner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" @@ -93,7 +92,7 @@ class ActiontecDeviceScanner(DeviceScanner): self.last_results = [Device(data['mac'], name, now) for name, data in actiontec_data.items() if data['timevalid'] > -60] - _LOGGER.info("actiontec scan successful") + _LOGGER.info("Scan successful") return True def get_actiontec_data(self): @@ -115,8 +114,7 @@ class ActiontecDeviceScanner(DeviceScanner): _LOGGER.exception("Unexpected response from router") return except ConnectionRefusedError: - _LOGGER.exception("Connection refused by router," + - " is telnet enabled?") + _LOGGER.exception("Connection refused by router. Telnet enabled?") return None devices = {} diff --git a/homeassistant/components/device_tracker/aruba.py b/homeassistant/components/device_tracker/aruba.py index 42e8a5b2d5c..bfb1588b323 100644 --- a/homeassistant/components/device_tracker/aruba.py +++ b/homeassistant/components/device_tracker/aruba.py @@ -17,11 +17,11 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) +_LOGGER = logging.getLogger(__name__) REQUIREMENTS = ['pexpect==4.0.1'] -_LOGGER = logging.getLogger(__name__) + +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) _DEVICES_REGEX = re.compile( r'(?P([^\s]+))\s+' + @@ -102,22 +102,22 @@ class ArubaDeviceScanner(DeviceScanner): 'Connection refused', 'Connection timed out'], timeout=120) if query == 1: - _LOGGER.error('Timeout') + _LOGGER.error("Timeout") return elif query == 2: - _LOGGER.error('Unexpected response from router') + _LOGGER.error("Unexpected response from router") return elif query == 3: ssh.sendline('yes') ssh.expect('password:') elif query == 4: - _LOGGER.error('Host key Changed') + _LOGGER.error("Host key changed") return elif query == 5: - _LOGGER.error('Connection refused by server') + _LOGGER.error("Connection refused by server") return elif query == 6: - _LOGGER.error('Connection timed out') + _LOGGER.error("Connection timed out") return ssh.sendline(self.password) ssh.expect('#') diff --git a/homeassistant/components/device_tracker/asuswrt.py b/homeassistant/components/device_tracker/asuswrt.py index 8ebc790ad3a..a0405b0b690 100644 --- a/homeassistant/components/device_tracker/asuswrt.py +++ b/homeassistant/components/device_tracker/asuswrt.py @@ -21,14 +21,19 @@ from homeassistant.const import ( from homeassistant.util import Throttle import homeassistant.helpers.config_validation as cv -# Return cached results if last scan was less then this time ago. +REQUIREMENTS = ['pexpect==4.0.1'] + +_LOGGER = logging.getLogger(__name__) + +CONF_MODE = 'mode' +CONF_PROTOCOL = 'protocol' +CONF_PUB_KEY = 'pub_key' +CONF_SSH_KEY = 'ssh_key' + +DEFAULT_SSH_PORT = 22 + MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) -CONF_PROTOCOL = 'protocol' -CONF_MODE = 'mode' -DEFAULT_SSH_PORT = 22 -CONF_SSH_KEY = 'ssh_key' -CONF_PUB_KEY = 'pub_key' SECRET_GROUP = 'Password or SSH Key' PLATFORM_SCHEMA = vol.All( @@ -47,9 +52,6 @@ PLATFORM_SCHEMA = vol.All( })) -_LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ['pexpect==4.0.1'] - _LEASES_CMD = 'cat /var/lib/misc/dnsmasq.leases' _LEASES_REGEX = re.compile( r'\w+\s' + @@ -57,7 +59,7 @@ _LEASES_REGEX = re.compile( r'(?P([0-9]{1,3}[\.]){3}[0-9]{1,3})\s' + r'(?P([^\s]+))') -# command to get both 5GHz and 2.4GHz clients +# Command to get both 5GHz and 2.4GHz clients _WL_CMD = '{ wl -i eth2 assoclist & wl -i eth1 assoclist ; }' _WL_REGEX = re.compile( r'\w+\s' + @@ -126,12 +128,12 @@ class AsusWrtDeviceScanner(DeviceScanner): elif self.password: self.ssh_args['password'] = self.password else: - _LOGGER.error('No password or private key specified') + _LOGGER.error("No password or private key specified") self.success_init = False return else: if not self.password: - _LOGGER.error('No password specified') + _LOGGER.error("No password specified") self.success_init = False return @@ -188,10 +190,10 @@ class AsusWrtDeviceScanner(DeviceScanner): try: ssh.login(self.host, self.username, **self.ssh_args) except exceptions.EOF as err: - _LOGGER.error('Connection refused. Is SSH enabled?') + _LOGGER.error("Connection refused. SSH enabled?") return None except pxssh.ExceptionPxssh as err: - _LOGGER.error('Unable to connect via SSH: %s', str(err)) + _LOGGER.error("Unable to connect via SSH: %s", str(err)) return None try: @@ -218,7 +220,7 @@ class AsusWrtDeviceScanner(DeviceScanner): return AsusWrtResult(neighbors, leases_result, arp_result, nvram_result) except pxssh.ExceptionPxssh as exc: - _LOGGER.error('Unexpected response from router: %s', exc) + _LOGGER.error("Unexpected response from router: %s", exc) return None def telnet_connection(self): @@ -252,16 +254,16 @@ class AsusWrtDeviceScanner(DeviceScanner): return AsusWrtResult(neighbors, leases_result, arp_result, nvram_result) except EOFError: - _LOGGER.error('Unexpected response from router') + _LOGGER.error("Unexpected response from router") return None except ConnectionRefusedError: - _LOGGER.error('Connection refused by router, is telnet enabled?') + _LOGGER.error("Connection refused by router. Telnet enabled?") return None except socket.gaierror as exc: - _LOGGER.error('Socket exception: %s', exc) + _LOGGER.error("Socket exception: %s", exc) return None except OSError as exc: - _LOGGER.error('OSError: %s', exc) + _LOGGER.error("OSError: %s", exc) return None def get_asuswrt_data(self): @@ -289,7 +291,7 @@ class AsusWrtDeviceScanner(DeviceScanner): match = _WL_REGEX.search(lease.decode('utf-8')) if not match: - _LOGGER.warning('Could not parse wl row: %s', lease) + _LOGGER.warning("Could not parse wl row: %s", lease) continue host = '' @@ -301,7 +303,7 @@ class AsusWrtDeviceScanner(DeviceScanner): arp_match = _ARP_REGEX.search( arp.decode('utf-8').lower()) if not arp_match: - _LOGGER.warning('Could not parse arp row: %s', arp) + _LOGGER.warning("Could not parse arp row: %s", arp) continue devices[arp_match.group('ip')] = { @@ -316,7 +318,7 @@ class AsusWrtDeviceScanner(DeviceScanner): if match.group('mac').upper() in nvr.decode('utf-8'): nvram_match = _NVRAM_REGEX.search(nvr.decode('utf-8')) if not nvram_match: - _LOGGER.warning('Could not parse nvr row: %s', nvr) + _LOGGER.warning("Could not parse nvr row: %s", nvr) continue # skip current check if already in ARP table @@ -337,7 +339,7 @@ class AsusWrtDeviceScanner(DeviceScanner): match = _LEASES_REGEX.search(lease.decode('utf-8')) if not match: - _LOGGER.warning('Could not parse lease row: %s', lease) + _LOGGER.warning("Could not parse lease row: %s", lease) continue # For leases where the client doesn't set a hostname, ensure it @@ -356,7 +358,7 @@ class AsusWrtDeviceScanner(DeviceScanner): for neighbor in result.neighbors: match = _IP_NEIGH_REGEX.search(neighbor.decode('utf-8')) if not match: - _LOGGER.warning('Could not parse neighbor row: %s', neighbor) + _LOGGER.warning("Could not parse neighbor row: %s", neighbor) continue if match.group('ip') in devices: devices[match.group('ip')]['status'] = match.group('status') diff --git a/homeassistant/components/device_tracker/automatic.py b/homeassistant/components/device_tracker/automatic.py index 55ec3151227..7fb665a7cc3 100644 --- a/homeassistant/components/device_tracker/automatic.py +++ b/homeassistant/components/device_tracker/automatic.py @@ -99,7 +99,7 @@ class AutomaticData(object): @asyncio.coroutine def update_vehicle(self, vehicle, name): - """Updated the specified vehicle's data.""" + """Update the specified vehicle's data.""" import aioautomatic kwargs = { diff --git a/homeassistant/components/device_tracker/bbox.py b/homeassistant/components/device_tracker/bbox.py index 60b9738cc71..0d0cdd7b1d5 100644 --- a/homeassistant/components/device_tracker/bbox.py +++ b/homeassistant/components/device_tracker/bbox.py @@ -37,7 +37,7 @@ class BboxDeviceScanner(DeviceScanner): self.last_results = [] # type: List[Device] self.success_init = self._update_info() - _LOGGER.info("Bbox scanner initialized") + _LOGGER.info("Scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" @@ -57,7 +57,7 @@ class BboxDeviceScanner(DeviceScanner): @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): - """Check the bbox for devices. + """Check the Bbox for devices. Returns boolean if scanning successful. """ @@ -79,5 +79,5 @@ class BboxDeviceScanner(DeviceScanner): self.last_results = last_results - _LOGGER.info("Bbox scan successful") + _LOGGER.info("Scan successful") return True diff --git a/homeassistant/components/device_tracker/bluetooth_le_tracker.py b/homeassistant/components/device_tracker/bluetooth_le_tracker.py index 7b7454d0a28..22713cdc18e 100644 --- a/homeassistant/components/device_tracker/bluetooth_le_tracker.py +++ b/homeassistant/components/device_tracker/bluetooth_le_tracker.py @@ -1,4 +1,9 @@ -"""Tracking for bluetooth low energy devices.""" +""" +Tracking for bluetooth low energy devices. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/device_tracker.bluetooth_le_tracker/ +""" import logging import voluptuous as vol @@ -16,17 +21,17 @@ REQUIREMENTS = ['gattlib==0.20150805'] BLE_PREFIX = 'BLE_' MIN_SEEN_NEW = 5 -CONF_SCAN_DURATION = "scan_duration" -CONF_BLUETOOTH_DEVICE = "device_id" +CONF_SCAN_DURATION = 'scan_duration' +CONF_BLUETOOTH_DEVICE = 'device_id' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_SCAN_DURATION, default=10): cv.positive_int, - vol.Optional(CONF_BLUETOOTH_DEVICE, default="hci0"): cv.string + vol.Optional(CONF_BLUETOOTH_DEVICE, default='hci0'): cv.string }) def setup_scanner(hass, config, see, discovery_info=None): - """Setup the Bluetooth LE Scanner.""" + """Set up the Bluetooth LE Scanner.""" # pylint: disable=import-error from gattlib import DiscoveryService @@ -36,8 +41,8 @@ def setup_scanner(hass, config, see, discovery_info=None): """Mark a device as seen.""" if new_device: if address in new_devices: - _LOGGER.debug("Seen %s %s times", address, - new_devices[address]) + _LOGGER.debug( + "Seen %s %s times", address, new_devices[address]) new_devices[address] += 1 if new_devices[address] >= MIN_SEEN_NEW: _LOGGER.debug("Adding %s to tracked devices", address) diff --git a/homeassistant/components/device_tracker/bluetooth_tracker.py b/homeassistant/components/device_tracker/bluetooth_tracker.py index f71f8c4271a..9e0957e363f 100644 --- a/homeassistant/components/device_tracker/bluetooth_tracker.py +++ b/homeassistant/components/device_tracker/bluetooth_tracker.py @@ -1,4 +1,9 @@ -"""Tracking for bluetooth devices.""" +""" +Tracking for bluetooth devices. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/device_tracker.bluetooth_tracker/ +""" import logging import voluptuous as vol @@ -22,7 +27,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_scanner(hass, config, see, discovery_info=None): - """Setup the Bluetooth Scanner.""" + """Set up the Bluetooth Scanner.""" # pylint: disable=import-error import bluetooth @@ -31,11 +36,10 @@ def setup_scanner(hass, config, see, discovery_info=None): see(mac=BT_PREFIX + device[0], host_name=device[1]) def discover_devices(): - """Discover bluetooth devices.""" - result = bluetooth.discover_devices(duration=8, - lookup_names=True, - flush_cache=True, - lookup_class=False) + """Discover Bluetooth devices.""" + result = bluetooth.discover_devices( + duration=8, lookup_names=True, flush_cache=True, + lookup_class=False) _LOGGER.debug("Bluetooth devices discovered = " + str(len(result))) return result @@ -47,14 +51,14 @@ def setup_scanner(hass, config, see, discovery_info=None): # We just need the devices so set consider_home and home range # to 0 for device in load_config(yaml_path, hass, 0): - # check if device is a valid bluetooth device + # Check if device is a valid bluetooth device if device.mac and device.mac[:3].upper() == BT_PREFIX: if device.track: devs_to_track.append(device.mac[3:]) else: devs_donot_track.append(device.mac[3:]) - # if track new devices is true discover new devices on startup. + # If track new devices is true discover new devices on startup. track_new = config.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) if track_new: for dev in discover_devices(): @@ -66,7 +70,7 @@ def setup_scanner(hass, config, see, discovery_info=None): interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) def update_bluetooth(now): - """Lookup bluetooth device and update status.""" + """Lookup Bluetooth device and update status.""" try: if track_new: for dev in discover_devices(): @@ -74,14 +78,14 @@ def setup_scanner(hass, config, see, discovery_info=None): dev[0] not in devs_donot_track: devs_to_track.append(dev[0]) for mac in devs_to_track: - _LOGGER.debug("Scanning " + mac) + _LOGGER.debug("Scanning %s", mac) result = bluetooth.lookup_name(mac, timeout=5) if not result: # Could not lookup device name continue see_device((mac, result)) except bluetooth.BluetoothError: - _LOGGER.exception('Error looking up bluetooth device!') + _LOGGER.exception("Error looking up Bluetooth device") track_point_in_utc_time( hass, update_bluetooth, dt_util.utcnow() + interval) diff --git a/homeassistant/components/device_tracker/bt_home_hub_5.py b/homeassistant/components/device_tracker/bt_home_hub_5.py index 301ec61abc2..5c1a14b446b 100644 --- a/homeassistant/components/device_tracker/bt_home_hub_5.py +++ b/homeassistant/components/device_tracker/bt_home_hub_5.py @@ -21,13 +21,11 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) - _LOGGER = logging.getLogger(__name__) - _MAC_REGEX = re.compile(r'(([0-9A-Fa-f]{1,2}\:){5}[0-9A-Fa-f]{1,2})') +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string }) @@ -46,7 +44,7 @@ class BTHomeHub5DeviceScanner(DeviceScanner): def __init__(self, config): """Initialise the scanner.""" - _LOGGER.info('Initialising BT Home Hub 5') + _LOGGER.info("Initialising BT Home Hub 5") self.host = config.get(CONF_HOST, '192.168.1.254') self.lock = threading.Lock() @@ -87,12 +85,12 @@ class BTHomeHub5DeviceScanner(DeviceScanner): return False with self.lock: - _LOGGER.info('Scanning') + _LOGGER.info("Scanning") data = _get_homehub_data(self.url) if not data: - _LOGGER.warning('Error scanning devices') + _LOGGER.warning("Error scanning devices") return False self.last_results = data diff --git a/homeassistant/components/device_tracker/cisco_ios.py b/homeassistant/components/device_tracker/cisco_ios.py index 95319a872ae..35ffa754348 100644 --- a/homeassistant/components/device_tracker/cisco_ios.py +++ b/homeassistant/components/device_tracker/cisco_ios.py @@ -16,7 +16,6 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, \ CONF_PORT from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -57,7 +56,7 @@ class CiscoDeviceScanner(DeviceScanner): # pylint: disable=no-self-use def get_device_name(self, device): - """The firmware doesn't save the name of the wireless device.""" + """Get the firmware doesn't save the name of the wireless device.""" return None def scan_devices(self): @@ -135,9 +134,9 @@ class CiscoDeviceScanner(DeviceScanner): devices_result = cisco_ssh.before - return devices_result.decode("utf-8") + return devices_result.decode('utf-8') except pxssh.ExceptionPxssh as px_e: - _LOGGER.error("pxssh failed on login.") + _LOGGER.error("pxssh failed on login") _LOGGER.error(px_e) return None diff --git a/homeassistant/components/device_tracker/ddwrt.py b/homeassistant/components/device_tracker/ddwrt.py index 2c8a2ec4907..4f1efcdb27c 100644 --- a/homeassistant/components/device_tracker/ddwrt.py +++ b/homeassistant/components/device_tracker/ddwrt.py @@ -18,7 +18,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -108,7 +107,7 @@ class DdWrtDeviceScanner(DeviceScanner): Return boolean if scanning successful. """ with self.lock: - _LOGGER.info('Checking ARP') + _LOGGER.info("Checking ARP") url = 'http://{}/Status_Wireless.live.asp'.format(self.host) data = self.get_ddwrt_data(url) @@ -137,22 +136,19 @@ class DdWrtDeviceScanner(DeviceScanner): """Retrieve data from DD-WRT and return parsed result.""" try: response = requests.get( - url, - auth=(self.username, self.password), - timeout=4) + url, auth=(self.username, self.password), timeout=4) except requests.exceptions.Timeout: - _LOGGER.exception('Connection to the router timed out') + _LOGGER.exception("Connection to the router timed out") return if response.status_code == 200: return _parse_ddwrt_response(response.text) elif response.status_code == 401: # Authentication error _LOGGER.exception( - 'Failed to authenticate, ' - 'please check your username and password') + "Failed to authenticate, check your username and password") return else: - _LOGGER.error('Invalid response from ddwrt: %s', response) + _LOGGER.error("Invalid response from DD-WRT: %s", response) def _parse_ddwrt_response(data_str): diff --git a/homeassistant/components/device_tracker/demo.py b/homeassistant/components/device_tracker/demo.py index dfd50a2b991..608fc560cf9 100644 --- a/homeassistant/components/device_tracker/demo.py +++ b/homeassistant/components/device_tracker/demo.py @@ -1,11 +1,16 @@ -"""Demo platform for the device tracker.""" +""" +Demo platform for the Device tracker component. + +For more details about this platform, please refer to the documentation +https://home-assistant.io/components/demo/ +""" import random from homeassistant.components.device_tracker import DOMAIN def setup_scanner(hass, config, see, discovery_info=None): - """Setup the demo tracker.""" + """Set up the demo tracker.""" def offset(): """Return random offset.""" return (random.randrange(500, 2000)) / 2e5 * random.choice((-1, 1)) diff --git a/homeassistant/components/device_tracker/fritz.py b/homeassistant/components/device_tracker/fritz.py index a11139afa0f..25de0a35c82 100644 --- a/homeassistant/components/device_tracker/fritz.py +++ b/homeassistant/components/device_tracker/fritz.py @@ -17,7 +17,6 @@ from homeassistant.util import Throttle REQUIREMENTS = ['fritzconnection==0.6.3'] -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -53,9 +52,8 @@ class FritzBoxScanner(DeviceScanner): # Establish a connection to the FRITZ!Box. try: - self.fritz_box = fc.FritzHosts(address=self.host, - user=self.username, - password=self.password) + self.fritz_box = fc.FritzHosts( + address=self.host, user=self.username, password=self.password) except (ValueError, TypeError): self.fritz_box = None @@ -65,12 +63,12 @@ class FritzBoxScanner(DeviceScanner): self.success_init = False if self.success_init: - _LOGGER.info('Successfully connected to %s', + _LOGGER.info("Successfully connected to %s", self.fritz_box.modelname) self._update_info() else: - _LOGGER.error('Failed to establish connection to FRITZ!Box ' - 'with IP: %s', self.host) + _LOGGER.error("Failed to establish connection to FRITZ!Box " + "with IP: %s", self.host) def scan_devices(self): """Scan for new devices and return a list of found device ids.""" @@ -96,6 +94,6 @@ class FritzBoxScanner(DeviceScanner): if not self.success_init: return False - _LOGGER.info('Scanning') + _LOGGER.info("Scanning") self.last_results = self.fritz_box.get_hosts_info() return True diff --git a/homeassistant/components/device_tracker/gpslogger.py b/homeassistant/components/device_tracker/gpslogger.py index c76c8fdd51b..733127cb0f2 100644 --- a/homeassistant/components/device_tracker/gpslogger.py +++ b/homeassistant/components/device_tracker/gpslogger.py @@ -20,14 +20,14 @@ DEPENDENCIES = ['http'] def setup_scanner(hass, config, see, discovery_info=None): - """Setup an endpoint for the GPSLogger application.""" + """Set up an endpoint for the GPSLogger application.""" hass.http.register_view(GPSLoggerView(see)) return True class GPSLoggerView(HomeAssistantView): - """View to handle gpslogger requests.""" + """View to handle GPSLogger requests.""" url = '/api/gpslogger' name = 'api:gpslogger' @@ -38,21 +38,20 @@ class GPSLoggerView(HomeAssistantView): @asyncio.coroutine def get(self, request): - """A GPSLogger message received as GET.""" + """Handle for GPSLogger message received as GET.""" res = yield from self._handle(request.app['hass'], request.GET) return res @asyncio.coroutine def _handle(self, hass, data): - """Handle gpslogger request.""" + """Handle GPSLogger requests.""" if 'latitude' not in data or 'longitude' not in data: return ('Latitude and longitude not specified.', HTTP_UNPROCESSABLE_ENTITY) if 'device' not in data: - _LOGGER.error('Device id not specified.') - return ('Device id not specified.', - HTTP_UNPROCESSABLE_ENTITY) + _LOGGER.error("Device id not specified") + return ('Device id not specified.', HTTP_UNPROCESSABLE_ENTITY) device = data['device'].replace('-', '') gps_location = (data['latitude'], data['longitude']) diff --git a/homeassistant/components/device_tracker/icloud.py b/homeassistant/components/device_tracker/icloud.py index b6fd9121295..194a2f4bfac 100644 --- a/homeassistant/components/device_tracker/icloud.py +++ b/homeassistant/components/device_tracker/icloud.py @@ -55,8 +55,12 @@ DEVICESTATUSSET = ['features', 'maxMsgChar', 'darkWake', 'fmlyShare', 'wipedTimestamp', 'modelDisplayName', 'locationEnabled', 'isMac', 'locFoundEnabled'] -DEVICESTATUSCODES = {'200': 'online', '201': 'offline', '203': 'pending', - '204': 'unregistered'} +DEVICESTATUSCODES = { + '200': 'online', + '201': 'offline', + '203': 'pending', + '204': 'unregistered', +} SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ACCOUNTNAME): vol.All(cv.ensure_list, [cv.slugify]), @@ -87,7 +91,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): return False def lost_iphone(call): - """Call the lost iphone function if the device is found.""" + """Call the lost iPhone function if the device is found.""" accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS) devicename = call.data.get(ATTR_DEVICENAME) for account in accounts: @@ -97,7 +101,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): schema=SERVICE_SCHEMA) def update_icloud(call): - """Call the update function of an icloud account.""" + """Call the update function of an iCloud account.""" accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS) devicename = call.data.get(ATTR_DEVICENAME) for account in accounts: @@ -107,7 +111,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): schema=SERVICE_SCHEMA) def reset_account_icloud(call): - """Reset an icloud account.""" + """Reset an iCloud account.""" accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS) for account in accounts: if account in ICLOUDTRACKERS: @@ -116,7 +120,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): reset_account_icloud, schema=SERVICE_SCHEMA) def setinterval(call): - """Call the update function of an icloud account.""" + """Call the update function of an iCloud account.""" accounts = call.data.get(ATTR_ACCOUNTNAME, ICLOUDTRACKERS) interval = call.data.get(ATTR_INTERVAL) devicename = call.data.get(ATTR_DEVICENAME) @@ -132,7 +136,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None): class Icloud(DeviceScanner): - """Represent an icloud account in Home Assistant.""" + """Representation of an iCloud account.""" def __init__(self, hass, username, password, name, see): """Initialize an iCloud account.""" @@ -157,12 +161,10 @@ class Icloud(DeviceScanner): randomseconds = random.randint(10, 59) track_utc_time_change( - self.hass, self.keep_alive, - second=randomseconds - ) + self.hass, self.keep_alive, second=randomseconds) def reset_account_icloud(self): - """Reset an icloud account.""" + """Reset an iCloud account.""" from pyicloud import PyiCloudService from pyicloud.exceptions import ( PyiCloudFailedLoginException, PyiCloudNoDevicesException) @@ -178,7 +180,7 @@ class Icloud(DeviceScanner): verify=True) except PyiCloudFailedLoginException as error: self.api = None - _LOGGER.error('Error logging into iCloud Service: %s', error) + _LOGGER.error("Error logging into iCloud Service: %s", error) return try: @@ -196,12 +198,12 @@ class Icloud(DeviceScanner): _LOGGER.error('No iCloud Devices found!') def icloud_trusted_device_callback(self, callback_data): - """The trusted device is chosen.""" + """Handle chosen trusted devices.""" self._trusted_device = int(callback_data.get('trusted_device')) self._trusted_device = self.api.trusted_devices[self._trusted_device] if not self.api.send_verification_code(self._trusted_device): - _LOGGER.error('Failed to send verification code') + _LOGGER.error("Failed to send verification code") self._trusted_device = None return @@ -223,8 +225,7 @@ class Icloud(DeviceScanner): devices = self.api.trusted_devices for i, device in enumerate(devices): devicename = device.get( - 'deviceName', - 'SMS to %s' % device.get('phoneNumber')) + 'deviceName', 'SMS to %s' % device.get('phoneNumber')) devicesstring += "{}: {};".format(i, devicename) _CONFIGURING[self.accountname] = configurator.request_config( @@ -239,7 +240,7 @@ class Icloud(DeviceScanner): ) def icloud_verification_callback(self, callback_data): - """The trusted device is chosen.""" + """Handle the chosen trusted device.""" from pyicloud.exceptions import PyiCloudException self._verification_code = callback_data.get('code') @@ -249,7 +250,7 @@ class Icloud(DeviceScanner): raise PyiCloudException('Unknown failure') except PyiCloudException as error: # Reset to the inital 2FA state to allow the user to retry - _LOGGER.error('Failed to verify verification code: %s', error) + _LOGGER.error("Failed to verify verification code: %s", error) self._trusted_device = None self._verification_code = None @@ -262,7 +263,7 @@ class Icloud(DeviceScanner): configurator.request_done(request_id) def icloud_need_verification_code(self): - """We need a verification code.""" + """Return the verification code.""" configurator = get_component('configurator') if self.accountname in _CONFIGURING: return @@ -277,7 +278,7 @@ class Icloud(DeviceScanner): ) def keep_alive(self, now): - """Keep the api alive.""" + """Keep the API alive.""" if self.api is None: self.reset_account_icloud() @@ -302,7 +303,7 @@ class Icloud(DeviceScanner): self._trusted_device = None self._verification_code = None except PyiCloudException as error: - _LOGGER.error("Error setting up 2fa: %s", error) + _LOGGER.error("Error setting up 2FA: %s", error) else: self.api.authenticate() @@ -320,8 +321,8 @@ class Icloud(DeviceScanner): zone_state = self.hass.states.get('zone.home') zone_state_lat = zone_state.attributes['latitude'] zone_state_long = zone_state.attributes['longitude'] - distancefromhome = distance(latitude, longitude, zone_state_lat, - zone_state_long) + distancefromhome = distance( + latitude, longitude, zone_state_lat, zone_state_long) distancefromhome = round(distancefromhome / 1000, 1) currentzone = active_zone(self.hass, latitude, longitude) @@ -400,7 +401,7 @@ class Icloud(DeviceScanner): _LOGGER.error('No iCloud Devices found!') def lost_iphone(self, devicename): - """Call the lost iphone function if the device is found.""" + """Call the lost iPhone function if the device is found.""" if self.api is None: return @@ -428,13 +429,13 @@ class Icloud(DeviceScanner): for device in self.devices: self.devices[device].location() except PyiCloudNoDevicesException: - _LOGGER.error('No iCloud Devices found!') + _LOGGER.error("No iCloud Devices found") def setinterval(self, interval=None, devicename=None): """Set the interval of the given devices.""" devs = [devicename] if devicename else self.devices for device in devs: - devid = DOMAIN + '.' + device + devid = '{}.{}'.format(DOMAIN, device) devicestate = self.hass.states.get(devid) if interval is not None: if devicestate is not None: diff --git a/homeassistant/components/device_tracker/linksys_ap.py b/homeassistant/components/device_tracker/linksys_ap.py index fc8f9f96a37..a337f71cec4 100644 --- a/homeassistant/components/device_tracker/linksys_ap.py +++ b/homeassistant/components/device_tracker/linksys_ap.py @@ -99,9 +99,8 @@ class LinksysAPDeviceScanner(object): # No, the '&&' is not a typo - this is expected by the web interface. login = base64.b64encode(bytes(self.username, 'utf8')).decode('ascii') pwd = base64.b64encode(bytes(self.password, 'utf8')).decode('ascii') + url = 'https://{}/StatusClients.htm&&unit={}&vap=0'.format( + self.host, unit) return requests.get( - 'https://%s/StatusClients.htm&&unit=%s&vap=0' % (self.host, unit), - timeout=DEFAULT_TIMEOUT, - verify=self.verify_ssl, - cookies={'LoginName': login, - 'LoginPWD': pwd}) + url, timeout=DEFAULT_TIMEOUT, verify=self.verify_ssl, + cookies={'LoginName': login, 'LoginPWD': pwd}) diff --git a/homeassistant/components/device_tracker/luci.py b/homeassistant/components/device_tracker/luci.py index 8cc6af48767..24af81b281e 100644 --- a/homeassistant/components/device_tracker/luci.py +++ b/homeassistant/components/device_tracker/luci.py @@ -20,7 +20,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -46,10 +45,7 @@ def get_scanner(hass, config): class LuciDeviceScanner(DeviceScanner): - """This class queries a wireless router running OpenWrt firmware. - - Adapted from Tomato scanner. - """ + """This class queries a wireless router running OpenWrt firmware.""" def __init__(self, config): """Initialize the scanner.""" @@ -106,7 +102,7 @@ class LuciDeviceScanner(DeviceScanner): return False with self.lock: - _LOGGER.info('Checking ARP') + _LOGGER.info("Checking ARP") url = 'http://{}/cgi-bin/luci/rpc/sys'.format(self.host) @@ -114,7 +110,7 @@ class LuciDeviceScanner(DeviceScanner): result = _req_json_rpc(url, 'net.arptable', params={'auth': self.token}) except InvalidLuciTokenError: - _LOGGER.info('Refreshing token') + _LOGGER.info("Refreshing token") self.refresh_token() return False @@ -138,28 +134,27 @@ def _req_json_rpc(url, method, *args, **kwargs): try: res = requests.post(url, data=data, timeout=5, **kwargs) except requests.exceptions.Timeout: - _LOGGER.exception('Connection to the router timed out') + _LOGGER.exception("Connection to the router timed out") return if res.status_code == 200: try: result = res.json() except ValueError: # If json decoder could not parse the response - _LOGGER.exception('Failed to parse response from luci') + _LOGGER.exception("Failed to parse response from luci") return try: return result['result'] except KeyError: - _LOGGER.exception('No result in response from luci') + _LOGGER.exception("No result in response from luci") return elif res.status_code == 401: # Authentication error _LOGGER.exception( - "Failed to authenticate, " - "please check your username and password") + "Failed to authenticate, check your username and password") return elif res.status_code == 403: - _LOGGER.error('Luci responded with a 403 Invalid token') + _LOGGER.error("Luci responded with a 403 Invalid token") raise InvalidLuciTokenError else: diff --git a/homeassistant/components/device_tracker/mqtt.py b/homeassistant/components/device_tracker/mqtt.py index 1f7fa9c1b84..aab5b43acea 100644 --- a/homeassistant/components/device_tracker/mqtt.py +++ b/homeassistant/components/device_tracker/mqtt.py @@ -27,7 +27,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(mqtt.SCHEMA_BASE).extend({ @asyncio.coroutine def async_setup_scanner(hass, config, async_see, discovery_info=None): - """Setup the MQTT tracker.""" + """Set up the MQTT tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] @@ -35,7 +35,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): @callback def async_tracker_message_received(topic, payload, qos): - """MQTT message received.""" + """Handle received MQTT message.""" hass.async_add_job( async_see(dev_id=dev_id_lookup[topic], location_name=payload)) diff --git a/homeassistant/components/device_tracker/mqtt_json.py b/homeassistant/components/device_tracker/mqtt_json.py index da85055ba96..0ef4f1835b6 100644 --- a/homeassistant/components/device_tracker/mqtt_json.py +++ b/homeassistant/components/device_tracker/mqtt_json.py @@ -37,7 +37,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(mqtt.SCHEMA_BASE).extend({ @asyncio.coroutine def async_setup_scanner(hass, config, async_see, discovery_info=None): - """Setup the MQTT tracker.""" + """Set up the MQTT JSON tracker.""" devices = config[CONF_DEVICES] qos = config[CONF_QOS] @@ -45,18 +45,18 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): @callback def async_tracker_message_received(topic, payload, qos): - """MQTT message received.""" + """Handle received MQTT message.""" dev_id = dev_id_lookup[topic] try: data = GPS_JSON_PAYLOAD_SCHEMA(json.loads(payload)) except vol.MultipleInvalid: - _LOGGER.error('Skipping update for following data ' - 'because of missing or malformatted data: %s', + _LOGGER.error("Skipping update for following data " + "because of missing or malformatted data: %s", payload) return except ValueError: - _LOGGER.error('Error parsing JSON payload: %s', payload) + _LOGGER.error("Error parsing JSON payload: %s", payload) return kwargs = _parse_see_args(dev_id, data) diff --git a/homeassistant/components/device_tracker/mysensors.py b/homeassistant/components/device_tracker/mysensors.py index 04801f834df..00bd2eef6e0 100644 --- a/homeassistant/components/device_tracker/mysensors.py +++ b/homeassistant/components/device_tracker/mysensors.py @@ -15,12 +15,12 @@ _LOGGER = logging.getLogger(__name__) def setup_scanner(hass, config, see, discovery_info=None): - """Setup the MySensors tracker.""" + """Set up the MySensors tracker.""" def mysensors_callback(gateway, msg): """Callback for mysensors platform.""" node = gateway.sensors[msg.node_id] if node.sketch_name is None: - _LOGGER.debug('No sketch_name: node %s', msg.node_id) + _LOGGER.debug("No sketch_name: node %s", msg.node_id) return pres = gateway.const.Presentation @@ -35,8 +35,8 @@ def setup_scanner(hass, config, see, discovery_info=None): try: latitude, longitude, _ = position.split(',') except ValueError: - _LOGGER.error('Payload for V_POSITION %s is not of format ' - 'latitude,longitude,altitude', position) + _LOGGER.error("Payload for V_POSITION %s is not of format " + "latitude, longitude, altitude", position) return name = '{} {} {}'.format( node.sketch_name, msg.node_id, child.id) diff --git a/homeassistant/components/device_tracker/netgear.py b/homeassistant/components/device_tracker/netgear.py index d6716dfb9b1..b3ec442198e 100644 --- a/homeassistant/components/device_tracker/netgear.py +++ b/homeassistant/components/device_tracker/netgear.py @@ -17,11 +17,11 @@ from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT) from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) +REQUIREMENTS = ['pynetgear==0.3.3'] _LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ['pynetgear==0.3.3'] + +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) DEFAULT_HOST = 'routerlogin.net' DEFAULT_USER = 'admin' @@ -60,7 +60,7 @@ class NetgearDeviceScanner(DeviceScanner): self._api = pynetgear.Netgear(password, host, username, port) - _LOGGER.info('Logging in') + _LOGGER.info("Logging in") results = self._api.get_attached_devices() @@ -69,7 +69,7 @@ class NetgearDeviceScanner(DeviceScanner): if self.success_init: self.last_results = results else: - _LOGGER.error('Failed to Login') + _LOGGER.error("Failed to Login") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" @@ -95,11 +95,11 @@ class NetgearDeviceScanner(DeviceScanner): return with self.lock: - _LOGGER.info('Scanning') + _LOGGER.info("Scanning") results = self._api.get_attached_devices() if results is None: - _LOGGER.warning('Error scanning devices') + _LOGGER.warning("Error scanning devices") self.last_results = results or [] diff --git a/homeassistant/components/device_tracker/nmap_tracker.py b/homeassistant/components/device_tracker/nmap_tracker.py index 182826a1f62..99dfc3829d7 100644 --- a/homeassistant/components/device_tracker/nmap_tracker.py +++ b/homeassistant/components/device_tracker/nmap_tracker.py @@ -80,7 +80,7 @@ class NmapDeviceScanner(DeviceScanner): self.home_interval = timedelta(minutes=minutes) self.success_init = self._update_info() - _LOGGER.info("nmap scanner initialized") + _LOGGER.info("Scanner initialized") def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" diff --git a/homeassistant/components/device_tracker/owntracks.py b/homeassistant/components/device_tracker/owntracks.py index 156e9d6a08a..40ab48b384a 100644 --- a/homeassistant/components/device_tracker/owntracks.py +++ b/homeassistant/components/device_tracker/owntracks.py @@ -85,8 +85,8 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): try: keylen, decrypt = get_cipher() except OSError: - _LOGGER.warning('Ignoring encrypted payload ' - 'because libsodium not installed.') + _LOGGER.warning( + "Ignoring encrypted payload because libsodium not installed") return None if isinstance(secret, dict): @@ -95,9 +95,9 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): key = secret if key is None: - _LOGGER.warning('Ignoring encrypted payload ' - 'because no decryption key known ' - 'for topic %s.', topic) + _LOGGER.warning( + "Ignoring encrypted payload because no decryption key known " + "for topic %s", topic) return None key = key.encode("utf-8") @@ -111,9 +111,9 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): _LOGGER.debug("Decrypted payload: %s", message) return message except ValueError: - _LOGGER.warning('Ignoring encrypted payload ' - 'because unable to decrypt using key ' - 'for topic %s.', topic) + _LOGGER.warning( + "Ignoring encrypted payload because unable to decrypt using " + "key for topic %s", topic) return None # pylint: disable=too-many-return-statements @@ -123,7 +123,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): data = json.loads(payload) except ValueError: # If invalid JSON - _LOGGER.error('Unable to parse payload as JSON: %s', payload) + _LOGGER.error("Unable to parse payload as JSON: %s", payload) return None if isinstance(data, dict) and \ @@ -136,22 +136,22 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): return validate_payload(topic, plaintext_payload, data_type) if not isinstance(data, dict) or data.get('_type') != data_type: - _LOGGER.debug('Skipping %s update for following data ' - 'because of missing or malformatted data: %s', + _LOGGER.debug("Skipping %s update for following data " + "because of missing or malformatted data: %s", data_type, data) return None if data_type == VALIDATE_TRANSITION or data_type == VALIDATE_WAYPOINTS: return data if max_gps_accuracy is not None and \ convert(data.get('acc'), float, 0.0) > max_gps_accuracy: - _LOGGER.info('Ignoring %s update because expected GPS ' - 'accuracy %s is not met: %s', + _LOGGER.info("Ignoring %s update because expected GPS " + "accuracy %s is not met: %s", data_type, max_gps_accuracy, payload) return None if convert(data.get('acc'), float, 1.0) == 0.0: - _LOGGER.warning('Ignoring %s update because GPS accuracy ' - 'is zero: %s', - data_type, payload) + _LOGGER.warning( + "Ignoring %s update because GPS accuracy is zero: %s", + data_type, payload) return None return data @@ -169,7 +169,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): if regions_entered[dev_id]: _LOGGER.debug( - "location update ignored - inside region %s", + "Location update ignored, inside region %s", regions_entered[-1]) return @@ -178,7 +178,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): @callback def async_owntracks_event_update(topic, payload, qos): - """MQTT event (geofences) received.""" + """Handle MQTT event (geofences).""" # Docs on available data: # http://owntracks.org/booklet/tech/json/#_typetransition data = validate_payload(topic, payload, VALIDATE_TRANSITION) @@ -242,15 +242,14 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): if data['acc'] == 0.0: valid_gps = False _LOGGER.warning( - 'Ignoring GPS in region exit because accuracy' - 'is zero: %s', - payload) + "Ignoring GPS in region exit because accuracy" + "is zero: %s", payload) if (max_gps_accuracy is not None and data['acc'] > max_gps_accuracy): valid_gps = False _LOGGER.info( - 'Ignoring GPS in region exit because expected ' - 'GPS accuracy %s is not met: %s', + "Ignoring GPS in region exit because expected " + "GPS accuracy %s is not met: %s", max_gps_accuracy, payload) if valid_gps: hass.async_add_job(async_see(**kwargs)) @@ -267,7 +266,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): leave_event() else: _LOGGER.error( - 'Misformatted mqtt msgs, _type=transition, event=%s', + "Misformatted mqtt msgs, _type=transition, event=%s", data['event']) return diff --git a/homeassistant/components/device_tracker/ping.py b/homeassistant/components/device_tracker/ping.py index ee9a4d19d37..1f21a25359c 100644 --- a/homeassistant/components/device_tracker/ping.py +++ b/homeassistant/components/device_tracker/ping.py @@ -37,8 +37,8 @@ class Host(object): self.ip_address = ip_address self.dev_id = dev_id self._count = config[CONF_PING_COUNT] - if sys.platform == "win32": - self._ping_cmd = ['ping', '-n 1', '-w 1000', self.ip_address] + if sys.platform == 'win32': + self._ping_cmd = ['ping', '-n 1', '-w', '1000', self.ip_address] else: self._ping_cmd = ['ping', '-n', '-q', '-c1', '-W1', self.ip_address] @@ -67,7 +67,7 @@ class Host(object): def setup_scanner(hass, config, see, discovery_info=None): - """Setup the Host objects and return the update function.""" + """Set up the Host objects and return the update function.""" hosts = [Host(ip, dev_id, hass, config) for (dev_id, ip) in config[const.CONF_HOSTS].items()] interval = timedelta(seconds=len(hosts) * config[CONF_PING_COUNT]) + \ diff --git a/homeassistant/components/device_tracker/swisscom.py b/homeassistant/components/device_tracker/swisscom.py index 530e39d3e57..d2a5a57e491 100644 --- a/homeassistant/components/device_tracker/swisscom.py +++ b/homeassistant/components/device_tracker/swisscom.py @@ -17,7 +17,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/device_tracker/tado.py b/homeassistant/components/device_tracker/tado.py index 63ed3e8819e..46096e62fbb 100644 --- a/homeassistant/components/device_tracker/tado.py +++ b/homeassistant/components/device_tracker/tado.py @@ -69,7 +69,7 @@ class TadoDeviceScanner(DeviceScanner): hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop)) self.success_init = self._update_info() - _LOGGER.info("Tado scanner initialized") + _LOGGER.info("Scanner initialized") @asyncio.coroutine def async_scan_devices(self): @@ -108,14 +108,12 @@ class TadoDeviceScanner(DeviceScanner): with async_timeout.timeout(10, loop=self.hass.loop): # Format the URL here, so we can log the template URL if # anything goes wrong without exposing username and password. - url = self.tadoapiurl.format(home_id=self.home_id, - username=self.username, - password=self.password) + url = self.tadoapiurl.format( + home_id=self.home_id, username=self.username, + password=self.password) - # Go get 'em! response = yield from self.websession.get(url) - # error on Tado webservice if response.status != 200: _LOGGER.warning( "Error %d on %s.", response.status, self.tadoapiurl) diff --git a/homeassistant/components/device_tracker/thomson.py b/homeassistant/components/device_tracker/thomson.py index e9ab4e347eb..6efe8d59beb 100644 --- a/homeassistant/components/device_tracker/thomson.py +++ b/homeassistant/components/device_tracker/thomson.py @@ -18,7 +18,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) _LOGGER = logging.getLogger(__name__) @@ -88,7 +87,7 @@ class ThomsonDeviceScanner(DeviceScanner): return False with self.lock: - _LOGGER.info('Checking ARP') + _LOGGER.info("Checking ARP") data = self.get_thomson_data() if not data: return False @@ -112,11 +111,11 @@ class ThomsonDeviceScanner(DeviceScanner): devices_result = telnet.read_until(b'=>').split(b'\r\n') telnet.write('exit\r\n'.encode('ascii')) except EOFError: - _LOGGER.exception('Unexpected response from router') + _LOGGER.exception("Unexpected response from router") return except ConnectionRefusedError: - _LOGGER.exception('Connection refused by router,' - ' is telnet enabled?') + _LOGGER.exception( + "Connection refused by router. Telnet enabled?") return devices = {} diff --git a/homeassistant/components/device_tracker/tomato.py b/homeassistant/components/device_tracker/tomato.py index 3f01600259b..51394ae64fe 100644 --- a/homeassistant/components/device_tracker/tomato.py +++ b/homeassistant/components/device_tracker/tomato.py @@ -19,10 +19,9 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) -CONF_HTTP_ID = "http_id" +CONF_HTTP_ID = 'http_id' _LOGGER = logging.getLogger(__name__) @@ -47,12 +46,10 @@ class TomatoDeviceScanner(DeviceScanner): host, http_id = config[CONF_HOST], config[CONF_HTTP_ID] username, password = config[CONF_USERNAME], config[CONF_PASSWORD] - self.req = requests.Request('POST', - 'http://{}/update.cgi'.format(host), - data={'_http_id': http_id, - 'exec': 'devlist'}, - auth=requests.auth.HTTPBasicAuth( - username, password)).prepare() + self.req = requests.Request( + 'POST', 'http://{}/update.cgi'.format(host), + data={'_http_id': http_id, 'exec': 'devlist'}, + auth=requests.auth.HTTPBasicAuth(username, password)).prepare() self.parse_api_pattern = re.compile(r"(?P\w*) = (?P.*);") @@ -112,20 +109,17 @@ class TomatoDeviceScanner(DeviceScanner): except requests.exceptions.ConnectionError: # We get this if we could not connect to the router or # an invalid http_id was supplied. - self.logger.exception(( - "Failed to connect to the router" - " or invalid http_id supplied")) + self.logger.exception("Failed to connect to the router or " + "invalid http_id supplied") return False except requests.exceptions.Timeout: # We get this if we could not connect to the router or # an invalid http_id was supplied. - self.logger.exception( - "Connection to the router timed out") + self.logger.exception("Connection to the router timed out") return False except ValueError: # If JSON decoder could not parse the response. - self.logger.exception( - "Failed to parse response from router") + self.logger.exception("Failed to parse response from router") return False diff --git a/homeassistant/components/device_tracker/tplink.py b/homeassistant/components/device_tracker/tplink.py index 8d476136d23..033ae84c712 100755 --- a/homeassistant/components/device_tracker/tplink.py +++ b/homeassistant/components/device_tracker/tplink.py @@ -20,7 +20,6 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) _LOGGER = logging.getLogger(__name__) @@ -69,7 +68,7 @@ class TplinkDeviceScanner(DeviceScanner): # pylint: disable=no-self-use def get_device_name(self, device): - """The firmware doesn't save the name of the wireless device.""" + """Get firmware doesn't save the name of the wireless device.""" return None @Throttle(MIN_TIME_BETWEEN_SCANS) @@ -83,8 +82,9 @@ class TplinkDeviceScanner(DeviceScanner): url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host) referer = 'http://{}'.format(self.host) - page = requests.get(url, auth=(self.username, self.password), - headers={'referer': referer}) + page = requests.get( + url, auth=(self.username, self.password), + headers={'referer': referer}, timeout=4) result = self.parse_macs.findall(page.text) @@ -105,7 +105,7 @@ class Tplink2DeviceScanner(TplinkDeviceScanner): # pylint: disable=no-self-use def get_device_name(self, device): - """The firmware doesn't save the name of the wireless device.""" + """Get firmware doesn't save the name of the wireless device.""" return self.last_results.get(device) @Throttle(MIN_TIME_BETWEEN_SCANS) @@ -130,8 +130,9 @@ class Tplink2DeviceScanner(TplinkDeviceScanner): cookie = 'Authorization=Basic {}' \ .format(b64_encoded_username_password) - response = requests.post(url, headers={'referer': referer, - 'cookie': cookie}) + response = requests.post( + url, headers={'referer': referer, 'cookie': cookie}, + timeout=4) try: result = response.json().get('data') @@ -166,7 +167,7 @@ class Tplink3DeviceScanner(TplinkDeviceScanner): # pylint: disable=no-self-use def get_device_name(self, device): - """The firmware doesn't save the name of the wireless device. + """Get the firmware doesn't save the name of the wireless device. We are forced to use the MAC address as name here. """ @@ -181,17 +182,16 @@ class Tplink3DeviceScanner(TplinkDeviceScanner): referer = 'http://{}/webpages/login.html'.format(self.host) # If possible implement rsa encryption of password here. - response = requests.post(url, - params={'operation': 'login', - 'username': self.username, - 'password': self.password}, - headers={'referer': referer}) + response = requests.post( + url, params={'operation': 'login', 'username': self.username, + 'password': self.password}, + headers={'referer': referer}, timeout=4) try: self.stok = response.json().get('data').get('stok') _LOGGER.info(self.stok) - regex_result = re.search('sysauth=(.*);', - response.headers['set-cookie']) + regex_result = re.search( + 'sysauth=(.*);', response.headers['set-cookie']) self.sysauth = regex_result.group(1) _LOGGER.info(self.sysauth) return True diff --git a/homeassistant/components/device_tracker/trackr.py b/homeassistant/components/device_tracker/trackr.py index 557d1f68b2a..84fb449c070 100644 --- a/homeassistant/components/device_tracker/trackr.py +++ b/homeassistant/components/device_tracker/trackr.py @@ -37,18 +37,18 @@ class TrackRDeviceScanner(object): """Initialize the TrackR device scanner.""" from pytrackr.api import trackrApiInterface self.hass = hass - self.api = trackrApiInterface(config.get(CONF_USERNAME), - config.get(CONF_PASSWORD)) + self.api = trackrApiInterface( + config.get(CONF_USERNAME), config.get(CONF_PASSWORD)) self.see = see self.devices = self.api.get_trackrs() self._update_info() - track_utc_time_change(self.hass, self._update_info, - second=range(0, 60, 30)) + track_utc_time_change( + self.hass, self._update_info, second=range(0, 60, 30)) def _update_info(self, now=None) -> None: """Update the device info.""" - _LOGGER.debug('Updating devices %s', now) + _LOGGER.debug("Updating devices %s", now) # Update self.devices to collect new devices added # to the users account. diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py index 083e1599d11..31c7d32c4c1 100644 --- a/homeassistant/components/device_tracker/ubus.py +++ b/homeassistant/components/device_tracker/ubus.py @@ -70,9 +70,9 @@ class UbusDeviceScanner(DeviceScanner): """Return the name of the given device or None if we don't know.""" with self.lock: if self.leasefile is None: - result = _req_json_rpc(self.url, self.session_id, - 'call', 'uci', 'get', - config="dhcp", type="dnsmasq") + result = _req_json_rpc( + self.url, self.session_id, 'call', 'uci', 'get', + config="dhcp", type="dnsmasq") if result: values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] @@ -80,9 +80,9 @@ class UbusDeviceScanner(DeviceScanner): return if self.mac2name is None: - result = _req_json_rpc(self.url, self.session_id, - 'call', 'file', 'read', - path=self.leasefile) + result = _req_json_rpc( + self.url, self.session_id, 'call', 'file', 'read', + path=self.leasefile) if result: self.mac2name = dict() for line in result["data"].splitlines(): @@ -107,15 +107,15 @@ class UbusDeviceScanner(DeviceScanner): _LOGGER.info("Checking ARP") if not self.hostapd: - hostapd = _req_json_rpc(self.url, self.session_id, - 'list', 'hostapd.*', '') + hostapd = _req_json_rpc( + self.url, self.session_id, 'list', 'hostapd.*', '') self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 for hostapd in self.hostapd: - result = _req_json_rpc(self.url, self.session_id, - 'call', hostapd, 'get_clients') + result = _req_json_rpc( + self.url, self.session_id, 'call', hostapd, 'get_clients') if result: results = results + 1 diff --git a/homeassistant/components/device_tracker/unifi.py b/homeassistant/components/device_tracker/unifi.py index e46abda08d0..42b5070b046 100644 --- a/homeassistant/components/device_tracker/unifi.py +++ b/homeassistant/components/device_tracker/unifi.py @@ -15,29 +15,31 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD from homeassistant.const import CONF_VERIFY_SSL -# Unifi package doesn't list urllib3 as a requirement REQUIREMENTS = ['pyunifi==2.0'] _LOGGER = logging.getLogger(__name__) CONF_PORT = 'port' CONF_SITE_ID = 'site_id' + +DEFAULT_HOST = 'localhost' +DEFAULT_PORT = 8443 DEFAULT_VERIFY_SSL = True NOTIFICATION_ID = 'unifi_notification' NOTIFICATION_TITLE = 'Unifi Device Tracker Setup' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_HOST, default='localhost'): cv.string, + vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_SITE_ID, default='default'): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, - vol.Required(CONF_PORT, default=8443): cv.port, + vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, }) def get_scanner(hass, config): - """Setup Unifi device_tracker.""" + """Set up the Unifi device_tracker.""" from pyunifi.controller import Controller host = config[DOMAIN].get(CONF_HOST) @@ -52,7 +54,7 @@ def get_scanner(hass, config): ctrl = Controller(host, username, password, port, version='v4', site_id=site_id, ssl_verify=verify_ssl) except urllib.error.HTTPError as ex: - _LOGGER.error('Failed to connect to Unifi: %s', ex) + _LOGGER.error("Failed to connect to Unifi: %s", ex) persistent_notification.create( hass, 'Failed to connect to Unifi. ' 'Error: {}
' @@ -78,7 +80,7 @@ class UnifiScanner(DeviceScanner): try: clients = self._controller.get_clients() except urllib.error.HTTPError as ex: - _LOGGER.error('Failed to scan clients: %s', ex) + _LOGGER.error("Failed to scan clients: %s", ex) clients = [] self._clients = {client['mac']: client for client in clients} @@ -96,5 +98,5 @@ class UnifiScanner(DeviceScanner): """ client = self._clients.get(mac, {}) name = client.get('name') or client.get('hostname') - _LOGGER.debug('Device %s name %s', mac, name) + _LOGGER.debug("Device %s name %s", mac, name) return name diff --git a/homeassistant/components/device_tracker/upc_connect.py b/homeassistant/components/device_tracker/upc_connect.py index cec00221aaf..ace7c4455a9 100644 --- a/homeassistant/components/device_tracker/upc_connect.py +++ b/homeassistant/components/device_tracker/upc_connect.py @@ -95,7 +95,7 @@ class UPCDeviceScanner(DeviceScanner): @asyncio.coroutine def async_get_device_name(self, device): - """The firmware doesn't save the name of the wireless device.""" + """Ge the firmware doesn't save the name of the wireless device.""" return None @asyncio.coroutine @@ -118,7 +118,7 @@ class UPCDeviceScanner(DeviceScanner): 'Password': self.password, }) - # successfull? + # Successful? return data is not None except (asyncio.TimeoutError, aiohttp.ClientError): diff --git a/homeassistant/components/device_tracker/volvooncall.py b/homeassistant/components/device_tracker/volvooncall.py index 9d5220b877c..df1c778dcb6 100644 --- a/homeassistant/components/device_tracker/volvooncall.py +++ b/homeassistant/components/device_tracker/volvooncall.py @@ -13,7 +13,7 @@ _LOGGER = logging.getLogger(__name__) def setup_scanner(hass, config, see, discovery_info=None): - """Setup Volvo tracker.""" + """Set up the Volvo tracker.""" if discovery_info is None: return @@ -24,7 +24,7 @@ def setup_scanner(hass, config, see, discovery_info=None): dev_id = 'volvo_' + slugify(host_name) def see_vehicle(vehicle): - """Callback for reporting vehicle position.""" + """Handle the reporting of the vehicle position.""" see(dev_id=dev_id, host_name=host_name, gps=(vehicle.position['latitude'], diff --git a/homeassistant/components/device_tracker/xiaomi.py b/homeassistant/components/device_tracker/xiaomi.py index 7c5c415f054..e87cae3d50b 100644 --- a/homeassistant/components/device_tracker/xiaomi.py +++ b/homeassistant/components/device_tracker/xiaomi.py @@ -17,11 +17,10 @@ from homeassistant.components.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.util import Throttle -# Return cached results if last scan was less then this time ago. -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) - _LOGGER = logging.getLogger(__name__) +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5) + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME, default='admin'): cv.string, @@ -98,12 +97,12 @@ class XiaomiDeviceScanner(DeviceScanner): Return the list if successful. """ - _LOGGER.info('Refreshing device list') + _LOGGER.info("Refreshing device list") result = _retrieve_list(self.host, self.token) if result: return result else: - _LOGGER.info('Refreshing token and retrying device list refresh') + _LOGGER.info("Refreshing token and retrying device list refresh") self.token = _get_token(self.host, self.username, self.password) return _retrieve_list(self.host, self.token) @@ -117,40 +116,40 @@ class XiaomiDeviceScanner(DeviceScanner): def _retrieve_list(host, token, **kwargs): - """"Get device list for the given host.""" + """Get device list for the given host.""" url = "http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist" url = url.format(host, token) try: res = requests.get(url, timeout=5, **kwargs) except requests.exceptions.Timeout: - _LOGGER.exception('Connection to the router timed out at URL [%s]', - url) + _LOGGER.exception( + "Connection to the router timed out at URL %s", url) return if res.status_code != 200: - _LOGGER.exception('Connection failed with http code [%s]', - res.status_code) + _LOGGER.exception( + "Connection failed with http code %s", res.status_code) return try: result = res.json() except ValueError: # If json decoder could not parse the response - _LOGGER.exception('Failed to parse response from mi router') + _LOGGER.exception("Failed to parse response from mi router") return try: xiaomi_code = result['code'] except KeyError: - _LOGGER.exception('No field code in response from mi router. %s', - result) + _LOGGER.exception( + "No field code in response from mi router. %s", result) return if xiaomi_code == 0: try: return result['list'] except KeyError: - _LOGGER.exception('No list in response from mi router. %s', result) + _LOGGER.exception("No list in response from mi router. %s", result) return else: _LOGGER.info( - 'Receive wrong Xiaomi code [%s], expected [0] in response [%s]', + "Receive wrong Xiaomi code %s, expected 0 in response %s", xiaomi_code, result) return @@ -162,14 +161,14 @@ def _get_token(host, username, password): try: res = requests.post(url, data=data, timeout=5) except requests.exceptions.Timeout: - _LOGGER.exception('Connection to the router timed out') + _LOGGER.exception("Connection to the router timed out") return if res.status_code == 200: try: result = res.json() except ValueError: - # If json decoder could not parse the response - _LOGGER.exception('Failed to parse response from mi router') + # If JSON decoder could not parse the response + _LOGGER.exception("Failed to parse response from mi router") return try: return result['token'] diff --git a/homeassistant/components/dweet.py b/homeassistant/components/dweet.py index d812daf50a6..b4e8d68e960 100644 --- a/homeassistant/components/dweet.py +++ b/homeassistant/components/dweet.py @@ -33,7 +33,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Dweet.io component.""" + """Set up the Dweet.io component.""" conf = config[DOMAIN] name = conf.get(CONF_NAME) whitelist = conf.get(CONF_WHITELIST) diff --git a/homeassistant/components/ecobee.py b/homeassistant/components/ecobee.py index f6aa0c33e0f..f217d177de0 100644 --- a/homeassistant/components/ecobee.py +++ b/homeassistant/components/ecobee.py @@ -68,7 +68,7 @@ def request_configuration(network, hass, config): def setup_ecobee(hass, network, config): - """Setup Ecobee thermostat.""" + """Set up the Ecobee thermostat.""" # If ecobee has a PIN then it needs to be configured. if network.pin is not None: request_configuration(network, hass, config) @@ -80,8 +80,8 @@ def setup_ecobee(hass, network, config): hold_temp = config[DOMAIN].get(CONF_HOLD_TEMP) - discovery.load_platform(hass, 'climate', DOMAIN, - {'hold_temp': hold_temp}, config) + discovery.load_platform( + hass, 'climate', DOMAIN, {'hold_temp': hold_temp}, config) discovery.load_platform(hass, 'sensor', DOMAIN, {}, config) discovery.load_platform(hass, 'binary_sensor', DOMAIN, {}, config) @@ -90,7 +90,7 @@ class EcobeeData(object): """Get the latest data and update the states.""" def __init__(self, config_file): - """Initialize the Ecobee data object.""" + """Init the Ecobee data object.""" from pyecobee import Ecobee self.ecobee = Ecobee(config_file) @@ -102,7 +102,7 @@ class EcobeeData(object): def setup(hass, config): - """Setup Ecobee. + """Set up the Ecobee. Will automatically load thermostat and sensor components to support devices discovered on the network. diff --git a/homeassistant/components/emulated_hue/__init__.py b/homeassistant/components/emulated_hue/__init__.py index 2412b283abe..567528b72ff 100644 --- a/homeassistant/components/emulated_hue/__init__.py +++ b/homeassistant/components/emulated_hue/__init__.py @@ -53,11 +53,9 @@ DEFAULT_TYPE = TYPE_GOOGLE CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Optional(CONF_HOST_IP): cv.string, - vol.Optional(CONF_LISTEN_PORT, default=DEFAULT_LISTEN_PORT): - vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)), + vol.Optional(CONF_LISTEN_PORT, default=DEFAULT_LISTEN_PORT): cv.port, vol.Optional(CONF_ADVERTISE_IP): cv.string, - vol.Optional(CONF_ADVERTISE_PORT): - vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)), + vol.Optional(CONF_ADVERTISE_PORT): cv.port, vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean, vol.Optional(CONF_OFF_MAPS_TO_ON_DOMAINS): cv.ensure_list, vol.Optional(CONF_EXPOSE_BY_DEFAULT): cv.boolean, @@ -111,8 +109,8 @@ def setup(hass, yaml_config): """Start the emulated hue bridge.""" upnp_listener.start() yield from server.start() - hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, - stop_emulated_hue_bridge) + hass.bus.async_listen_once( + EVENT_HOMEASSISTANT_STOP, stop_emulated_hue_bridge) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_emulated_hue_bridge) @@ -120,7 +118,7 @@ def setup(hass, yaml_config): class Config(object): - """Holds configuration variables for the emulated hue bridge.""" + """Hold configuration variables for the emulated hue bridge.""" def __init__(self, hass, conf): """Initialize the instance.""" @@ -130,8 +128,8 @@ class Config(object): self.cached_states = {} if self.type == TYPE_ALEXA: - _LOGGER.warning('Alexa type is deprecated and will be removed in a' - ' future version') + _LOGGER.warning("Alexa type is deprecated and will be removed in a" + "future version") # Get the IP address that will be passed to the Echo during discovery self.host_ip_addr = conf.get(CONF_HOST_IP) @@ -150,8 +148,8 @@ class Config(object): self.listen_port) if self.type == TYPE_GOOGLE and self.listen_port != 80: - _LOGGER.warning('When targetting Google Home, listening port has ' - 'to be port 80') + _LOGGER.warning("When targetting Google Home, listening port has " + "to be port 80") # Get whether or not UPNP binds to multicast address (239.255.255.250) # or to the unicast address (host_ip_addr) @@ -245,7 +243,7 @@ class Config(object): # OSError if file not found or unaccessible/no permissions # ValueError if could not parse JSON if not isinstance(err, FileNotFoundError): - _LOGGER.warning('Failed to open %s: %s', NUMBERS_FILE, err) + _LOGGER.warning("Failed to open %s: %s", NUMBERS_FILE, err) return {} def _save_numbers_json(self): @@ -256,4 +254,4 @@ class Config(object): fil.write(json.dumps(self.numbers)) except OSError as err: # OSError if file write permissions - _LOGGER.warning('Failed to write %s: %s', NUMBERS_FILE, err) + _LOGGER.warning("Failed to write %s: %s", NUMBERS_FILE, err) diff --git a/homeassistant/components/enocean.py b/homeassistant/components/enocean.py index 33c6359d43f..17b82a5eeeb 100644 --- a/homeassistant/components/enocean.py +++ b/homeassistant/components/enocean.py @@ -27,7 +27,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the EnOcean component.""" + """Set up the EnOcean component.""" global ENOCEAN_DONGLE serial_dev = config[DOMAIN].get(CONF_DEVICE) @@ -43,8 +43,8 @@ class EnOceanDongle: def __init__(self, hass, ser): """Initialize the EnOcean dongle.""" from enocean.communicators.serialcommunicator import SerialCommunicator - self.__communicator = SerialCommunicator(port=ser, - callback=self.callback) + self.__communicator = SerialCommunicator( + port=ser, callback=self.callback) self.__communicator.start() self.__devices = [] @@ -65,11 +65,10 @@ class EnOceanDongle: return output def callback(self, temp): - """Callback function for EnOcean Device. + """Function for an EnOcean device's callback. - This is the callback function called by - python-enocan whenever there is an incoming - packet. + This is the callback function called by python-enocan whenever there + is an incoming packet. """ from enocean.protocol.packet import RadioPacket if isinstance(temp, RadioPacket): diff --git a/homeassistant/components/envisalink.py b/homeassistant/components/envisalink.py index 05439213284..4a26295be96 100644 --- a/homeassistant/components/envisalink.py +++ b/homeassistant/components/envisalink.py @@ -19,26 +19,26 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send REQUIREMENTS = ['pyenvisalink==2.0'] _LOGGER = logging.getLogger(__name__) + DOMAIN = 'envisalink' DATA_EVL = 'envisalink' -CONF_EVL_HOST = 'host' -CONF_EVL_PORT = 'port' -CONF_PANEL_TYPE = 'panel_type' -CONF_EVL_VERSION = 'evl_version' CONF_CODE = 'code' -CONF_USERNAME = 'user_name' -CONF_PASS = 'password' +CONF_EVL_HOST = 'host' CONF_EVL_KEEPALIVE = 'keepalive_interval' -CONF_ZONEDUMP_INTERVAL = 'zonedump_interval' -CONF_ZONES = 'zones' -CONF_PARTITIONS = 'partitions' - -CONF_ZONENAME = 'name' -CONF_ZONETYPE = 'type' -CONF_PARTITIONNAME = 'name' +CONF_EVL_PORT = 'port' +CONF_EVL_VERSION = 'evl_version' +CONF_PANEL_TYPE = 'panel_type' CONF_PANIC = 'panic_type' +CONF_PARTITIONNAME = 'name' +CONF_PARTITIONS = 'partitions' +CONF_PASS = 'password' +CONF_USERNAME = 'user_name' +CONF_ZONEDUMP_INTERVAL = 'zonedump_interval' +CONF_ZONENAME = 'name' +CONF_ZONES = 'zones' +CONF_ZONETYPE = 'type' DEFAULT_PORT = 4025 DEFAULT_EVL_VERSION = 3 @@ -83,7 +83,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Common setup for Envisalink devices.""" + """Set up for Envisalink devices.""" from pyenvisalink import EnvisalinkAlarmPanel conf = config.get(DOMAIN) @@ -109,27 +109,27 @@ def async_setup(hass, config): @callback def login_fail_callback(data): - """Callback for when the evl rejects our login.""" - _LOGGER.error("The envisalink rejected your credentials.") + """The callback for when the evl rejects our login.""" + _LOGGER.error("The Envisalink rejected your credentials") sync_connect.set_result(False) @callback def connection_fail_callback(data): """Network failure callback.""" - _LOGGER.error("Could not establish a connection with the envisalink.") + _LOGGER.error("Could not establish a connection with the Envisalink") sync_connect.set_result(False) @callback def connection_success_callback(data): - """Callback for a successful connection.""" - _LOGGER.info("Established a connection with the envisalink.") + """The callback for a successful connection.""" + _LOGGER.info("Established a connection with the Envisalink") hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_envisalink) sync_connect.set_result(True) @callback def zones_updated_callback(data): """Handle zone timer updates.""" - _LOGGER.info("Envisalink sent a zone update event. Updating zones...") + _LOGGER.info("Envisalink sent a zone update event. Updating zones...") async_dispatcher_send(hass, SIGNAL_ZONE_UPDATE, data) @callback @@ -141,13 +141,13 @@ def async_setup(hass, config): @callback def partition_updated_callback(data): """Handle partition changes thrown by evl (including alarms).""" - _LOGGER.info("The envisalink sent a partition update event.") + _LOGGER.info("The envisalink sent a partition update event") async_dispatcher_send(hass, SIGNAL_PARTITION_UPDATE, data) @callback def stop_envisalink(event): """Shutdown envisalink connection and thread on exit.""" - _LOGGER.info("Shutting down envisalink.") + _LOGGER.info("Shutting down Envisalink") controller.stop() controller.callback_zone_timer_dump = zones_updated_callback diff --git a/homeassistant/components/fan/__init__.py b/homeassistant/components/fan/__init__.py index fc2ddb32500..500cebfe73b 100644 --- a/homeassistant/components/fan/__init__.py +++ b/homeassistant/components/fan/__init__.py @@ -22,11 +22,11 @@ from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa import homeassistant.helpers.config_validation as cv +_LOGGER = logging.getLogger(__name__) DOMAIN = 'fan' -SCAN_INTERVAL = timedelta(seconds=30) -_LOGGER = logging.getLogger(__name__) +SCAN_INTERVAL = timedelta(seconds=30) GROUP_NAME_ALL_FANS = 'all fans' ENTITY_ID_ALL_FANS = group.ENTITY_ID_FORMAT.format(GROUP_NAME_ALL_FANS) diff --git a/homeassistant/components/fan/demo.py b/homeassistant/components/fan/demo.py index 931f4914552..3a3f255b806 100644 --- a/homeassistant/components/fan/demo.py +++ b/homeassistant/components/fan/demo.py @@ -4,13 +4,11 @@ Demo fan platform that has a fake fan. For more details about this platform, please refer to the documentation https://home-assistant.io/components/demo/ """ - from homeassistant.components.fan import (SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH, FanEntity, SUPPORT_SET_SPEED, SUPPORT_OSCILLATE, SUPPORT_DIRECTION) from homeassistant.const import STATE_OFF - FAN_NAME = 'Living Room Fan' FAN_ENTITY_ID = 'fan.living_room_fan' @@ -19,7 +17,7 @@ DEMO_SUPPORT = SUPPORT_SET_SPEED | SUPPORT_OSCILLATE | SUPPORT_DIRECTION # pylint: disable=unused-argument def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup demo fan platform.""" + """Set up the demo fan platform.""" add_devices_callback([ DemoFan(hass, FAN_NAME, STATE_OFF), ]) diff --git a/homeassistant/components/fan/isy994.py b/homeassistant/components/fan/isy994.py index f8c7b2e867d..4e61a0c209b 100644 --- a/homeassistant/components/fan/isy994.py +++ b/homeassistant/components/fan/isy994.py @@ -37,7 +37,7 @@ def setup_platform(hass, config: ConfigType, add_devices: Callable[[list], None], discovery_info=None): """Setup 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.') + _LOGGER.error("A connection has not been made to the ISY controller") return False devices = [] @@ -78,7 +78,7 @@ class ISYFanDevice(isy.ISYDevice, FanEntity): def set_speed(self, speed: str) -> None: """Send the set speed command to the ISY994 fan device.""" if not self._node.on(val=STATE_TO_VALUE.get(speed, 0)): - _LOGGER.debug('Unable to set fan speed') + _LOGGER.debug("Unable to set fan speed") else: self.speed = self.state @@ -89,7 +89,7 @@ class ISYFanDevice(isy.ISYDevice, FanEntity): def turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 fan device.""" if not self._node.off(): - _LOGGER.debug('Unable to set fan speed') + _LOGGER.debug("Unable to set fan speed") else: self.speed = self.state @@ -112,13 +112,13 @@ class ISYFanProgram(ISYFanDevice): def turn_off(self, **kwargs) -> None: """Send the turn on command to ISY994 fan program.""" if not self._actions.runThen(): - _LOGGER.error('Unable to open the cover') + _LOGGER.error("Unable to turn off the fan") else: self.speed = STATE_ON if self.is_on else STATE_OFF def turn_on(self, **kwargs) -> None: """Send the turn off command to ISY994 fan program.""" if not self._actions.runElse(): - _LOGGER.error('Unable to close the cover') + _LOGGER.error("Unable to turn on the fan") else: self.speed = STATE_ON if self.is_on else STATE_OFF diff --git a/homeassistant/components/fan/mqtt.py b/homeassistant/components/fan/mqtt.py index 968f666fa72..bc732aa0aff 100644 --- a/homeassistant/components/fan/mqtt.py +++ b/homeassistant/components/fan/mqtt.py @@ -77,7 +77,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup MQTT fan platform.""" + """Set up the MQTT fan platform.""" async_add_devices([MqttFan( config.get(CONF_NAME), { @@ -140,7 +140,7 @@ class MqttFan(FanEntity): @asyncio.coroutine def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method is a coroutine. """ @@ -154,7 +154,7 @@ class MqttFan(FanEntity): @callback def state_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new received MQTT message.""" payload = templates[CONF_STATE](payload) if payload == self._payload[STATE_ON]: self._state = True @@ -169,7 +169,7 @@ class MqttFan(FanEntity): @callback def speed_received(topic, payload, qos): - """A new MQTT message for the speed has been received.""" + """Handle new received MQTT message for the speed.""" payload = templates[ATTR_SPEED](payload) if payload == self._payload[SPEED_LOW]: self._speed = SPEED_LOW @@ -187,7 +187,7 @@ class MqttFan(FanEntity): @callback def oscillation_received(topic, payload, qos): - """A new MQTT message has been received.""" + """Handle new received MQTT message for the oscillation.""" payload = templates[OSCILLATION](payload) if payload == self._payload[OSCILLATE_ON_PAYLOAD]: self._oscillation = True diff --git a/homeassistant/components/fan/wink.py b/homeassistant/components/fan/wink.py index 00eb082212d..98e301f5a48 100644 --- a/homeassistant/components/fan/wink.py +++ b/homeassistant/components/fan/wink.py @@ -14,8 +14,8 @@ from homeassistant.components.wink import WinkDevice, DOMAIN _LOGGER = logging.getLogger(__name__) -SPEED_LOWEST = "lowest" -SPEED_AUTO = "auto" +SPEED_LOWEST = 'lowest' +SPEED_AUTO = 'auto' def setup_platform(hass, config, add_devices, discovery_info=None): diff --git a/homeassistant/components/ffmpeg.py b/homeassistant/components/ffmpeg.py index 5b012ffad4a..959962f02ac 100644 --- a/homeassistant/components/ffmpeg.py +++ b/homeassistant/components/ffmpeg.py @@ -1,5 +1,5 @@ """ -Component that will help set the ffmpeg component. +Component that will help set the FFmpeg component. For more details about this component, please refer to the documentation at https://home-assistant.io/components/ffmpeg/ @@ -19,8 +19,9 @@ from homeassistant.helpers.dispatcher import ( import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity +REQUIREMENTS = ['ha-ffmpeg==1.5'] + DOMAIN = 'ffmpeg' -REQUIREMENTS = ["ha-ffmpeg==1.5"] _LOGGER = logging.getLogger(__name__) @@ -58,28 +59,28 @@ SERVICE_FFMPEG_SCHEMA = vol.Schema({ @callback def async_start(hass, entity_id=None): - """Start a ffmpeg process on entity.""" + """Start a FFmpeg process on entity.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_START, data)) @callback def async_stop(hass, entity_id=None): - """Stop a ffmpeg process on entity.""" + """Stop a FFmpeg process on entity.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_STOP, data)) @callback def async_restart(hass, entity_id=None): - """Restart a ffmpeg process on entity.""" + """Restart a FFmpeg process on entity.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_RESTART, data)) @asyncio.coroutine def async_setup(hass, config): - """Setup the FFmpeg component.""" + """Set up the FFmpeg component.""" conf = config.get(DOMAIN, {}) manager = FFmpegManager( @@ -92,7 +93,7 @@ def async_setup(hass, config): None, load_yaml_config_file, os.path.join(os.path.dirname(__file__), 'services.yaml')) - # register service + # Register service @asyncio.coroutine def async_service_handle(service): """Handle service ffmpeg process.""" @@ -162,7 +163,7 @@ class FFmpegManager(object): class FFmpegBase(Entity): - """Interface object for ffmpeg.""" + """Interface object for FFmpeg.""" def __init__(self, initial_state=True): """Initialize ffmpeg base object.""" @@ -197,7 +198,7 @@ class FFmpegBase(Entity): @asyncio.coroutine def _async_start_ffmpeg(self, entity_ids): - """Start a ffmpeg process. + """Start a FFmpeg process. This method is a coroutine. """ @@ -205,7 +206,7 @@ class FFmpegBase(Entity): @asyncio.coroutine def _async_stop_ffmpeg(self, entity_ids): - """Stop a ffmpeg process. + """Stop a FFmpeg process. This method is a coroutine. """ @@ -214,7 +215,7 @@ class FFmpegBase(Entity): @asyncio.coroutine def _async_restart_ffmpeg(self, entity_ids): - """Stop a ffmpeg process. + """Stop a FFmpeg process. This method is a coroutine. """ @@ -224,10 +225,10 @@ class FFmpegBase(Entity): @callback def _async_register_events(self): - """Register a ffmpeg process/device.""" + """Register a FFmpeg process/device.""" @asyncio.coroutine def async_shutdown_handle(event): - """Stop ffmpeg process.""" + """Stop FFmpeg process.""" yield from self._async_stop_ffmpeg(None) self.hass.bus.async_listen_once( @@ -239,7 +240,7 @@ class FFmpegBase(Entity): @asyncio.coroutine def async_start_handle(event): - """Start ffmpeg process.""" + """Start FFmpeg process.""" yield from self._async_start_ffmpeg(None) self.hass.async_add_job(self.async_update_ha_state()) diff --git a/homeassistant/components/foursquare.py b/homeassistant/components/foursquare.py index 2afa808b502..61c5e9b1da6 100644 --- a/homeassistant/components/foursquare.py +++ b/homeassistant/components/foursquare.py @@ -1,5 +1,5 @@ """ -Allows utilizing the Foursquare (Swarm) API. +Support for the Foursquare (Swarm) API. For more details about this component, please refer to the documentation at https://home-assistant.io/components/foursquare/ @@ -11,9 +11,9 @@ import os import requests import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_BAD_REQUEST from homeassistant.config import load_yaml_config_file -import homeassistant.helpers.config_validation as cv from homeassistant.components.http import HomeAssistantView _LOGGER = logging.getLogger(__name__) @@ -49,7 +49,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Foursquare component.""" + """Set up the Foursquare component.""" descriptions = load_yaml_config_file( os.path.join(os.path.dirname(__file__), 'services.yaml')) diff --git a/homeassistant/components/frontend/__init__.py b/homeassistant/components/frontend/__init__.py index b6f65d9953a..617db06be2c 100644 --- a/homeassistant/components/frontend/__init__.py +++ b/homeassistant/components/frontend/__init__.py @@ -17,27 +17,30 @@ from .version import FINGERPRINTS DOMAIN = 'frontend' DEPENDENCIES = ['api', 'websocket_api'] + URL_PANEL_COMPONENT = '/frontend/panels/{}.html' URL_PANEL_COMPONENT_FP = '/frontend/panels/{}-{}.html' + STATIC_PATH = os.path.join(os.path.dirname(__file__), 'www_static/') + MANIFEST_JSON = { - "background_color": "#FFFFFF", - "description": "Open-source home automation platform running on Python 3.", - "dir": "ltr", - "display": "standalone", - "icons": [], - "lang": "en-US", - "name": "Home Assistant", - "short_name": "Assistant", - "start_url": "/", - "theme_color": "#03A9F4" + 'background_color': '#FFFFFF', + 'description': 'Open-source home automation platform running on Python 3.', + 'dir': 'ltr', + 'display': 'standalone', + 'icons': [], + 'lang': 'en-US', + 'name': 'Home Assistant', + 'short_name': 'Assistant', + 'start_url': '/', + 'theme_color': '#03A9F4' } for size in (192, 384, 512, 1024): MANIFEST_JSON['icons'].append({ - "src": "/static/icons/favicon-{}x{}.png".format(size, size), - "sizes": "{}x{}".format(size, size), - "type": "image/png" + 'src': '/static/icons/favicon-{}x{}.png'.format(size, size), + 'sizes': '{}x{}'.format(size, size), + 'type': 'image/png' }) DATA_PANELS = 'frontend_panels' @@ -92,10 +95,10 @@ def register_panel(hass, component_name, path, md5=None, sidebar_title=None, url_path = component_name if url_path in panels: - _LOGGER.warning('Overwriting component %s', url_path) + _LOGGER.warning("Overwriting component %s", url_path) if not os.path.isfile(path): - _LOGGER.error('Panel %s component does not exist: %s', - component_name, path) + _LOGGER.error( + "Panel %s component does not exist: %s", component_name, path) return if md5 is None: @@ -133,8 +136,8 @@ def register_panel(hass, component_name, path, md5=None, sidebar_title=None, index_view = hass.data.get(DATA_INDEX_VIEW) if index_view: - hass.http.app.router.add_route('get', '/{}'.format(url_path), - index_view.get) + hass.http.app.router.add_route( + 'get', '/{}'.format(url_path), index_view.get) def add_manifest_json_key(key, val): @@ -143,7 +146,7 @@ def add_manifest_json_key(key, val): def setup(hass, config): - """Setup serving the frontend.""" + """Set up the serving of the frontend.""" hass.http.register_view(BootstrapView) hass.http.register_view(ManifestJSONView) @@ -186,8 +189,8 @@ def setup(hass, config): class BootstrapView(HomeAssistantView): """View to bootstrap frontend with all needed data.""" - url = "/api/bootstrap" - name = "api:bootstrap" + url = '/api/bootstrap' + name = 'api:bootstrap' @callback def get(self, request): @@ -207,7 +210,7 @@ class IndexView(HomeAssistantView): """Serve the frontend.""" url = '/' - name = "frontend:index" + name = 'frontend:index' requires_auth = False extra_urls = ['/states', '/states/{entity_id}'] @@ -284,8 +287,8 @@ class ManifestJSONView(HomeAssistantView): """View to return a manifest.json.""" requires_auth = False - url = "/manifest.json" - name = "manifestjson" + url = '/manifest.json' + name = 'manifestjson' @asyncio.coroutine def get(self, request): # pylint: disable=no-self-use diff --git a/homeassistant/components/google.py b/homeassistant/components/google.py index 0e1caf3e137..f7f8e63167f 100644 --- a/homeassistant/components/google.py +++ b/homeassistant/components/google.py @@ -158,7 +158,7 @@ def do_authentication(hass, config): def setup(hass, config): - """Setup the platform.""" + """Set up the Google platform.""" if DATA_INDEX not in hass.data: hass.data[DATA_INDEX] = {} @@ -174,7 +174,7 @@ def setup(hass, config): def setup_services(hass, track_new_found_calendars, calendar_service): - """Setup service listeners.""" + """Set up the service listeners.""" def _found_calendar(call): """Check if we know about a calendar and generate PLATFORM_DISCOVER.""" calendar = get_calendar_info(hass, call.data) @@ -214,7 +214,7 @@ def setup_services(hass, track_new_found_calendars, calendar_service): def do_setup(hass, config): """Run the setup after we have everything configured.""" - # load calendars the user has configured + # Load calendars the user has configured hass.data[DATA_INDEX] = load_config(hass.config.path(YAML_DEVICES)) calendar_service = GoogleCalendarService(hass.config.path(TOKEN_FILE)) @@ -228,16 +228,16 @@ def do_setup(hass, config): for calendar in hass.data[DATA_INDEX].values(): discovery.load_platform(hass, 'calendar', DOMAIN, calendar) - # look for any new calendars + # Look for any new calendars hass.services.call(DOMAIN, SERVICE_SCAN_CALENDARS, None) return True class GoogleCalendarService(object): - """Calendar service interface to google.""" + """Calendar service interface to Google.""" def __init__(self, token_file): - """We just need the token_file.""" + """Init the Google Calendar service.""" self.token_file = token_file def get(self): @@ -247,8 +247,8 @@ class GoogleCalendarService(object): from googleapiclient import discovery as google_discovery credentials = Storage(self.token_file).get() http = credentials.authorize(httplib2.Http()) - service = google_discovery.build('calendar', 'v3', http=http, - cache_discovery=False) + service = google_discovery.build( + 'calendar', 'v3', http=http, cache_discovery=False) return service @@ -259,8 +259,8 @@ def get_calendar_info(hass, calendar): CONF_ENTITIES: [{ CONF_TRACK: calendar['track'], CONF_NAME: calendar['summary'], - CONF_DEVICE_ID: generate_entity_id('{}', calendar['summary'], - hass=hass), + CONF_DEVICE_ID: generate_entity_id( + '{}', calendar['summary'], hass=hass), }] }) return calendar_info @@ -278,7 +278,7 @@ def load_config(path): DEVICE_SCHEMA(calendar)}) except VoluptuousError as exception: # keep going - _LOGGER.warning('Calendar Invalid Data: %s', exception) + _LOGGER.warning("Calendar Invalid Data: %s", exception) except FileNotFoundError: # When YAML file could not be loaded/did not contain a dict return {} diff --git a/homeassistant/components/graphite.py b/homeassistant/components/graphite.py index 4fef17f0927..fc2a196c4c6 100644 --- a/homeassistant/components/graphite.py +++ b/homeassistant/components/graphite.py @@ -12,11 +12,11 @@ import time import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF_PREFIX, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED) from homeassistant.helpers import state -import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -35,7 +35,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Graphite feeder.""" + """Set up the Graphite feeder.""" conf = config[DOMAIN] host = conf.get(CONF_HOST) prefix = conf.get(CONF_PREFIX) @@ -75,28 +75,28 @@ class GraphiteFeeder(threading.Thread): hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.shutdown) hass.bus.listen(EVENT_STATE_CHANGED, self.event_listener) - _LOGGER.debug('Graphite feeding to %s:%i initialized', + _LOGGER.debug("Graphite feeding to %s:%i initialized", self._host, self._port) def start_listen(self, event): """Start event-processing thread.""" - _LOGGER.debug('Event processing thread started') + _LOGGER.debug("Event processing thread started") self._we_started = True self.start() def shutdown(self, event): """Signal shutdown of processing event.""" - _LOGGER.debug('Event processing signaled exit') + _LOGGER.debug("Event processing signaled exit") self._queue.put(self._quit_object) def event_listener(self, event): """Queue an event for processing.""" if self.is_alive() or not self._we_started: - _LOGGER.debug('Received event') + _LOGGER.debug("Received event") self._queue.put(event) else: - _LOGGER.error('Graphite feeder thread has died, not ' - 'queuing event!') + _LOGGER.error( + "Graphite feeder thread has died, not queuing event!") def _send_to_graphite(self, data): """Send data to Graphite.""" @@ -122,25 +122,25 @@ class GraphiteFeeder(threading.Thread): if isinstance(value, (float, int))] if not lines: return - _LOGGER.debug('Sending to graphite: %s', lines) + _LOGGER.debug("Sending to graphite: %s", lines) try: self._send_to_graphite('\n'.join(lines)) 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 graphite') + _LOGGER.exception("Failed to send data to graphite") def run(self): """Run the process to export the data.""" while True: event = self._queue.get() if event == self._quit_object: - _LOGGER.debug('Event processing thread stopped') + _LOGGER.debug("Event processing thread stopped") self._queue.task_done() return elif (event.event_type == EVENT_STATE_CHANGED and event.data.get('new_state')): - _LOGGER.debug('Processing STATE_CHANGED event for %s', + _LOGGER.debug("Processing STATE_CHANGED event for %s", event.data['entity_id']) try: self._report_attributes(event.data['entity_id'], @@ -149,9 +149,9 @@ class GraphiteFeeder(threading.Thread): except Exception: # Catch this so we can avoid the thread dying and # make it visible. - _LOGGER.exception('Failed to process STATE_CHANGED event') + _LOGGER.exception("Failed to process STATE_CHANGED event") else: - _LOGGER.warning('Processing unexpected event type %s', + _LOGGER.warning("Processing unexpected event type %s", event.event_type) self._queue.task_done() diff --git a/homeassistant/components/group.py b/homeassistant/components/group.py index f582ff33a07..5dde5d6fea8 100644 --- a/homeassistant/components/group.py +++ b/homeassistant/components/group.py @@ -1,5 +1,5 @@ """ -Provides functionality to group entities. +Provide the functionality to group entities. For more details about this component, please refer to the documentation at https://home-assistant.io/components/group/ @@ -168,7 +168,7 @@ def get_entity_ids(hass, entity_id, domain_filter=None): @asyncio.coroutine def async_setup(hass, config): - """Setup all groups found definded in the configuration.""" + """Set up all groups found definded in the configuration.""" component = EntityComponent(_LOGGER, DOMAIN, hass) yield from _async_process_config(hass, config, component) diff --git a/homeassistant/components/hassio.py b/homeassistant/components/hassio.py index 7431d646769..be0424e592c 100644 --- a/homeassistant/components/hassio.py +++ b/homeassistant/components/hassio.py @@ -1,5 +1,5 @@ """ -Exposes regular rest commands as services. +Exposes regular REST commands as services. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/hassio/ @@ -21,11 +21,11 @@ from homeassistant.components.http import HomeAssistantView from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.components.frontend import register_built_in_panel +_LOGGER = logging.getLogger(__name__) + DOMAIN = 'hassio' DEPENDENCIES = ['http'] -_LOGGER = logging.getLogger(__name__) - TIMEOUT = 10 HASSIO_REST_COMMANDS = { @@ -59,7 +59,7 @@ ADDON_REST_COMMANDS = { @asyncio.coroutine def async_setup(hass, config): - """Setup the hassio component.""" + """Set up the HASSio component.""" try: host = os.environ['HASSIO'] except KeyError: diff --git a/homeassistant/components/hdmi_cec.py b/homeassistant/components/hdmi_cec.py index 7b966e25022..1b6f644e23c 100644 --- a/homeassistant/components/hdmi_cec.py +++ b/homeassistant/components/hdmi_cec.py @@ -155,7 +155,7 @@ def parse_mapping(mapping, parents=None): def setup(hass: HomeAssistant, base_config): - """Setup CEC capability.""" + """Set up the CEC capability.""" from pycec.network import HDMINetwork from pycec.commands import CecCommand, KeyReleaseCommand, KeyPressCommand from pycec.const import KEY_VOLUME_UP, KEY_VOLUME_DOWN, KEY_MUTE_ON, \ @@ -283,9 +283,9 @@ def setup(hass: HomeAssistant, base_config): def _update(call): """ - Callback called when device update is needed. + The function called when device update is needed. - - called by service, requests CEC network to update data. + Called by service, requests CEC network to update data. """ hdmi_network.scan() diff --git a/homeassistant/components/history.py b/homeassistant/components/history.py index 5c68f767cd2..70c61589bb3 100644 --- a/homeassistant/components/history.py +++ b/homeassistant/components/history.py @@ -36,7 +36,7 @@ IGNORE_DOMAINS = ('zone', 'scene',) def last_recorder_run(hass): - """Retireve the last closed recorder run from the DB.""" + """Retrieve the last closed recorder run from the database.""" from homeassistant.components.recorder.models import RecorderRuns with session_scope(hass=hass) as session: @@ -174,7 +174,7 @@ def get_state(hass, utc_point_in_time, entity_id, run=None): # pylint: disable=unused-argument def setup(hass, config): - """Setup the history hooks.""" + """Set up the history hooks.""" filters = Filters() exclude = config[DOMAIN].get(CONF_EXCLUDE) if exclude: diff --git a/homeassistant/components/homematic.py b/homeassistant/components/homematic.py index 0b0d073fe1d..8c107fae26a 100644 --- a/homeassistant/components/homematic.py +++ b/homeassistant/components/homematic.py @@ -21,7 +21,7 @@ from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import track_time_interval from homeassistant.config import load_yaml_config_file -REQUIREMENTS = ["pyhomematic==0.1.25"] +REQUIREMENTS = ['pyhomematic==0.1.25'] DOMAIN = 'homematic' @@ -215,7 +215,7 @@ def virtualkey(hass, address, channel, param, proxy=None): def set_var_value(hass, entity_id, value): - """Change value of homematic system variable.""" + """Change value of a Homematic system variable.""" data = { ATTR_ENTITY_ID: entity_id, ATTR_VALUE: value, @@ -225,7 +225,7 @@ def set_var_value(hass, entity_id, value): def set_dev_value(hass, address, channel, param, value, proxy=None): - """Send virtual keypress to homematic controlller.""" + """Send virtual keypress to the Homematic controlller.""" data = { ATTR_ADDRESS: address, ATTR_CHANNEL: channel, @@ -296,7 +296,7 @@ def setup(hass, config): entity_hubs.append(HMHub( hass, hub_data[CONF_NAME], hub_data[CONF_VARIABLES])) - # Regeister homematic services + # Register Homematic services descriptions = load_yaml_config_file( os.path.join(os.path.dirname(__file__), 'services.yaml')) @@ -389,7 +389,7 @@ def setup(hass, config): def _system_callback_handler(hass, config, src, *args): - """Callback handler.""" + """Handle the callback.""" if src == 'newDevices': _LOGGER.debug("newDevices with: %s", args) # pylint: disable=unused-variable diff --git a/homeassistant/components/http/__init__.py b/homeassistant/components/http/__init__.py index 536517604fc..dc5e59f4155 100644 --- a/homeassistant/components/http/__init__.py +++ b/homeassistant/components/http/__init__.py @@ -81,14 +81,13 @@ DEFAULT_LOGIN_ATTEMPT_THRESHOLD = -1 HTTP_SCHEMA = vol.Schema({ vol.Optional(CONF_API_PASSWORD, default=None): cv.string, vol.Optional(CONF_SERVER_HOST, default=DEFAULT_SERVER_HOST): cv.string, - vol.Optional(CONF_SERVER_PORT, default=SERVER_PORT): - vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)), + vol.Optional(CONF_SERVER_PORT, default=SERVER_PORT): cv.port, vol.Optional(CONF_BASE_URL): cv.string, vol.Optional(CONF_DEVELOPMENT, default=DEFAULT_DEVELOPMENT): cv.string, vol.Optional(CONF_SSL_CERTIFICATE, default=None): cv.isfile, vol.Optional(CONF_SSL_KEY, default=None): cv.isfile, - vol.Optional(CONF_CORS_ORIGINS, default=[]): vol.All(cv.ensure_list, - [cv.string]), + vol.Optional(CONF_CORS_ORIGINS, default=[]): + vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_USE_X_FORWARDED_FOR, default=False): cv.boolean, vol.Optional(CONF_TRUSTED_NETWORKS, default=[]): vol.All(cv.ensure_list, [ip_network]), @@ -143,12 +142,12 @@ def async_setup(hass, config): @asyncio.coroutine def stop_server(event): - """Callback to stop the server.""" + """Stop the server.""" yield from server.stop() @asyncio.coroutine def start_server(event): - """Callback to start the server.""" + """Start the server.""" hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server) yield from server.start() @@ -294,7 +293,7 @@ class HomeAssistantWSGI(object): @asyncio.coroutine def start(self): - """Start the wsgi server.""" + """Start the WSGI server.""" cors_added = set() if self.cors is not None: for route in list(self.app.router.routes()): @@ -400,7 +399,7 @@ class HomeAssistantView(object): def request_handler_factory(view, handler): - """Factory to wrap our handler classes.""" + """Wrap the handler classes.""" assert asyncio.iscoroutinefunction(handler) or is_callback(handler), \ "Handler should be a coroutine or a callback." diff --git a/homeassistant/components/http/auth.py b/homeassistant/components/http/auth.py index 6ff653eef35..2a0413e9dbc 100644 --- a/homeassistant/components/http/auth.py +++ b/homeassistant/components/http/auth.py @@ -14,7 +14,7 @@ _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def auth_middleware(app, handler): - """Authentication middleware.""" + """Authenticate as middleware.""" # If no password set, just always set authenticated=True if app['hass'].http.api_password is None: @asyncio.coroutine @@ -32,8 +32,8 @@ def auth_middleware(app, handler): authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers and - validate_password(request, - request.headers[HTTP_HEADER_HA_AUTH])): + validate_password( + request, request.headers[HTTP_HEADER_HA_AUTH])): # A valid auth header has been set authenticated = True @@ -62,5 +62,5 @@ def is_trusted_ip(request): def validate_password(request, api_password): """Test if password is valid.""" - return hmac.compare_digest(api_password, - request.app['hass'].http.api_password) + return hmac.compare_digest( + api_password, request.app['hass'].http.api_password) diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py index 8ae18ef6e80..53635af9fc8 100644 --- a/homeassistant/components/http/ban.py +++ b/homeassistant/components/http/ban.py @@ -94,8 +94,8 @@ def process_wrong_login(request): None, update_ip_bans_config, hass.config.path(IP_BANS_FILE), new_ban) - _LOGGER.warning('Banned IP %s for too many login attempts', - remote_addr) + _LOGGER.warning( + "Banned IP %s for too many login attempts", remote_addr) persistent_notification.async_create( hass, @@ -107,13 +107,13 @@ class IpBan(object): """Represents banned IP address.""" def __init__(self, ip_ban: str, banned_at: datetime=None) -> None: - """Initializing Ip Ban object.""" + """Initialize IP Ban object.""" self.ip_address = ip_address(ip_ban) self.banned_at = banned_at or datetime.utcnow() def load_ip_bans_config(path: str): - """Loading list of banned IPs from config file.""" + """Load list of banned IPs from config file.""" ip_list = [] if not os.path.isfile(path): @@ -130,7 +130,7 @@ def load_ip_bans_config(path: str): ip_info = SCHEMA_IP_BAN_ENTRY(ip_info) ip_list.append(IpBan(ip_ban, ip_info['banned_at'])) except vol.Invalid as err: - _LOGGER.error('Failed to load IP ban %s: %s', ip_info, err) + _LOGGER.error("Failed to load IP ban %s: %s", ip_info, err) continue return ip_list diff --git a/homeassistant/components/ifttt.py b/homeassistant/components/ifttt.py index 123d1a9d382..0a4ad66ce56 100644 --- a/homeassistant/components/ifttt.py +++ b/homeassistant/components/ifttt.py @@ -52,7 +52,7 @@ def trigger(hass, event, value1=None, value2=None, value3=None): def setup(hass, config): - """Setup the IFTTT service component.""" + """Set up the IFTTT service component.""" key = config[DOMAIN][CONF_KEY] def trigger_service(call): diff --git a/homeassistant/components/image_processing/__init__.py b/homeassistant/components/image_processing/__init__.py index c63d3d01ce9..a37f1163b3d 100644 --- a/homeassistant/components/image_processing/__init__.py +++ b/homeassistant/components/image_processing/__init__.py @@ -20,7 +20,6 @@ from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.loader import get_component - DOMAIN = 'image_processing' DEPENDENCIES = ['camera'] @@ -67,7 +66,7 @@ def scan(hass, entity_id=None): @asyncio.coroutine def async_setup(hass, config): - """Setup image processing.""" + """Set up image processing.""" component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL) yield from component.async_setup(config) diff --git a/homeassistant/components/image_processing/demo.py b/homeassistant/components/image_processing/demo.py index 3cc2c17654c..a7f4ad5e3d6 100644 --- a/homeassistant/components/image_processing/demo.py +++ b/homeassistant/components/image_processing/demo.py @@ -12,7 +12,7 @@ from homeassistant.components.image_processing.microsoft_face_identify import ( def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the demo image_processing platform.""" + """Set up the demo image_processing platform.""" add_devices([ DemoImageProcessingAlpr('camera.demo_camera', "Demo Alpr"), DemoImageProcessingFace( diff --git a/homeassistant/components/image_processing/microsoft_face_detect.py b/homeassistant/components/image_processing/microsoft_face_detect.py index bb1a7accd15..e12c2d1d646 100644 --- a/homeassistant/components/image_processing/microsoft_face_detect.py +++ b/homeassistant/components/image_processing/microsoft_face_detect.py @@ -50,7 +50,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up the microsoft face detection platform.""" + """Set up the Microsoft Face detection platform.""" api = hass.data[DATA_MICROSOFT_FACE] attributes = config[CONF_ATTRIBUTES] @@ -64,10 +64,10 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class MicrosoftFaceDetectEntity(ImageProcessingFaceEntity): - """Microsoft face api entity for identify.""" + """Microsoft Face API entity for identify.""" def __init__(self, camera_entity, api, attributes, name=None): - """Initialize openalpr local api.""" + """Initialize Microsoft Face.""" super().__init__() self._api = api diff --git a/homeassistant/components/image_processing/microsoft_face_identify.py b/homeassistant/components/image_processing/microsoft_face_identify.py index 273a00c294d..a645aef2fcb 100644 --- a/homeassistant/components/image_processing/microsoft_face_identify.py +++ b/homeassistant/components/image_processing/microsoft_face_identify.py @@ -42,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up the Microsoft face identify platform.""" + """Set up the Microsoft Face identify platform.""" api = hass.data[DATA_MICROSOFT_FACE] face_group = config[CONF_GROUP] confidence = config[CONF_CONFIDENCE] @@ -145,10 +145,10 @@ class ImageProcessingFaceEntity(ImageProcessingEntity): class MicrosoftFaceIdentifyEntity(ImageProcessingFaceEntity): - """Microsoft face api entity for identify.""" + """Representation of the Microsoft Face API entity for identify.""" def __init__(self, camera_entity, api, face_group, confidence, name=None): - """Initialize openalpr local api.""" + """Initialize the Microsoft Face API.""" super().__init__() self._api = api diff --git a/homeassistant/components/image_processing/openalpr_cloud.py b/homeassistant/components/image_processing/openalpr_cloud.py index 1ba8dfcfbc4..1143c1e04ae 100644 --- a/homeassistant/components/image_processing/openalpr_cloud.py +++ b/homeassistant/components/image_processing/openalpr_cloud.py @@ -1,5 +1,5 @@ """ -Component that will help set the openalpr cloud for alpr processing. +Component that will help set the OpenALPR cloud for ALPR processing. For more details about this component, please refer to the documentation at https://home-assistant.io/components/image_processing.openalpr_cloud/ @@ -51,7 +51,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up the openalpr cloud api platform.""" + """Set up the OpenALPR cloud API platform.""" confidence = config[CONF_CONFIDENCE] params = { 'secret_key': config[CONF_API_KEY], @@ -70,10 +70,10 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class OpenAlprCloudEntity(ImageProcessingAlprEntity): - """OpenAlpr cloud entity.""" + """OpenALPR cloud entity.""" def __init__(self, camera_entity, params, confidence, name=None): - """Initialize openalpr local api.""" + """Initialize OpenALPR cloud API.""" super().__init__() self._params = params @@ -126,7 +126,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity): return except (asyncio.TimeoutError, aiohttp.ClientError): - _LOGGER.error("Timeout for openalpr api.") + _LOGGER.error("Timeout for OpenALPR API") return # processing api data diff --git a/homeassistant/components/image_processing/openalpr_local.py b/homeassistant/components/image_processing/openalpr_local.py index 4040efe3bf4..05ca2cffcd0 100644 --- a/homeassistant/components/image_processing/openalpr_local.py +++ b/homeassistant/components/image_processing/openalpr_local.py @@ -1,5 +1,5 @@ """ -Component that will help set the openalpr local for alpr processing. +Component that will help set the OpenALPR local for ALPR processing. For more details about this component, please refer to the documentation at https://home-assistant.io/components/image_processing.openalpr_local/ @@ -60,7 +60,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up the openalpr local platform.""" + """Set up the OpenALPR local platform.""" command = [config[CONF_ALPR_BIN], '-c', config[CONF_REGION], '-'] confidence = config[CONF_CONFIDENCE] @@ -74,7 +74,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): class ImageProcessingAlprEntity(ImageProcessingEntity): - """Base entity class for alpr image processing.""" + """Base entity class for ALPR image processing.""" def __init__(self): """Initialize base alpr entity.""" @@ -144,10 +144,10 @@ class ImageProcessingAlprEntity(ImageProcessingEntity): class OpenAlprLocalEntity(ImageProcessingAlprEntity): - """OpenAlpr local api entity.""" + """OpenALPR local api entity.""" def __init__(self, camera_entity, command, confidence, name=None): - """Initialize openalpr local api.""" + """Initialize OpenALPR local API.""" super().__init__() self._cmd = command diff --git a/homeassistant/components/influxdb.py b/homeassistant/components/influxdb.py index 58479b6c14e..abd02554ac0 100644 --- a/homeassistant/components/influxdb.py +++ b/homeassistant/components/influxdb.py @@ -58,7 +58,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the InfluxDB component.""" + """Set up the InfluxDB component.""" from influxdb import InfluxDBClient, exceptions conf = config[DOMAIN] diff --git a/homeassistant/components/input_boolean.py b/homeassistant/components/input_boolean.py index dd27ab3ebda..e975e42bcdc 100644 --- a/homeassistant/components/input_boolean.py +++ b/homeassistant/components/input_boolean.py @@ -63,7 +63,7 @@ def toggle(hass, entity_id): @asyncio.coroutine def async_setup(hass, config): - """Set up input boolean.""" + """Set up an input boolean.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entities = [] @@ -140,7 +140,7 @@ class InputBoolean(ToggleEntity): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity about to be added to hass.""" + """Call when entity about to be added to hass.""" # If not None, we got an initial value. if self._state is not None: return diff --git a/homeassistant/components/input_select.py b/homeassistant/components/input_select.py index 7247a8b1093..94ef3318930 100644 --- a/homeassistant/components/input_select.py +++ b/homeassistant/components/input_select.py @@ -56,7 +56,7 @@ SERVICE_SET_OPTIONS_SCHEMA = vol.Schema({ def _cv_input_select(cfg): - """Config validation helper for input select (Voluptuous).""" + """Configuration validation helper for input select (voluptuous).""" options = cfg[CONF_OPTIONS] initial = cfg.get(CONF_INITIAL) if initial is not None and initial not in options: @@ -109,7 +109,7 @@ def set_options(hass, entity_id, options): @asyncio.coroutine def async_setup(hass, config): - """Setup input select.""" + """Set up an input select.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entities = [] @@ -197,7 +197,7 @@ class InputSelect(Entity): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity about to be added to hass.""" + """Run when entity about to be added.""" if self._current_option is not None: return diff --git a/homeassistant/components/input_slider.py b/homeassistant/components/input_slider.py index c4976bb43e8..b0975f9dbae 100644 --- a/homeassistant/components/input_slider.py +++ b/homeassistant/components/input_slider.py @@ -9,9 +9,9 @@ import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT, CONF_ICON, CONF_NAME) -import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.restore_state import async_get_last_state @@ -39,7 +39,7 @@ SERVICE_SELECT_VALUE_SCHEMA = vol.Schema({ def _cv_input_slider(cfg): - """Config validation helper for input slider (Voluptuous).""" + """Configuration validation helper for input slider (voluptuous).""" minimum = cfg.get(CONF_MIN) maximum = cfg.get(CONF_MAX) if minimum >= maximum: @@ -78,7 +78,7 @@ def select_value(hass, entity_id, value): @asyncio.coroutine def async_setup(hass, config): - """Set up input slider.""" + """Set up an input slider.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entities = [] @@ -92,8 +92,8 @@ def async_setup(hass, config): icon = cfg.get(CONF_ICON) unit = cfg.get(ATTR_UNIT_OF_MEASUREMENT) - entities.append(InputSlider(object_id, name, initial, minimum, maximum, - step, icon, unit)) + entities.append(InputSlider( + object_id, name, initial, minimum, maximum, step, icon, unit)) if not entities: return False @@ -138,27 +138,27 @@ class InputSlider(Entity): @property def name(self): - """Name of the select input.""" + """Return the name of the select input slider.""" return self._name @property def icon(self): - """Icon to be used for this entity.""" + """Return the icon to be used for this entity.""" return self._icon @property def state(self): - """State of the component.""" + """Return the state of the component.""" return self._current_value @property def unit_of_measurement(self): - """Unit of measurement of slider.""" + """Return the unit the value is expressed in.""" return self._unit @property def state_attributes(self): - """State attributes.""" + """Return the state attributes.""" return { ATTR_MIN: self._minimum, ATTR_MAX: self._maximum, @@ -167,7 +167,7 @@ class InputSlider(Entity): @asyncio.coroutine def async_added_to_hass(self): - """Called when entity about to be added to hass.""" + """Run when entity about to be added to hass.""" if self._current_value is not None: return @@ -185,7 +185,7 @@ class InputSlider(Entity): """Select new value.""" num_value = float(value) if num_value < self._minimum or num_value > self._maximum: - _LOGGER.warning('Invalid value: %s (range %s - %s)', + _LOGGER.warning("Invalid value: %s (range %s - %s)", num_value, self._minimum, self._maximum) return self._current_value = num_value diff --git a/homeassistant/components/insteon_hub.py b/homeassistant/components/insteon_hub.py index 9d77a0fc5c3..49e6c566c46 100644 --- a/homeassistant/components/insteon_hub.py +++ b/homeassistant/components/insteon_hub.py @@ -29,12 +29,12 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup Insteon Hub component. + """Set up the Insteon Hub component. This will automatically import associated lights. """ - _LOGGER.warning('Component disabled at request from Insteon. ' - 'For more information: https://goo.gl/zLJaic') + _LOGGER.warning("Component disabled at request from Insteon. " + "For more information: https://goo.gl/zLJaic") return False # pylint: disable=unreachable import insteon diff --git a/homeassistant/components/insteon_local.py b/homeassistant/components/insteon_local.py index cf93bc97e57..1f700b5ff3e 100644 --- a/homeassistant/components/insteon_local.py +++ b/homeassistant/components/insteon_local.py @@ -33,7 +33,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Set up Insteon Hub component. + """Set up the Insteon Hub component. This will automatically import associated lights. """ @@ -48,7 +48,7 @@ def setup(hass, config): try: insteonhub = Hub(host, username, password, port, timeout, _LOGGER) - # check for successful connection + # Check for successful connection insteonhub.get_buffer_status() except requests.exceptions.ConnectTimeout: _LOGGER.error("Error on insteon_local." diff --git a/homeassistant/components/insteon_plm.py b/homeassistant/components/insteon_plm.py index d786de7ac8a..b62a2e229ae 100644 --- a/homeassistant/components/insteon_plm.py +++ b/homeassistant/components/insteon_plm.py @@ -40,7 +40,7 @@ PLM_PLATFORMS = { @asyncio.coroutine def async_setup(hass, config): - """Set up our connection to the PLM.""" + """Set up the connection to the PLM.""" import insteonplm conf = config[DOMAIN] @@ -49,12 +49,12 @@ def async_setup(hass, config): @callback def async_plm_new_device(device): - """New device detected from transport to be delegated to platform.""" + """Detect device from transport to be delegated to platform.""" name = device.get('address') address = device.get('address_hex') capabilities = device.get('capabilities', []) - _LOGGER.info('New INSTEON PLM device: %s (%s) %r', + _LOGGER.info("New INSTEON PLM device: %s (%s) %r", name, address, capabilities) loadlist = [] @@ -72,7 +72,7 @@ def async_setup(hass, config): hass, loadplatform, DOMAIN, discovered=[device], hass_config=config)) - _LOGGER.info('Looking for PLM on %s', port) + _LOGGER.info("Looking for PLM on %s", port) plm = yield from insteonplm.Connection.create(device=port, loop=hass.loop) for device in overrides: diff --git a/homeassistant/components/introduction.py b/homeassistant/components/introduction.py index afbcca14253..367eeb1a6c3 100644 --- a/homeassistant/components/introduction.py +++ b/homeassistant/components/introduction.py @@ -16,7 +16,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config=None): - """Setup the introduction component.""" + """Set up the introduction component.""" log = logging.getLogger(__name__) log.info(""" diff --git a/homeassistant/components/ios.py b/homeassistant/components/ios.py index bac5bb59d96..e6edcc21b05 100644 --- a/homeassistant/components/ios.py +++ b/homeassistant/components/ios.py @@ -1,7 +1,7 @@ """ Native Home Assistant iOS app component. -For more details about this platform, please refer to the documentation at +For more details about this component, please refer to the documentation at https://home-assistant.io/ecosystem/ios/ """ import asyncio @@ -28,76 +28,76 @@ from homeassistant.const import (HTTP_INTERNAL_SERVER_ERROR, _LOGGER = logging.getLogger(__name__) -DOMAIN = "ios" +DOMAIN = 'ios' -DEPENDENCIES = ["device_tracker", "http", "zeroconf"] +DEPENDENCIES = ['device_tracker', 'http', 'zeroconf'] -CONF_PUSH = "push" -CONF_PUSH_CATEGORIES = "categories" -CONF_PUSH_CATEGORIES_NAME = "name" -CONF_PUSH_CATEGORIES_IDENTIFIER = "identifier" -CONF_PUSH_CATEGORIES_ACTIONS = "actions" +CONF_PUSH = 'push' +CONF_PUSH_CATEGORIES = 'categories' +CONF_PUSH_CATEGORIES_NAME = 'name' +CONF_PUSH_CATEGORIES_IDENTIFIER = 'identifier' +CONF_PUSH_CATEGORIES_ACTIONS = 'actions' -CONF_PUSH_ACTIONS_IDENTIFIER = "identifier" -CONF_PUSH_ACTIONS_TITLE = "title" -CONF_PUSH_ACTIONS_ACTIVATION_MODE = "activationMode" -CONF_PUSH_ACTIONS_AUTHENTICATION_REQUIRED = "authenticationRequired" -CONF_PUSH_ACTIONS_DESTRUCTIVE = "destructive" -CONF_PUSH_ACTIONS_BEHAVIOR = "behavior" -CONF_PUSH_ACTIONS_CONTEXT = "context" -CONF_PUSH_ACTIONS_TEXT_INPUT_BUTTON_TITLE = "textInputButtonTitle" -CONF_PUSH_ACTIONS_TEXT_INPUT_PLACEHOLDER = "textInputPlaceholder" +CONF_PUSH_ACTIONS_IDENTIFIER = 'identifier' +CONF_PUSH_ACTIONS_TITLE = 'title' +CONF_PUSH_ACTIONS_ACTIVATION_MODE = 'activationMode' +CONF_PUSH_ACTIONS_AUTHENTICATION_REQUIRED = 'authenticationRequired' +CONF_PUSH_ACTIONS_DESTRUCTIVE = 'destructive' +CONF_PUSH_ACTIONS_BEHAVIOR = 'behavior' +CONF_PUSH_ACTIONS_CONTEXT = 'context' +CONF_PUSH_ACTIONS_TEXT_INPUT_BUTTON_TITLE = 'textInputButtonTitle' +CONF_PUSH_ACTIONS_TEXT_INPUT_PLACEHOLDER = 'textInputPlaceholder' -ATTR_FOREGROUND = "foreground" -ATTR_BACKGROUND = "background" +ATTR_FOREGROUND = 'foreground' +ATTR_BACKGROUND = 'background' ACTIVATION_MODES = [ATTR_FOREGROUND, ATTR_BACKGROUND] -ATTR_DEFAULT_BEHAVIOR = "default" -ATTR_TEXT_INPUT_BEHAVIOR = "textInput" +ATTR_DEFAULT_BEHAVIOR = 'default' +ATTR_TEXT_INPUT_BEHAVIOR = 'textInput' BEHAVIORS = [ATTR_DEFAULT_BEHAVIOR, ATTR_TEXT_INPUT_BEHAVIOR] -ATTR_LAST_SEEN_AT = "lastSeenAt" +ATTR_LAST_SEEN_AT = 'lastSeenAt' -ATTR_DEVICE = "device" -ATTR_PUSH_TOKEN = "pushToken" -ATTR_APP = "app" -ATTR_PERMISSIONS = "permissions" -ATTR_PUSH_ID = "pushId" -ATTR_DEVICE_ID = "deviceId" -ATTR_PUSH_SOUNDS = "pushSounds" -ATTR_BATTERY = "battery" +ATTR_DEVICE = 'device' +ATTR_PUSH_TOKEN = 'pushToken' +ATTR_APP = 'app' +ATTR_PERMISSIONS = 'permissions' +ATTR_PUSH_ID = 'pushId' +ATTR_DEVICE_ID = 'deviceId' +ATTR_PUSH_SOUNDS = 'pushSounds' +ATTR_BATTERY = 'battery' -ATTR_DEVICE_NAME = "name" -ATTR_DEVICE_LOCALIZED_MODEL = "localizedModel" -ATTR_DEVICE_MODEL = "model" -ATTR_DEVICE_PERMANENT_ID = "permanentID" -ATTR_DEVICE_SYSTEM_VERSION = "systemVersion" -ATTR_DEVICE_TYPE = "type" -ATTR_DEVICE_SYSTEM_NAME = "systemName" +ATTR_DEVICE_NAME = 'name' +ATTR_DEVICE_LOCALIZED_MODEL = 'localizedModel' +ATTR_DEVICE_MODEL = 'model' +ATTR_DEVICE_PERMANENT_ID = 'permanentID' +ATTR_DEVICE_SYSTEM_VERSION = 'systemVersion' +ATTR_DEVICE_TYPE = 'type' +ATTR_DEVICE_SYSTEM_NAME = 'systemName' -ATTR_APP_BUNDLE_IDENTIFER = "bundleIdentifer" -ATTR_APP_BUILD_NUMBER = "buildNumber" -ATTR_APP_VERSION_NUMBER = "versionNumber" +ATTR_APP_BUNDLE_IDENTIFER = 'bundleIdentifer' +ATTR_APP_BUILD_NUMBER = 'buildNumber' +ATTR_APP_VERSION_NUMBER = 'versionNumber' -ATTR_LOCATION_PERMISSION = "location" -ATTR_NOTIFICATIONS_PERMISSION = "notifications" +ATTR_LOCATION_PERMISSION = 'location' +ATTR_NOTIFICATIONS_PERMISSION = 'notifications' PERMISSIONS = [ATTR_LOCATION_PERMISSION, ATTR_NOTIFICATIONS_PERMISSION] -ATTR_BATTERY_STATE = "state" -ATTR_BATTERY_LEVEL = "level" +ATTR_BATTERY_STATE = 'state' +ATTR_BATTERY_LEVEL = 'level' -ATTR_BATTERY_STATE_UNPLUGGED = "Unplugged" -ATTR_BATTERY_STATE_CHARGING = "Charging" -ATTR_BATTERY_STATE_FULL = "Full" -ATTR_BATTERY_STATE_UNKNOWN = "Unknown" +ATTR_BATTERY_STATE_UNPLUGGED = 'Unplugged' +ATTR_BATTERY_STATE_CHARGING = 'Charging' +ATTR_BATTERY_STATE_FULL = 'Full' +ATTR_BATTERY_STATE_UNKNOWN = 'Unknown' BATTERY_STATES = [ATTR_BATTERY_STATE_UNPLUGGED, ATTR_BATTERY_STATE_CHARGING, ATTR_BATTERY_STATE_FULL, ATTR_BATTERY_STATE_UNKNOWN] -ATTR_DEVICES = "devices" +ATTR_DEVICES = 'devices' ACTION_SCHEMA = vol.Schema({ vol.Required(CONF_PUSH_ACTIONS_IDENTIFIER): vol.Upper, @@ -167,7 +167,7 @@ IDENTIFY_SCHEMA = vol.Schema({ vol.Optional(ATTR_PUSH_SOUNDS): list }, extra=vol.ALLOW_EXTRA) -CONFIGURATION_FILE = "ios.conf" +CONFIGURATION_FILE = 'ios.conf' CONFIG_FILE = {ATTR_DEVICES: {}} @@ -196,7 +196,7 @@ def _load_config(filename): def _save_config(filename, config): """Save configuration.""" try: - with open(filename, "w") as fdesc: + with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config, cls=JSONEncoder)) except (IOError, TypeError) as error: _LOGGER.error("Saving config file failed: %s", error) @@ -237,7 +237,7 @@ def device_name_for_push_id(push_id): def setup(hass, config): - """Setup the iOS component.""" + """Set up the iOS component.""" # pylint: disable=global-statement, import-error global CONFIG_FILE global CONFIG_FILE_PATH @@ -249,9 +249,9 @@ def setup(hass, config): if CONFIG_FILE == {}: CONFIG_FILE[ATTR_DEVICES] = {} - discovery.load_platform(hass, "notify", DOMAIN, {}, config) + discovery.load_platform(hass, 'notify', DOMAIN, {}, config) - discovery.load_platform(hass, "sensor", DOMAIN, {}, config) + discovery.load_platform(hass, 'sensor', DOMAIN, {}, config) hass.http.register_view(iOSIdentifyDeviceView) @@ -265,8 +265,8 @@ def setup(hass, config): class iOSPushConfigView(HomeAssistantView): """A view that provides the push categories configuration.""" - url = "/api/ios/push" - name = "api:ios:push" + url = '/api/ios/push' + name = 'api:ios:push' def __init__(self, push_config): """Init the view.""" @@ -281,8 +281,8 @@ class iOSPushConfigView(HomeAssistantView): class iOSIdentifyDeviceView(HomeAssistantView): """A view that accepts device identification requests.""" - url = "/api/ios/identify" - name = "api:ios:identify" + url = '/api/ios/identify' + name = 'api:ios:identify' @asyncio.coroutine def post(self, request): diff --git a/homeassistant/components/isy994.py b/homeassistant/components/isy994.py index 171c78a2fc8..a834cc0a3e4 100644 --- a/homeassistant/components/isy994.py +++ b/homeassistant/components/isy994.py @@ -7,32 +7,35 @@ https://home-assistant.io/components/isy994/ from collections import namedtuple import logging from urllib.parse import urlparse + import voluptuous as vol from homeassistant.core import HomeAssistant # noqa from homeassistant.const import ( - CONF_HOST, CONF_PASSWORD, CONF_USERNAME, - EVENT_HOMEASSISTANT_STOP) + CONF_HOST, CONF_PASSWORD, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP) from homeassistant.helpers import discovery, config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, Dict # noqa - -DOMAIN = "isy994" REQUIREMENTS = ['PyISY==1.0.7'] -ISY = None -DEFAULT_SENSOR_STRING = 'sensor' -DEFAULT_HIDDEN_STRING = '{HIDE ME}' -CONF_TLS_VER = 'tls' +_LOGGER = logging.getLogger(__name__) + +DOMAIN = 'isy994' + CONF_HIDDEN_STRING = 'hidden_string' CONF_SENSOR_STRING = 'sensor_string' -KEY_MY_PROGRAMS = 'My Programs' -KEY_FOLDER = 'folder' -KEY_ACTIONS = 'actions' -KEY_STATUS = 'status' +CONF_TLS_VER = 'tls' -_LOGGER = logging.getLogger(__name__) +DEFAULT_HIDDEN_STRING = '{HIDE ME}' +DEFAULT_SENSOR_STRING = 'sensor' + +ISY = None + +KEY_ACTIONS = 'actions' +KEY_FOLDER = 'folder' +KEY_MY_PROGRAMS = 'My Programs' +KEY_STATUS = 'status' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ @@ -158,10 +161,10 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool: host = urlparse(isy_config.get(CONF_HOST)) port = host.port addr = host.geturl() - hidden_identifier = isy_config.get(CONF_HIDDEN_STRING, - DEFAULT_HIDDEN_STRING) - sensor_identifier = isy_config.get(CONF_SENSOR_STRING, - DEFAULT_SENSOR_STRING) + hidden_identifier = isy_config.get( + CONF_HIDDEN_STRING, DEFAULT_HIDDEN_STRING) + sensor_identifier = isy_config.get( + CONF_SENSOR_STRING, DEFAULT_SENSOR_STRING) global HIDDEN_STRING HIDDEN_STRING = hidden_identifier @@ -173,7 +176,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool: addr = addr.replace('https://', '') https = True else: - _LOGGER.error('isy994 host value in configuration is invalid.') + _LOGGER.error("isy994 host value in configuration is invalid") return False addr = addr.replace(':{}'.format(port), '') @@ -225,8 +228,8 @@ class ISYDevice(Entity): """Initialize the insteon device.""" self._node = node - self._change_handler = self._node.status.subscribe('changed', - self.on_update) + self._change_handler = self._node.status.subscribe( + 'changed', self.on_update) # pylint: disable=unused-argument def on_update(self, event: object) -> None: diff --git a/homeassistant/components/joaoapps_join.py b/homeassistant/components/joaoapps_join.py index 4f01a3cf411..97572512411 100644 --- a/homeassistant/components/joaoapps_join.py +++ b/homeassistant/components/joaoapps_join.py @@ -5,9 +5,11 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/join/ """ import logging + import voluptuous as vol -from homeassistant.const import CONF_NAME, CONF_API_KEY + import homeassistant.helpers.config_validation as cv +from homeassistant.const import CONF_NAME, CONF_API_KEY REQUIREMENTS = [ 'https://github.com/nkgilley/python-join-api/archive/' @@ -71,7 +73,7 @@ def register_device(hass, device_id, api_key, name): def setup(hass, config): - """Setup Join services.""" + """Set up the Join services.""" from pyjoin import get_devices for device in config[DOMAIN]: device_id = device.get(CONF_DEVICE_ID) diff --git a/homeassistant/components/keyboard_remote.py b/homeassistant/components/keyboard_remote.py index 69151043276..88d406ace0b 100644 --- a/homeassistant/components/keyboard_remote.py +++ b/homeassistant/components/keyboard_remote.py @@ -4,7 +4,6 @@ Receive signals from a keyboard and use it as a remote control. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/keyboard_remote/ """ - # pylint: disable=import-error import threading import logging @@ -15,24 +14,26 @@ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( - EVENT_HOMEASSISTANT_START, - EVENT_HOMEASSISTANT_STOP -) + EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) -DOMAIN = "keyboard_remote" REQUIREMENTS = ['evdev==0.6.1'] + _LOGGER = logging.getLogger(__name__) + +DEVICE_DESCRIPTOR = 'device_descriptor' +DEVICE_ID_GROUP = 'Device descriptor or name' +DEVICE_NAME = 'device_name' +DOMAIN = 'keyboard_remote' + ICON = 'mdi:remote' + +KEY_CODE = 'key_code' +KEY_VALUE = {'key_up': 0, 'key_down': 1, 'key_hold': 2} KEYBOARD_REMOTE_COMMAND_RECEIVED = 'keyboard_remote_command_received' KEYBOARD_REMOTE_CONNECTED = 'keyboard_remote_connected' KEYBOARD_REMOTE_DISCONNECTED = 'keyboard_remote_disconnected' -KEY_CODE = 'key_code' -KEY_VALUE = {'key_up': 0, 'key_down': 1, 'key_hold': 2} -TYPE = 'type' -DEVICE_DESCRIPTOR = 'device_descriptor' -DEVICE_NAME = 'device_name' -DEVICE_ID_GROUP = 'Device descriptor or name' +TYPE = 'type' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ @@ -45,12 +46,12 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup keyboard_remote.""" + """Set up the keyboard_remote.""" config = config.get(DOMAIN) if not config.get(DEVICE_DESCRIPTOR) and\ not config.get(DEVICE_NAME): - _LOGGER.error('No device_descriptor or device_name found.') + _LOGGER.error("No device_descriptor or device_name found") return keyboard_remote = KeyboardRemote( @@ -91,10 +92,7 @@ class KeyboardRemote(threading.Thread): self.device_id = self.device_name self.dev = self._get_keyboard_device() if self.dev is not None: - _LOGGER.debug( - 'Keyboard connected, %s', - self.device_id - ) + _LOGGER.debug("Keyboard connected, %s", self.device_id) else: id_folder = '/dev/input/by-id/' device_names = [InputDevice(file_name).name @@ -116,6 +114,7 @@ class KeyboardRemote(threading.Thread): self.key_value = KEY_VALUE.get(config.get(TYPE, 'key_up')) def _get_keyboard_device(self): + """Get the keyboard device.""" from evdev import InputDevice, list_devices if self.device_name: devices = [InputDevice(file_name) for file_name in list_devices()] @@ -132,14 +131,12 @@ class KeyboardRemote(threading.Thread): return None def run(self): - """Main loop of the KeyboardRemote.""" + """Run the loop of the KeyboardRemote.""" from evdev import categorize, ecodes if self.dev is not None: self.dev.grab() - _LOGGER.debug( - 'Interface started for %s', - self.dev) + _LOGGER.debug("Interface started for %s", self.dev) while not self.stopped.isSet(): # Sleeps to ease load on processor @@ -152,8 +149,7 @@ class KeyboardRemote(threading.Thread): self.hass.bus.fire( KEYBOARD_REMOTE_CONNECTED ) - _LOGGER.debug('Keyboard re-connected, %s', - self.device_id) + _LOGGER.debug("Keyboard re-connected, %s", self.device_id) else: continue @@ -164,8 +160,7 @@ class KeyboardRemote(threading.Thread): self.hass.bus.fire( KEYBOARD_REMOTE_DISCONNECTED ) - _LOGGER.debug('Keyboard disconnected, %s', - self.device_id) + _LOGGER.debug("Keyboard disconnected, %s", self.device_id) continue if not event: diff --git a/homeassistant/components/knx.py b/homeassistant/components/knx.py index 53c414922e4..f72a3048dec 100644 --- a/homeassistant/components/knx.py +++ b/homeassistant/components/knx.py @@ -8,10 +8,10 @@ import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, CONF_HOST, CONF_PORT) from homeassistant.helpers.entity import Entity -import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['knxip==0.3.3'] @@ -34,7 +34,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the connection to the KNX IP interface.""" + """Set up the connection to the KNX IP interface.""" global KNXTUNNEL from knxip.ip import KNXIPTunnel @@ -94,12 +94,12 @@ class KNXConfig(object): @property def name(self): - """The name given to the entity.""" + """Return the name given to the entity.""" return self.config['name'] @property def address(self): - """The address of the device as an integer value. + """Return the address of the device as an integer value. 3 types of addresses are supported: integer - 0-65535 @@ -110,7 +110,7 @@ class KNXConfig(object): @property def state_address(self): - """The group address the device sends its current state to. + """Return the group address the device sends its current state to. Some KNX devices can send the current state to a seperate group address. This makes send e.g. when an actuator can @@ -145,12 +145,12 @@ class KNXGroupAddress(Entity): @property def name(self): - """The entity's display name.""" + """Return the entity's display name.""" return self._config.name @property def config(self): - """The entity's configuration.""" + """Return the entity's configuration.""" return self._config @property @@ -175,7 +175,7 @@ class KNXGroupAddress(Entity): @property def cache(self): - """The name given to the entity.""" + """Return the name given to the entity.""" return self._config.config.get('cache', True) def group_write(self, value): @@ -257,12 +257,12 @@ class KNXMultiAddressDevice(Entity): @property def name(self): - """The entity's display name.""" + """Return the entity's display name.""" return self._config.name @property def config(self): - """The entity's configuration.""" + """Return the entity's configuration.""" return self._config @property @@ -272,7 +272,7 @@ class KNXMultiAddressDevice(Entity): @property def cache(self): - """The name given to the entity.""" + """Return the name given to the entity.""" return self._config.config.get('cache', True) def has_attribute(self, name): diff --git a/homeassistant/components/lirc.py b/homeassistant/components/lirc.py index ac4807b26af..8b9ad0209da 100644 --- a/homeassistant/components/lirc.py +++ b/homeassistant/components/lirc.py @@ -32,7 +32,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup LIRC capability.""" + """Set up the LIRC capability.""" import lirc # blocking=True gives unexpected behavior (multiple responses for 1 press) @@ -70,7 +70,7 @@ class LircInterface(threading.Thread): self.hass = hass def run(self): - """Main loop of LIRC interface thread.""" + """Run the loop of the LIRC interface thread.""" import lirc _LOGGER.debug("LIRC interface thread started") while not self.stopped.isSet(): diff --git a/homeassistant/components/litejet.py b/homeassistant/components/litejet.py index aa4488c1277..e7c8452b27b 100644 --- a/homeassistant/components/litejet.py +++ b/homeassistant/components/litejet.py @@ -7,9 +7,9 @@ import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.helpers import discovery from homeassistant.const import CONF_PORT -import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pylitejet==0.1'] @@ -30,7 +30,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Initialize the LiteJet component.""" + """Set up the LiteJet component.""" from pylitejet import LiteJet url = config[DOMAIN].get(CONF_PORT) diff --git a/homeassistant/components/logbook.py b/homeassistant/components/logbook.py index 92f99887867..98a0973a807 100644 --- a/homeassistant/components/logbook.py +++ b/homeassistant/components/logbook.py @@ -17,13 +17,12 @@ import homeassistant.util.dt as dt_util from homeassistant.components import sun from homeassistant.components.frontend import register_built_in_panel from homeassistant.components.http import HomeAssistantView -from homeassistant.const import (EVENT_HOMEASSISTANT_START, - EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED, - STATE_NOT_HOME, STATE_OFF, STATE_ON, - ATTR_HIDDEN, HTTP_BAD_REQUEST) +from homeassistant.const import ( + EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED, + STATE_NOT_HOME, STATE_OFF, STATE_ON, ATTR_HIDDEN, HTTP_BAD_REQUEST) from homeassistant.core import State, split_entity_id, DOMAIN as HA_DOMAIN -DOMAIN = "logbook" +DOMAIN = 'logbook' DEPENDENCIES = ['recorder', 'frontend'] _LOGGER = logging.getLogger(__name__) @@ -100,11 +99,11 @@ def setup(hass, config): hass.http.register_view(LogbookView(config.get(DOMAIN, {}))) - register_built_in_panel(hass, 'logbook', 'Logbook', - 'mdi:format-list-bulleted-type') + register_built_in_panel( + hass, 'logbook', 'Logbook', 'mdi:format-list-bulleted-type') - hass.services.register(DOMAIN, 'log', log_message, - schema=LOG_MESSAGE_SCHEMA) + hass.services.register( + DOMAIN, 'log', log_message, schema=LOG_MESSAGE_SCHEMA) return True @@ -164,11 +163,11 @@ class Entry(object): def humanify(events): - """Generator that converts a list of events into Entry objects. + """Generate a converted list of events into Entry objects. Will try to group events if possible: - - if 2+ sensor updates in GROUP_BY_MINUTES, show last - - if home assistant stop and start happen in same minute call it restarted + - if 2+ sensor updates in GROUP_BY_MINUTES, show last + - if home assistant stop and start happen in same minute call it restarted """ # Group events in batches of GROUP_BY_MINUTES for _, g_events in groupby( diff --git a/homeassistant/components/logentries.py b/homeassistant/components/logentries.py index ef79b033922..6dc76d8d932 100644 --- a/homeassistant/components/logentries.py +++ b/homeassistant/components/logentries.py @@ -10,9 +10,9 @@ import requests import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import (CONF_TOKEN, EVENT_STATE_CHANGED) from homeassistant.helpers import state as state_helper -import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -28,7 +28,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Logentries component.""" + """Set up the Logentries component.""" conf = config[DOMAIN] token = conf.get(CONF_TOKEN) le_wh = '{}{}'.format(DEFAULT_HOST, token) @@ -52,11 +52,13 @@ def setup(hass, config): } ] try: - payload = {"host": le_wh, - "event": json_body} + payload = { + "host": le_wh, + "event": json_body + } requests.post(le_wh, data=json.dumps(payload), timeout=10) except requests.exceptions.RequestException as error: - _LOGGER.exception('Error sending to Logentries: %s', error) + _LOGGER.exception("Error sending to Logentries: %s", error) hass.bus.listen(EVENT_STATE_CHANGED, logentries_event_listener) diff --git a/homeassistant/components/logger.py b/homeassistant/components/logger.py index 8572bbc044a..e36053900fd 100644 --- a/homeassistant/components/logger.py +++ b/homeassistant/components/logger.py @@ -62,7 +62,7 @@ class HomeAssistantLogFilter(logging.Filter): self.logfilter = logfilter def filter(self, record): - """A filter to use.""" + """The filter to use.""" # Log with filtered severity if LOGGER_LOGS in self.logfilter: for filtername in self.logfilter[LOGGER_LOGS]: @@ -77,7 +77,7 @@ class HomeAssistantLogFilter(logging.Filter): @asyncio.coroutine def async_setup(hass, config): - """Setup the logger component.""" + """Set up the logger component.""" logfilter = {} # Set default log severity diff --git a/homeassistant/components/lutron.py b/homeassistant/components/lutron.py index 3bd1682bc41..ed3134c275a 100644 --- a/homeassistant/components/lutron.py +++ b/homeassistant/components/lutron.py @@ -22,7 +22,7 @@ LUTRON_DEVICES = 'lutron_devices' def setup(hass, base_config): - """Setup the Lutron component.""" + """Set up the Lutron component.""" from pylutron import Lutron hass.data[LUTRON_CONTROLLER] = None @@ -66,7 +66,7 @@ class LutronDevice(Entity): ) def _update_callback(self, _device): - """Callback invoked by pylutron when the device state changes.""" + """Run when invoked by pylutron when the device state changes.""" self.schedule_update_ha_state() @property diff --git a/homeassistant/components/lutron_caseta.py b/homeassistant/components/lutron_caseta.py index 1e19083e959..375e2930a4f 100644 --- a/homeassistant/components/lutron_caseta.py +++ b/homeassistant/components/lutron_caseta.py @@ -32,7 +32,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, base_config): - """Setup the Lutron component.""" + """Set up the Lutron component.""" from pylutron_caseta.smartbridge import Smartbridge config = base_config.get(DOMAIN) @@ -44,8 +44,7 @@ def setup(hass, base_config): config[CONF_HOST]) return False - _LOGGER.info("Connected to Lutron smartbridge at %s", - config[CONF_HOST]) + _LOGGER.info("Connected to Lutron smartbridge at %s", config[CONF_HOST]) for component in ('light', 'switch'): discovery.load_platform(hass, component, DOMAIN, {}, config) @@ -88,8 +87,10 @@ class LutronCasetaDevice(Entity): @property def device_state_attributes(self): """Return the state attributes.""" - attr = {'Device ID': self._device_id, - 'Zone ID': self._device_zone} + attr = { + 'Device ID': self._device_id, + 'Zone ID': self._device_zone, + } return attr @property diff --git a/homeassistant/components/microsoft_face.py b/homeassistant/components/microsoft_face.py index 5d98f04d01e..53a856e0eb4 100644 --- a/homeassistant/components/microsoft_face.py +++ b/homeassistant/components/microsoft_face.py @@ -23,11 +23,11 @@ from homeassistant.helpers.entity import Entity from homeassistant.loader import get_component from homeassistant.util import slugify +_LOGGER = logging.getLogger(__name__) + DOMAIN = 'microsoft_face' DEPENDENCIES = ['camera'] -_LOGGER = logging.getLogger(__name__) - FACE_API_URL = "https://westus.api.cognitive.microsoft.com/face/v1.0/{0}" DATA_MICROSOFT_FACE = 'microsoft_face' diff --git a/homeassistant/components/mochad.py b/homeassistant/components/mochad.py index 83665a3c6d1..a42d142112d 100644 --- a/homeassistant/components/mochad.py +++ b/homeassistant/components/mochad.py @@ -4,15 +4,14 @@ Support for CM15A/CM19A X10 Controller using mochad daemon. For more details about this component, please refer to the documentation at https://home-assistant.io/components/mochad/ """ - import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) from homeassistant.const import (CONF_HOST, CONF_PORT) -from homeassistant.helpers import config_validation as cv REQUIREMENTS = ['pymochad==0.1.1'] @@ -31,7 +30,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the mochad platform.""" + """Set up the mochad component.""" conf = config[DOMAIN] host = conf.get(CONF_HOST) port = conf.get(CONF_PORT) @@ -72,12 +71,12 @@ class MochadCtrl(object): @property def host(self): - """The server where mochad is running.""" + """Return the server where mochad is running.""" return self._host @property def port(self): - """The port mochad is running on.""" + """Return the port mochad is running on.""" return self._port def disconnect(self): diff --git a/homeassistant/components/modbus.py b/homeassistant/components/modbus.py index 3ed9fff9cf0..416ce7ec6ce 100644 --- a/homeassistant/components/modbus.py +++ b/homeassistant/components/modbus.py @@ -9,22 +9,22 @@ import threading import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, CONF_HOST, CONF_METHOD, CONF_PORT) -import homeassistant.helpers.config_validation as cv -DOMAIN = "modbus" +DOMAIN = 'modbus' REQUIREMENTS = ['https://github.com/bashwork/pymodbus/archive/' 'd7fc4f1cc975631e0a9011390e8017f64b612661.zip#pymodbus==1.2.0'] # Type of network -CONF_BAUDRATE = "baudrate" -CONF_BYTESIZE = "bytesize" -CONF_STOPBITS = "stopbits" -CONF_TYPE = "type" -CONF_PARITY = "parity" +CONF_BAUDRATE = 'baudrate' +CONF_BYTESIZE = 'bytesize' +CONF_STOPBITS = 'stopbits' +CONF_TYPE = 'type' +CONF_PARITY = 'parity' SERIAL_SCHEMA = { vol.Required(CONF_BAUDRATE): cv.positive_int, @@ -50,11 +50,11 @@ CONFIG_SCHEMA = vol.Schema({ _LOGGER = logging.getLogger(__name__) -SERVICE_WRITE_REGISTER = "write_register" +SERVICE_WRITE_REGISTER = 'write_register' -ATTR_ADDRESS = "address" -ATTR_UNIT = "unit" -ATTR_VALUE = "value" +ATTR_ADDRESS = 'address' +ATTR_UNIT = 'unit' +ATTR_VALUE = 'value' SERVICE_WRITE_REGISTER_SCHEMA = vol.Schema({ vol.Required(ATTR_UNIT): cv.positive_int, @@ -75,7 +75,7 @@ def setup(hass, config): # Connect to Modbus network # pylint: disable=global-statement, import-error - if client_type == "serial": + if client_type == 'serial': from pymodbus.client.sync import ModbusSerialClient as ModbusClient client = ModbusClient(method=config[DOMAIN][CONF_METHOD], port=config[DOMAIN][CONF_PORT], @@ -83,11 +83,11 @@ def setup(hass, config): stopbits=config[DOMAIN][CONF_STOPBITS], bytesize=config[DOMAIN][CONF_BYTESIZE], parity=config[DOMAIN][CONF_PARITY]) - elif client_type == "tcp": + elif client_type == 'tcp': from pymodbus.client.sync import ModbusTcpClient as ModbusClient client = ModbusClient(host=config[DOMAIN][CONF_HOST], port=config[DOMAIN][CONF_PORT]) - elif client_type == "udp": + elif client_type == 'udp': from pymodbus.client.sync import ModbusUdpClient as ModbusClient client = ModbusClient(host=config[DOMAIN][CONF_HOST], port=config[DOMAIN][CONF_PORT]) diff --git a/homeassistant/components/mqtt_eventstream.py b/homeassistant/components/mqtt_eventstream.py index bd149b6397d..40a752807ed 100644 --- a/homeassistant/components/mqtt_eventstream.py +++ b/homeassistant/components/mqtt_eventstream.py @@ -20,7 +20,7 @@ from homeassistant.core import EventOrigin, State import homeassistant.helpers.config_validation as cv from homeassistant.remote import JSONEncoder -DOMAIN = "mqtt_eventstream" +DOMAIN = 'mqtt_eventstream' DEPENDENCIES = ['mqtt'] CONF_PUBLISH_TOPIC = 'publish_topic' @@ -39,7 +39,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Setup the MQTT eventstream component.""" + """Set up the MQTT eventstream component.""" mqtt = loader.get_component('mqtt') conf = config.get(DOMAIN, {}) pub_topic = conf.get(CONF_PUBLISH_TOPIC) diff --git a/homeassistant/components/mysensors.py b/homeassistant/components/mysensors.py index dbf66c2288b..a7e5c7cacfa 100644 --- a/homeassistant/components/mysensors.py +++ b/homeassistant/components/mysensors.py @@ -13,41 +13,45 @@ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.setup import setup_component -from homeassistant.components.mqtt import (valid_publish_topic, - valid_subscribe_topic) -from homeassistant.const import (ATTR_BATTERY_LEVEL, CONF_NAME, - CONF_OPTIMISTIC, EVENT_HOMEASSISTANT_START, - EVENT_HOMEASSISTANT_STOP, STATE_OFF, STATE_ON) +from homeassistant.components.mqtt import ( + valid_publish_topic, valid_subscribe_topic) +from homeassistant.const import ( + ATTR_BATTERY_LEVEL, CONF_NAME, CONF_OPTIMISTIC, EVENT_HOMEASSISTANT_START, + EVENT_HOMEASSISTANT_STOP, STATE_OFF, STATE_ON) from homeassistant.helpers import discovery from homeassistant.loader import get_component -_LOGGER = logging.getLogger(__name__) - -ATTR_NODE_ID = 'node_id' -ATTR_CHILD_ID = 'child_id' -ATTR_DESCRIPTION = 'description' -ATTR_DEVICE = 'device' -CONF_BAUD_RATE = 'baud_rate' -CONF_DEVICE = 'device' -CONF_DEBUG = 'debug' -CONF_GATEWAYS = 'gateways' -CONF_PERSISTENCE = 'persistence' -CONF_PERSISTENCE_FILE = 'persistence_file' -CONF_TCP_PORT = 'tcp_port' -CONF_TOPIC_IN_PREFIX = 'topic_in_prefix' -CONF_TOPIC_OUT_PREFIX = 'topic_out_prefix' -CONF_RETAIN = 'retain' -CONF_VERSION = 'version' -DEFAULT_VERSION = 1.4 -DEFAULT_BAUD_RATE = 115200 -DEFAULT_TCP_PORT = 5003 -DOMAIN = 'mysensors' -MYSENSORS_GATEWAYS = 'mysensors_gateways' -MQTT_COMPONENT = 'mqtt' REQUIREMENTS = [ 'https://github.com/theolind/pymysensors/archive/' 'c6990eaaa741444a638608e6e00488195e2ca74c.zip#pymysensors==0.9.1'] +_LOGGER = logging.getLogger(__name__) + +ATTR_CHILD_ID = 'child_id' +ATTR_DESCRIPTION = 'description' +ATTR_DEVICE = 'device' +ATTR_NODE_ID = 'node_id' + +CONF_BAUD_RATE = 'baud_rate' +CONF_DEBUG = 'debug' +CONF_DEVICE = 'device' +CONF_GATEWAYS = 'gateways' +CONF_PERSISTENCE = 'persistence' +CONF_PERSISTENCE_FILE = 'persistence_file' +CONF_RETAIN = 'retain' +CONF_TCP_PORT = 'tcp_port' +CONF_TOPIC_IN_PREFIX = 'topic_in_prefix' +CONF_TOPIC_OUT_PREFIX = 'topic_out_prefix' +CONF_VERSION = 'version' + +DEFAULT_BAUD_RATE = 115200 +DEFAULT_TCP_PORT = 5003 +DEFAULT_VERSION = 1.4 +DOMAIN = 'mysensors' + +MQTT_COMPONENT = 'mqtt' +MYSENSORS_GATEWAYS = 'mysensors_gateways' + def is_socket_address(value): """Validate that value is a valid address.""" @@ -148,7 +152,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the MySensors component.""" + """Set up the MySensors component.""" import mysensors.mysensors as mysensors version = config[DOMAIN].get(CONF_VERSION) @@ -201,7 +205,7 @@ def setup(hass, config): gateway.event_callback = gateway.callback_factory() def gw_start(event): - """Callback to trigger start of gateway and any persistence.""" + """Trigger to start of the gateway and any persistence.""" if persistence: for node_id in gateway.sensors: node = gateway.sensors[node_id] @@ -220,7 +224,7 @@ def setup(hass, config): gateways = hass.data.get(MYSENSORS_GATEWAYS) if gateways is not None: _LOGGER.error( - '%s already exists in %s, will not setup %s component', + "%s already exists in %s, will not setup %s component", MYSENSORS_GATEWAYS, hass.data, DOMAIN) return False @@ -245,7 +249,7 @@ def setup(hass, config): if not gateways: _LOGGER.error( - 'No devices could be setup as gateways, check your configuration') + "No devices could be setup as gateways, check your configuration") return False hass.data[MYSENSORS_GATEWAYS] = gateways @@ -266,9 +270,9 @@ def setup(hass, config): def pf_callback_factory(map_sv_types, devices, entity_class, add_devices=None): """Return a new callback for the platform.""" def mysensors_callback(gateway, msg): - """Callback for mysensors platform.""" + """Run when a message from the gateway arrives.""" if gateway.sensors[msg.node_id].sketch_name is None: - _LOGGER.debug('No sketch_name: node %s', msg.node_id) + _LOGGER.debug("No sketch_name: node %s", msg.node_id) return child = gateway.sensors[msg.node_id].children.get(msg.child_id) if child is None: @@ -294,7 +298,7 @@ def pf_callback_factory(map_sv_types, devices, entity_class, add_devices=None): devices[key] = device_class( gateway, msg.node_id, child.id, name, value_type) if add_devices: - _LOGGER.info('Adding new devices: %s', [devices[key]]) + _LOGGER.info("Adding new devices: %s", [devices[key]]) add_devices([devices[key]], True) else: devices[key].update() @@ -305,7 +309,7 @@ class GatewayWrapper(object): """Gateway wrapper class.""" def __init__(self, gateway, optimistic, device): - """Setup class attributes on instantiation. + """Set up the class attributes on instantiation. Args: gateway (mysensors.SerialGateway): Gateway to wrap. @@ -348,7 +352,7 @@ class GatewayWrapper(object): def node_update(msg): """Callback for node updates from the MySensors gateway.""" _LOGGER.debug( - 'Update: node %s, child %s sub_type %s', + "Update: node %s, child %s sub_type %s", msg.node_id, msg.child_id, msg.sub_type) for callback in self.platform_callbacks: callback(self, msg) @@ -357,10 +361,10 @@ class GatewayWrapper(object): class MySensorsDeviceEntity(object): - """Represent a MySensors entity.""" + """Representation of a MySensors entity.""" def __init__(self, gateway, node_id, child_id, name, value_type): - """Set up MySensors device.""" + """Set up the MySensors device.""" self.gateway = gateway self.node_id = node_id self.child_id = child_id diff --git a/homeassistant/components/neato.py b/homeassistant/components/neato.py index 67716c6a2e5..2401bc6604f 100644 --- a/homeassistant/components/neato.py +++ b/homeassistant/components/neato.py @@ -10,10 +10,10 @@ from urllib.error import HTTPError import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import discovery from homeassistant.util import Throttle -import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -81,13 +81,13 @@ ALERTS = { def setup(hass, config): - """Setup the Neato component.""" + """Set up the Neato component.""" from pybotvac import Account hass.data[NEATO_LOGIN] = NeatoHub(hass, config[DOMAIN], Account) hub = hass.data[NEATO_LOGIN] if not hub.login(): - _LOGGER.debug('Failed to login to Neato API') + _LOGGER.debug("Failed to login to Neato API") return False hub.update_robots() for component in ('camera', 'sensor', 'switch'): @@ -114,9 +114,9 @@ class NeatoHub(object): def login(self): """Login to My Neato.""" try: - _LOGGER.debug('Trying to connect to Neato API') - self.my_neato = self._neato(self.config[CONF_USERNAME], - self.config[CONF_PASSWORD]) + _LOGGER.debug("Trying to connect to Neato API") + self.my_neato = self._neato( + self.config[CONF_USERNAME], self.config[CONF_PASSWORD]) return True except HTTPError: _LOGGER.error("Unable to connect to Neato API") @@ -125,7 +125,7 @@ class NeatoHub(object): @Throttle(timedelta(seconds=1)) def update_robots(self): """Update the robot states.""" - _LOGGER.debug('Running HUB.update_robots %s', + _LOGGER.debug("Running HUB.update_robots %s", self._hass.data[NEATO_ROBOTS]) self._hass.data[NEATO_ROBOTS] = self.my_neato.robots self._hass.data[NEATO_MAP_DATA] = self.my_neato.maps diff --git a/homeassistant/components/nest.py b/homeassistant/components/nest.py index 94a0db35f4d..8d99a4d0327 100644 --- a/homeassistant/components/nest.py +++ b/homeassistant/components/nest.py @@ -11,16 +11,16 @@ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers import discovery -from homeassistant.const import (CONF_STRUCTURE, CONF_FILENAME, - CONF_BINARY_SENSORS, CONF_SENSORS, - CONF_MONITORED_CONDITIONS) +from homeassistant.const import ( + CONF_STRUCTURE, CONF_FILENAME, CONF_BINARY_SENSORS, CONF_SENSORS, + CONF_MONITORED_CONDITIONS) from homeassistant.loader import get_component +REQUIREMENTS = ['python-nest==3.1.0'] + _CONFIGURING = {} _LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ['python-nest==3.1.0'] - DOMAIN = 'nest' DATA_NEST = 'nest' @@ -54,7 +54,7 @@ def request_configuration(nest, hass, config): return def nest_configuration_callback(data): - """The actions to do when our configuration callback is called.""" + """Run when the configuration callback is called.""" _LOGGER.debug("configurator callback") pin = data.get('pin') setup_nest(hass, nest, config, pin=pin) @@ -72,7 +72,7 @@ def request_configuration(nest, hass, config): def setup_nest(hass, nest, config, pin=None): - """Setup Nest Devices.""" + """Set up the Nest devices.""" if pin is not None: _LOGGER.debug("pin acquired, requesting access token") nest.request_token(pin) @@ -108,7 +108,7 @@ def setup_nest(hass, nest, config, pin=None): def setup(hass, config): - """Setup the Nest thermostat component.""" + """Set up the Nest thermostat component.""" import nest if 'nest' in _CONFIGURING: @@ -144,7 +144,7 @@ class NestDevice(object): _LOGGER.debug("Structures to include: %s", self._structure) def thermostats(self): - """Generator returning list of thermostats and their location.""" + """Generate a list of thermostats and their location.""" try: for structure in self.nest.structures: if structure.name in self._structure: @@ -158,7 +158,7 @@ class NestDevice(object): "Connection error logging into the nest web service.") def smoke_co_alarms(self): - """Generator returning list of smoke co alarams.""" + """Generate a list of smoke co alarams.""" try: for structure in self.nest.structures: if structure.name in self._structure: @@ -172,7 +172,7 @@ class NestDevice(object): "Connection error logging into the nest web service.") def cameras(self): - """Generator returning list of cameras.""" + """Generate a list of cameras.""" try: for structure in self.nest.structures: if structure.name in self._structure: diff --git a/homeassistant/components/nuimo_controller.py b/homeassistant/components/nuimo_controller.py index e9fd41bd098..68bf050ae43 100644 --- a/homeassistant/components/nuimo_controller.py +++ b/homeassistant/components/nuimo_controller.py @@ -7,7 +7,9 @@ https://home-assistant.io/components/nuimo_controller/ import logging import threading import time + import voluptuous as vol + import homeassistant.helpers.config_validation as cv from homeassistant.const import (CONF_MAC, CONF_NAME, EVENT_HOMEASSISTANT_STOP) @@ -44,7 +46,7 @@ DEFAULT_ADAPTER = 'hci0' def setup(hass, config): - """Setup the Nuimo component.""" + """Set up the Nuimo component.""" conf = config[DOMAIN] mac = conf.get(CONF_MAC) name = conf.get(CONF_NAME) @@ -62,7 +64,7 @@ class NuimoLogger(object): def received_gesture_event(self, event): """Input Event received.""" - _LOGGER.debug("received event: name=%s, gesture_id=%s,value=%s", + _LOGGER.debug("Received event: name=%s, gesture_id=%s,value=%s", event.name, event.gesture, event.value) self._hass.bus.fire(EVENT_NUIMO, {'type': event.name, 'value': event.value, @@ -83,7 +85,7 @@ class NuimoThread(threading.Thread): hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) def run(self): - """Setup connection or be idle.""" + """Set up the connection or be idle.""" while self._hass_is_running: if not self._nuimo or not self._nuimo.is_connected(): self._attach() @@ -102,7 +104,7 @@ class NuimoThread(threading.Thread): self._hass_is_running = False def _attach(self): - """Create a nuimo object from mac address or discovery.""" + """Create a Nuimo object from MAC address or discovery.""" # pylint: disable=import-error from nuimo import NuimoController, NuimoDiscoveryManager @@ -118,7 +120,7 @@ class NuimoThread(threading.Thread): nuimo_manager.start_discovery() # Were any Nuimos found? if not nuimo_manager.nuimos: - _LOGGER.debug('No Nuimos detected') + _LOGGER.debug("No Nuimo devices detected") return # Take the first Nuimo found. self._nuimo = nuimo_manager.nuimos[0] @@ -131,9 +133,9 @@ class NuimoThread(threading.Thread): try: self._nuimo.connect() - _LOGGER.debug('connected to %s', self._mac) + _LOGGER.debug("Connected to %s", self._mac) except RuntimeError as error: - _LOGGER.error('could not connect to %s: %s', self._mac, error) + _LOGGER.error("Could not connect to %s: %s", self._mac, error) time.sleep(1) return @@ -148,9 +150,9 @@ class NuimoThread(threading.Thread): if self._name == name and matrix: self._nuimo.write_matrix(matrix, interval) - self._hass.services.register(DOMAIN, SERVICE_NUIMO, - handle_write_matrix, - schema=SERVICE_NUIMO_SCHEMA) + self._hass.services.register( + DOMAIN, SERVICE_NUIMO, handle_write_matrix, + schema=SERVICE_NUIMO_SCHEMA) self._nuimo.write_matrix(HOMEASSIST_LOGO, 2.0) @@ -173,15 +175,15 @@ class DiscoveryLogger(object): # pylint: disable=no-self-use def discovery_started(self): - """Discovery startet.""" - _LOGGER.info("started discovery") + """Discovery started.""" + _LOGGER.info("Started discovery") # pylint: disable=no-self-use def discovery_finished(self): """Discovery finished.""" - _LOGGER.info("finished discovery") + _LOGGER.info("Finished discovery") # pylint: disable=no-self-use def controller_added(self, nuimo): - """Controller found.""" - _LOGGER.info("added Nuimo: %s", nuimo) + """Return that a controller was found.""" + _LOGGER.info("Added Nuimo: %s", nuimo) diff --git a/homeassistant/components/octoprint.py b/homeassistant/components/octoprint.py index 24f7039a41c..db6dd9931be 100644 --- a/homeassistant/components/octoprint.py +++ b/homeassistant/components/octoprint.py @@ -28,7 +28,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Set up OctoPrint API.""" + """Set up the OctoPrint component.""" base_url = 'http://{}/api/'.format(config[DOMAIN][CONF_HOST]) api_key = config[DOMAIN][CONF_API_KEY] @@ -75,9 +75,8 @@ class OctoPrintAPI(object): return self.printer_last_reading[0] url = self.api_url + endpoint try: - response = requests.get(url, - headers=self.headers, - timeout=30) + response = requests.get( + url, headers=self.headers, timeout=30) response.raise_for_status() if endpoint == "job": self.job_last_reading[0] = response.json() @@ -94,8 +93,8 @@ class OctoPrintAPI(object): def update(self, sensor_type, end_point, group, tool=None): """Return the value for sensor_type from the provided endpoint.""" try: - return get_value_from_json(self.get(end_point), sensor_type, - group, tool) + return get_value_from_json( + self.get(end_point), sensor_type, group, tool) except requests.exceptions.ConnectionError: raise diff --git a/homeassistant/components/panel_iframe.py b/homeassistant/components/panel_iframe.py index d0f9d20f838..50e764ba1f9 100644 --- a/homeassistant/components/panel_iframe.py +++ b/homeassistant/components/panel_iframe.py @@ -1,4 +1,9 @@ -"""Add an iframe panel to Home Assistant.""" +""" +Register an iFrame front end panel. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/panel_iframe/ +""" import voluptuous as vol import homeassistant.helpers.config_validation as cv @@ -22,7 +27,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup iframe frontend panels.""" + """Set up the iFrame frontend panels.""" for url_path, info in config[DOMAIN].items(): register_built_in_panel( hass, 'iframe', info.get(CONF_TITLE), info.get(CONF_ICON), diff --git a/homeassistant/components/persistent_notification.py b/homeassistant/components/persistent_notification.py index d7eef848679..7173045c06d 100644 --- a/homeassistant/components/persistent_notification.py +++ b/homeassistant/components/persistent_notification.py @@ -17,13 +17,15 @@ from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.util import slugify from homeassistant.config import load_yaml_config_file +ATTR_MESSAGE = 'message' +ATTR_NOTIFICATION_ID = 'notification_id' +ATTR_TITLE = 'title' + DOMAIN = 'persistent_notification' + ENTITY_ID_FORMAT = DOMAIN + '.{}' SERVICE_CREATE = 'create' -ATTR_TITLE = 'title' -ATTR_MESSAGE = 'message' -ATTR_NOTIFICATION_ID = 'notification_id' SCHEMA_SERVICE_CREATE = vol.Schema({ vol.Required(ATTR_MESSAGE): cv.template, @@ -57,7 +59,7 @@ def async_create(hass, message, title=None, notification_id=None): @asyncio.coroutine def async_setup(hass, config): - """Setup the persistent notification component.""" + """Set up the persistent notification component.""" @callback def create_service(call): """Handle a create notification service call.""" diff --git a/homeassistant/components/pilight.py b/homeassistant/components/pilight.py index 1d5bf2563de..18782fe4207 100644 --- a/homeassistant/components/pilight.py +++ b/homeassistant/components/pilight.py @@ -53,7 +53,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Pilight component.""" + """Set up the Pilight component.""" from pilight import pilight host = config[DOMAIN][CONF_HOST] @@ -69,13 +69,13 @@ def setup(hass, config): return False def start_pilight_client(_): - """Called once when Home Assistant starts.""" + """Run when Home Assistant starts.""" pilight_client.start() hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_pilight_client) def stop_pilight_client(_): - """Called once when Home Assistant stops.""" + """Run once when Home Assistant stops.""" pilight_client.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_pilight_client) @@ -100,7 +100,7 @@ def setup(hass, config): whitelist = config[DOMAIN].get(CONF_WHITELIST) def handle_received_code(data): - """Called when RF codes are received.""" + """Run when RF codes are received.""" # Unravel dict of dicts to make event_data cut in automation rule # possible data = dict({'protocol': data['protocol'], 'uuid': data['uuid']}, @@ -140,10 +140,10 @@ class CallRateDelayThrottle(object): self._schedule = functools.partial(track_point_in_utc_time, hass) def limited(self, method): - """Decorator to delay calls on a certain method.""" + """The decorater to delay calls on a certain method.""" @functools.wraps(method) def decorated(*args, **kwargs): - """The decorated function.""" + """Delay a call.""" if self._delay.total_seconds() == 0.0: method(*args, **kwargs) return diff --git a/homeassistant/components/proximity.py b/homeassistant/components/proximity.py index 084d6ac7407..38b37cad51e 100644 --- a/homeassistant/components/proximity.py +++ b/homeassistant/components/proximity.py @@ -11,13 +11,13 @@ import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_ZONE, CONF_DEVICES, CONF_UNIT_OF_MEASUREMENT) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import track_state_change from homeassistant.util.distance import convert from homeassistant.util.location import distance -import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -56,7 +56,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup_proximity_component(hass, name, config): - """Set up individual proximity component.""" + """Set up the individual proximity component.""" ignored_zones = config.get(CONF_IGNORED_ZONES) proximity_devices = config.get(CONF_DEVICES) tolerance = config.get(CONF_TOLERANCE) @@ -129,7 +129,7 @@ class Proximity(Entity): } def check_proximity_state_change(self, entity, old_state, new_state): - """Function to perform the proximity checking.""" + """Perform the proximity checking.""" entity_name = new_state.name devices_to_calculate = False devices_in_zone = '' diff --git a/homeassistant/components/qwikswitch.py b/homeassistant/components/qwikswitch.py index f4f1c6129a1..dd8ceefb169 100644 --- a/homeassistant/components/qwikswitch.py +++ b/homeassistant/components/qwikswitch.py @@ -123,7 +123,7 @@ class QSLight(QSToggleEntity, Light): def setup(hass, config): - """Setup the QSUSB component.""" + """Set up the QSUSB component.""" from pyqwikswitch import ( QSUsb, CMD_BUTTONS, QS_NAME, QS_ID, QS_CMD, PQS_VALUE, PQS_TYPE, QSType) diff --git a/homeassistant/components/rest_command.py b/homeassistant/components/rest_command.py index 5bf629ed37f..026f0e9a19b 100644 --- a/homeassistant/components/rest_command.py +++ b/homeassistant/components/rest_command.py @@ -54,7 +54,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Setup the rest_command component.""" + """Set up the REST command component.""" websession = async_get_clientsession(hass) def async_register_rest_command(name, command_config): diff --git a/homeassistant/components/rfxtrx.py b/homeassistant/components/rfxtrx.py index 1370aa73e1f..b7f016d1029 100644 --- a/homeassistant/components/rfxtrx.py +++ b/homeassistant/components/rfxtrx.py @@ -16,7 +16,7 @@ from homeassistant.const import (ATTR_ENTITY_ID, TEMP_CELSIUS) REQUIREMENTS = ['pyRFXtrx==0.18.0'] -DOMAIN = "rfxtrx" +DOMAIN = 'rfxtrx' DEFAULT_SIGNAL_REPETITIONS = 1 @@ -126,10 +126,10 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the RFXtrx component.""" + """Set up the RFXtrx component.""" # Declare the Handle event def handle_receive(event): - """Callback all subscribers for RFXtrx gateway.""" + """Handle revieved messgaes from RFXtrx gateway.""" # Log RFXCOM event if not event.device.id_string: return diff --git a/homeassistant/components/ring.py b/homeassistant/components/ring.py index 01b9cee9996..fe5e7bc07ea 100644 --- a/homeassistant/components/ring.py +++ b/homeassistant/components/ring.py @@ -35,7 +35,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Set up Ring component.""" + """Set up the Ring component.""" conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) diff --git a/homeassistant/components/rpi_gpio.py b/homeassistant/components/rpi_gpio.py index 0f2f5792cbc..dfc60b5e45e 100644 --- a/homeassistant/components/rpi_gpio.py +++ b/homeassistant/components/rpi_gpio.py @@ -19,7 +19,7 @@ DOMAIN = 'rpi_gpio' # pylint: disable=no-member def setup(hass, config): - """Setup the Raspberry PI GPIO component.""" + """Set up the Raspberry PI GPIO component.""" import RPi.GPIO as GPIO def cleanup_gpio(event): @@ -36,13 +36,13 @@ def setup(hass, config): def setup_output(port): - """Setup a GPIO as output.""" + """Set up a GPIO as output.""" import RPi.GPIO as GPIO GPIO.setup(port, GPIO.OUT) def setup_input(port, pull_mode): - """Setup a GPIO as input.""" + """Set up a GPIO as input.""" import RPi.GPIO as GPIO GPIO.setup(port, GPIO.IN, GPIO.PUD_DOWN if pull_mode == 'DOWN' else GPIO.PUD_UP) diff --git a/homeassistant/components/rss_feed_template.py b/homeassistant/components/rss_feed_template.py index a94ab2d04af..e6af34a9b5e 100644 --- a/homeassistant/components/rss_feed_template.py +++ b/homeassistant/components/rss_feed_template.py @@ -14,10 +14,10 @@ import voluptuous as vol from homeassistant.components.http import HomeAssistantView import homeassistant.helpers.config_validation as cv -DOMAIN = "rss_feed_template" +CONTENT_TYPE_XML = 'text/xml' DEPENDENCIES = ['http'] -CONTENT_TYPE_XML = "text/xml" +DOMAIN = 'rss_feed_template' CONFIG_SCHEMA = vol.Schema({ DOMAIN: cv.ordered_dict( @@ -37,7 +37,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the RSS feeds.""" + """Set up the RSS feed template component.""" for (feeduri, feedconfig) in config[DOMAIN].items(): url = '/api/rss_template/%s' % feeduri @@ -78,7 +78,7 @@ class RssView(HomeAssistantView): @asyncio.coroutine def get(self, request, entity_id=None): - """Generate the rss view XML.""" + """Generate the RSS view XML.""" response = '\n\n' response += '\n' diff --git a/homeassistant/components/script.py b/homeassistant/components/script.py index bcab6465dc1..6d2982dd262 100644 --- a/homeassistant/components/script.py +++ b/homeassistant/components/script.py @@ -22,18 +22,20 @@ import homeassistant.helpers.config_validation as cv from homeassistant.helpers.script import Script -DOMAIN = "script" -ENTITY_ID_FORMAT = DOMAIN + '.{}' -GROUP_NAME_ALL_SCRIPTS = 'all scripts' +_LOGGER = logging.getLogger(__name__) -CONF_SEQUENCE = "sequence" - -ATTR_VARIABLES = 'variables' +ATTR_CAN_CANCEL = 'can_cancel' ATTR_LAST_ACTION = 'last_action' ATTR_LAST_TRIGGERED = 'last_triggered' -ATTR_CAN_CANCEL = 'can_cancel' +ATTR_VARIABLES = 'variables' -_LOGGER = logging.getLogger(__name__) +CONF_SEQUENCE = 'sequence' + +DOMAIN = 'script' + +ENTITY_ID_FORMAT = DOMAIN + '.{}' + +GROUP_NAME_ALL_SCRIPTS = 'all scripts' _SCRIPT_ENTRY_SCHEMA = vol.Schema({ CONF_ALIAS: cv.string, diff --git a/homeassistant/components/scsgate.py b/homeassistant/components/scsgate.py index 54e4b821c4b..8c5c6570515 100644 --- a/homeassistant/components/scsgate.py +++ b/homeassistant/components/scsgate.py @@ -38,7 +38,7 @@ SCSGATE_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the SCSGate component.""" + """Set up the SCSGate component.""" device = config[DOMAIN][CONF_DEVICE] global SCSGATE @@ -61,7 +61,7 @@ def setup(hass, config): class SCSGate(object): - """The class for dealing with the SCSGate device via scsgate.Reactor.""" + """The class for dealing with the SCSGate device via scsgate.Reactor.""" def __init__(self, device, logger): """Initialize the SCSGate.""" @@ -81,7 +81,7 @@ class SCSGate(object): handle_message=self.handle_message) def handle_message(self, message): - """Method called whenever a message is seen on the bus.""" + """Handle a messages seen on the bus.""" from scsgate.messages import StateMessage, ScenarioTriggeredMessage self._logger.debug("Received message {}".format(message)) @@ -114,7 +114,7 @@ class SCSGate(object): @property def devices(self): - """Dictionary with known devices. + """Return a dictionary with known devices. Key is device ID, value is the device itself. """ diff --git a/homeassistant/components/shell_command.py b/homeassistant/components/shell_command.py index e4807251932..6aabdc8ddf7 100644 --- a/homeassistant/components/shell_command.py +++ b/homeassistant/components/shell_command.py @@ -26,7 +26,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the shell_command component.""" + """Set up the shell_command component.""" conf = config.get(DOMAIN, {}) cache = {} @@ -51,16 +51,16 @@ def setup(hass, config): try: rendered_args = args_compiled.render(call.data) except TemplateError as ex: - _LOGGER.exception('Error rendering command template: %s', ex) + _LOGGER.exception("Error rendering command template: %s", ex) return else: rendered_args = None if rendered_args == args: - # no template used. default behavior + # No template used. default behavior shell = True else: - # template used. Break into list and use shell=False for security + # Template used. Break into list and use shell=False for security cmd = [prog] + shlex.split(rendered_args) shell = False @@ -69,7 +69,7 @@ def setup(hass, config): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except subprocess.SubprocessError: - _LOGGER.exception('Error running command: %s', cmd) + _LOGGER.exception("Error running command: %s", cmd) for name in conf.keys(): hass.services.register(DOMAIN, name, service_handler) diff --git a/homeassistant/components/sleepiq.py b/homeassistant/components/sleepiq.py index 610f4e79bb2..d9d81d3fee0 100644 --- a/homeassistant/components/sleepiq.py +++ b/homeassistant/components/sleepiq.py @@ -4,7 +4,6 @@ Support for SleepIQ from SleepNumber. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sleepiq/ """ - import logging from datetime import timedelta @@ -47,7 +46,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup SleepIQ. + """Set up the SleepIQ component. Will automatically load sensor components to support devices discovered on the account. @@ -76,7 +75,7 @@ def setup(hass, config): class SleepIQData(object): - """Gets the latest data from SleepIQ.""" + """Get the latest data from SleepIQ.""" def __init__(self, client): """Initialize the data object.""" @@ -112,9 +111,8 @@ class SleepIQSensor(Entity): @property def name(self): """Return the name of the sensor.""" - return 'SleepNumber {} {} {}'.format(self.bed.name, - self.side.sleeper.first_name, - self._name) + return 'SleepNumber {} {} {}'.format( + self.bed.name, self.side.sleeper.first_name, self._name) def update(self): """Get the latest data from SleepIQ and updates the states.""" diff --git a/homeassistant/components/splunk.py b/homeassistant/components/splunk.py index 2ae2842bceb..e9a2ee13ae2 100644 --- a/homeassistant/components/splunk.py +++ b/homeassistant/components/splunk.py @@ -34,7 +34,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Splunk component.""" + """Set up the Splunk component.""" conf = config[DOMAIN] host = conf.get(CONF_HOST) port = conf.get(CONF_PORT) @@ -73,12 +73,14 @@ def setup(hass, config): ] try: - payload = {"host": event_collector, - "event": json_body} + payload = { + "host": event_collector, + "event": json_body, + } requests.post(event_collector, data=json.dumps(payload), - headers=headers) + headers=headers, timeout=10) except requests.exceptions.RequestException as error: - _LOGGER.exception('Error saving event to Splunk: %s', error) + _LOGGER.exception("Error saving event to Splunk: %s", error) hass.bus.listen(EVENT_STATE_CHANGED, splunk_event_listener) diff --git a/homeassistant/components/statsd.py b/homeassistant/components/statsd.py index d85bc1e030c..452faf8933b 100644 --- a/homeassistant/components/statsd.py +++ b/homeassistant/components/statsd.py @@ -39,7 +39,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the StatsD component.""" + """Set up the StatsD component.""" import statsd conf = config[DOMAIN] diff --git a/homeassistant/components/sun.py b/homeassistant/components/sun.py index f5fb0115a43..b2af30d8438 100644 --- a/homeassistant/components/sun.py +++ b/homeassistant/components/sun.py @@ -356,7 +356,7 @@ class Sun(Entity): self.location.longitude) def point_in_time_listener(self, now): - """Called when the state of the sun has changed.""" + """Run when the state of the sun has changed.""" self.update_as_of(now) self.schedule_update_ha_state() diff --git a/homeassistant/components/tado.py b/homeassistant/components/tado.py index b7758c95c0e..a465119dc2d 100644 --- a/homeassistant/components/tado.py +++ b/homeassistant/components/tado.py @@ -107,21 +107,21 @@ class TadoDataStore: return data def get_zones(self): - """Wrapper for getZones().""" + """Wrap for getZones().""" return self.tado.getZones() def get_capabilities(self, tado_id): - """Wrapper for getCapabilities(..).""" + """Wrap for getCapabilities(..).""" return self.tado.getCapabilities(tado_id) def get_me(self): - """Wrapper for getMet().""" + """Wrap for getMet().""" return self.tado.getMe() def reset_zone_overlay(self, zone_id): - """Wrapper for resetZoneOverlay(..).""" + """Wrap for resetZoneOverlay(..).""" return self.tado.resetZoneOverlay(zone_id) def set_zone_overlay(self, zone_id, mode, temperature=None, duration=None): - """Wrapper for setZoneOverlay(..).""" + """Wrap for setZoneOverlay(..).""" return self.tado.setZoneOverlay(zone_id, mode, temperature, duration) diff --git a/homeassistant/components/tellduslive.py b/homeassistant/components/tellduslive.py index eb2957d7b4a..a9f3cea81e7 100644 --- a/homeassistant/components/tellduslive.py +++ b/homeassistant/components/tellduslive.py @@ -46,14 +46,13 @@ ATTR_LAST_UPDATED = 'time_last_updated' def setup(hass, config): - """Setup the Telldus Live component.""" + """Set up the Telldus Live component.""" client = TelldusLiveClient(hass, config) if not client.validate_session(): _LOGGER.error( - 'Authentication Error: ' - 'Please make sure you have configured your keys ' - 'that can be aquired from https://api.telldus.com/keys/index') + "Authentication Error: Please make sure you have configured your " + "keys that can be aquired from https://api.telldus.com/keys/index") return False hass.data[DOMAIN] = client @@ -94,7 +93,7 @@ class TelldusLiveClient(object): def update(self, now): """Periodically poll the servers for current state.""" - _LOGGER.debug('Updating') + _LOGGER.debug("Updating") try: self._sync() finally: @@ -104,7 +103,7 @@ class TelldusLiveClient(object): def _sync(self): """Update local list of devices.""" if not self._client.update(): - _LOGGER.warning('Failed request') + _LOGGER.warning("Failed request") def identify_device(device): """Find out what type of HA component to create.""" @@ -116,8 +115,8 @@ class TelldusLiveClient(object): elif device.methods & TURNON: return 'switch' else: - _LOGGER.warning('Unidentified device type (methods: %d)', - device.methods) + _LOGGER.warning( + "Unidentified device type (methods: %d)", device.methods) return 'switch' def discover(device_id, component): @@ -158,10 +157,10 @@ class TelldusLiveEntity(Entity): self._client = hass.data[DOMAIN] self._client.entities.append(self) self._name = self.device.name - _LOGGER.debug('Created device %s', self) + _LOGGER.debug("Created device %s", self) def changed(self): - """A property of the device might have changed.""" + """Return the property of the device might have changed.""" if self.device.name: self._name = self.device.name self.schedule_update_ha_state() @@ -183,7 +182,7 @@ class TelldusLiveEntity(Entity): @property def should_poll(self): - """Polling is not needed.""" + """Return the polling state.""" return False @property diff --git a/homeassistant/components/tellstick.py b/homeassistant/components/tellstick.py index ea71ef3cdef..5d0ec78dfa7 100644 --- a/homeassistant/components/tellstick.py +++ b/homeassistant/components/tellstick.py @@ -56,7 +56,7 @@ def _discover(hass, config, component_name, found_tellcore_devices): def setup(hass, config): - """Setup the Tellstick component.""" + """Set up the Tellstick component.""" from tellcore.constants import TELLSTICK_DIM from tellcore.telldus import AsyncioCallbackDispatcher from tellcore.telldus import TelldusCore @@ -151,7 +151,7 @@ class TellstickDevice(Entity): """ def __init__(self, tellcore_id, tellcore_registry, signal_repetitions): - """Initalize the Tellstick device.""" + """Init the Tellstick device.""" self._signal_repetitions = signal_repetitions self._state = None self._requested_state = None @@ -217,7 +217,7 @@ class TellstickDevice(Entity): _LOGGER.error(err) def _change_device_state(self, new_state, data): - """The logic for actually turning on or off the device.""" + """Turn on or off the device.""" with TELLSTICK_LOCK: # Set the requested state and number of repeats before calling # _send_repeated_command the first time. Subsequent calls will be @@ -244,8 +244,8 @@ class TellstickDevice(Entity): def _update_model_from_command(self, tellcore_command, tellcore_data): """Update the model, from a sent tellcore command and data.""" - from tellcore.constants import (TELLSTICK_TURNON, TELLSTICK_TURNOFF, - TELLSTICK_DIM) + from tellcore.constants import ( + TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM) if tellcore_command not in [TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM]: @@ -268,8 +268,8 @@ class TellstickDevice(Entity): def _update_from_tellcore(self): """Read the current state of the device from the tellcore library.""" from tellcore.library import TelldusError - from tellcore.constants import (TELLSTICK_TURNON, TELLSTICK_TURNOFF, - TELLSTICK_DIM) + from tellcore.constants import ( + TELLSTICK_TURNON, TELLSTICK_TURNOFF, TELLSTICK_DIM) with TELLSTICK_LOCK: try: diff --git a/homeassistant/components/tradfri.py b/homeassistant/components/tradfri.py index 3fd51a68db0..7af31a66b9d 100644 --- a/homeassistant/components/tradfri.py +++ b/homeassistant/components/tradfri.py @@ -73,14 +73,14 @@ def request_configuration(hass, config, host): @asyncio.coroutine def async_setup(hass, config): - """Setup Tradfri.""" + """Set up the Tradfri component.""" conf = config.get(DOMAIN, {}) host = conf.get(CONF_HOST) key = conf.get(CONF_API_KEY) @asyncio.coroutine def gateway_discovered(service, info): - """Called when a gateway is discovered.""" + """Run when a gateway is discovered.""" keys = yield from hass.async_add_job(_read_config, hass) host = info['host'] diff --git a/homeassistant/components/vera.py b/homeassistant/components/vera.py index 655c8100f8c..6dbac5496c2 100644 --- a/homeassistant/components/vera.py +++ b/homeassistant/components/vera.py @@ -56,7 +56,7 @@ VERA_COMPONENTS = [ # pylint: disable=unused-argument, too-many-function-args def setup(hass, base_config): - """Common setup for Vera devices.""" + """Set up for Vera devices.""" global VERA_CONTROLLER import pyvera as veraApi @@ -102,7 +102,7 @@ def setup(hass, base_config): # pylint: disable=too-many-return-statements def map_vera_device(vera_device, remap): - """Map vera classes to HA types.""" + """Map vera classes to Home Assistant types.""" import pyvera as veraApi if isinstance(vera_device, veraApi.VeraDimmer): return 'light' @@ -145,6 +145,7 @@ class VeraDevice(Entity): self.update() def _update_callback(self, _device): + """Update the state.""" self.update() self.schedule_update_ha_state() diff --git a/homeassistant/components/verisure.py b/homeassistant/components/verisure.py index f2b091aa0f1..72837b07019 100644 --- a/homeassistant/components/verisure.py +++ b/homeassistant/components/verisure.py @@ -23,6 +23,7 @@ REQUIREMENTS = ['vsure==0.11.1'] _LOGGER = logging.getLogger(__name__) ATTR_DEVICE_SERIAL = 'device_serial' + CONF_ALARM = 'alarm' CONF_CODE_DIGITS = 'code_digits' CONF_HYDROMETERS = 'hygrometers' @@ -31,7 +32,9 @@ CONF_MOUSE = 'mouse' CONF_SMARTPLUGS = 'smartplugs' CONF_THERMOMETERS = 'thermometers' CONF_SMARTCAM = 'smartcam' + DOMAIN = 'verisure' + SERVICE_CAPTURE_SMARTCAM = 'capture_smartcam' HUB = None @@ -57,7 +60,7 @@ CAPTURE_IMAGE_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Verisure component.""" + """Set up the Verisure component.""" import verisure global HUB HUB = VerisureHub(config[DOMAIN], verisure) @@ -75,7 +78,7 @@ def setup(hass, config): """Capture a new picture from a smartcam.""" device_id = service.data.get(ATTR_DEVICE_SERIAL) HUB.smartcam_capture(device_id) - _LOGGER.debug('Capturing new image from %s', ATTR_DEVICE_SERIAL) + _LOGGER.debug("Capturing new image from %s", ATTR_DEVICE_SERIAL) hass.services.register(DOMAIN, SERVICE_CAPTURE_SMARTCAM, capture_smartcam, @@ -119,7 +122,7 @@ class VerisureHub(object): try: self.my_pages.login() except self._verisure.Error as ex: - _LOGGER.error('Could not log in to verisure mypages, %s', ex) + _LOGGER.error("Could not log in to verisure mypages, %s", ex) return False return True @@ -168,9 +171,9 @@ class VerisureHub(object): @Throttle(timedelta(seconds=30)) def update_smartcam_imagelist(self): """Update the imagelist for the camera.""" - _LOGGER.debug('Running update imagelist') + _LOGGER.debug("Running update imagelist") self.smartcam_dict = self.my_pages.smartcam.get_imagelist() - _LOGGER.debug('New dict: %s', self.smartcam_dict) + _LOGGER.debug("New dict: %s", self.smartcam_dict) @Throttle(timedelta(seconds=30)) def smartcam_capture(self, device_id): @@ -191,7 +194,7 @@ class VerisureHub(object): except AttributeError: status[overview.deviceLabel] = overview except self._verisure.Error as ex: - _LOGGER.info('Caught connection error %s, tries to reconnect', ex) + _LOGGER.info("Caught connection error %s, tries to reconnect", ex) self.reconnect() def reconnect(self): diff --git a/homeassistant/components/volvooncall.py b/homeassistant/components/volvooncall.py index 04420bec567..da419ff0ab3 100644 --- a/homeassistant/components/volvooncall.py +++ b/homeassistant/components/volvooncall.py @@ -56,7 +56,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the VOC component.""" + """Set up the Volvo On Call component.""" from volvooncall import Connection connection = Connection( config[DOMAIN].get(CONF_USERNAME), @@ -79,14 +79,11 @@ def setup(hass, config): for attr, (component, *_) in RESOURCES.items(): if (getattr(vehicle, attr + '_supported', True) and attr in config[DOMAIN].get(CONF_RESOURCES, [attr])): - discovery.load_platform(hass, - component, - DOMAIN, - (vehicle.vin, attr), - config) + discovery.load_platform( + hass, component, DOMAIN, (vehicle.vin, attr), config) def update_vehicle(vehicle): - """Updated information on vehicle received.""" + """Revieve updated information on vehicle.""" state.vehicles[vehicle.vin] = vehicle if vehicle.vin not in state.entities: discover_vehicle(vehicle) @@ -101,7 +98,7 @@ def setup(hass, config): """Update status from the online service.""" try: if not connection.update(): - _LOGGER.warning('Could not query server') + _LOGGER.warning("Could not query server") return False for vehicle in connection.vehicles: @@ -111,7 +108,7 @@ def setup(hass, config): finally: track_point_in_utc_time(hass, update, utcnow() + interval) - _LOGGER.info('Logging in to service') + _LOGGER.info("Logging in to service") return update(utcnow()) @@ -154,7 +151,7 @@ class VolvoEntity(Entity): @property def should_poll(self): - """Polling is not needed.""" + """Return the polling state.""" return False @property diff --git a/homeassistant/components/weblink.py b/homeassistant/components/weblink.py index 7fe121d64c9..f55fe1f0bb5 100644 --- a/homeassistant/components/weblink.py +++ b/homeassistant/components/weblink.py @@ -34,7 +34,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup weblink component.""" + """Set up the weblink component.""" links = config.get(DOMAIN) for link in links.get(CONF_ENTITIES): diff --git a/homeassistant/components/websocket_api.py b/homeassistant/components/websocket_api.py index a3557a301c5..009c0d1f1d6 100644 --- a/homeassistant/components/websocket_api.py +++ b/homeassistant/components/websocket_api.py @@ -1,4 +1,9 @@ -"""Websocket based API for Home Assistant.""" +""" +Websocket based API for Home Assistant. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/developers/websocket_api/ +""" import asyncio from functools import partial import json @@ -22,7 +27,7 @@ from homeassistant.components.http.ban import process_wrong_login DOMAIN = 'websocket_api' -URL = "/api/websocket" +URL = '/api/websocket' DEPENDENCIES = 'http', ERR_ID_REUSE = 1 @@ -209,15 +214,15 @@ class ActiveConnection: def debug(self, message1, message2=''): """Print a debug message.""" - _LOGGER.debug('WS %s: %s %s', id(self.wsock), message1, message2) + _LOGGER.debug("WS %s: %s %s", id(self.wsock), message1, message2) def log_error(self, message1, message2=''): """Print an error message.""" - _LOGGER.error('WS %s: %s %s', id(self.wsock), message1, message2) + _LOGGER.error("WS %s: %s %s", id(self.wsock), message1, message2) def send_message(self, message): - """Helper method to send messages.""" - self.debug('Sending', message) + """Send messages.""" + self.debug("Sending", message) self.wsock.send_json(message, dumps=JSON_DUMP) @asyncio.coroutine @@ -234,10 +239,10 @@ class ActiveConnection: """Cancel this connection.""" socket_task.cancel() - unsub_stop = self.hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, - cancel_connection) + unsub_stop = self.hass.bus.async_listen( + EVENT_HOMEASSISTANT_STOP, cancel_connection) - self.debug('Connected') + self.debug("Connected") msg = None authenticated = False @@ -255,7 +260,7 @@ class ActiveConnection: authenticated = True else: - self.debug('Invalid password') + self.debug("Invalid password") self.send_message(auth_invalid_message('Invalid password')) if not authenticated: @@ -269,7 +274,7 @@ class ActiveConnection: last_id = 0 while msg: - self.debug('Received', msg) + self.debug("Received", msg) msg = BASE_COMMAND_MESSAGE_SCHEMA(msg) cur_id = msg['id'] @@ -286,7 +291,7 @@ class ActiveConnection: msg = yield from wsock.receive_json() except vol.Invalid as err: - error_msg = 'Message incorrectly formatted: ' + error_msg = "Message incorrectly formatted: " if msg: error_msg += humanize_error(msg, err) else: @@ -303,27 +308,27 @@ class ActiveConnection: else: iden = None - self.send_message(error_message(iden, ERR_INVALID_FORMAT, - error_msg)) + self.send_message(error_message( + iden, ERR_INVALID_FORMAT, error_msg)) except TypeError as err: if wsock.closed: - self.debug('Connection closed by client') + self.debug("Connection closed by client") else: - self.log_error('Unexpected TypeError', msg) + self.log_error("Unexpected TypeError", msg) except ValueError as err: - msg = 'Received invalid JSON' + msg = "Received invalid JSON" value = getattr(err, 'doc', None) # Py3.5+ only if value: msg += ': {}'.format(value) self.log_error(msg) except asyncio.CancelledError: - self.debug('Connection cancelled by server') + self.debug("Connection cancelled by server") except Exception: # pylint: disable=broad-except - error = 'Unexpected error inside websocket API. ' + error = "Unexpected error inside websocket API. " if msg is not None: error += str(msg) _LOGGER.exception(error) @@ -335,7 +340,7 @@ class ActiveConnection: unsub() yield from wsock.close() - self.debug('Closed connection') + self.debug("Closed connection") return wsock @@ -345,7 +350,7 @@ class ActiveConnection: @callback def forward_events(event): - """Helper to forward events to websocket.""" + """Forward events to websocket.""" if event.event_type == EVENT_TIME_CHANGED: return @@ -380,7 +385,7 @@ class ActiveConnection: @asyncio.coroutine def call_service_helper(msg): - """Helper to call a service and fire complete message.""" + """Call a service and fire complete message.""" yield from self.hass.services.async_call( msg['domain'], msg['service'], msg['service_data'], True) try: @@ -395,22 +400,22 @@ class ActiveConnection: """Handle get states command.""" msg = GET_STATES_MESSAGE_SCHEMA(msg) - self.send_message(result_message(msg['id'], - self.hass.states.async_all())) + self.send_message(result_message( + msg['id'], self.hass.states.async_all())) def handle_get_services(self, msg): """Handle get services command.""" msg = GET_SERVICES_MESSAGE_SCHEMA(msg) - self.send_message(result_message(msg['id'], - self.hass.services.async_services())) + self.send_message(result_message( + msg['id'], self.hass.services.async_services())) def handle_get_config(self, msg): """Handle get config command.""" msg = GET_CONFIG_MESSAGE_SCHEMA(msg) - self.send_message(result_message(msg['id'], - self.hass.config.as_dict())) + self.send_message(result_message( + msg['id'], self.hass.config.as_dict())) def handle_get_panels(self, msg): """Handle get panels command.""" diff --git a/homeassistant/components/wemo.py b/homeassistant/components/wemo.py index 98eefbc42d8..3d7226e3c8b 100644 --- a/homeassistant/components/wemo.py +++ b/homeassistant/components/wemo.py @@ -45,7 +45,7 @@ CONFIG_SCHEMA = vol.Schema({ # pylint: disable=unused-argument, too-many-function-args def setup(hass, config): - """Common setup for WeMo devices.""" + """Set up for WeMo devices.""" import pywemo global SUBSCRIPTION_REGISTRY diff --git a/homeassistant/components/wink.py b/homeassistant/components/wink.py index 8cf32f64d61..d755d59056b 100644 --- a/homeassistant/components/wink.py +++ b/homeassistant/components/wink.py @@ -120,7 +120,7 @@ def setup(hass, config): def pull_new_devices(call): """Pull new devices added to users Wink account since startup.""" - _LOGGER.info("Getting new devices from Wink API.") + _LOGGER.info("Getting new devices from Wink API") for component in WINK_COMPONENTS: discovery.load_platform(hass, component, DOMAIN, {}, config) hass.services.register(DOMAIN, 'Add new devices', pull_new_devices) @@ -166,7 +166,7 @@ class WinkDevice(Entity): @property def available(self): - """True if connection == True.""" + """Return true if connection == True.""" return self.wink.available() def update(self): diff --git a/homeassistant/components/zha/__init__.py b/homeassistant/components/zha/__init__.py index e9e21b634d1..8c84fe166f0 100644 --- a/homeassistant/components/zha/__init__.py +++ b/homeassistant/components/zha/__init__.py @@ -9,13 +9,11 @@ import logging import voluptuous as vol +import homeassistant.helpers.config_validation as cv from homeassistant import const as ha_const from homeassistant.helpers import discovery, entity from homeassistant.util import slugify -import homeassistant.helpers.config_validation as cv - -# Definitions for interfacing with the rest of HA REQUIREMENTS = ['bellows==0.2.7'] DOMAIN = 'zha' @@ -38,9 +36,9 @@ CONFIG_SCHEMA = vol.Schema({ }) }, extra=vol.ALLOW_EXTRA) -ATTR_DURATION = "duration" +ATTR_DURATION = 'duration' -SERVICE_PERMIT = "permit" +SERVICE_PERMIT = 'permit' SERVICE_DESCRIPTIONS = { SERVICE_PERMIT: { "description": "Allow nodes to join the Zigbee network", @@ -72,7 +70,7 @@ _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def async_setup(hass, config): - """Setup ZHA. + """Set up ZHA. Will automatically load components to support devices found on the network. """ @@ -109,7 +107,7 @@ def async_setup(hass, config): class ApplicationListener: - """Handlers for events that happen on the ZigBee application.""" + """All handlers for events that happen on the ZigBee application.""" def __init__(self, hass, config): """Initialize the listener.""" @@ -213,7 +211,7 @@ class Entity(entity.Entity): _domain = None # Must be overriden by subclasses def __init__(self, endpoint, clusters, manufacturer, model, **kwargs): - """Initialize ZHA entity.""" + """Init ZHA entity.""" self._device_state_attributes = {} ieeetail = ''.join([ '%02x' % (o, ) for o in endpoint.device.ieee[-4:] diff --git a/homeassistant/components/zha/const.py b/homeassistant/components/zha/const.py index 5e2dfb12d6f..ed06f18c1f5 100644 --- a/homeassistant/components/zha/const.py +++ b/homeassistant/components/zha/const.py @@ -1,6 +1,5 @@ -"""Constants related to the zha component.""" +"""All constants related to the ZHA component.""" -# Populated by populate_data() when zha component is initialized DEVICE_CLASS = {} SINGLE_CLUSTER_DEVICE_CLASS = {} COMPONENT_CLUSTERS = {} diff --git a/homeassistant/components/zigbee.py b/homeassistant/components/zigbee.py index 817e7e432db..95b0971373d 100644 --- a/homeassistant/components/zigbee.py +++ b/homeassistant/components/zigbee.py @@ -61,7 +61,7 @@ PLATFORM_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the connection to the ZigBee device.""" + """Set up the connection to the ZigBee device.""" global DEVICE global GPIO_DIGITAL_OUTPUT_LOW global GPIO_DIGITAL_OUTPUT_HIGH @@ -98,7 +98,7 @@ def setup(hass, config): hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_serial_port) def _frame_received(frame): - """Called when a ZigBee frame is received. + """Run when a ZigBee frame is received. Pickles the frame, then encodes it into base64 since it contains non JSON serializable binary. @@ -134,12 +134,12 @@ class ZigBeeConfig(object): @property def name(self): - """The name given to the entity.""" + """Return the name given to the entity.""" return self._config["name"] @property def address(self): - """The address of the device. + """Return the address of the device. If an address has been provided, unhexlify it, otherwise return None as we're talking to our local ZigBee device. @@ -151,16 +151,16 @@ class ZigBeeConfig(object): @property def should_poll(self): - """No polling needed.""" + """Return the polling state.""" return self._should_poll class ZigBeePinConfig(ZigBeeConfig): - """Handle the fetching of configuration from the config file.""" + """Handle the fetching of configuration from the configuration file.""" @property def pin(self): - """The GPIO pin number.""" + """Return the GPIO pin number.""" return self._config["pin"] @@ -195,7 +195,7 @@ class ZigBeeDigitalInConfig(ZigBeePinConfig): @property def bool2state(self): - """A dictionary mapping the internal value to the ZigBee value. + """Return a dictionary mapping the internal value to the ZigBee value. For the translation of on/off as being pin high or low. """ @@ -203,7 +203,7 @@ class ZigBeeDigitalInConfig(ZigBeePinConfig): @property def state2bool(self): - """A dictionary mapping the ZigBee value to the internal value. + """Return a dictionary mapping the ZigBee value to the internal value. For the translation of pin high/low as being on or off. """ @@ -245,7 +245,7 @@ class ZigBeeDigitalOutConfig(ZigBeePinConfig): @property def bool2state(self): - """A dictionary mapping booleans to GPIOSetting objects. + """Return a dictionary mapping booleans to GPIOSetting objects. For the translation of on/off as being pin high or low. """ @@ -253,7 +253,7 @@ class ZigBeeDigitalOutConfig(ZigBeePinConfig): @property def state2bool(self): - """A dictionary mapping GPIOSetting objects to booleans. + """Return a dictionary mapping GPIOSetting objects to booleans. For the translation of pin high/low as being on or off. """ @@ -265,7 +265,7 @@ class ZigBeeAnalogInConfig(ZigBeePinConfig): @property def max_voltage(self): - """The voltage at which the ADC will report its highest value.""" + """Return the voltage for ADC to report its highest value.""" return float(self._config.get("max_volts", DEFAULT_ADC_MAX_VOLTS)) @@ -306,7 +306,7 @@ class ZigBeeDigitalIn(Entity): @property def config(self): - """The entity's configuration.""" + """Return the entity's configuration.""" return self._config @property @@ -428,17 +428,17 @@ class ZigBeeAnalogIn(Entity): @property def name(self): - """The name of the input.""" + """Return the name of the input.""" return self._config.name @property def config(self): - """The entity's configuration.""" + """Return the entity's configuration.""" return self._config @property def should_poll(self): - """The state of the polling, if needed.""" + """Return the polling state, if needed.""" return self._config.should_poll @property diff --git a/homeassistant/components/zone.py b/homeassistant/components/zone.py index 235fe11934a..e1a8b8e721b 100644 --- a/homeassistant/components/zone.py +++ b/homeassistant/components/zone.py @@ -104,7 +104,7 @@ def in_zone(zone, latitude, longitude, radius=0): @asyncio.coroutine def async_setup(hass, config): - """Setup zone.""" + """Set up the zone.""" entities = set() tasks = [] for _, entry in config_per_platform(config, DOMAIN): @@ -112,8 +112,8 @@ def async_setup(hass, config): zone = Zone(hass, name, entry[CONF_LATITUDE], entry[CONF_LONGITUDE], entry.get(CONF_RADIUS), entry.get(CONF_ICON), entry.get(CONF_PASSIVE)) - zone.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, name, - entities) + zone.entity_id = async_generate_entity_id( + ENTITY_ID_FORMAT, name, entities) tasks.append(zone.async_update_ha_state()) entities.add(zone.entity_id) diff --git a/homeassistant/config.py b/homeassistant/config.py index 6e349ea486a..253a6af4e2f 100644 --- a/homeassistant/config.py +++ b/homeassistant/config.py @@ -325,7 +325,7 @@ def async_process_ha_core_config(hass, config): hac = hass.config def set_time_zone(time_zone_str): - """Helper method to set time zone.""" + """Help to set the time zone.""" if time_zone_str is None: return diff --git a/homeassistant/core.py b/homeassistant/core.py index c9cba0a1357..a0a80b9c8bd 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -164,7 +164,7 @@ class HomeAssistant(object): self.bus.async_fire(EVENT_HOMEASSISTANT_START) try: - # only block for EVENT_HOMEASSISTANT_START listener + # Only block for EVENT_HOMEASSISTANT_START listener self.async_stop_track_tasks() with timeout(TIMEOUT_EVENT_START, loop=self.loop): yield from self.async_block_till_done() @@ -208,7 +208,7 @@ class HomeAssistant(object): else: task = self.loop.run_in_executor(None, target, *args) - # if a task is sheduled + # If a task is sheduled if self._track_task and task is not None: self._pending_tasks.append(task) @@ -296,7 +296,7 @@ class EventOrigin(enum.Enum): class Event(object): - """Represents an event within the Bus.""" + """Representation of an event within the bus.""" __slots__ = ['event_type', 'data', 'origin', 'time_fired'] @@ -341,7 +341,7 @@ class Event(object): class EventBus(object): - """Allows firing of and listening for events.""" + """Allow the firing of and listening for events.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize a new event bus.""" @@ -350,7 +350,7 @@ class EventBus(object): @callback def async_listeners(self): - """Dict with events and the number of listeners. + """Dictionary with events and the number of listeners. This method must be run in the event loop. """ @@ -359,7 +359,7 @@ class EventBus(object): @property def listeners(self): - """Dict with events and the number of listeners.""" + """Dictionary with events and the number of listeners.""" return run_callback_threadsafe( self._hass.loop, self.async_listeners ).result() @@ -736,7 +736,7 @@ class StateMachine(object): class Service(object): - """Represents a callable service.""" + """Representation of a callable service.""" __slots__ = ['func', 'description', 'fields', 'schema', 'is_callback', 'is_coroutinefunction'] @@ -759,7 +759,7 @@ class Service(object): class ServiceCall(object): - """Represents a call to a service.""" + """Representation of a call to a service.""" __slots__ = ['domain', 'service', 'data', 'call_id'] @@ -780,7 +780,7 @@ class ServiceCall(object): class ServiceRegistry(object): - """Offers services over the eventbus.""" + """Offer the services over the eventbus.""" def __init__(self, hass): """Initialize a service registry.""" @@ -799,14 +799,14 @@ class ServiceRegistry(object): @property def services(self): - """Dict with per domain a list of available services.""" + """Dictionary with per domain a list of available services.""" return run_callback_threadsafe( self._hass.loop, self.async_services, ).result() @callback def async_services(self): - """Dict with per domain a list of available services. + """Dictionary with per domain a list of available services. This method must be run in the event loop. """ @@ -952,7 +952,7 @@ class ServiceRegistry(object): @callback def service_executed(event): - """Callback method that is called when service is executed.""" + """Method that is called when service is executed.""" if event.data[ATTR_SERVICE_CALL_ID] == call_id: fut.set_result(True) @@ -970,7 +970,7 @@ class ServiceRegistry(object): @asyncio.coroutine def _event_to_service_call(self, event): - """Callback for SERVICE_CALLED events from the event bus.""" + """Method for the SERVICE_CALLED events from the EventBus.""" service_data = event.data.get(ATTR_SERVICE_DATA) or {} domain = event.data.get(ATTR_DOMAIN).lower() service = event.data.get(ATTR_SERVICE).lower() @@ -1056,7 +1056,7 @@ class Config(object): location.distance(self.latitude, self.longitude, lat, lon), 'm') def path(self, *path): - """Generate path to the file within the config dir. + """Generate path to the file within the configuration directory. Async friendly. """ @@ -1065,7 +1065,7 @@ class Config(object): return os.path.join(self.config_dir, *path) def as_dict(self): - """Create a dict representation of this dict. + """Create a dictionary representation of this dict. Async friendly. """ diff --git a/homeassistant/exceptions.py b/homeassistant/exceptions.py index f45fd3c3841..4981e13beeb 100644 --- a/homeassistant/exceptions.py +++ b/homeassistant/exceptions.py @@ -1,4 +1,4 @@ -"""Exceptions used by Home Assistant.""" +"""The exceptions used by Home Assistant.""" class HomeAssistantError(Exception): @@ -23,6 +23,6 @@ class TemplateError(HomeAssistantError): """Error during template rendering.""" def __init__(self, exception): - """Initalize the error.""" + """Init the error.""" super().__init__('{}: {}'.format(exception.__class__.__name__, exception)) diff --git a/homeassistant/remote.py b/homeassistant/remote.py index c0e3d9d6459..b65b3f3de22 100644 --- a/homeassistant/remote.py +++ b/homeassistant/remote.py @@ -25,15 +25,15 @@ from homeassistant.const import ( HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON) from homeassistant.exceptions import HomeAssistantError -METHOD_GET = "get" -METHOD_POST = "post" -METHOD_DELETE = "delete" - _LOGGER = logging.getLogger(__name__) +METHOD_GET = 'get' +METHOD_POST = 'post' +METHOD_DELETE = 'delete' + class APIStatus(enum.Enum): - """Represent API status.""" + """Representation of an API status.""" # pylint: disable=no-init, invalid-name OK = "ok" @@ -51,7 +51,7 @@ class API(object): def __init__(self, host: str, api_password: Optional[str]=None, port: Optional[int]=SERVER_PORT, use_ssl: bool=False) -> None: - """Initalize the API.""" + """Init the API.""" self.host = host self.port = port self.api_password = api_password diff --git a/homeassistant/setup.py b/homeassistant/setup.py index f10e3f21124..96d27e3494b 100644 --- a/homeassistant/setup.py +++ b/homeassistant/setup.py @@ -1,4 +1,4 @@ -"""Provides methods to bootstrap a home assistant instance.""" +"""All methods needed to bootstrap a Home Assistant instance.""" import asyncio import logging import logging.handlers @@ -28,7 +28,7 @@ SLOW_SETUP_WARNING = 10 def setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict]=None) -> bool: - """Setup a component and all its dependencies.""" + """Set up a component and all its dependencies.""" return run_coroutine_threadsafe( async_setup_component(hass, domain, config), loop=hass.loop).result() @@ -36,7 +36,7 @@ def setup_component(hass: core.HomeAssistant, domain: str, @asyncio.coroutine def async_setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict]=None) -> bool: - """Setup a component and all its dependencies. + """Set up a component and all its dependencies. This method is a coroutine. """ @@ -78,15 +78,15 @@ def _async_process_requirements(hass: core.HomeAssistant, name: str, """Install packages.""" return pkg_util.install_package( mod, target=hass.config.path('deps'), - constraints=os.path.join(os.path.dirname(__file__), - CONSTRAINT_FILE)) + constraints=os.path.join( + os.path.dirname(__file__), CONSTRAINT_FILE)) with (yield from pip_lock): for req in requirements: ret = yield from hass.loop.run_in_executor(None, pip_install, req) if not ret: - _LOGGER.error('Not initializing %s because could not install ' - 'dependency %s', name, req) + _LOGGER.error("Not initializing %s because could not install " + "dependency %s", name, req) async_notify_setup_error(hass, name) return False @@ -100,8 +100,8 @@ def _async_process_dependencies(hass, config, name, dependencies): if dep in loader.DEPENDENCY_BLACKLIST] if blacklisted: - _LOGGER.error('Unable to setup dependencies of %s: ' - 'found blacklisted dependencies: %s', + _LOGGER.error("Unable to setup dependencies of %s: " + "found blacklisted dependencies: %s", name, ', '.join(blacklisted)) return False @@ -117,8 +117,8 @@ def _async_process_dependencies(hass, config, name, dependencies): in enumerate(results) if not res] if failed: - _LOGGER.error('Unable to setup dependencies of %s. ' - 'Setup failed for dependencies: %s', + _LOGGER.error("Unable to setup dependencies of %s. " + "Setup failed for dependencies: %s", name, ', '.join(failed)) return False @@ -128,23 +128,19 @@ def _async_process_dependencies(hass, config, name, dependencies): @asyncio.coroutine def _async_setup_component(hass: core.HomeAssistant, domain: str, config) -> bool: - """Setup a component for Home Assistant. + """Set up a component for Home Assistant. This method is a coroutine. - - hass: Home Assistant instance. - domain: Domain of component to setup. - config: The Home Assistant configuration. """ def log_error(msg, link=True): """Log helper.""" - _LOGGER.error('Setup failed for %s: %s', domain, msg) + _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) component = loader.get_component(domain) if not component: - log_error('Component not found.', False) + log_error("Component not found.", False) return False # Validate no circular dependencies @@ -152,21 +148,21 @@ def _async_setup_component(hass: core.HomeAssistant, # OrderedSet is empty if component or dependencies could not be resolved if not components: - log_error('Unable to resolve component or dependencies.') + log_error("Unable to resolve component or dependencies.") return False processed_config = \ conf_util.async_process_component_config(hass, config, domain) if processed_config is None: - log_error('Invalid config.') + log_error("Invalid config.") return False if not hass.config.skip_pip and hasattr(component, 'REQUIREMENTS'): req_success = yield from _async_process_requirements( hass, domain, component.REQUIREMENTS) if not req_success: - log_error('Could not install all requirements.') + log_error("Could not install all requirements.") return False if hasattr(component, 'DEPENDENCIES'): @@ -174,7 +170,7 @@ def _async_setup_component(hass: core.HomeAssistant, hass, config, domain, component.DEPENDENCIES) if not dep_success: - log_error('Could not setup all dependencies.') + log_error("Could not setup all dependencies.") return False async_comp = hasattr(component, 'async_setup') @@ -182,7 +178,7 @@ def _async_setup_component(hass: core.HomeAssistant, _LOGGER.info("Setting up %s", domain) warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, - 'Setup of %s is taking over %s seconds.', domain, SLOW_SETUP_WARNING) + "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING) try: if async_comp: @@ -191,24 +187,24 @@ def _async_setup_component(hass: core.HomeAssistant, result = yield from hass.loop.run_in_executor( None, component.setup, hass, processed_config) except Exception: # pylint: disable=broad-except - _LOGGER.exception('Error during setup of component %s', domain) + _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, True) return False finally: warn_task.cancel() if result is False: - log_error('Component failed to initialize.') + log_error("Component failed to initialize.") return False elif result is not True: - log_error('Component did not return boolean if setup was successful. ' - 'Disabling component.') + log_error("Component did not return boolean if setup was successful. " + "Disabling component.") loader.set_component(domain, None) return False hass.config.components.add(component.DOMAIN) - # cleanup + # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) @@ -231,7 +227,7 @@ def async_prepare_setup_platform(hass: core.HomeAssistant, config, domain: str, def log_error(msg): """Log helper.""" - _LOGGER.error('Unable to prepare setup for platform %s: %s', + _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) @@ -239,7 +235,7 @@ def async_prepare_setup_platform(hass: core.HomeAssistant, config, domain: str, # Not found if platform is None: - log_error('Platform not found.') + log_error("Platform not found.") return None # Already loaded @@ -252,7 +248,7 @@ def async_prepare_setup_platform(hass: core.HomeAssistant, config, domain: str, hass, config, platform_path, platform.DEPENDENCIES) if not dep_success: - log_error('Could not setup all dependencies.') + log_error("Could not setup all dependencies.") return None if not hass.config.skip_pip and hasattr(platform, 'REQUIREMENTS'): @@ -260,7 +256,7 @@ def async_prepare_setup_platform(hass: core.HomeAssistant, config, domain: str, hass, platform_path, platform.REQUIREMENTS) if not req_success: - log_error('Could not install all requirements.') + log_error("Could not install all requirements.") return None return platform diff --git a/homeassistant/util/temperature.py b/homeassistant/util/temperature.py index c773e564011..adaa8afcb57 100644 --- a/homeassistant/util/temperature.py +++ b/homeassistant/util/temperature.py @@ -1,30 +1,26 @@ """Temperature util functions.""" from homeassistant.const import ( - TEMP_CELSIUS, - TEMP_FAHRENHEIT, - UNIT_NOT_RECOGNIZED_TEMPLATE, - TEMPERATURE -) + TEMP_CELSIUS, TEMP_FAHRENHEIT, UNIT_NOT_RECOGNIZED_TEMPLATE, TEMPERATURE) def fahrenheit_to_celsius(fahrenheit: float) -> float: - """Convert a Fahrenheit temperature to Celsius.""" + """Convert a temperature in Fahrenheit to Celsius.""" return (fahrenheit - 32.0) / 1.8 def celsius_to_fahrenheit(celsius: float) -> float: - """Convert a Celsius temperature to Fahrenheit.""" + """Convert a temperature in Celsius to Fahrenheit.""" return celsius * 1.8 + 32.0 def convert(temperature: float, from_unit: str, to_unit: str) -> float: """Convert a temperature from one unit to another.""" if from_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT): - raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit, - TEMPERATURE)) + raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format( + from_unit, TEMPERATURE)) if to_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT): - raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit, - TEMPERATURE)) + raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format( + to_unit, TEMPERATURE)) if from_unit == to_unit: return temperature diff --git a/homeassistant/util/yaml.py b/homeassistant/util/yaml.py index 15366f1b670..19e614da1f8 100644 --- a/homeassistant/util/yaml.py +++ b/homeassistant/util/yaml.py @@ -65,12 +65,12 @@ def load_yaml(fname: str) -> Union[List, Dict]: _LOGGER.error(exc) raise HomeAssistantError(exc) except UnicodeDecodeError as exc: - _LOGGER.error('Unable to read file %s: %s', fname, exc) + _LOGGER.error("Unable to read file %s: %s", fname, exc) raise HomeAssistantError(exc) def dump(_dict: dict) -> str: - """Dump yaml to a string and remove null.""" + """Dump YAML to a string and remove null.""" return yaml.safe_dump(_dict, default_flow_style=False) \ .replace(': null\n', ':\n') @@ -237,8 +237,8 @@ def _secret_yaml(loader: SafeLineLoader, secrets = _load_secret_yaml(secret_path) if node.value in secrets: - _LOGGER.debug('Secret %s retrieved from secrets.yaml in ' - 'folder %s', node.value, secret_path) + _LOGGER.debug("Secret %s retrieved from secrets.yaml in " + "folder %s", node.value, secret_path) return secrets[node.value] if secret_path == os.path.dirname(sys.path[0]): @@ -252,10 +252,10 @@ def _secret_yaml(loader: SafeLineLoader, # do some keyring stuff pwd = keyring.get_password(_SECRET_NAMESPACE, node.value) if pwd: - _LOGGER.debug('Secret %s retrieved from keyring.', node.value) + _LOGGER.debug("Secret %s retrieved from keyring", node.value) return pwd - _LOGGER.error('Secret %s not defined.', node.value) + _LOGGER.error("Secret %s not defined", node.value) raise HomeAssistantError(node.value) diff --git a/tests/components/device_tracker/test_ddwrt.py b/tests/components/device_tracker/test_ddwrt.py index 4d4f22f2181..d55bc4e2ae1 100644 --- a/tests/components/device_tracker/test_ddwrt.py +++ b/tests/components/device_tracker/test_ddwrt.py @@ -87,7 +87,7 @@ class TestDdwrt(unittest.TestCase): }}) self.assertTrue( - 'Invalid response from ddwrt' in + 'Invalid response from DD-WRT' in str(mock_error.call_args_list[-1])) @mock.patch('homeassistant.components.device_tracker._LOGGER.error') diff --git a/tests/components/test_splunk.py b/tests/components/test_splunk.py index 661f53b533a..4d5d4cc5d45 100644 --- a/tests/components/test_splunk.py +++ b/tests/components/test_splunk.py @@ -106,7 +106,8 @@ class TestSplunk(unittest.TestCase): self.mock_post.call_args, mock.call( payload['host'], data=payload, - headers={'Authorization': 'Splunk secret'} + headers={'Authorization': 'Splunk secret'}, + timeout=10 ) ) self.mock_post.reset_mock()