diff --git a/homeassistant/components/ads/__init__.py b/homeassistant/components/ads/__init__.py index 20a4489da90e..d603843f51f3 100644 --- a/homeassistant/components/ads/__init__.py +++ b/homeassistant/components/ads/__init__.py @@ -1,9 +1,8 @@ """ -ADS Component. +Support for Automation Device Specification (ADS). For more details about this component, please refer to the documentation. https://home-assistant.io/components/ads/ - """ import threading import struct @@ -29,7 +28,6 @@ ADSTYPE_BOOL = 'bool' DOMAIN = 'ads' -# config variable names CONF_ADS_VAR = 'adsvar' CONF_ADS_VAR_BRIGHTNESS = 'adsvar_brightness' CONF_ADS_TYPE = 'adstype' @@ -47,10 +45,10 @@ CONFIG_SCHEMA = vol.Schema({ }, extra=vol.ALLOW_EXTRA) SCHEMA_SERVICE_WRITE_DATA_BY_NAME = vol.Schema({ + vol.Required(CONF_ADS_TYPE): + vol.In([ADSTYPE_INT, ADSTYPE_UINT, ADSTYPE_BYTE]), + vol.Required(CONF_ADS_VALUE): cv.match_all, vol.Required(CONF_ADS_VAR): cv.string, - vol.Required(CONF_ADS_TYPE): vol.In([ADSTYPE_INT, ADSTYPE_UINT, - ADSTYPE_BYTE]), - vol.Required(CONF_ADS_VALUE): cv.match_all }) @@ -59,15 +57,12 @@ def setup(hass, config): import pyads conf = config[DOMAIN] - # get ads connection parameters from config net_id = conf.get(CONF_DEVICE) ip_address = conf.get(CONF_IP_ADDRESS) port = conf.get(CONF_PORT) - # create a new ads connection client = pyads.Connection(net_id, port, ip_address) - # add some constants to AdsHub AdsHub.ADS_TYPEMAP = { ADSTYPE_BOOL: pyads.PLCTYPE_BOOL, ADSTYPE_BYTE: pyads.PLCTYPE_BYTE, @@ -81,16 +76,13 @@ def setup(hass, config): AdsHub.PLCTYPE_UINT = pyads.PLCTYPE_UINT AdsHub.ADSError = pyads.ADSError - # connect to ads client and try to connect try: ads = AdsHub(client) except pyads.pyads.ADSError: _LOGGER.error( - 'Could not connect to ADS host (netid=%s, port=%s)', net_id, port - ) + "Could not connect to ADS host (netid=%s, port=%s)", net_id, port) return False - # add ads hub to hass data collection, listen to shutdown hass.data[DATA_ADS] = ads hass.bus.listen(EVENT_HOMEASSISTANT_STOP, ads.shutdown) @@ -107,43 +99,41 @@ def setup(hass, config): hass.services.register( DOMAIN, SERVICE_WRITE_DATA_BY_NAME, handle_write_data_by_name, - schema=SCHEMA_SERVICE_WRITE_DATA_BY_NAME - ) + schema=SCHEMA_SERVICE_WRITE_DATA_BY_NAME) return True -# tuple to hold data needed for notification +# Tuple to hold data needed for notification NotificationItem = namedtuple( 'NotificationItem', 'hnotify huser name plc_datatype callback' ) -class AdsHub: - """Representation of a PyADS connection.""" +class AdsHub(object): + """Representation of an ADS connection.""" def __init__(self, ads_client): - """Initialize the ADS Hub.""" + """Initialize the ADS hub.""" self._client = ads_client self._client.open() - # all ADS devices are registered here + # All ADS devices are registered here self._devices = [] self._notification_items = {} self._lock = threading.Lock() def shutdown(self, *args, **kwargs): """Shutdown ADS connection.""" - _LOGGER.debug('Shutting down ADS') + _LOGGER.debug("Shutting down ADS") for notification_item in self._notification_items.values(): self._client.del_device_notification( notification_item.hnotify, notification_item.huser ) _LOGGER.debug( - 'Deleting device notification %d, %d', - notification_item.hnotify, notification_item.huser - ) + "Deleting device notification %d, %d", + notification_item.hnotify, notification_item.huser) self._client.close() def register_device(self, device): @@ -167,33 +157,30 @@ class AdsHub: with self._lock: hnotify, huser = self._client.add_device_notification( - name, attr, self._device_notification_callback - ) + name, attr, self._device_notification_callback) hnotify = int(hnotify) _LOGGER.debug( - 'Added Device Notification %d for variable %s', hnotify, name - ) + "Added device notification %d for variable %s", hnotify, name) self._notification_items[hnotify] = NotificationItem( - hnotify, huser, name, plc_datatype, callback - ) + hnotify, huser, name, plc_datatype, callback) def _device_notification_callback(self, addr, notification, huser): """Handle device notifications.""" contents = notification.contents hnotify = int(contents.hNotification) - _LOGGER.debug('Received Notification %d', hnotify) + _LOGGER.debug("Received notification %d", hnotify) data = contents.data try: notification_item = self._notification_items[hnotify] except KeyError: - _LOGGER.debug('Unknown Device Notification handle: %d', hnotify) + _LOGGER.debug("Unknown device notification handle: %d", hnotify) return - # parse data to desired datatype + # Parse data to desired datatype if notification_item.plc_datatype == self.PLCTYPE_BOOL: value = bool(struct.unpack(' dt_util.utcnow() @property def code_format(self): - """One or more characters.""" + """Return one or more characters.""" return None if self._code is None else '.+' def alarm_disarm(self, code=None): @@ -250,6 +255,7 @@ class ManualAlarm(alarm.AlarmControlPanel): self._update_state(STATE_ALARM_TRIGGERED) def _update_state(self, state): + """Update the state.""" if self._state == state: return diff --git a/homeassistant/components/alarm_control_panel/manual_mqtt.py b/homeassistant/components/alarm_control_panel/manual_mqtt.py index 9e388806e734..ef12cbe365fe 100644 --- a/homeassistant/components/alarm_control_panel/manual_mqtt.py +++ b/homeassistant/components/alarm_control_panel/manual_mqtt.py @@ -26,6 +26,8 @@ from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_point_in_time +_LOGGER = logging.getLogger(__name__) + CONF_CODE_TEMPLATE = 'code_template' CONF_PAYLOAD_DISARM = 'payload_disarm' @@ -58,6 +60,7 @@ ATTR_POST_PENDING_STATE = 'post_pending_state' def _state_validator(config): + """Validate the state.""" config = copy.deepcopy(config) for state in SUPPORTED_PRETRIGGER_STATES: if CONF_DELAY_TIME not in config[state]: @@ -72,6 +75,7 @@ def _state_validator(config): def _state_schema(state): + """Validate the state.""" schema = {} if state in SUPPORTED_PRETRIGGER_STATES: schema[vol.Optional(CONF_DELAY_TIME)] = vol.All( @@ -117,8 +121,6 @@ PLATFORM_SCHEMA = vol.Schema(vol.All(mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend({ vol.Optional(CONF_PAYLOAD_DISARM, default=DEFAULT_DISARM): cv.string, }), _state_validator)) -_LOGGER = logging.getLogger(__name__) - def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the manual MQTT alarm platform.""" @@ -150,11 +152,10 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel): A trigger_time of zero disables the alarm_trigger service. """ - def __init__(self, hass, name, code, code_template, - disarm_after_trigger, - state_topic, command_topic, qos, - payload_disarm, payload_arm_home, payload_arm_away, - payload_arm_night, config): + def __init__(self, hass, name, code, code_template, disarm_after_trigger, + state_topic, command_topic, qos, payload_disarm, + payload_arm_home, payload_arm_away, payload_arm_night, + config): """Init the manual MQTT alarm panel.""" self._state = STATE_ALARM_DISARMED self._hass = hass @@ -219,23 +220,26 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel): @property def _active_state(self): + """Get the current state.""" if self.state == STATE_ALARM_PENDING: return self._previous_state else: return self._state def _pending_time(self, state): + """Get the pending time.""" pending_time = self._pending_time_by_state[state] if state == STATE_ALARM_TRIGGERED: pending_time += self._delay_time_by_state[self._previous_state] return pending_time def _within_pending_time(self, state): + """Get if the action is in the pending time window.""" return self._state_ts + self._pending_time(state) > dt_util.utcnow() @property def code_format(self): - """One or more characters.""" + """Return one or more characters.""" return None if self._code is None else '.+' def alarm_disarm(self, code=None): @@ -280,6 +284,7 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel): self._update_state(STATE_ALARM_TRIGGERED) def _update_state(self, state): + """Update the state.""" if self._state == state: return @@ -329,7 +334,7 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel): return state_attr def async_added_to_hass(self): - """Subscribe mqtt events. + """Subscribe to MQTT events. This method must be run in the event loop and returns a coroutine. """ @@ -358,5 +363,5 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel): @asyncio.coroutine def _async_state_changed_listener(self, entity_id, old_state, new_state): """Publish state change to MQTT.""" - mqtt.async_publish(self.hass, self._state_topic, new_state.state, - self._qos, True) + mqtt.async_publish( + self.hass, self._state_topic, new_state.state, self._qos, True) diff --git a/homeassistant/components/alarm_control_panel/nx584.py b/homeassistant/components/alarm_control_panel/nx584.py index 81a8b02cc64b..ceb79c1dc7b4 100644 --- a/homeassistant/components/alarm_control_panel/nx584.py +++ b/homeassistant/components/alarm_control_panel/nx584.py @@ -12,8 +12,8 @@ import voluptuous as vol import homeassistant.components.alarm_control_panel as alarm from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA from homeassistant.const import ( - STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, - STATE_UNKNOWN, CONF_NAME, CONF_HOST, CONF_PORT) + CONF_HOST, CONF_NAME, CONF_PORT, STATE_ALARM_ARMED_AWAY, + STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pynx584==0.4'] @@ -25,14 +25,14 @@ DEFAULT_NAME = 'NX584' DEFAULT_PORT = 5007 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the nx584 platform.""" + """Set up the NX584 platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) @@ -88,7 +88,7 @@ class NX584Alarm(alarm.AlarmControlPanel): self._state = STATE_UNKNOWN zones = [] except IndexError: - _LOGGER.error("nx584 reports no partitions") + _LOGGER.error("NX584 reports no partitions") self._state = STATE_UNKNOWN zones = [] diff --git a/homeassistant/components/alarm_control_panel/satel_integra.py b/homeassistant/components/alarm_control_panel/satel_integra.py index 6115311f8732..964047f91e96 100644 --- a/homeassistant/components/alarm_control_panel/satel_integra.py +++ b/homeassistant/components/alarm_control_panel/satel_integra.py @@ -8,9 +8,8 @@ import asyncio import logging import homeassistant.components.alarm_control_panel as alarm -from homeassistant.components.satel_integra import (CONF_ARM_HOME_MODE, - DATA_SATEL, - SIGNAL_PANEL_MESSAGE) +from homeassistant.components.satel_integra import ( + CONF_ARM_HOME_MODE, DATA_SATEL, SIGNAL_PANEL_MESSAGE) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -21,12 +20,12 @@ DEPENDENCIES = ['satel_integra'] @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Set up for AlarmDecoder alarm panels.""" + """Set up for Satel Integra alarm panels.""" if not discovery_info: return - device = SatelIntegraAlarmPanel("Alarm Panel", - discovery_info.get(CONF_ARM_HOME_MODE)) + device = SatelIntegraAlarmPanel( + "Alarm Panel", discovery_info.get(CONF_ARM_HOME_MODE)) async_add_devices([device]) @@ -47,7 +46,7 @@ class SatelIntegraAlarmPanel(alarm.AlarmControlPanel): @callback def _message_callback(self, message): - + """Handle received messages.""" if message != self._state: self._state = message self.async_schedule_update_ha_state() @@ -90,5 +89,5 @@ class SatelIntegraAlarmPanel(alarm.AlarmControlPanel): def async_alarm_arm_home(self, code=None): """Send arm home command.""" if code: - yield from self.hass.data[DATA_SATEL].arm(code, - self._arm_home_mode) + yield from self.hass.data[DATA_SATEL].arm( + code, self._arm_home_mode) diff --git a/homeassistant/components/alarm_control_panel/simplisafe.py b/homeassistant/components/alarm_control_panel/simplisafe.py index 7f4e4dfa756a..3b991c5b236b 100644 --- a/homeassistant/components/alarm_control_panel/simplisafe.py +++ b/homeassistant/components/alarm_control_panel/simplisafe.py @@ -11,9 +11,9 @@ import voluptuous as vol 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_UNKNOWN, CONF_CODE, CONF_NAME, - STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, - EVENT_HOMEASSISTANT_STOP) + CONF_CODE, CONF_NAME, CONF_PASSWORD, CONF_USERNAME, + EVENT_HOMEASSISTANT_STOP, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, + STATE_ALARM_DISARMED, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['simplisafe-python==1.0.5'] @@ -22,6 +22,7 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'SimpliSafe' DOMAIN = 'simplisafe' + NOTIFICATION_ID = 'simplisafe_notification' NOTIFICATION_TITLE = 'SimpliSafe Setup' @@ -65,7 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class SimpliSafeAlarm(alarm.AlarmControlPanel): - """Representation a SimpliSafe alarm.""" + """Representation of a SimpliSafe alarm.""" def __init__(self, simplisafe, name, code): """Initialize the SimpliSafe alarm.""" @@ -82,7 +83,7 @@ class SimpliSafeAlarm(alarm.AlarmControlPanel): @property def code_format(self): - """One or more characters if code is defined.""" + """Return one or more characters if code is defined.""" return None if self._code is None else '.+' @property @@ -103,12 +104,12 @@ class SimpliSafeAlarm(alarm.AlarmControlPanel): def device_state_attributes(self): """Return the state attributes.""" return { - 'temperature': self.simplisafe.temperature(), + 'alarm': self.simplisafe.alarm(), 'co': self.simplisafe.carbon_monoxide(), 'fire': self.simplisafe.fire(), - 'alarm': self.simplisafe.alarm(), + 'flood': self.simplisafe.flood(), 'last_event': self.simplisafe.last_event(), - 'flood': self.simplisafe.flood() + 'temperature': self.simplisafe.temperature(), } def update(self): diff --git a/homeassistant/components/alarm_control_panel/spc.py b/homeassistant/components/alarm_control_panel/spc.py index 4d9c72df2f1b..5d5b2284bab6 100644 --- a/homeassistant/components/alarm_control_panel/spc.py +++ b/homeassistant/components/alarm_control_panel/spc.py @@ -9,26 +9,27 @@ import logging import homeassistant.components.alarm_control_panel as alarm from homeassistant.components.spc import ( - SpcWebGateway, ATTR_DISCOVER_AREAS, DATA_API, DATA_REGISTRY) + ATTR_DISCOVER_AREAS, DATA_API, DATA_REGISTRY, SpcWebGateway) from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_UNKNOWN) - _LOGGER = logging.getLogger(__name__) -SPC_AREA_MODE_TO_STATE = {'0': STATE_ALARM_DISARMED, - '1': STATE_ALARM_ARMED_HOME, - '3': STATE_ALARM_ARMED_AWAY} +SPC_AREA_MODE_TO_STATE = { + '0': STATE_ALARM_DISARMED, + '1': STATE_ALARM_ARMED_HOME, + '3': STATE_ALARM_ARMED_AWAY, +} def _get_alarm_state(spc_mode): + """Get the alarm state.""" return SPC_AREA_MODE_TO_STATE.get(spc_mode, STATE_UNKNOWN) @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the SPC alarm control panel platform.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_AREAS] is None): @@ -42,7 +43,7 @@ def async_setup_platform(hass, config, async_add_devices, class SpcAlarm(alarm.AlarmControlPanel): - """Represents the SPC alarm panel.""" + """Representation of the SPC alarm panel.""" def __init__(self, api, area): """Initialize the SPC alarm panel.""" @@ -57,7 +58,7 @@ class SpcAlarm(alarm.AlarmControlPanel): @asyncio.coroutine def async_added_to_hass(self): - """Calbback for init handlers.""" + """Call for adding new entities.""" self.hass.data[DATA_REGISTRY].register_alarm_device( self._area_id, self) diff --git a/homeassistant/components/alarm_control_panel/verisure.py b/homeassistant/components/alarm_control_panel/verisure.py index 66764f58c269..74d63b1fb9c0 100644 --- a/homeassistant/components/alarm_control_panel/verisure.py +++ b/homeassistant/components/alarm_control_panel/verisure.py @@ -8,8 +8,8 @@ import logging from time import sleep import homeassistant.components.alarm_control_panel as alarm +from homeassistant.components.verisure import CONF_ALARM, CONF_CODE_DIGITS from homeassistant.components.verisure import HUB as hub -from homeassistant.components.verisure import (CONF_ALARM, CONF_CODE_DIGITS) from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_UNKNOWN) @@ -43,7 +43,7 @@ class VerisureAlarm(alarm.AlarmControlPanel): """Representation of a Verisure alarm status.""" def __init__(self): - """Initalize the Verisure alarm panel.""" + """Initialize the Verisure alarm panel.""" self._state = STATE_UNKNOWN self._digits = hub.config.get(CONF_CODE_DIGITS) self._changed_by = None diff --git a/homeassistant/components/alarm_control_panel/wink.py b/homeassistant/components/alarm_control_panel/wink.py index 8bc2539f7725..771d157efe0e 100644 --- a/homeassistant/components/alarm_control_panel/wink.py +++ b/homeassistant/components/alarm_control_panel/wink.py @@ -8,11 +8,10 @@ import asyncio import logging import homeassistant.components.alarm_control_panel as alarm -from homeassistant.const import (STATE_UNKNOWN, - STATE_ALARM_DISARMED, - STATE_ALARM_ARMED_HOME, - STATE_ALARM_ARMED_AWAY) -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice +from homeassistant.const import ( + STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, + STATE_UNKNOWN) _LOGGER = logging.getLogger(__name__) @@ -41,7 +40,7 @@ class WinkCameraDevice(WinkDevice, alarm.AlarmControlPanel): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['alarm_control_panel'].append(self) @property diff --git a/homeassistant/components/alexa/__init__.py b/homeassistant/components/alexa/__init__.py index 65243aa83ceb..a5ed4b59628e 100644 --- a/homeassistant/components/alexa/__init__.py +++ b/homeassistant/components/alexa/__init__.py @@ -11,17 +11,15 @@ import voluptuous as vol from homeassistant.helpers import config_validation as cv -from .const import ( - DOMAIN, CONF_UID, CONF_TITLE, CONF_AUDIO, CONF_TEXT, CONF_DISPLAY_URL) from . import flash_briefings, intent +from .const import ( + CONF_AUDIO, CONF_DISPLAY_URL, CONF_TEXT, CONF_TITLE, CONF_UID, DOMAIN) _LOGGER = logging.getLogger(__name__) - -DEPENDENCIES = ['http'] - CONF_FLASH_BRIEFINGS = 'flash_briefings' +DEPENDENCIES = ['http'] CONFIG_SCHEMA = vol.Schema({ DOMAIN: { diff --git a/homeassistant/components/alexa/flash_briefings.py b/homeassistant/components/alexa/flash_briefings.py index ec7e3521c0a4..02f47b056179 100644 --- a/homeassistant/components/alexa/flash_briefings.py +++ b/homeassistant/components/alexa/flash_briefings.py @@ -5,19 +5,18 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/alexa/ """ import copy -import logging from datetime import datetime +import logging import uuid +from homeassistant.components import http from homeassistant.core import callback from homeassistant.helpers import template -from homeassistant.components import http from .const import ( - CONF_UID, CONF_TITLE, CONF_AUDIO, CONF_TEXT, CONF_DISPLAY_URL, ATTR_UID, - ATTR_UPDATE_DATE, ATTR_TITLE_TEXT, ATTR_STREAM_URL, ATTR_MAIN_TEXT, - ATTR_REDIRECTION_URL, DATE_FORMAT) - + ATTR_MAIN_TEXT, ATTR_REDIRECTION_URL, ATTR_STREAM_URL, ATTR_TITLE_TEXT, + ATTR_UID, ATTR_UPDATE_DATE, CONF_AUDIO, CONF_DISPLAY_URL, CONF_TEXT, + CONF_TITLE, CONF_UID, DATE_FORMAT) _LOGGER = logging.getLogger(__name__) @@ -46,11 +45,11 @@ class AlexaFlashBriefingView(http.HomeAssistantView): @callback def get(self, request, briefing_id): """Handle Alexa Flash Briefing request.""" - _LOGGER.debug('Received Alexa flash briefing request for: %s', + _LOGGER.debug("Received Alexa flash briefing request for: %s", briefing_id) if self.flash_briefings.get(briefing_id) is None: - err = 'No configured Alexa flash briefing was found for: %s' + err = "No configured Alexa flash briefing was found for: %s" _LOGGER.error(err, briefing_id) return b'', 404 diff --git a/homeassistant/components/alexa/intent.py b/homeassistant/components/alexa/intent.py index 8283b563591b..b6d406bd550f 100644 --- a/homeassistant/components/alexa/intent.py +++ b/homeassistant/components/alexa/intent.py @@ -3,30 +3,31 @@ Support for Alexa skill service end point. For more details about this component, please refer to the documentation at https://home-assistant.io/components/alexa/ - """ import asyncio import enum import logging -from homeassistant.exceptions import HomeAssistantError -from homeassistant.core import callback -from homeassistant.helpers import intent from homeassistant.components import http +from homeassistant.core import callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import intent from homeassistant.util.decorator import Registry from .const import DOMAIN, SYN_RESOLUTION_MATCH -INTENTS_API_ENDPOINT = '/api/alexa' -HANDLERS = Registry() _LOGGER = logging.getLogger(__name__) +HANDLERS = Registry() + +INTENTS_API_ENDPOINT = '/api/alexa' + class SpeechType(enum.Enum): """The Alexa speech types.""" - plaintext = "PlainText" - ssml = "SSML" + plaintext = 'PlainText' + ssml = 'SSML' SPEECH_MAPPINGS = { @@ -38,8 +39,8 @@ SPEECH_MAPPINGS = { class CardType(enum.Enum): """The Alexa card types.""" - simple = "Simple" - link_account = "LinkAccount" + simple = 'Simple' + link_account = 'LinkAccount' @callback @@ -64,7 +65,7 @@ class AlexaIntentsView(http.HomeAssistantView): hass = request.app['hass'] message = yield from request.json() - _LOGGER.debug('Received Alexa request: %s', message) + _LOGGER.debug("Received Alexa request: %s", message) try: response = yield from async_handle_message(hass, message) @@ -81,7 +82,7 @@ class AlexaIntentsView(http.HomeAssistantView): "This intent is not yet configured within Home Assistant.")) except intent.InvalidSlotInfo as err: - _LOGGER.error('Received invalid slot data from Alexa: %s', err) + _LOGGER.error("Received invalid slot data from Alexa: %s", err) return self.json(intent_error_response( hass, message, "Invalid slot information received for this intent.")) @@ -109,6 +110,7 @@ def async_handle_message(hass, message): - intent.UnknownIntent - intent.InvalidSlotInfo - intent.IntentError + """ req = message.get('request') req_type = req['type'] @@ -138,6 +140,7 @@ def async_handle_intent(hass, message): - intent.UnknownIntent - intent.InvalidSlotInfo - intent.IntentError + """ req = message.get('request') alexa_intent_info = req.get('intent') diff --git a/homeassistant/components/alexa/smart_home.py b/homeassistant/components/alexa/smart_home.py index 3c14826037ca..b5115025c080 100644 --- a/homeassistant/components/alexa/smart_home.py +++ b/homeassistant/components/alexa/smart_home.py @@ -4,20 +4,19 @@ import logging import math from uuid import uuid4 -import homeassistant.core as ha +from homeassistant.components import ( + alert, automation, cover, fan, group, input_boolean, light, lock, + media_player, scene, script, switch) from homeassistant.const import ( - ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, SERVICE_LOCK, + ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, CONF_NAME, SERVICE_LOCK, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_STOP, SERVICE_SET_COVER_POSITION, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_UNLOCK, SERVICE_VOLUME_SET) -from homeassistant.components import ( - alert, automation, cover, fan, group, input_boolean, light, lock, - media_player, scene, script, switch) +import homeassistant.core as ha import homeassistant.util.color as color_util from homeassistant.util.decorator import Registry -HANDLERS = Registry() _LOGGER = logging.getLogger(__name__) API_DIRECTIVE = 'directive' @@ -28,8 +27,8 @@ API_PAYLOAD = 'payload' CONF_DESCRIPTION = 'description' CONF_DISPLAY_CATEGORIES = 'display_categories' -CONF_NAME = 'name' +HANDLERS = Registry() MAPPING_COMPONENT = { alert.DOMAIN: ['OTHER', ('Alexa.PowerController',), None], @@ -174,8 +173,8 @@ def async_api_discovery(hass, config, request): scene_fmt = '{} (Scene connected via Home Assistant)' description = scene_fmt.format(description) - display_categories = entity_conf.get(CONF_DISPLAY_CATEGORIES, - class_data[0]) + display_categories = entity_conf.get( + CONF_DISPLAY_CATEGORIES, class_data[0]) endpoint = { 'displayCategories': [display_categories], @@ -216,7 +215,7 @@ def async_api_discovery(hass, config, request): def extract_entity(funct): - """Decorator for extract entity object from request.""" + """Decorate for extract entity object from request.""" @asyncio.coroutine def async_api_entity_wrapper(hass, config, request): """Process a turn on request.""" diff --git a/homeassistant/components/apple_tv.py b/homeassistant/components/apple_tv.py index beacb3840ef0..230b0ea8a1b4 100644 --- a/homeassistant/components/apple_tv.py +++ b/homeassistant/components/apple_tv.py @@ -7,13 +7,14 @@ https://home-assistant.io/components/apple_tv/ import asyncio import logging +from typing import Sequence, TypeVar, Union + import voluptuous as vol -from typing import Union, TypeVar, Sequence -from homeassistant.const import (CONF_HOST, CONF_NAME, ATTR_ENTITY_ID) -from homeassistant.helpers.aiohttp_client import async_get_clientsession -from homeassistant.helpers import discovery from homeassistant.components.discovery import SERVICE_APPLE_TV +from homeassistant.const import ATTR_ENTITY_ID, CONF_HOST, CONF_NAME +from homeassistant.helpers import discovery +from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pyatv==0.3.9'] @@ -59,9 +60,9 @@ CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.All(ensure_list, [vol.Schema({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_LOGIN_ID): cv.string, - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_CREDENTIALS, default=None): cv.string, - vol.Optional(CONF_START_OFF, default=False): cv.boolean + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_START_OFF, default=False): cv.boolean, })]) }, extra=vol.ALLOW_EXTRA) @@ -140,7 +141,7 @@ def async_setup(hass, config): @asyncio.coroutine def async_service_handler(service): - """Handler for service calls.""" + """Handle service calls.""" entity_ids = service.data.get(ATTR_ENTITY_ID) if service.service == SERVICE_SCAN: @@ -167,7 +168,7 @@ def async_setup(hass, config): @asyncio.coroutine def atv_discovered(service, info): - """Setup an Apple TV that was auto discovered.""" + """Set up an Apple TV that was auto discovered.""" yield from _setup_atv(hass, { CONF_NAME: info['name'], CONF_HOST: info['host'], @@ -194,7 +195,7 @@ def async_setup(hass, config): @asyncio.coroutine def _setup_atv(hass, atv_config): - """Setup an Apple TV.""" + """Set up an Apple TV.""" import pyatv name = atv_config.get(CONF_NAME) host = atv_config.get(CONF_HOST) @@ -245,7 +246,7 @@ class AppleTVPowerManager: @property def turned_on(self): - """If device is on or off.""" + """Return true if device is on or off.""" return self._is_on def set_power_on(self, value): diff --git a/homeassistant/components/axis.py b/homeassistant/components/axis.py index 16bd544e96ec..fab7d98ed983 100644 --- a/homeassistant/components/axis.py +++ b/homeassistant/components/axis.py @@ -4,24 +4,21 @@ Support for Axis devices. For more details about this component, please refer to the documentation at https://home-assistant.io/components/axis/ """ - import logging import voluptuous as vol from homeassistant.components.discovery import SERVICE_AXIS -from homeassistant.const import (ATTR_LOCATION, ATTR_TRIPPED, - CONF_EVENT, CONF_HOST, CONF_INCLUDE, - CONF_NAME, CONF_PASSWORD, CONF_PORT, - CONF_TRIGGER_TIME, CONF_USERNAME, - EVENT_HOMEASSISTANT_STOP) +from homeassistant.const import ( + ATTR_LOCATION, ATTR_TRIPPED, CONF_EVENT, CONF_HOST, CONF_INCLUDE, + CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_TRIGGER_TIME, CONF_USERNAME, + EVENT_HOMEASSISTANT_STOP) from homeassistant.helpers import config_validation as cv from homeassistant.helpers import discovery from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.entity import Entity from homeassistant.util.json import load_json, save_json - REQUIREMENTS = ['axis==14'] _LOGGER = logging.getLogger(__name__) @@ -81,10 +78,10 @@ def request_configuration(hass, config, name, host, serialnumber): configurator = hass.components.configurator def configuration_callback(callback_data): - """Called when config is submitted.""" + """Call when configuration is submitted.""" if CONF_INCLUDE not in callback_data: - configurator.notify_errors(request_id, - "Functionality mandatory.") + configurator.notify_errors( + request_id, "Functionality mandatory.") return False callback_data[CONF_INCLUDE] = callback_data[CONF_INCLUDE].split() @@ -96,8 +93,8 @@ def request_configuration(hass, config, name, host, serialnumber): try: device_config = DEVICE_SCHEMA(callback_data) except vol.Invalid: - configurator.notify_errors(request_id, - "Bad input, please check spelling.") + configurator.notify_errors( + request_id, "Bad input, please check spelling.") return False if setup_device(hass, config, device_config): @@ -108,8 +105,8 @@ def request_configuration(hass, config, name, host, serialnumber): save_json(hass.config.path(CONFIG_FILE), config_file) configurator.request_done(request_id) else: - configurator.notify_errors(request_id, - "Failed to register, please try again.") + configurator.notify_errors( + request_id, "Failed to register, please try again.") return False title = '{} ({})'.format(name, host) @@ -147,7 +144,7 @@ def request_configuration(hass, config, name, host, serialnumber): def setup(hass, config): - """Common setup for Axis devices.""" + """Set up for Axis devices.""" def _shutdown(call): # pylint: disable=unused-argument """Stop the event stream on shutdown.""" for serialnumber, device in AXIS_DEVICES.items(): @@ -157,7 +154,7 @@ def setup(hass, config): hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown) def axis_device_discovered(service, discovery_info): - """Called when axis devices has been found.""" + """Call when axis devices has been found.""" host = discovery_info[CONF_HOST] name = discovery_info['hostname'] serialnumber = discovery_info['properties']['macaddress'] @@ -173,8 +170,8 @@ def setup(hass, config): _LOGGER.error("Bad data from %s. %s", CONFIG_FILE, err) return False if not setup_device(hass, config, device_config): - _LOGGER.error("Couldn\'t set up %s", - device_config[CONF_NAME]) + _LOGGER.error( + "Couldn't set up %s", device_config[CONF_NAME]) else: # New device, create configuration request for UI request_configuration(hass, config, name, host, serialnumber) @@ -193,7 +190,7 @@ def setup(hass, config): if CONF_NAME not in device_config: device_config[CONF_NAME] = device if not setup_device(hass, config, device_config): - _LOGGER.error("Couldn\'t set up %s", device_config[CONF_NAME]) + _LOGGER.error("Couldn't set up %s", device_config[CONF_NAME]) def vapix_service(call): """Service to send a message.""" @@ -205,23 +202,21 @@ def setup(hass, config): call.data[SERVICE_PARAM]) hass.bus.fire(SERVICE_VAPIX_CALL_RESPONSE, response) return True - _LOGGER.info("Couldn\'t find device %s", call.data[CONF_NAME]) + _LOGGER.info("Couldn't find device %s", call.data[CONF_NAME]) return False # Register service with Home Assistant. - hass.services.register(DOMAIN, - SERVICE_VAPIX_CALL, - vapix_service, - schema=SERVICE_SCHEMA) + hass.services.register( + DOMAIN, SERVICE_VAPIX_CALL, vapix_service, schema=SERVICE_SCHEMA) return True def setup_device(hass, config, device_config): - """Set up device.""" + """Set up an Axis device.""" from axis import AxisDevice def signal_callback(action, event): - """Callback to configure events when initialized on event stream.""" + """Call to configure events when initialized on event stream.""" if action == 'add': event_config = { CONF_EVENT: event, @@ -230,11 +225,8 @@ def setup_device(hass, config, device_config): CONF_TRIGGER_TIME: device_config[CONF_TRIGGER_TIME] } component = event.event_platform - discovery.load_platform(hass, - component, - DOMAIN, - event_config, - config) + discovery.load_platform( + hass, component, DOMAIN, event_config, config) event_types = list(filter(lambda x: x in device_config[CONF_INCLUDE], EVENT_TYPES)) @@ -245,7 +237,7 @@ def setup_device(hass, config, device_config): if device.serial_number is None: # If there is no serial number a connection could not be made - _LOGGER.error("Couldn\'t connect to %s", device_config[CONF_HOST]) + _LOGGER.error("Couldn't connect to %s", device_config[CONF_HOST]) return False for component in device_config[CONF_INCLUDE]: @@ -257,11 +249,8 @@ def setup_device(hass, config, device_config): CONF_USERNAME: device_config[CONF_USERNAME], CONF_PASSWORD: device_config[CONF_PASSWORD] } - discovery.load_platform(hass, - component, - DOMAIN, - camera_config, - config) + discovery.load_platform( + hass, component, DOMAIN, camera_config, config) AXIS_DEVICES[device.serial_number] = device if event_types: @@ -275,9 +264,9 @@ class AxisDeviceEvent(Entity): def __init__(self, event_config): """Initialize the event.""" self.axis_event = event_config[CONF_EVENT] - self._name = '{}_{}_{}'.format(event_config[CONF_NAME], - self.axis_event.event_type, - self.axis_event.id) + self._name = '{}_{}_{}'.format( + event_config[CONF_NAME], self.axis_event.event_type, + self.axis_event.id) self.location = event_config[ATTR_LOCATION] self.axis_event.callback = self._update_callback @@ -298,7 +287,7 @@ class AxisDeviceEvent(Entity): @property def should_poll(self): - """No polling needed.""" + """Return the polling state. No polling needed.""" return False @property diff --git a/homeassistant/components/binary_sensor/ads.py b/homeassistant/components/binary_sensor/ads.py index e6b86ed97e68..b7f0ebcc9d3d 100644 --- a/homeassistant/components/binary_sensor/ads.py +++ b/homeassistant/components/binary_sensor/ads.py @@ -3,23 +3,22 @@ Support for ADS binary sensors. For more details about this platform, please refer to the documentation. https://home-assistant.io/components/binary_sensor.ads/ - """ import asyncio import logging -import voluptuous as vol -from homeassistant.components.binary_sensor import BinarySensorDevice, \ - PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA -from homeassistant.components.ads import DATA_ADS, CONF_ADS_VAR -from homeassistant.const import CONF_NAME, CONF_DEVICE_CLASS -import homeassistant.helpers.config_validation as cv +import voluptuous as vol + +from homeassistant.components.ads import CONF_ADS_VAR, DATA_ADS +from homeassistant.components.binary_sensor import ( + DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, BinarySensorDevice) +from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME +import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) -DEPENDENCIES = ['ads'] DEFAULT_NAME = 'ADS binary sensor' - +DEPENDENCIES = ['ads'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ADS_VAR): cv.string, @@ -44,7 +43,7 @@ class AdsBinarySensor(BinarySensorDevice): """Representation of ADS binary sensors.""" def __init__(self, ads_hub, name, ads_var, device_class): - """Initialize AdsBinarySensor entity.""" + """Initialize ADS binary sensor.""" self._name = name self._state = False self._device_class = device_class or 'moving' @@ -56,15 +55,13 @@ class AdsBinarySensor(BinarySensorDevice): """Register device notification.""" def update(name, value): """Handle device notifications.""" - _LOGGER.debug('Variable %s changed its value to %d', - name, value) + _LOGGER.debug('Variable %s changed its value to %d', name, value) self._state = value self.schedule_update_ha_state() self.hass.async_add_job( self._ads_hub.add_device_notification, - self.ads_var, self._ads_hub.PLCTYPE_BOOL, update - ) + self.ads_var, self._ads_hub.PLCTYPE_BOOL, update) @property def name(self): diff --git a/homeassistant/components/binary_sensor/axis.py b/homeassistant/components/binary_sensor/axis.py index a6e80dbf97f8..84137d95b06b 100644 --- a/homeassistant/components/binary_sensor/axis.py +++ b/homeassistant/components/binary_sensor/axis.py @@ -4,13 +4,12 @@ Support for Axis binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.axis/ """ - -import logging from datetime import timedelta +import logging -from homeassistant.components.binary_sensor import (BinarySensorDevice) -from homeassistant.components.axis import (AxisDeviceEvent) -from homeassistant.const import (CONF_TRIGGER_TIME) +from homeassistant.components.axis import AxisDeviceEvent +from homeassistant.components.binary_sensor import BinarySensorDevice +from homeassistant.const import CONF_TRIGGER_TIME from homeassistant.helpers.event import track_point_in_utc_time from homeassistant.util.dt import utcnow @@ -20,7 +19,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Axis device event.""" + """Set up the Axis binary devices.""" add_devices([AxisBinarySensor(hass, discovery_info)], True) @@ -28,7 +27,7 @@ class AxisBinarySensor(AxisDeviceEvent, BinarySensorDevice): """Representation of a binary Axis event.""" def __init__(self, hass, event_config): - """Initialize the binary sensor.""" + """Initialize the Axis binary sensor.""" self.hass = hass self._state = False self._delay = event_config[CONF_TRIGGER_TIME] @@ -56,7 +55,7 @@ class AxisBinarySensor(AxisDeviceEvent, BinarySensorDevice): # Set timer to wait until updating the state def _delay_update(now): """Timer callback for sensor update.""" - _LOGGER.debug("%s Called delayed (%s sec) update.", + _LOGGER.debug("%s called delayed (%s sec) update", self._name, self._delay) self.schedule_update_ha_state() self._timer = None diff --git a/homeassistant/components/binary_sensor/concord232.py b/homeassistant/components/binary_sensor/concord232.py index c8442491b294..3bac561700ad 100644 --- a/homeassistant/components/binary_sensor/concord232.py +++ b/homeassistant/components/binary_sensor/concord232.py @@ -53,7 +53,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): sensors = [] try: - _LOGGER.debug("Initializing Client") + _LOGGER.debug("Initializing client") client = concord232_client.Client('http://{}:{}'.format(host, port)) client.zones = client.list_zones() client.last_zone_update = datetime.datetime.now() diff --git a/homeassistant/components/binary_sensor/knx.py b/homeassistant/components/binary_sensor/knx.py index 9e5ddf5cac4e..c01654a3663a 100644 --- a/homeassistant/components/binary_sensor/knx.py +++ b/homeassistant/components/binary_sensor/knx.py @@ -5,12 +5,13 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES, \ - KNXAutomation -from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, \ - BinarySensorDevice +from homeassistant.components.binary_sensor import ( + PLATFORM_SCHEMA, BinarySensorDevice) +from homeassistant.components.knx import ( + ATTR_DISCOVER_DEVICES, DATA_KNX, KNXAutomation) from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -53,20 +54,16 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up binary sensor(s) for KNX platform.""" - if DATA_KNX not in hass.data \ - or not hass.data[DATA_KNX].initialized: - return False + if DATA_KNX not in hass.data or not hass.data[DATA_KNX].initialized: + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): @@ -80,7 +77,7 @@ def async_add_devices_discovery(hass, discovery_info, async_add_devices): @callback def async_add_devices_config(hass, config, async_add_devices): - """Set up binary senor for KNX platform configured within plattform.""" + """Set up binary senor for KNX platform configured within platform.""" name = config.get(CONF_NAME) import xknx binary_sensor = xknx.devices.BinarySensor( @@ -108,7 +105,7 @@ class KNXBinarySensor(BinarySensorDevice): """Representation of a KNX binary sensor.""" def __init__(self, hass, device): - """Initialization of KNXBinarySensor.""" + """Initialize of KNX binary sensor.""" self.device = device self.hass = hass self.async_register_callbacks() @@ -119,7 +116,7 @@ class KNXBinarySensor(BinarySensorDevice): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) diff --git a/homeassistant/components/binary_sensor/mysensors.py b/homeassistant/components/binary_sensor/mysensors.py index 4b83f0c8f2df..19fa02f63df6 100644 --- a/homeassistant/components/binary_sensor/mysensors.py +++ b/homeassistant/components/binary_sensor/mysensors.py @@ -5,21 +5,20 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.mysensors/ """ from homeassistant.components import mysensors -from homeassistant.components.binary_sensor import (DEVICE_CLASSES, DOMAIN, - BinarySensorDevice) +from homeassistant.components.binary_sensor import ( + DEVICE_CLASSES, DOMAIN, BinarySensorDevice) from homeassistant.const import STATE_ON def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors platform for binary sensors.""" + """Set up the MySensors platform for binary sensors.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsBinarySensor, add_devices=add_devices) -class MySensorsBinarySensor( - mysensors.MySensorsEntity, BinarySensorDevice): - """Represent the value of a MySensors Binary Sensor child node.""" +class MySensorsBinarySensor(mysensors.MySensorsEntity, BinarySensorDevice): + """Representation of a MySensors Binary Sensor child node.""" @property def is_on(self): diff --git a/homeassistant/components/binary_sensor/mystrom.py b/homeassistant/components/binary_sensor/mystrom.py index 2afaa032745b..93d56a97c427 100644 --- a/homeassistant/components/binary_sensor/mystrom.py +++ b/homeassistant/components/binary_sensor/mystrom.py @@ -7,7 +7,7 @@ https://home-assistant.io/components/binary_sensor.mystrom/ import asyncio import logging -from homeassistant.components.binary_sensor import (BinarySensorDevice, DOMAIN) +from homeassistant.components.binary_sensor import DOMAIN, BinarySensorDevice from homeassistant.components.http import HomeAssistantView from homeassistant.const import HTTP_UNPROCESSABLE_ENTITY @@ -37,7 +37,7 @@ class MyStromView(HomeAssistantView): @asyncio.coroutine def get(self, request): - """The GET request received from a myStrom button.""" + """Handle the GET request received from a myStrom button.""" res = yield from self._handle(request.app['hass'], request.query) return res diff --git a/homeassistant/components/binary_sensor/raspihats.py b/homeassistant/components/binary_sensor/raspihats.py index ad19fb525a12..9d489a59711a 100644 --- a/homeassistant/components/binary_sensor/raspihats.py +++ b/homeassistant/components/binary_sensor/raspihats.py @@ -5,18 +5,17 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.raspihats/ """ import logging + import voluptuous as vol -from homeassistant.const import ( - CONF_NAME, CONF_DEVICE_CLASS, DEVICE_DEFAULT_NAME -) -import homeassistant.helpers.config_validation as cv + from homeassistant.components.binary_sensor import ( - PLATFORM_SCHEMA, BinarySensorDevice -) + PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.components.raspihats import ( - CONF_I2C_HATS, CONF_BOARD, CONF_ADDRESS, CONF_CHANNELS, CONF_INDEX, - CONF_INVERT_LOGIC, I2C_HAT_NAMES, I2C_HATS_MANAGER, I2CHatsException -) + CONF_ADDRESS, CONF_BOARD, CONF_CHANNELS, CONF_I2C_HATS, CONF_INDEX, + CONF_INVERT_LOGIC, I2C_HAT_NAMES, I2C_HATS_MANAGER, I2CHatsException) +from homeassistant.const import ( + CONF_DEVICE_CLASS, CONF_NAME, DEVICE_DEFAULT_NAME) +import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -45,7 +44,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the raspihats binary_sensor devices.""" + """Set up the raspihats binary_sensor devices.""" I2CHatBinarySensor.I2C_HATS_MANAGER = hass.data[I2C_HATS_MANAGER] binary_sensors = [] i2c_hat_configs = config.get(CONF_I2C_HATS) @@ -65,39 +64,32 @@ def setup_platform(hass, config, add_devices, discovery_info=None): ) ) except I2CHatsException as ex: - _LOGGER.error( - "Failed to register " + board + "I2CHat@" + hex(address) + " " - + str(ex) - ) + _LOGGER.error("Failed to register %s I2CHat@%s %s", + board, hex(address), str(ex)) add_devices(binary_sensors) class I2CHatBinarySensor(BinarySensorDevice): - """Represents a binary sensor that uses a I2C-HAT digital input.""" + """Representation of a binary sensor that uses a I2C-HAT digital input.""" I2C_HATS_MANAGER = None def __init__(self, address, channel, name, invert_logic, device_class): - """Initialize sensor.""" + """Initialize the raspihats sensor.""" self._address = address self._channel = channel self._name = name or DEVICE_DEFAULT_NAME self._invert_logic = invert_logic self._device_class = device_class self._state = self.I2C_HATS_MANAGER.read_di( - self._address, - self._channel - ) + self._address, self._channel) def online_callback(): - """Callback fired when board is online.""" + """Call fired when board is online.""" self.schedule_update_ha_state() self.I2C_HATS_MANAGER.register_online_callback( - self._address, - self._channel, - online_callback - ) + self._address, self._channel, online_callback) def edge_callback(state): """Read digital input state.""" @@ -105,10 +97,7 @@ class I2CHatBinarySensor(BinarySensorDevice): self.schedule_update_ha_state() self.I2C_HATS_MANAGER.register_di_callback( - self._address, - self._channel, - edge_callback - ) + self._address, self._channel, edge_callback) @property def device_class(self): @@ -122,7 +111,7 @@ class I2CHatBinarySensor(BinarySensorDevice): @property def should_poll(self): - """Polling not needed for this sensor.""" + """No polling needed for this sensor.""" return False @property diff --git a/homeassistant/components/binary_sensor/rfxtrx.py b/homeassistant/components/binary_sensor/rfxtrx.py index 9a23b419cfc1..763003cab030 100644 --- a/homeassistant/components/binary_sensor/rfxtrx.py +++ b/homeassistant/components/binary_sensor/rfxtrx.py @@ -1,33 +1,30 @@ """ Support for RFXtrx binary sensors. -Lighting4 devices (sensors based on PT2262 encoder) are supported and -tested. Other types may need some work. - +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/binary_sensor.rfxtrx/ """ - import logging import voluptuous as vol -from homeassistant.const import ( - CONF_DEVICE_CLASS, CONF_COMMAND_ON, CONF_COMMAND_OFF, CONF_NAME) from homeassistant.components import rfxtrx -from homeassistant.helpers import event as evt -from homeassistant.helpers import config_validation as cv from homeassistant.components.binary_sensor import ( - BinarySensorDevice, PLATFORM_SCHEMA) + PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.components.rfxtrx import ( - ATTR_NAME, CONF_AUTOMATIC_ADD, CONF_FIRE_EVENT, - CONF_OFF_DELAY, CONF_DATA_BITS, CONF_DEVICES) -from homeassistant.util import slugify + ATTR_NAME, CONF_AUTOMATIC_ADD, CONF_DATA_BITS, CONF_DEVICES, + CONF_FIRE_EVENT, CONF_OFF_DELAY) +from homeassistant.const import ( + CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_DEVICE_CLASS, CONF_NAME) +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import event as evt from homeassistant.util import dt as dt_util - - -DEPENDENCIES = ["rfxtrx"] +from homeassistant.util import slugify _LOGGER = logging.getLogger(__name__) +DEPENDENCIES = ['rfxtrx'] + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_DEVICES, default={}): { cv.string: vol.Schema({ @@ -45,8 +42,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ }, extra=vol.ALLOW_EXTRA) -def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup the Binary Sensor platform to rfxtrx.""" +def setup_platform(hass, config, add_devices, discovery_info=None): + """Set up the Binary Sensor platform to RFXtrx.""" import RFXtrx as rfxtrxmod sensors = [] @@ -58,29 +55,26 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): continue if entity[CONF_DATA_BITS] is not None: - _LOGGER.debug("Masked device id: %s", - rfxtrx.get_pt2262_deviceid(device_id, - entity[CONF_DATA_BITS])) + _LOGGER.debug( + "Masked device id: %s", rfxtrx.get_pt2262_deviceid( + device_id, entity[CONF_DATA_BITS])) _LOGGER.debug("Add %s rfxtrx.binary_sensor (class %s)", entity[ATTR_NAME], entity[CONF_DEVICE_CLASS]) - device = RfxtrxBinarySensor(event, entity[ATTR_NAME], - entity[CONF_DEVICE_CLASS], - entity[CONF_FIRE_EVENT], - entity[CONF_OFF_DELAY], - entity[CONF_DATA_BITS], - entity[CONF_COMMAND_ON], - entity[CONF_COMMAND_OFF]) + device = RfxtrxBinarySensor( + event, entity[ATTR_NAME], entity[CONF_DEVICE_CLASS], + entity[CONF_FIRE_EVENT], entity[CONF_OFF_DELAY], + entity[CONF_DATA_BITS], entity[CONF_COMMAND_ON], + entity[CONF_COMMAND_OFF]) device.hass = hass sensors.append(device) rfxtrx.RFX_DEVICES[device_id] = device - add_devices_callback(sensors) + add_devices(sensors) - # pylint: disable=too-many-branches def binary_sensor_update(event): - """Callback for control updates from the RFXtrx gateway.""" + """Call for control updates from the RFXtrx gateway.""" if not isinstance(event, rfxtrxmod.ControlEvent): return @@ -100,29 +94,26 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): poss_dev = rfxtrx.find_possible_pt2262_device(device_id) if poss_dev is not None: poss_id = slugify(poss_dev.event.device.id_string.lower()) - _LOGGER.debug("Found possible matching deviceid %s.", - poss_id) + _LOGGER.debug( + "Found possible matching device ID: %s", poss_id) pkt_id = "".join("{0:02x}".format(x) for x in event.data) sensor = RfxtrxBinarySensor(event, pkt_id) sensor.hass = hass rfxtrx.RFX_DEVICES[device_id] = sensor - add_devices_callback([sensor]) - _LOGGER.info("Added binary sensor %s " - "(Device_id: %s Class: %s Sub: %s)", - pkt_id, - slugify(event.device.id_string.lower()), - event.device.__class__.__name__, - event.device.subtype) + add_devices([sensor]) + _LOGGER.info( + "Added binary sensor %s (Device ID: %s Class: %s Sub: %s)", + pkt_id, slugify(event.device.id_string.lower()), + event.device.__class__.__name__, event.device.subtype) elif not isinstance(sensor, RfxtrxBinarySensor): return else: - _LOGGER.debug("Binary sensor update " - "(Device_id: %s Class: %s Sub: %s)", - slugify(event.device.id_string.lower()), - event.device.__class__.__name__, - event.device.subtype) + _LOGGER.debug( + "Binary sensor update (Device ID: %s Class: %s Sub: %s)", + slugify(event.device.id_string.lower()), + event.device.__class__.__name__, event.device.subtype) if sensor.is_lighting4: if sensor.data_bits is not None: @@ -142,22 +133,20 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): sensor.update_state(False) sensor.delay_listener = evt.track_point_in_time( - hass, off_delay_listener, dt_util.utcnow() + sensor.off_delay - ) + hass, off_delay_listener, dt_util.utcnow() + sensor.off_delay) - # Subscribe to main rfxtrx events + # Subscribe to main RFXtrx events if binary_sensor_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(binary_sensor_update) -# pylint: disable=too-many-instance-attributes,too-many-arguments class RfxtrxBinarySensor(BinarySensorDevice): - """An Rfxtrx binary sensor.""" + """A representation of a RFXtrx binary sensor.""" def __init__(self, event, name, device_class=None, should_fire=False, off_delay=None, data_bits=None, cmd_on=None, cmd_off=None): - """Initialize the sensor.""" + """Initialize the RFXtrx sensor.""" self.event = event self._name = name self._should_fire_event = should_fire @@ -172,8 +161,7 @@ class RfxtrxBinarySensor(BinarySensorDevice): if data_bits is not None: self._masked_id = rfxtrx.get_pt2262_deviceid( - event.device.id_string.lower(), - data_bits) + event.device.id_string.lower(), data_bits) else: self._masked_id = None diff --git a/homeassistant/components/binary_sensor/rpi_pfio.py b/homeassistant/components/binary_sensor/rpi_pfio.py index 92d02067dfc6..7acbadf873af 100644 --- a/homeassistant/components/binary_sensor/rpi_pfio.py +++ b/homeassistant/components/binary_sensor/rpi_pfio.py @@ -8,18 +8,17 @@ import logging import voluptuous as vol -import homeassistant.components.rpi_pfio as rpi_pfio from homeassistant.components.binary_sensor import ( - BinarySensorDevice, PLATFORM_SCHEMA) -from homeassistant.const import DEVICE_DEFAULT_NAME + PLATFORM_SCHEMA, BinarySensorDevice) +import homeassistant.components.rpi_pfio as rpi_pfio +from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) -ATTR_NAME = 'name' -ATTR_INVERT_LOGIC = 'invert_logic' -ATTR_SETTLE_TIME = 'settle_time' +CONF_INVERT_LOGIC = 'invert_logic' CONF_PORTS = 'ports' +CONF_SETTLE_TIME = 'settle_time' DEFAULT_INVERT_LOGIC = False DEFAULT_SETTLE_TIME = 20 @@ -27,27 +26,27 @@ DEFAULT_SETTLE_TIME = 20 DEPENDENCIES = ['rpi_pfio'] PORT_SCHEMA = vol.Schema({ - vol.Optional(ATTR_NAME, default=None): cv.string, - vol.Optional(ATTR_SETTLE_TIME, default=DEFAULT_SETTLE_TIME): + vol.Optional(CONF_NAME, default=None): cv.string, + vol.Optional(CONF_SETTLE_TIME, default=DEFAULT_SETTLE_TIME): cv.positive_int, - vol.Optional(ATTR_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean + vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_PORTS, default={}): vol.Schema({ - cv.positive_int: PORT_SCHEMA + cv.positive_int: PORT_SCHEMA, }) }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the PiFace Digital Input devices.""" + """Set up the PiFace Digital Input devices.""" binary_sensors = [] - ports = config.get('ports') + ports = config.get(CONF_PORTS) for port, port_entity in ports.items(): - name = port_entity[ATTR_NAME] - settle_time = port_entity[ATTR_SETTLE_TIME] / 1000 - invert_logic = port_entity[ATTR_INVERT_LOGIC] + name = port_entity[CONF_NAME] + settle_time = port_entity[CONF_SETTLE_TIME] / 1000 + invert_logic = port_entity[CONF_INVERT_LOGIC] binary_sensors.append(RPiPFIOBinarySensor( hass, port, name, settle_time, invert_logic)) diff --git a/homeassistant/components/binary_sensor/spc.py b/homeassistant/components/binary_sensor/spc.py index a3a84580eddd..95723f938704 100644 --- a/homeassistant/components/binary_sensor/spc.py +++ b/homeassistant/components/binary_sensor/spc.py @@ -4,46 +4,49 @@ Support for Vanderbilt (formerly Siemens) SPC alarm systems. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.spc/ """ -import logging import asyncio +import logging -from homeassistant.components.spc import ( - ATTR_DISCOVER_DEVICES, DATA_REGISTRY) from homeassistant.components.binary_sensor import BinarySensorDevice -from homeassistant.const import (STATE_UNAVAILABLE, STATE_ON, STATE_OFF) - +from homeassistant.components.spc import ATTR_DISCOVER_DEVICES, DATA_REGISTRY +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE _LOGGER = logging.getLogger(__name__) -SPC_TYPE_TO_DEVICE_CLASS = {'0': 'motion', - '1': 'opening', - '3': 'smoke'} +SPC_TYPE_TO_DEVICE_CLASS = { + '0': 'motion', + '1': 'opening', + '3': 'smoke', +} - -SPC_INPUT_TO_SENSOR_STATE = {'0': STATE_OFF, - '1': STATE_ON} +SPC_INPUT_TO_SENSOR_STATE = { + '0': STATE_OFF, + '1': STATE_ON, +} def _get_device_class(spc_type): + """Get the device class.""" return SPC_TYPE_TO_DEVICE_CLASS.get(spc_type, None) def _get_sensor_state(spc_input): + """Get the sensor state.""" return SPC_INPUT_TO_SENSOR_STATE.get(spc_input, STATE_UNAVAILABLE) def _create_sensor(hass, zone): - return SpcBinarySensor(zone_id=zone['id'], - name=zone['zone_name'], - state=_get_sensor_state(zone['input']), - device_class=_get_device_class(zone['type']), - spc_registry=hass.data[DATA_REGISTRY]) + """Create a SPC sensor.""" + return SpcBinarySensor( + zone_id=zone['id'], name=zone['zone_name'], + state=_get_sensor_state(zone['input']), + device_class=_get_device_class(zone['type']), + spc_registry=hass.data[DATA_REGISTRY]) @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): - """Initialize the platform.""" +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): + """Set up the SPC binary sensor.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None): return @@ -55,7 +58,7 @@ def async_setup_platform(hass, config, async_add_devices, class SpcBinarySensor(BinarySensorDevice): - """Represents a sensor based on an SPC zone.""" + """Representation of a sensor based on a SPC zone.""" def __init__(self, zone_id, name, state, device_class, spc_registry): """Initialize the sensor device.""" @@ -74,7 +77,7 @@ class SpcBinarySensor(BinarySensorDevice): @property def name(self): - """The name of the device.""" + """Return the name of the device.""" return self._name @property @@ -85,7 +88,7 @@ class SpcBinarySensor(BinarySensorDevice): @property def hidden(self) -> bool: """Whether the device is hidden by default.""" - # these type of sensors are probably mainly used for automations + # These type of sensors are probably mainly used for automations return True @property @@ -95,5 +98,5 @@ class SpcBinarySensor(BinarySensorDevice): @property def device_class(self): - """The device class.""" + """Return the device class.""" return self._device_class diff --git a/homeassistant/components/binary_sensor/tapsaff.py b/homeassistant/components/binary_sensor/tapsaff.py index 565abb73b36e..09d28b96f724 100644 --- a/homeassistant/components/binary_sensor/tapsaff.py +++ b/homeassistant/components/binary_sensor/tapsaff.py @@ -4,15 +4,15 @@ Support for Taps Affs. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.tapsaff/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.binary_sensor import ( - BinarySensorDevice, PLATFORM_SCHEMA) -from homeassistant.const import (CONF_NAME) + PLATFORM_SCHEMA, BinarySensorDevice) +from homeassistant.const import CONF_NAME +import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['tapsaff==0.1.3'] @@ -67,7 +67,7 @@ class TapsAffData(object): """Class for handling the data retrieval for pins.""" def __init__(self, location): - """Initialize the sensor.""" + """Initialize the data object.""" from tapsaff import TapsAff self._is_taps_aff = None diff --git a/homeassistant/components/binary_sensor/tesla.py b/homeassistant/components/binary_sensor/tesla.py index a7cda90b3f65..3d494a28ea8e 100644 --- a/homeassistant/components/binary_sensor/tesla.py +++ b/homeassistant/components/binary_sensor/tesla.py @@ -28,7 +28,7 @@ class TeslaBinarySensor(TeslaDevice, BinarySensorDevice): """Implement an Tesla binary sensor for parking and charger.""" def __init__(self, tesla_device, controller, sensor_type): - """Initialisation of binary sensor.""" + """Initialise of a Tesla binary sensor.""" super().__init__(tesla_device, controller) self._state = False self.entity_id = ENTITY_ID_FORMAT.format(self.tesla_id) diff --git a/homeassistant/components/binary_sensor/verisure.py b/homeassistant/components/binary_sensor/verisure.py index 8702c8bd7701..4a1b99f4b9bc 100644 --- a/homeassistant/components/binary_sensor/verisure.py +++ b/homeassistant/components/binary_sensor/verisure.py @@ -6,15 +6,15 @@ https://home-assistant.io/components/binary_sensor.verisure/ """ import logging -from homeassistant.components.verisure import HUB as hub from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.verisure import CONF_DOOR_WINDOW +from homeassistant.components.verisure import HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Verisure binary sensors.""" + """Set up the Verisure binary sensors.""" sensors = [] hub.update_overview() @@ -27,10 +27,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class VerisureDoorWindowSensor(BinarySensorDevice): - """Verisure door window sensor.""" + """Representation of a Verisure door window sensor.""" def __init__(self, device_label): - """Initialize the modbus coil sensor.""" + """Initialize the Verisure door window sensor.""" self._device_label = device_label @property diff --git a/homeassistant/components/binary_sensor/vultr.py b/homeassistant/components/binary_sensor/vultr.py index 66b5a127be1e..eecd3f87c404 100644 --- a/homeassistant/components/binary_sensor/vultr.py +++ b/homeassistant/components/binary_sensor/vultr.py @@ -31,7 +31,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the Vultr subscription (server) sensor.""" + """Set up the Vultr subscription (server) binary sensor.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) @@ -39,7 +39,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) - return False + return add_devices([VultrBinarySensor(vultr, subscription, name)], True) @@ -48,7 +48,7 @@ class VultrBinarySensor(BinarySensorDevice): """Representation of a Vultr subscription sensor.""" def __init__(self, vultr, subscription, name): - """Initialize a new Vultr sensor.""" + """Initialize a new Vultr binary sensor.""" self._vultr = vultr self._name = name diff --git a/homeassistant/components/binary_sensor/wink.py b/homeassistant/components/binary_sensor/wink.py index e0bf23ecee24..55f6af3719eb 100644 --- a/homeassistant/components/binary_sensor/wink.py +++ b/homeassistant/components/binary_sensor/wink.py @@ -8,7 +8,7 @@ import asyncio import logging from homeassistant.components.binary_sensor import BinarySensorDevice -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice _LOGGER = logging.getLogger(__name__) @@ -16,18 +16,18 @@ 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', + 'capturing_video': None, 'co_detected': 'gas', + 'liquid_detected': 'moisture', + 'loudness': 'sound', + 'motion': 'motion', + 'noise': 'sound', + 'opened': 'opening', + 'presence': 'occupancy', 'smoke_detected': 'smoke', - 'capturing_video': None + 'vibration': 'vibration', } @@ -103,7 +103,7 @@ class WinkBinarySensorDevice(WinkDevice, BinarySensorDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['binary_sensor'].append(self) @property @@ -118,7 +118,7 @@ class WinkBinarySensorDevice(WinkDevice, BinarySensorDevice): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" return super().device_state_attributes @@ -127,7 +127,7 @@ class WinkSmokeDetector(WinkBinarySensorDevice): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" _attributes = super().device_state_attributes _attributes['test_activated'] = self.wink.test_activated() return _attributes @@ -138,7 +138,7 @@ class WinkHub(WinkBinarySensorDevice): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" _attributes = super().device_state_attributes _attributes['update_needed'] = self.wink.update_needed() _attributes['firmware_version'] = self.wink.firmware_version() @@ -170,7 +170,7 @@ class WinkButton(WinkBinarySensorDevice): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" _attributes = super().device_state_attributes _attributes['pressed'] = self.wink.pressed() _attributes['long_pressed'] = self.wink.long_pressed() diff --git a/homeassistant/components/calendar/caldav.py b/homeassistant/components/calendar/caldav.py index 36894dcab615..8b2401aa5891 100644 --- a/homeassistant/components/calendar/caldav.py +++ b/homeassistant/components/calendar/caldav.py @@ -4,18 +4,18 @@ Support for WebDav Calendar. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/calendar.caldav/ """ +from datetime import datetime, timedelta import logging import re -from datetime import datetime, timedelta import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.calendar import ( - CalendarEventDevice, PLATFORM_SCHEMA) + PLATFORM_SCHEMA, CalendarEventDevice) from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, CONF_URL, CONF_USERNAME) -from homeassistant.util import dt, Throttle +import homeassistant.helpers.config_validation as cv +from homeassistant.util import Throttle, dt REQUIREMENTS = ['caldav==0.5.0'] @@ -39,9 +39,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_CUSTOM_CALENDARS, default=[]): vol.All(cv.ensure_list, vol.Schema([ vol.Schema({ - vol.Required(CONF_NAME): cv.string, vol.Required(CONF_CALENDAR): cv.string, - vol.Required(CONF_SEARCH): cv.string + vol.Required(CONF_NAME): cv.string, + vol.Required(CONF_SEARCH): cv.string, }) ])) }) @@ -53,12 +53,12 @@ def setup_platform(hass, config, add_devices, disc_info=None): """Set up the WebDav Calendar platform.""" import caldav - client = caldav.DAVClient(config.get(CONF_URL), - None, - config.get(CONF_USERNAME), - config.get(CONF_PASSWORD)) + url = config.get(CONF_URL) + username = config.get(CONF_USERNAME) + password = config.get(CONF_PASSWORD) + + client = caldav.DAVClient(url, None, username, password) - # Retrieve all the remote calendars calendars = client.principal().calendars() calendar_devices = [] @@ -70,8 +70,7 @@ def setup_platform(hass, config, add_devices, disc_info=None): _LOGGER.debug("Ignoring calendar '%s'", calendar.name) continue - # Create additional calendars based on custom filtering - # rules + # Create additional calendars based on custom filtering rules for cust_calendar in config.get(CONF_CUSTOM_CALENDARS): # Check that the base calendar matches if cust_calendar.get(CONF_CALENDAR) != calendar.name: @@ -85,12 +84,9 @@ def setup_platform(hass, config, add_devices, disc_info=None): } calendar_devices.append( - WebDavCalendarEventDevice(hass, - device_data, - calendar, - True, - cust_calendar.get(CONF_SEARCH)) - ) + WebDavCalendarEventDevice( + hass, device_data, calendar, True, + cust_calendar.get(CONF_SEARCH))) # Create a default calendar if there was no custom one if not config.get(CONF_CUSTOM_CALENDARS): @@ -102,18 +98,13 @@ def setup_platform(hass, config, add_devices, disc_info=None): WebDavCalendarEventDevice(hass, device_data, calendar) ) - # Finally add all the calendars we've created add_devices(calendar_devices) class WebDavCalendarEventDevice(CalendarEventDevice): """A device for getting the next Task from a WebDav Calendar.""" - def __init__(self, - hass, - device_data, - calendar, - all_day=False, + def __init__(self, hass, device_data, calendar, all_day=False, search=None): """Create the WebDav Calendar Event Device.""" self.data = WebDavCalendarData(calendar, all_day, search) @@ -167,9 +158,7 @@ class WebDavCalendarData(object): if vevent is None: _LOGGER.debug( "No matching event found in the %d results for %s", - len(results), - self.calendar.name, - ) + len(results), self.calendar.name) self.event = None return True diff --git a/homeassistant/components/calendar/todoist.py b/homeassistant/components/calendar/todoist.py index ecf8bfb7cf7b..81191e3025eb 100644 --- a/homeassistant/components/calendar/todoist.py +++ b/homeassistant/components/calendar/todoist.py @@ -4,29 +4,28 @@ Support for Todoist task management (https://todoist.com). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/calendar.todoist/ """ - - -from datetime import datetime -from datetime import timedelta +from datetime import datetime, timedelta import logging import voluptuous as vol from homeassistant.components.calendar import ( - CalendarEventDevice, DOMAIN, PLATFORM_SCHEMA) -from homeassistant.components.google import ( - CONF_DEVICE_ID) -from homeassistant.const import ( - CONF_ID, CONF_NAME, CONF_TOKEN) + DOMAIN, PLATFORM_SCHEMA, CalendarEventDevice) +from homeassistant.components.google import CONF_DEVICE_ID +from homeassistant.const import CONF_ID, CONF_NAME, CONF_TOKEN import homeassistant.helpers.config_validation as cv from homeassistant.helpers.template import DATE_STR_FORMAT -from homeassistant.util import dt -from homeassistant.util import Throttle +from homeassistant.util import Throttle, dt REQUIREMENTS = ['todoist-python==7.0.17'] _LOGGER = logging.getLogger(__name__) +CONF_EXTRA_PROJECTS = 'custom_projects' +CONF_PROJECT_DUE_DATE = 'due_date_days' +CONF_PROJECT_LABEL_WHITELIST = 'labels' +CONF_PROJECT_WHITELIST = 'include_projects' + # Calendar Platform: Does this calendar event last all day? ALL_DAY = 'all_day' # Attribute: All tasks in this project @@ -78,20 +77,15 @@ SUMMARY = 'summary' TASKS = 'items' SERVICE_NEW_TASK = 'todoist_new_task' + NEW_TASK_SERVICE_SCHEMA = vol.Schema({ vol.Required(CONTENT): cv.string, vol.Optional(PROJECT_NAME, default='inbox'): vol.All(cv.string, vol.Lower), vol.Optional(LABELS): cv.ensure_list_csv, - vol.Optional(PRIORITY): vol.All(vol.Coerce(int), - vol.Range(min=1, max=4)), - vol.Optional(DUE_DATE): cv.string + vol.Optional(PRIORITY): vol.All(vol.Coerce(int), vol.Range(min=1, max=4)), + vol.Optional(DUE_DATE): cv.string, }) -CONF_EXTRA_PROJECTS = 'custom_projects' -CONF_PROJECT_DUE_DATE = 'due_date_days' -CONF_PROJECT_WHITELIST = 'include_projects' -CONF_PROJECT_LABEL_WHITELIST = 'labels' - PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_TOKEN): cv.string, vol.Optional(CONF_EXTRA_PROJECTS, default=[]): @@ -111,8 +105,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Todoist platform.""" - # Check token: + """Set up the Todoist platform.""" token = config.get(CONF_TOKEN) # Look up IDs based on (lowercase) names. @@ -176,7 +169,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): add_devices(project_devices) def handle_new_task(call): - """Called when a user creates a new Todoist Task from HASS.""" + """Call when a user creates a new Todoist Task from HASS.""" project_name = call.data[PROJECT_NAME] project_id = project_id_lookup[project_name] @@ -528,8 +521,7 @@ class TodoistProjectData(object): # Let's set our "due date" to tomorrow self.event[END] = { DATETIME: ( - datetime.utcnow() + - timedelta(days=1) + datetime.utcnow() + timedelta(days=1) ).strftime(DATE_STR_FORMAT) } _LOGGER.debug("Updated %s", self._name) diff --git a/homeassistant/components/camera/axis.py b/homeassistant/components/camera/axis.py index 492c2a47729d..51c3bc89b053 100644 --- a/homeassistant/components/camera/axis.py +++ b/homeassistant/components/camera/axis.py @@ -6,11 +6,11 @@ https://home-assistant.io/components/camera.axis/ """ import logging -from homeassistant.const import ( - CONF_HOST, CONF_NAME, CONF_USERNAME, CONF_PASSWORD, CONF_PORT, - CONF_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION) from homeassistant.components.camera.mjpeg import ( CONF_MJPEG_URL, CONF_STILL_IMAGE_URL, MjpegCamera) +from homeassistant.const import ( + CONF_AUTHENTICATION, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, + CONF_USERNAME, HTTP_DIGEST_AUTHENTICATION) from homeassistant.helpers.dispatcher import dispatcher_connect _LOGGER = logging.getLogger(__name__) @@ -20,6 +20,7 @@ DEPENDENCIES = [DOMAIN] def _get_image_url(host, port, mode): + """Set the URL to get the image.""" if mode == 'mjpeg': return 'http://{}:{}/axis-cgi/mjpg/video.cgi'.format(host, port) elif mode == 'single': @@ -27,34 +28,32 @@ def _get_image_url(host, port, mode): def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Axis camera.""" + """Set up the Axis camera.""" camera_config = { CONF_NAME: discovery_info[CONF_NAME], CONF_USERNAME: discovery_info[CONF_USERNAME], CONF_PASSWORD: discovery_info[CONF_PASSWORD], - CONF_MJPEG_URL: _get_image_url(discovery_info[CONF_HOST], - str(discovery_info[CONF_PORT]), - 'mjpeg'), - CONF_STILL_IMAGE_URL: _get_image_url(discovery_info[CONF_HOST], - str(discovery_info[CONF_PORT]), - 'single'), + CONF_MJPEG_URL: _get_image_url( + discovery_info[CONF_HOST], str(discovery_info[CONF_PORT]), + 'mjpeg'), + CONF_STILL_IMAGE_URL: _get_image_url( + discovery_info[CONF_HOST], str(discovery_info[CONF_PORT]), + 'single'), CONF_AUTHENTICATION: HTTP_DIGEST_AUTHENTICATION, } - add_devices([AxisCamera(hass, - camera_config, - str(discovery_info[CONF_PORT]))]) + add_devices([AxisCamera( + hass, camera_config, str(discovery_info[CONF_PORT]))]) class AxisCamera(MjpegCamera): - """AxisCamera class.""" + """Representation of a Axis camera.""" def __init__(self, hass, config, port): """Initialize Axis Communications camera component.""" super().__init__(hass, config) self.port = port - dispatcher_connect(hass, - DOMAIN + '_' + config[CONF_NAME] + '_new_ip', - self._new_ip) + dispatcher_connect( + hass, DOMAIN + '_' + config[CONF_NAME] + '_new_ip', self._new_ip) def _new_ip(self, host): """Set new IP for video stream.""" diff --git a/homeassistant/components/camera/blink.py b/homeassistant/components/camera/blink.py index 4b708817cfd9..8475ca8fd1e8 100644 --- a/homeassistant/components/camera/blink.py +++ b/homeassistant/components/camera/blink.py @@ -4,21 +4,21 @@ Support for Blink system camera. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/camera.blink/ """ +from datetime import timedelta import logging -from datetime import timedelta import requests from homeassistant.components.blink import DOMAIN from homeassistant.components.camera import Camera from homeassistant.util import Throttle +_LOGGER = logging.getLogger(__name__) + DEPENDENCIES = ['blink'] MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=90) -_LOGGER = logging.getLogger(__name__) - def setup_platform(hass, config, add_devices, discovery_info=None): """Set up a Blink Camera.""" @@ -45,7 +45,7 @@ class BlinkCamera(Camera): self.notifications = self.data.cameras[self._name].notifications self.response = None - _LOGGER.info("Initialized blink camera %s", self._name) + _LOGGER.debug("Initialized blink camera %s", self._name) @property def name(self): @@ -55,7 +55,7 @@ class BlinkCamera(Camera): @Throttle(MIN_TIME_BETWEEN_UPDATES) def request_image(self): """Request a new image from Blink servers.""" - _LOGGER.info("Requesting new image from blink servers") + _LOGGER.debug("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) @@ -68,7 +68,7 @@ class BlinkCamera(Camera): # We detected motion at some point self.data.last_motion() self.notifications = notifs - # returning motion image currently not working + # Returning motion image currently not working # return self.data.cameras[self._name].motion['image'] elif notifs < self.notifications: self.notifications = notifs diff --git a/homeassistant/components/climate/daikin.py b/homeassistant/components/climate/daikin.py index 8f6df034b896..1f3515b7b986 100644 --- a/homeassistant/components/climate/daikin.py +++ b/homeassistant/components/climate/daikin.py @@ -9,25 +9,18 @@ import re import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.climate import ( - ATTR_OPERATION_MODE, ATTR_FAN_MODE, ATTR_SWING_MODE, - ATTR_CURRENT_TEMPERATURE, ClimateDevice, PLATFORM_SCHEMA, - SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE, SUPPORT_OPERATION_MODE, - SUPPORT_SWING_MODE, STATE_OFF, STATE_AUTO, STATE_HEAT, STATE_COOL, - STATE_DRY, STATE_FAN_ONLY -) + ATTR_CURRENT_TEMPERATURE, ATTR_FAN_MODE, ATTR_OPERATION_MODE, + ATTR_SWING_MODE, PLATFORM_SCHEMA, STATE_AUTO, STATE_COOL, STATE_DRY, + STATE_FAN_ONLY, STATE_HEAT, STATE_OFF, SUPPORT_FAN_MODE, + SUPPORT_OPERATION_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, + ClimateDevice) from homeassistant.components.daikin import ( - daikin_api_setup, - ATTR_TARGET_TEMPERATURE, - ATTR_INSIDE_TEMPERATURE, - ATTR_OUTSIDE_TEMPERATURE -) + ATTR_INSIDE_TEMPERATURE, ATTR_OUTSIDE_TEMPERATURE, ATTR_TARGET_TEMPERATURE, + daikin_api_setup) from homeassistant.const import ( - CONF_HOST, CONF_NAME, - TEMP_CELSIUS, - ATTR_TEMPERATURE -) + ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, TEMP_CELSIUS) +import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pydaikin==0.4'] @@ -60,15 +53,15 @@ HA_ATTR_TO_DAIKIN = { def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Daikin HVAC platform.""" + """Set up the Daikin HVAC platform.""" if discovery_info is not None: host = discovery_info.get('ip') name = None - _LOGGER.info("Discovered a Daikin AC on %s", host) + _LOGGER.debug("Discovered a Daikin AC on %s", host) else: host = config.get(CONF_HOST) name = config.get(CONF_NAME) - _LOGGER.info("Added Daikin AC on %s", host) + _LOGGER.debug("Added Daikin AC on %s", host) api = daikin_api_setup(hass, host, name) add_devices([DaikinClimate(api)], True) @@ -130,7 +123,7 @@ class DaikinClimate(ClimateDevice): ).title() if value is None: - _LOGGER.warning("Invalid value requested for key %s", key) + _LOGGER.error("Invalid value requested for key %s", key) else: if value == "-" or value == "--": value = None diff --git a/homeassistant/components/climate/econet.py b/homeassistant/components/climate/econet.py index 8f2342782ede..bb92a92467ae 100644 --- a/homeassistant/components/climate/econet.py +++ b/homeassistant/components/climate/econet.py @@ -10,17 +10,12 @@ import logging import voluptuous as vol from homeassistant.components.climate import ( - DOMAIN, - PLATFORM_SCHEMA, - STATE_ECO, STATE_GAS, STATE_ELECTRIC, - STATE_HEAT_PUMP, STATE_HIGH_DEMAND, - STATE_OFF, SUPPORT_TARGET_TEMPERATURE, - SUPPORT_OPERATION_MODE, - STATE_PERFORMANCE, - ClimateDevice) -from homeassistant.const import (ATTR_ENTITY_ID, - CONF_PASSWORD, CONF_USERNAME, TEMP_FAHRENHEIT, - ATTR_TEMPERATURE) + DOMAIN, PLATFORM_SCHEMA, STATE_ECO, STATE_ELECTRIC, STATE_GAS, + STATE_HEAT_PUMP, STATE_HIGH_DEMAND, STATE_OFF, STATE_PERFORMANCE, + SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, ClimateDevice) +from homeassistant.const import ( + ATTR_ENTITY_ID, ATTR_TEMPERATURE, CONF_PASSWORD, CONF_USERNAME, + TEMP_FAHRENHEIT) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pyeconet==0.0.4'] @@ -89,7 +84,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): hass.data[ECONET_DATA]['water_heaters'].extend(hass_water_heaters) def service_handle(service): - """Handler for services.""" + """Handle the service calls.""" entity_ids = service.data.get('entity_id') all_heaters = hass.data[ECONET_DATA]['water_heaters'] _heaters = [ @@ -107,12 +102,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): _water_heater.schedule_update_ha_state(True) - hass.services.register(DOMAIN, SERVICE_ADD_VACATION, - service_handle, + hass.services.register(DOMAIN, SERVICE_ADD_VACATION, service_handle, schema=ADD_VACATION_SCHEMA) - hass.services.register(DOMAIN, SERVICE_DELETE_VACATION, - service_handle, + hass.services.register(DOMAIN, SERVICE_DELETE_VACATION, service_handle, schema=DELETE_VACATION_SCHEMA) @@ -140,7 +133,7 @@ class EcoNetWaterHeater(ClimateDevice): @property def device_state_attributes(self): - """Return the optional state attributes.""" + """Return the optional device state attributes.""" data = {} vacations = self.water_heater.get_vacations() if vacations: @@ -159,8 +152,7 @@ class EcoNetWaterHeater(ClimateDevice): """ Return current operation as one of the following. - ["eco", "heat_pump", - "high_demand", "electric_only"] + ["eco", "heat_pump", "high_demand", "electric_only"] """ current_op = ECONET_STATE_TO_HA.get(self.water_heater.mode) return current_op @@ -191,7 +183,7 @@ class EcoNetWaterHeater(ClimateDevice): if target_temp is not None: self.water_heater.set_target_set_point(target_temp) else: - _LOGGER.error("A target temperature must be provided.") + _LOGGER.error("A target temperature must be provided") def set_operation_mode(self, operation_mode): """Set operation mode.""" @@ -199,7 +191,7 @@ class EcoNetWaterHeater(ClimateDevice): if op_mode_to_set is not None: self.water_heater.set_mode(op_mode_to_set) else: - _LOGGER.error("An operation mode must be provided.") + _LOGGER.error("An operation mode must be provided") def add_vacation(self, start, end): """Add a vacation to this water heater.""" diff --git a/homeassistant/components/climate/knx.py b/homeassistant/components/climate/knx.py index 97bd3e9503c8..a78c277fa33b 100644 --- a/homeassistant/components/climate/knx.py +++ b/homeassistant/components/climate/knx.py @@ -5,13 +5,14 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES from homeassistant.components.climate import ( - PLATFORM_SCHEMA, ClimateDevice, SUPPORT_TARGET_TEMPERATURE, - SUPPORT_OPERATION_MODE) -from homeassistant.const import CONF_NAME, TEMP_CELSIUS, ATTR_TEMPERATURE + PLATFORM_SCHEMA, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, + ClimateDevice) +from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX +from homeassistant.const import ATTR_TEMPERATURE, CONF_NAME, TEMP_CELSIUS from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -61,24 +62,20 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up climate(s) for KNX platform.""" - if DATA_KNX not in hass.data \ - or not hass.data[DATA_KNX].initialized: - return False + if DATA_KNX not in hass.data or not hass.data[DATA_KNX].initialized: + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): - """Set up climates for KNX platform configured within plattform.""" + """Set up climates for KNX platform configured within platform.""" entities = [] for device_name in discovery_info[ATTR_DISCOVER_DEVICES]: device = hass.data[DATA_KNX].xknx.devices[device_name] @@ -88,28 +85,22 @@ def async_add_devices_discovery(hass, discovery_info, async_add_devices): @callback def async_add_devices_config(hass, config, async_add_devices): - """Set up climate for KNX platform configured within plattform.""" + """Set up climate for KNX platform configured within platform.""" import xknx climate = xknx.devices.Climate( hass.data[DATA_KNX].xknx, name=config.get(CONF_NAME), - group_address_temperature=config.get( - CONF_TEMPERATURE_ADDRESS), + group_address_temperature=config.get(CONF_TEMPERATURE_ADDRESS), group_address_target_temperature=config.get( CONF_TARGET_TEMPERATURE_ADDRESS), - group_address_setpoint_shift=config.get( - CONF_SETPOINT_SHIFT_ADDRESS), + group_address_setpoint_shift=config.get(CONF_SETPOINT_SHIFT_ADDRESS), group_address_setpoint_shift_state=config.get( CONF_SETPOINT_SHIFT_STATE_ADDRESS), - setpoint_shift_step=config.get( - CONF_SETPOINT_SHIFT_STEP), - setpoint_shift_max=config.get( - CONF_SETPOINT_SHIFT_MAX), - setpoint_shift_min=config.get( - CONF_SETPOINT_SHIFT_MIN), - group_address_operation_mode=config.get( - CONF_OPERATION_MODE_ADDRESS), + setpoint_shift_step=config.get(CONF_SETPOINT_SHIFT_STEP), + setpoint_shift_max=config.get(CONF_SETPOINT_SHIFT_MAX), + setpoint_shift_min=config.get(CONF_SETPOINT_SHIFT_MIN), + group_address_operation_mode=config.get(CONF_OPERATION_MODE_ADDRESS), group_address_operation_mode_state=config.get( CONF_OPERATION_MODE_STATE_ADDRESS), group_address_controller_status=config.get( @@ -127,10 +118,10 @@ def async_add_devices_config(hass, config, async_add_devices): class KNXClimate(ClimateDevice): - """Representation of a KNX climate.""" + """Representation of a KNX climate device.""" def __init__(self, hass, device): - """Initialization of KNXClimate.""" + """Initialize of a KNX climate device.""" self.device = device self.hass = hass self.async_register_callbacks() @@ -149,7 +140,7 @@ class KNXClimate(ClimateDevice): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) diff --git a/homeassistant/components/climate/mysensors.py b/homeassistant/components/climate/mysensors.py index db43a6d3be4b..ff1400a8fae9 100644 --- a/homeassistant/components/climate/mysensors.py +++ b/homeassistant/components/climate/mysensors.py @@ -7,9 +7,10 @@ https://home-assistant.io/components/climate.mysensors/ from homeassistant.components import mysensors from homeassistant.components.climate import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, DOMAIN, STATE_AUTO, - STATE_COOL, STATE_HEAT, STATE_OFF, ClimateDevice, - SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH, - SUPPORT_TARGET_TEMPERATURE_LOW, SUPPORT_FAN_MODE, SUPPORT_OPERATION_MODE) + STATE_COOL, STATE_HEAT, STATE_OFF, SUPPORT_FAN_MODE, + SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, + SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_TARGET_TEMPERATURE_LOW, + ClimateDevice) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT DICT_HA_TO_MYS = { @@ -31,7 +32,7 @@ SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_HIGH | def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors climate.""" + """Set up the MySensors climate.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsHVAC, add_devices=add_devices) @@ -52,8 +53,7 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice): @property def temperature_unit(self): """Return the unit of measurement.""" - return (TEMP_CELSIUS - if self.gateway.metric else TEMP_FAHRENHEIT) + return TEMP_CELSIUS if self.gateway.metric else TEMP_FAHRENHEIT @property def current_temperature(self): @@ -139,7 +139,8 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice): self.gateway.set_child_value( self.node_id, self.child_id, value_type, value) if self.gateway.optimistic: - # optimistically assume that device has changed state + # O + # ptimistically assume that device has changed state self._values[value_type] = value self.schedule_update_ha_state() @@ -149,7 +150,7 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice): self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_HVAC_SPEED, fan) if self.gateway.optimistic: - # optimistically assume that device has changed state + # Optimistically assume that device has changed state self._values[set_req.V_HVAC_SPEED] = fan self.schedule_update_ha_state() @@ -159,7 +160,7 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice): self.node_id, self.child_id, self.value_type, DICT_HA_TO_MYS[operation_mode]) if self.gateway.optimistic: - # optimistically assume that device has changed state + # Optimistically assume that device has changed state self._values[self.value_type] = operation_mode self.schedule_update_ha_state() diff --git a/homeassistant/components/climate/tesla.py b/homeassistant/components/climate/tesla.py index 6295b85a1b7b..459d9c666fdf 100644 --- a/homeassistant/components/climate/tesla.py +++ b/homeassistant/components/climate/tesla.py @@ -6,13 +6,13 @@ https://home-assistant.io/components/climate.tesla/ """ import logging -from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.components.climate import ( - ClimateDevice, ENTITY_ID_FORMAT, SUPPORT_TARGET_TEMPERATURE, - SUPPORT_OPERATION_MODE) -from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN, TeslaDevice + ENTITY_ID_FORMAT, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, + ClimateDevice) +from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN +from homeassistant.components.tesla import TeslaDevice from homeassistant.const import ( - TEMP_FAHRENHEIT, TEMP_CELSIUS, ATTR_TEMPERATURE) + ATTR_TEMPERATURE, STATE_OFF, STATE_ON, TEMP_CELSIUS, TEMP_FAHRENHEIT) _LOGGER = logging.getLogger(__name__) @@ -60,7 +60,7 @@ class TeslaThermostat(TeslaDevice, ClimateDevice): return OPERATION_LIST def update(self): - """Called by the Tesla device callback to update state.""" + """Call by the Tesla device callback to update state.""" _LOGGER.debug("Updating: %s", self._name) self.tesla_device.update() self._target_temperature = self.tesla_device.get_goal_temp() diff --git a/homeassistant/components/climate/toon.py b/homeassistant/components/climate/toon.py index 0ff9f1290819..330801fc2319 100644 --- a/homeassistant/components/climate/toon.py +++ b/homeassistant/components/climate/toon.py @@ -7,25 +7,25 @@ Eneco. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.toon/ """ -import homeassistant.components.toon as toon_main from homeassistant.components.climate import ( - ClimateDevice, ATTR_TEMPERATURE, STATE_PERFORMANCE, STATE_HEAT, STATE_ECO, - STATE_COOL, SUPPORT_TARGET_TEMPERATURE, SUPPORT_OPERATION_MODE) + ATTR_TEMPERATURE, STATE_COOL, STATE_ECO, STATE_HEAT, STATE_PERFORMANCE, + SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, ClimateDevice) +import homeassistant.components.toon as toon_main from homeassistant.const import TEMP_CELSIUS SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the Toon thermostat.""" + """Set up the Toon climate device.""" add_devices([ThermostatDevice(hass)], True) class ThermostatDevice(ClimateDevice): - """Interface class for the toon module and HA.""" + """Representation of a Toon climate device.""" def __init__(self, hass): - """Initialize the device.""" + """Initialize the Toon climate device.""" self._name = 'Toon van Eneco' self.hass = hass self.thermos = hass.data[toon_main.TOON_HANDLE] @@ -47,12 +47,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 @@ -63,7 +63,7 @@ class ThermostatDevice(ClimateDevice): @property def operation_list(self): - """List of available operation modes.""" + """Return a list of available operation modes.""" return self._operation_list @property @@ -82,7 +82,7 @@ class ThermostatDevice(ClimateDevice): self.thermos.set_temp(temp) def set_operation_mode(self, operation_mode): - """Set new operation mode as toonlib requires it.""" + """Set new operation mode.""" toonlib_values = { STATE_PERFORMANCE: 'Comfort', STATE_HEAT: 'Home', diff --git a/homeassistant/components/climate/wink.py b/homeassistant/components/climate/wink.py index 33ba0f56d336..2c287fc68464 100644 --- a/homeassistant/components/climate/wink.py +++ b/homeassistant/components/climate/wink.py @@ -8,16 +8,16 @@ import asyncio import logging from homeassistant.components.climate import ( - STATE_ECO, STATE_GAS, STATE_AUTO, STATE_COOL, STATE_HEAT, STATE_ELECTRIC, - STATE_FAN_ONLY, STATE_HEAT_PUMP, ATTR_TEMPERATURE, STATE_HIGH_DEMAND, - STATE_PERFORMANCE, ATTR_TARGET_TEMP_LOW, ATTR_CURRENT_HUMIDITY, - ATTR_TARGET_TEMP_HIGH, ClimateDevice, SUPPORT_TARGET_TEMPERATURE, + ATTR_CURRENT_HUMIDITY, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, + ATTR_TEMPERATURE, STATE_AUTO, STATE_COOL, STATE_ECO, STATE_ELECTRIC, + STATE_FAN_ONLY, STATE_GAS, STATE_HEAT, STATE_HEAT_PUMP, STATE_HIGH_DEMAND, + STATE_PERFORMANCE, SUPPORT_AUX_HEAT, SUPPORT_AWAY_MODE, SUPPORT_FAN_MODE, + SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_TARGET_TEMPERATURE_LOW, - SUPPORT_OPERATION_MODE, SUPPORT_AWAY_MODE, SUPPORT_FAN_MODE, - SUPPORT_AUX_HEAT) + ClimateDevice) from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.const import ( - STATE_ON, STATE_OFF, TEMP_CELSIUS, STATE_UNKNOWN, PRECISION_TENTHS) + PRECISION_TENTHS, STATE_OFF, STATE_ON, STATE_UNKNOWN, TEMP_CELSIUS) from homeassistant.helpers.temperature import display_temp as show_temp _LOGGER = logging.getLogger(__name__) @@ -93,7 +93,7 @@ class WinkThermostat(WinkDevice, ClimateDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['climate'].append(self) @property @@ -104,7 +104,7 @@ class WinkThermostat(WinkDevice, ClimateDevice): @property def device_state_attributes(self): - """Return the optional state attributes.""" + """Return the optional device state attributes.""" data = {} target_temp_high = self.target_temperature_high target_temp_low = self.target_temperature_low @@ -385,7 +385,7 @@ class WinkAC(WinkDevice, ClimateDevice): @property def device_state_attributes(self): - """Return the optional state attributes.""" + """Return the optional device state attributes.""" data = {} target_temp_high = self.target_temperature_high target_temp_low = self.target_temperature_low @@ -508,7 +508,7 @@ class WinkWaterHeater(WinkDevice, ClimateDevice): @property def device_state_attributes(self): - """Return the optional state attributes.""" + """Return the optional device state attributes.""" data = {} data[ATTR_VACATION_MODE] = self.wink.vacation_mode_enabled() data[ATTR_RHEEM_TYPE] = self.wink.rheem_type() diff --git a/homeassistant/components/cloud/__init__.py b/homeassistant/components/cloud/__init__.py index e497f4677e47..a5bbf805d429 100644 --- a/homeassistant/components/cloud/__init__.py +++ b/homeassistant/components/cloud/__init__.py @@ -1,4 +1,9 @@ -"""Component to integrate the Home Assistant cloud.""" +""" +Component to integrate the Home Assistant cloud. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/cloud/ +""" import asyncio from datetime import datetime import json @@ -26,18 +31,18 @@ REQUIREMENTS = ['warrant==0.6.1'] _LOGGER = logging.getLogger(__name__) CONF_ALEXA = 'alexa' -CONF_GOOGLE_ACTIONS = 'google_actions' -CONF_FILTER = 'filter' +CONF_ALIASES = 'aliases' CONF_COGNITO_CLIENT_ID = 'cognito_client_id' +CONF_ENTITY_CONFIG = 'entity_config' +CONF_FILTER = 'filter' +CONF_GOOGLE_ACTIONS = 'google_actions' CONF_RELAYER = 'relayer' CONF_USER_POOL_ID = 'user_pool_id' -CONF_ALIASES = 'aliases' -MODE_DEV = 'development' DEFAULT_MODE = 'production' DEPENDENCIES = ['http'] -CONF_ENTITY_CONFIG = 'entity_config' +MODE_DEV = 'development' ALEXA_ENTITY_SCHEMA = vol.Schema({ vol.Optional(alexa_sh.CONF_DESCRIPTION): cv.string, @@ -149,7 +154,7 @@ class Cloud: @property def subscription_expired(self): - """Return a boolen if the subscription has expired.""" + """Return a boolean if the subscription has expired.""" return dt_util.utcnow() > self.expiration_date @property @@ -195,8 +200,8 @@ class Cloud: if not jwt_success: return False - self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, - self._start_cloud) + self.hass.bus.async_listen_once( + EVENT_HOMEASSISTANT_START, self._start_cloud) return True @@ -248,7 +253,7 @@ class Cloud: for token in 'id_token', 'access_token': self._decode_claims(info[token]) except ValueError as err: # Raised when token is invalid - _LOGGER.warning('Found invalid token %s: %s', token, err) + _LOGGER.warning("Found invalid token %s: %s", token, err) return self.id_token = info['id_token'] @@ -282,15 +287,15 @@ class Cloud: header = jwt.get_unverified_header(token) except jose_exceptions.JWTError as err: raise ValueError(str(err)) from None - kid = header.get("kid") + kid = header.get('kid') if kid is None: - raise ValueError('No kid in header') + raise ValueError("No kid in header") # Locate the key for this kid key = None - for key_dict in self.jwt_keyset["keys"]: - if key_dict["kid"] == kid: + for key_dict in self.jwt_keyset['keys']: + if key_dict['kid'] == kid: key = key_dict break if not key: diff --git a/homeassistant/components/cloud/auth_api.py b/homeassistant/components/cloud/auth_api.py index 500ff062a0f2..e96f2a2d8a52 100644 --- a/homeassistant/components/cloud/auth_api.py +++ b/homeassistant/components/cloud/auth_api.py @@ -1,7 +1,6 @@ """Package to communicate with the authentication API.""" import logging - _LOGGER = logging.getLogger(__name__) @@ -22,7 +21,7 @@ class UserNotConfirmed(CloudError): class ExpiredCode(CloudError): - """Raised when an expired code is encoutered.""" + """Raised when an expired code is encountered.""" class InvalidCode(CloudError): @@ -38,7 +37,7 @@ class PasswordChangeRequired(CloudError): class UnknownError(CloudError): - """Raised when an unknown error occurrs.""" + """Raised when an unknown error occurs.""" AWS_EXCEPTIONS = { @@ -98,7 +97,7 @@ def resend_email_confirm(cloud, email): def forgot_password(cloud, email): - """Initiate forgotten password flow.""" + """Initialize forgotten password flow.""" from botocore.exceptions import ClientError cognito = _cognito(cloud, username=email) diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index 338e004ce527..af966e180eb7 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -3,8 +3,8 @@ import asyncio from functools import wraps import logging -import voluptuous as vol import async_timeout +import voluptuous as vol from homeassistant.components.http import ( HomeAssistantView, RequestDataValidator) @@ -17,7 +17,7 @@ _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def async_setup(hass): - """Initialize the HTTP api.""" + """Initialize the HTTP API.""" hass.http.register_view(CloudLoginView) hass.http.register_view(CloudLogoutView) hass.http.register_view(CloudAccountView) @@ -40,7 +40,7 @@ _CLOUD_ERRORS = { def _handle_cloud_errors(handler): - """Helper method to handle auth errors.""" + """Handle auth errors.""" @asyncio.coroutine @wraps(handler) def error_handler(view, request, *args, **kwargs): diff --git a/homeassistant/components/cloud/iot.py b/homeassistant/components/cloud/iot.py index ffe68c3c8779..2d3ab025e433 100644 --- a/homeassistant/components/cloud/iot.py +++ b/homeassistant/components/cloud/iot.py @@ -12,7 +12,6 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession from . import auth_api from .const import MESSAGE_EXPIRATION - HANDLERS = Registry() _LOGGER = logging.getLogger(__name__) @@ -85,7 +84,7 @@ class CloudIoT: }) self.tries = 0 - _LOGGER.info('Connected') + _LOGGER.info("Connected") self.state = STATE_CONNECTED while not client.closed: @@ -107,7 +106,7 @@ class CloudIoT: disconnect_warn = 'Received invalid JSON.' break - _LOGGER.debug('Received message: %s', msg) + _LOGGER.debug("Received message: %s", msg) response = { 'msgid': msg['msgid'], @@ -126,14 +125,14 @@ class CloudIoT: response['error'] = 'unknown-handler' except Exception: # pylint: disable=broad-except - _LOGGER.exception('Error handling message') + _LOGGER.exception("Error handling message") response['error'] = 'exception' - _LOGGER.debug('Publishing message: %s', response) + _LOGGER.debug("Publishing message: %s", response) yield from client.send_json(response) except auth_api.CloudError: - _LOGGER.warning('Unable to connect: Unable to refresh token.') + _LOGGER.warning("Unable to connect: Unable to refresh token.") except client_exceptions.WSServerHandshakeError as err: if err.code == 401: @@ -141,18 +140,18 @@ class CloudIoT: self.close_requested = True # Should we notify user? else: - _LOGGER.warning('Unable to connect: %s', err) + _LOGGER.warning("Unable to connect: %s", err) except client_exceptions.ClientError as err: - _LOGGER.warning('Unable to connect: %s', err) + _LOGGER.warning("Unable to connect: %s", err) except Exception: # pylint: disable=broad-except if not self.close_requested: - _LOGGER.exception('Unexpected error') + _LOGGER.exception("Unexpected error") finally: if disconnect_warn is not None: - _LOGGER.warning('Connection closed: %s', disconnect_warn) + _LOGGER.warning("Connection closed: %s", disconnect_warn) if remove_hass_stop_listener is not None: remove_hass_stop_listener() @@ -169,7 +168,7 @@ class CloudIoT: self.tries += 1 try: - # Sleep 0, 5, 10, 15 … up to 30 seconds between retries + # Sleep 0, 5, 10, 15 ... up to 30 seconds between retries self.retry_task = hass.async_add_job(asyncio.sleep( min(30, (self.tries - 1) * 5), loop=hass.loop)) yield from self.retry_task @@ -205,8 +204,8 @@ def async_handle_message(hass, cloud, handler_name, payload): @asyncio.coroutine def async_handle_alexa(hass, cloud, payload): """Handle an incoming IoT message for Alexa.""" - result = yield from alexa.async_handle_message(hass, cloud.alexa_config, - payload) + result = yield from alexa.async_handle_message( + hass, cloud.alexa_config, payload) return result @@ -214,8 +213,8 @@ def async_handle_alexa(hass, cloud, payload): @asyncio.coroutine def async_handle_google_actions(hass, cloud, payload): """Handle an incoming IoT message for Google Actions.""" - result = yield from ga.async_handle_message(hass, cloud.gactions_config, - payload) + result = yield from ga.async_handle_message( + hass, cloud.gactions_config, payload) return result @@ -227,9 +226,9 @@ def async_handle_cloud(hass, cloud, payload): if action == 'logout': yield from cloud.logout() - _LOGGER.error('You have been logged out from Home Assistant cloud: %s', + _LOGGER.error("You have been logged out from Home Assistant cloud: %s", payload['reason']) else: - _LOGGER.warning('Received unknown cloud action: %s', action) + _LOGGER.warning("Received unknown cloud action: %s", action) return None diff --git a/homeassistant/components/comfoconnect.py b/homeassistant/components/comfoconnect.py index ba2180078e3b..425ed6f9c9a5 100644 --- a/homeassistant/components/comfoconnect.py +++ b/homeassistant/components/comfoconnect.py @@ -8,11 +8,11 @@ import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.const import ( - CONF_HOST, CONF_NAME, CONF_TOKEN, CONF_PIN, EVENT_HOMEASSISTANT_STOP) -from homeassistant.helpers import (discovery) -from homeassistant.helpers.dispatcher import (dispatcher_send) + CONF_HOST, CONF_NAME, CONF_PIN, CONF_TOKEN, EVENT_HOMEASSISTANT_STOP) +from homeassistant.helpers import discovery +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.dispatcher import dispatcher_send REQUIREMENTS = ['pycomfoconnect==0.3'] @@ -115,7 +115,7 @@ class ComfoConnectBridge(object): self.comfoconnect.disconnect() def sensor_callback(self, var, value): - """Callback function for sensor updates.""" + """Call function for sensor updates.""" _LOGGER.debug("Got value from bridge: %d = %d", var, value) from pycomfoconnect import ( diff --git a/homeassistant/components/cover/knx.py b/homeassistant/components/cover/knx.py index d8313caeb5f8..79c57c41e908 100644 --- a/homeassistant/components/cover/knx.py +++ b/homeassistant/components/cover/knx.py @@ -5,17 +5,18 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES -from homeassistant.helpers.event import async_track_utc_time_change from homeassistant.components.cover import ( - CoverDevice, PLATFORM_SCHEMA, SUPPORT_OPEN, SUPPORT_CLOSE, - SUPPORT_SET_POSITION, SUPPORT_STOP, SUPPORT_SET_TILT_POSITION, - ATTR_POSITION, ATTR_TILT_POSITION) -from homeassistant.core import callback + ATTR_POSITION, ATTR_TILT_POSITION, PLATFORM_SCHEMA, SUPPORT_CLOSE, + SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, + SUPPORT_STOP, CoverDevice) +from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX from homeassistant.const import CONF_NAME +from homeassistant.core import callback import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.event import async_track_utc_time_change CONF_MOVE_LONG_ADDRESS = 'move_long_address' CONF_MOVE_SHORT_ADDRESS = 'move_short_address' @@ -50,20 +51,16 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up cover(s) for KNX platform.""" - if DATA_KNX not in hass.data \ - or not hass.data[DATA_KNX].initialized: - return False + if DATA_KNX not in hass.data or not hass.data[DATA_KNX].initialized: + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): @@ -114,7 +111,7 @@ class KNXCover(CoverDevice): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) @@ -209,7 +206,7 @@ class KNXCover(CoverDevice): @callback def auto_updater_hook(self, now): - """Callback for autoupdater.""" + """Call for the autoupdater.""" # pylint: disable=unused-argument self.async_schedule_update_ha_state() if self.device.position_reached(): diff --git a/homeassistant/components/cover/mysensors.py b/homeassistant/components/cover/mysensors.py index cd4ff62b3e90..391d2a22bda0 100644 --- a/homeassistant/components/cover/mysensors.py +++ b/homeassistant/components/cover/mysensors.py @@ -5,12 +5,12 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.mysensors/ """ from homeassistant.components import mysensors -from homeassistant.components.cover import CoverDevice, ATTR_POSITION, DOMAIN -from homeassistant.const import STATE_ON, STATE_OFF +from homeassistant.components.cover import ATTR_POSITION, DOMAIN, CoverDevice +from homeassistant.const import STATE_OFF, STATE_ON def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors platform for covers.""" + """Set up the MySensors platform for covers.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsCover, add_devices=add_devices) diff --git a/homeassistant/components/cover/rfxtrx.py b/homeassistant/components/cover/rfxtrx.py index 66f2fde52f42..aefb7ab89d71 100644 --- a/homeassistant/components/cover/rfxtrx.py +++ b/homeassistant/components/cover/rfxtrx.py @@ -29,12 +29,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ }) -def setup_platform(hass, config, add_devices_callback, discovery_info=None): +def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the RFXtrx cover.""" import RFXtrx as rfxtrxmod covers = rfxtrx.get_devices_from_config(config, RfxtrxCover) - add_devices_callback(covers) + add_devices(covers) def cover_update(event): """Handle cover updates from the RFXtrx gateway.""" @@ -45,7 +45,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): new_device = rfxtrx.get_new_device(event, config, RfxtrxCover) if new_device: - add_devices_callback([new_device]) + add_devices([new_device]) rfxtrx.apply_received_command(event) @@ -59,7 +59,7 @@ class RfxtrxCover(rfxtrx.RfxtrxDevice, CoverDevice): @property def should_poll(self): - """No polling available in RFXtrx cover.""" + """Return the polling state. No polling available in RFXtrx cover.""" return False @property diff --git a/homeassistant/components/cover/wink.py b/homeassistant/components/cover/wink.py index ce96b4d75e0e..b3276bdf8cc9 100644 --- a/homeassistant/components/cover/wink.py +++ b/homeassistant/components/cover/wink.py @@ -7,7 +7,7 @@ https://home-assistant.io/components/cover.wink/ import asyncio from homeassistant.components.cover import CoverDevice -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice DEPENDENCIES = ['wink'] @@ -31,7 +31,7 @@ class WinkCoverDevice(WinkDevice, CoverDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['cover'].append(self) def close_cover(self, **kwargs): diff --git a/homeassistant/components/datadog.py b/homeassistant/components/datadog.py index 2c8145177b77..58503d7187b3 100644 --- a/homeassistant/components/datadog.py +++ b/homeassistant/components/datadog.py @@ -5,11 +5,12 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/datadog/ """ import logging + import voluptuous as vol -from homeassistant.const import (CONF_HOST, CONF_PORT, CONF_PREFIX, - EVENT_LOGBOOK_ENTRY, EVENT_STATE_CHANGED, - STATE_UNKNOWN) +from homeassistant.const import ( + CONF_HOST, CONF_PORT, CONF_PREFIX, EVENT_LOGBOOK_ENTRY, + EVENT_STATE_CHANGED, STATE_UNKNOWN) from homeassistant.helpers import state as state_helper import homeassistant.helpers.config_validation as cv @@ -36,7 +37,7 @@ CONFIG_SCHEMA = vol.Schema({ def setup(hass, config): - """Setup the Datadog component.""" + """Set up the Datadog component.""" from datadog import initialize, statsd conf = config[DOMAIN] @@ -81,36 +82,19 @@ def setup(hass, config): if isinstance(value, (float, int)): attribute = "{}.{}".format(metric, key.replace(' ', '_')) statsd.gauge( - attribute, - value, - sample_rate=sample_rate, - tags=tags - ) + attribute, value, sample_rate=sample_rate, tags=tags) _LOGGER.debug( - 'Sent metric %s: %s (tags: %s)', - attribute, - value, - tags - ) + "Sent metric %s: %s (tags: %s)", attribute, value, tags) try: value = state_helper.state_as_number(state) except ValueError: _LOGGER.debug( - 'Error sending %s: %s (tags: %s)', - metric, - state.state, - tags - ) + "Error sending %s: %s (tags: %s)", metric, state.state, tags) return - statsd.gauge( - metric, - value, - sample_rate=sample_rate, - tags=tags - ) + statsd.gauge(metric, value, sample_rate=sample_rate, tags=tags) _LOGGER.debug('Sent metric %s: %s (tags: %s)', metric, value, tags) diff --git a/homeassistant/components/deconz/__init__.py b/homeassistant/components/deconz/__init__.py index 72845ee671fc..269b81360202 100644 --- a/homeassistant/components/deconz/__init__.py +++ b/homeassistant/components/deconz/__init__.py @@ -60,7 +60,7 @@ def async_setup(hass, config): @asyncio.coroutine def async_deconz_discovered(service, discovery_info): - """Called when deCONZ gateway has been found.""" + """Call when deCONZ gateway has been found.""" deconz_config = {} deconz_config[CONF_HOST] = discovery_info.get(CONF_HOST) deconz_config[CONF_PORT] = discovery_info.get(CONF_PORT) @@ -90,13 +90,13 @@ def async_setup_deconz(hass, config, deconz_config): Load config, group, light and sensor data for server information. Start websocket for push notification of state changes from deCONZ. """ - _LOGGER.debug('deCONZ config %s', deconz_config) + _LOGGER.debug("deCONZ config %s", deconz_config) from pydeconz import DeconzSession websession = async_get_clientsession(hass) deconz = DeconzSession(hass.loop, websession, **deconz_config) result = yield from deconz.async_load_parameters() if result is False: - _LOGGER.error("Failed to communicate with deCONZ.") + _LOGGER.error("Failed to communicate with deCONZ") return False hass.data[DOMAIN] = deconz @@ -126,8 +126,7 @@ def async_setup_deconz(hass, config, deconz_config): data = call.data.get(SERVICE_DATA) yield from deconz.async_put_state(field, data) hass.services.async_register( - DOMAIN, 'configure', async_configure, - schema=SERVICE_SCHEMA) + DOMAIN, 'configure', async_configure, schema=SERVICE_SCHEMA) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, deconz.close) return True diff --git a/homeassistant/components/device_tracker/automatic.py b/homeassistant/components/device_tracker/automatic.py index ef747657cb46..5ad3995ad2a4 100644 --- a/homeassistant/components/device_tracker/automatic.py +++ b/homeassistant/components/device_tracker/automatic.py @@ -14,8 +14,8 @@ from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import ( - PLATFORM_SCHEMA, ATTR_ATTRIBUTES, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_MAC, - ATTR_GPS, ATTR_GPS_ACCURACY) + ATTR_ATTRIBUTES, ATTR_DEV_ID, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_HOST_NAME, + ATTR_MAC, PLATFORM_SCHEMA) from homeassistant.components.http import HomeAssistantView from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback @@ -24,35 +24,33 @@ import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_track_time_interval REQUIREMENTS = ['aioautomatic==0.6.4'] -DEPENDENCIES = ['http'] _LOGGER = logging.getLogger(__name__) -CONF_CLIENT_ID = 'client_id' -CONF_SECRET = 'secret' -CONF_DEVICES = 'devices' -CONF_CURRENT_LOCATION = 'current_location' - -DEFAULT_TIMEOUT = 5 - -DEFAULT_SCOPE = ['location', 'trip', 'vehicle:events', 'vehicle:profile'] -FULL_SCOPE = DEFAULT_SCOPE + ['current_location'] - ATTR_FUEL_LEVEL = 'fuel_level' - -EVENT_AUTOMATIC_UPDATE = 'automatic_update' - AUTOMATIC_CONFIG_FILE = '.automatic/session-{}.json' +CONF_CLIENT_ID = 'client_id' +CONF_CURRENT_LOCATION = 'current_location' +CONF_DEVICES = 'devices' +CONF_SECRET = 'secret' + DATA_CONFIGURING = 'automatic_configurator_clients' DATA_REFRESH_TOKEN = 'refresh_token' +DEFAULT_SCOPE = ['location', 'trip', 'vehicle:events', 'vehicle:profile'] +DEFAULT_TIMEOUT = 5 +DEPENDENCIES = ['http'] + +EVENT_AUTOMATIC_UPDATE = 'automatic_update' + +FULL_SCOPE = DEFAULT_SCOPE + ['current_location'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_CLIENT_ID): cv.string, vol.Required(CONF_SECRET): cv.string, vol.Optional(CONF_CURRENT_LOCATION, default=False): cv.boolean, - vol.Optional(CONF_DEVICES, default=None): vol.All( - cv.ensure_list, [cv.string]) + vol.Optional(CONF_DEVICES, default=None): + vol.All(cv.ensure_list, [cv.string]), }) @@ -142,7 +140,7 @@ def async_setup_scanner(hass, config, async_see, discovery_info=None): @asyncio.coroutine def initialize_callback(code, state): - """Callback after OAuth2 response is returned.""" + """Call after OAuth2 response is returned.""" try: session = yield from client.create_session_from_oauth_code( code, state) @@ -181,12 +179,12 @@ class AutomaticAuthCallbackView(HomeAssistantView): return response else: _LOGGER.error( - "Error authorizing Automatic. Invalid response returned.") + "Error authorizing Automatic. Invalid response returned") return response if DATA_CONFIGURING not in hass.data or \ params['state'] not in hass.data[DATA_CONFIGURING]: - _LOGGER.error("Automatic configuration request not found.") + _LOGGER.error("Automatic configuration request not found") return response code = params['code'] @@ -220,16 +218,15 @@ class AutomaticData(object): @asyncio.coroutine def handle_event(self, name, event): - """Coroutine to update state for a realtime event.""" + """Coroutine to update state for a real time event.""" import aioautomatic - # Fire a hass event self.hass.bus.async_fire(EVENT_AUTOMATIC_UPDATE, event.data) if event.vehicle.id not in self.vehicle_info: # If vehicle hasn't been seen yet, request the detailed # info for this vehicle. - _LOGGER.info("New vehicle found.") + _LOGGER.info("New vehicle found") try: vehicle = yield from event.get_vehicle() except aioautomatic.exceptions.AutomaticError as err: @@ -240,7 +237,7 @@ class AutomaticData(object): if event.created_at < self.vehicle_seen[event.vehicle.id]: # Skip events received out of order _LOGGER.debug("Skipping out of order event. Event Created %s. " - "Last seen event: %s.", event.created_at, + "Last seen event: %s", event.created_at, self.vehicle_seen[event.vehicle.id]) return self.vehicle_seen[event.vehicle.id] = event.created_at @@ -270,13 +267,13 @@ class AutomaticData(object): self.ws_close_requested = False if self.ws_reconnect_handle is not None: - _LOGGER.debug("Retrying websocket connection.") + _LOGGER.debug("Retrying websocket connection") try: ws_loop_future = yield from self.client.ws_connect() except aioautomatic.exceptions.UnauthorizedClientError: _LOGGER.error("Client unauthorized for websocket connection. " "Ensure Websocket is selected in the Automatic " - "developer application event delivery preferences.") + "developer application event delivery preferences") return except aioautomatic.exceptions.AutomaticError as err: if self.ws_reconnect_handle is None: @@ -290,14 +287,14 @@ class AutomaticData(object): self.ws_reconnect_handle() self.ws_reconnect_handle = None - _LOGGER.info("Websocket connected.") + _LOGGER.info("Websocket connected") try: yield from ws_loop_future except aioautomatic.exceptions.AutomaticError as err: _LOGGER.error(str(err)) - _LOGGER.info("Websocket closed.") + _LOGGER.info("Websocket closed") # If websocket was close was not requested, attempt to reconnect if not self.ws_close_requested: diff --git a/homeassistant/components/device_tracker/ubus.py b/homeassistant/components/device_tracker/ubus.py index 99f20d4385e0..2306a66070b0 100644 --- a/homeassistant/components/device_tracker/ubus.py +++ b/homeassistant/components/device_tracker/ubus.py @@ -11,11 +11,11 @@ import re import requests import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.exceptions import HomeAssistantError +import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -30,8 +30,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, - vol.Optional(CONF_DHCP_SOFTWARE, - default=DEFAULT_DHCP_SOFTWARE): vol.In(DHCP_SOFTWARES) + vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): + vol.In(DHCP_SOFTWARES), }) @@ -49,14 +49,14 @@ def get_scanner(hass, config): def _refresh_on_acccess_denied(func): """If remove rebooted, it lost our session so rebuld one and try again.""" def decorator(self, *args, **kwargs): - """Wrapper function to refresh session_id on PermissionError.""" + """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning("Invalid session detected." + - " Tryign to refresh session_id and re-run the rpc") - self.session_id = _get_session_id(self.url, self.username, - self.password) + " Trying to refresh session_id and re-run RPC") + self.session_id = _get_session_id( + self.url, self.username, self.password) return func(self, *args, **kwargs) @@ -80,8 +80,8 @@ class UbusDeviceScanner(DeviceScanner): self.last_results = {} self.url = 'http://{}/ubus'.format(host) - self.session_id = _get_session_id(self.url, self.username, - self.password) + self.session_id = _get_session_id( + self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.session_id is not None diff --git a/homeassistant/components/device_tracker/upc_connect.py b/homeassistant/components/device_tracker/upc_connect.py index fbcd753713c5..ea0645e012f3 100644 --- a/homeassistant/components/device_tracker/upc_connect.py +++ b/homeassistant/components/device_tracker/upc_connect.py @@ -84,7 +84,7 @@ class UPCDeviceScanner(DeviceScanner): @asyncio.coroutine def async_get_device_name(self, device): - """The firmware doesn't save the name of the wireless device.""" + """Get the device name (the name of the wireless device not used).""" return None @asyncio.coroutine diff --git a/homeassistant/components/fan/dyson.py b/homeassistant/components/fan/dyson.py index f2630aa98d2a..c5e5b8736ae7 100644 --- a/homeassistant/components/fan/dyson.py +++ b/homeassistant/components/fan/dyson.py @@ -3,38 +3,42 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/fan.dyson/ """ -import logging import asyncio -import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.components.fan import (FanEntity, SUPPORT_OSCILLATE, - SUPPORT_SET_SPEED, - DOMAIN) -from homeassistant.helpers.entity import ToggleEntity -from homeassistant.components.dyson import DYSON_DEVICES +import logging -DEPENDENCIES = ['dyson'] +import voluptuous as vol + +from homeassistant.components.dyson import DYSON_DEVICES +from homeassistant.components.fan import ( + DOMAIN, SUPPORT_OSCILLATE, SUPPORT_SET_SPEED, FanEntity) +from homeassistant.const import CONF_ENTITY_ID +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import ToggleEntity _LOGGER = logging.getLogger(__name__) +CONF_NIGHT_MODE = 'night_mode' + +DEPENDENCIES = ['dyson'] +DYSON_FAN_DEVICES = 'dyson_fan_devices' -DYSON_FAN_DEVICES = "dyson_fan_devices" SERVICE_SET_NIGHT_MODE = 'dyson_set_night_mode' DYSON_SET_NIGHT_MODE_SCHEMA = vol.Schema({ - vol.Required('entity_id'): cv.entity_id, - vol.Required('night_mode'): cv.boolean + vol.Required(CONF_ENTITY_ID): cv.entity_id, + vol.Required(CONF_NIGHT_MODE): cv.boolean, }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Dyson fan components.""" - _LOGGER.info("Creating new Dyson fans") + """Set up the Dyson fan components.""" + from libpurecoollink.dyson_pure_cool_link import DysonPureCoolLink + + _LOGGER.debug("Creating new Dyson fans") if DYSON_FAN_DEVICES not in hass.data: hass.data[DYSON_FAN_DEVICES] = [] # Get Dyson Devices from parent component - from libpurecoollink.dyson_pure_cool_link import DysonPureCoolLink for device in [d for d in hass.data[DYSON_DEVICES] if isinstance(d, DysonPureCoolLink)]: dyson_entity = DysonPureCoolLinkDevice(hass, device) @@ -43,9 +47,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): add_devices(hass.data[DYSON_FAN_DEVICES]) def service_handle(service): - """Handle dyson services.""" - entity_id = service.data.get('entity_id') - night_mode = service.data.get('night_mode') + """Handle the Dyson services.""" + entity_id = service.data.get(CONF_ENTITY_ID) + night_mode = service.data.get(CONF_NIGHT_MODE) fan_device = next([fan for fan in hass.data[DYSON_FAN_DEVICES] if fan.entity_id == entity_id].__iter__(), None) if fan_device is None: @@ -57,9 +61,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): fan_device.night_mode(night_mode) # Register dyson service(s) - hass.services.register(DOMAIN, SERVICE_SET_NIGHT_MODE, - service_handle, - schema=DYSON_SET_NIGHT_MODE_SCHEMA) + hass.services.register( + DOMAIN, SERVICE_SET_NIGHT_MODE, service_handle, + schema=DYSON_SET_NIGHT_MODE_SCHEMA) class DysonPureCoolLinkDevice(FanEntity): @@ -67,21 +71,22 @@ class DysonPureCoolLinkDevice(FanEntity): def __init__(self, hass, device): """Initialize the fan.""" - _LOGGER.info("Creating device %s", device.name) + _LOGGER.debug("Creating device %s", device.name) self.hass = hass self._device = device @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.async_add_job( self._device.add_message_listener, self.on_message) def on_message(self, message): - """Called when new messages received from the fan.""" + """Call when new messages received from the fan.""" from libpurecoollink.dyson_pure_state import DysonPureCoolState + if isinstance(message, DysonPureCoolState): - _LOGGER.debug("Message received for fan device %s : %s", self.name, + _LOGGER.debug("Message received for fan device %s: %s", self.name, message) self.schedule_update_ha_state() @@ -97,41 +102,46 @@ class DysonPureCoolLinkDevice(FanEntity): def set_speed(self: ToggleEntity, speed: str) -> None: """Set the speed of the fan. Never called ??.""" - _LOGGER.debug("Set fan speed to: " + speed) from libpurecoollink.const import FanSpeed, FanMode + + _LOGGER.debug("Set fan speed to: %s", speed) + if speed == FanSpeed.FAN_SPEED_AUTO.value: self._device.set_configuration(fan_mode=FanMode.AUTO) else: fan_speed = FanSpeed('{0:04d}'.format(int(speed))) - self._device.set_configuration(fan_mode=FanMode.FAN, - fan_speed=fan_speed) + self._device.set_configuration( + fan_mode=FanMode.FAN, fan_speed=fan_speed) def turn_on(self: ToggleEntity, speed: str=None, **kwargs) -> None: """Turn on the fan.""" - _LOGGER.debug("Turn on fan %s with speed %s", self.name, speed) from libpurecoollink.const import FanSpeed, FanMode + + _LOGGER.debug("Turn on fan %s with speed %s", self.name, speed) if speed: if speed == FanSpeed.FAN_SPEED_AUTO.value: self._device.set_configuration(fan_mode=FanMode.AUTO) else: fan_speed = FanSpeed('{0:04d}'.format(int(speed))) - self._device.set_configuration(fan_mode=FanMode.FAN, - fan_speed=fan_speed) + self._device.set_configuration( + fan_mode=FanMode.FAN, fan_speed=fan_speed) else: # Speed not set, just turn on self._device.set_configuration(fan_mode=FanMode.FAN) def turn_off(self: ToggleEntity, **kwargs) -> None: """Turn off the fan.""" - _LOGGER.debug("Turn off fan %s", self.name) from libpurecoollink.const import FanMode + + _LOGGER.debug("Turn off fan %s", self.name) self._device.set_configuration(fan_mode=FanMode.OFF) def oscillate(self: ToggleEntity, oscillating: bool) -> None: """Turn on/off oscillating.""" + from libpurecoollink.const import Oscillation + _LOGGER.debug("Turn oscillation %s for device %s", oscillating, self.name) - from libpurecoollink.const import Oscillation if oscillating: self._device.set_configuration( @@ -155,8 +165,9 @@ class DysonPureCoolLinkDevice(FanEntity): @property def speed(self) -> str: """Return the current speed.""" + from libpurecoollink.const import FanSpeed + if self._device.state: - from libpurecoollink.const import FanSpeed if self._device.state.speed == FanSpeed.FAN_SPEED_AUTO.value: return self._device.state.speed return int(self._device.state.speed) @@ -174,8 +185,9 @@ class DysonPureCoolLinkDevice(FanEntity): def night_mode(self: ToggleEntity, night_mode: bool) -> None: """Turn fan in night mode.""" - _LOGGER.debug("Set %s night mode %s", self.name, night_mode) from libpurecoollink.const import NightMode + + _LOGGER.debug("Set %s night mode %s", self.name, night_mode) if night_mode: self._device.set_configuration(night_mode=NightMode.NIGHT_MODE_ON) else: @@ -188,8 +200,9 @@ class DysonPureCoolLinkDevice(FanEntity): def auto_mode(self: ToggleEntity, auto_mode: bool) -> None: """Turn fan in auto mode.""" - _LOGGER.debug("Set %s auto mode %s", self.name, auto_mode) from libpurecoollink.const import FanMode + + _LOGGER.debug("Set %s auto mode %s", self.name, auto_mode) if auto_mode: self._device.set_configuration(fan_mode=FanMode.AUTO) else: @@ -199,17 +212,20 @@ class DysonPureCoolLinkDevice(FanEntity): def speed_list(self: ToggleEntity) -> list: """Get the list of available speeds.""" from libpurecoollink.const import FanSpeed - supported_speeds = [FanSpeed.FAN_SPEED_AUTO.value, - int(FanSpeed.FAN_SPEED_1.value), - int(FanSpeed.FAN_SPEED_2.value), - int(FanSpeed.FAN_SPEED_3.value), - int(FanSpeed.FAN_SPEED_4.value), - int(FanSpeed.FAN_SPEED_5.value), - int(FanSpeed.FAN_SPEED_6.value), - int(FanSpeed.FAN_SPEED_7.value), - int(FanSpeed.FAN_SPEED_8.value), - int(FanSpeed.FAN_SPEED_9.value), - int(FanSpeed.FAN_SPEED_10.value)] + + supported_speeds = [ + FanSpeed.FAN_SPEED_AUTO.value, + int(FanSpeed.FAN_SPEED_1.value), + int(FanSpeed.FAN_SPEED_2.value), + int(FanSpeed.FAN_SPEED_3.value), + int(FanSpeed.FAN_SPEED_4.value), + int(FanSpeed.FAN_SPEED_5.value), + int(FanSpeed.FAN_SPEED_6.value), + int(FanSpeed.FAN_SPEED_7.value), + int(FanSpeed.FAN_SPEED_8.value), + int(FanSpeed.FAN_SPEED_9.value), + int(FanSpeed.FAN_SPEED_10.value), + ] return supported_speeds diff --git a/homeassistant/components/fan/wink.py b/homeassistant/components/fan/wink.py index 3920e606d906..827f134cc085 100644 --- a/homeassistant/components/fan/wink.py +++ b/homeassistant/components/fan/wink.py @@ -7,20 +7,18 @@ https://home-assistant.io/components/fan.wink/ import asyncio import logging -from homeassistant.components.fan import (FanEntity, SPEED_HIGH, - SPEED_LOW, SPEED_MEDIUM, - STATE_UNKNOWN, SUPPORT_SET_SPEED, - SUPPORT_DIRECTION) +from homeassistant.components.fan import ( + SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, STATE_UNKNOWN, SUPPORT_DIRECTION, + SUPPORT_SET_SPEED, FanEntity) +from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.helpers.entity import ToggleEntity -from homeassistant.components.wink import WinkDevice, DOMAIN - -DEPENDENCIES = ['wink'] _LOGGER = logging.getLogger(__name__) -SPEED_LOWEST = 'lowest' -SPEED_AUTO = 'auto' +DEPENDENCIES = ['wink'] +SPEED_AUTO = 'auto' +SPEED_LOWEST = 'lowest' SUPPORTED_FEATURES = SUPPORT_DIRECTION + SUPPORT_SET_SPEED @@ -38,7 +36,7 @@ class WinkFanDevice(WinkDevice, FanEntity): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['fan'].append(self) def set_direction(self: ToggleEntity, direction: str) -> None: diff --git a/homeassistant/components/frontend/__init__.py b/homeassistant/components/frontend/__init__.py index 002f680927e2..ea8a4d92540c 100644 --- a/homeassistant/components/frontend/__init__.py +++ b/homeassistant/components/frontend/__init__.py @@ -260,10 +260,10 @@ def async_register_panel(hass, component_name, path, md5=None, component_name: name of the web component path: path to the HTML of the web component (required unless url is provided) - md5: the md5 hash of the web component (for versioning in url, optional) + md5: the md5 hash of the web component (for versioning in URL, optional) sidebar_title: title to show in the sidebar (optional) sidebar_icon: icon to show next to title in sidebar (optional) - url_path: name to use in the url (defaults to component_name) + url_path: name to use in the URL (defaults to component_name) config: config to be passed into the web component """ panel = ExternalPanel(component_name, path, md5, sidebar_title, diff --git a/homeassistant/components/hassio.py b/homeassistant/components/hassio.py index 4e4e6e7e64c9..efd83c7ea9e7 100644 --- a/homeassistant/components/hassio.py +++ b/homeassistant/components/hassio.py @@ -12,21 +12,22 @@ import re import aiohttp from aiohttp import web -from aiohttp.web_exceptions import HTTPBadGateway from aiohttp.hdrs import CONTENT_TYPE +from aiohttp.web_exceptions import HTTPBadGateway import async_timeout import voluptuous as vol -from homeassistant.core import callback, DOMAIN as HASS_DOMAIN -from homeassistant.const import ( - CONTENT_TYPE_TEXT_PLAIN, SERVER_PORT, CONF_TIME_ZONE, - SERVICE_HOMEASSISTANT_STOP, SERVICE_HOMEASSISTANT_RESTART) from homeassistant.components import SERVICE_CHECK_CONFIG from homeassistant.components.http import ( - HomeAssistantView, KEY_AUTHENTICATED, CONF_API_PASSWORD, CONF_SERVER_PORT, - CONF_SERVER_HOST, CONF_SSL_CERTIFICATE) -from homeassistant.loader import bind_hass + CONF_API_PASSWORD, CONF_SERVER_HOST, CONF_SERVER_PORT, + CONF_SSL_CERTIFICATE, KEY_AUTHENTICATED, HomeAssistantView) +from homeassistant.const import ( + CONF_TIME_ZONE, CONTENT_TYPE_TEXT_PLAIN, SERVER_PORT, + SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP) +from homeassistant.core import DOMAIN as HASS_DOMAIN +from homeassistant.core import callback import homeassistant.helpers.config_validation as cv +from homeassistant.loader import bind_hass from homeassistant.util.dt import utcnow _LOGGER = logging.getLogger(__name__) @@ -126,7 +127,7 @@ MAP_SERVICE_API = { @callback @bind_hass def get_homeassistant_version(hass): - """Return latest available HomeAssistant version. + """Return latest available Home Assistant version. Async friendly. """ @@ -136,7 +137,7 @@ def get_homeassistant_version(hass): @callback @bind_hass def is_hassio(hass): - """Return True if hass.io is loaded. + """Return true if hass.io is loaded. Async friendly. """ @@ -146,7 +147,7 @@ def is_hassio(hass): @bind_hass @asyncio.coroutine def async_check_config(hass): - """Check config over Hass.io API.""" + """Check configuration over Hass.io API.""" result = yield from hass.data[DOMAIN].send_command( '/homeassistant/check', timeout=300) @@ -159,18 +160,18 @@ def async_check_config(hass): @asyncio.coroutine def async_setup(hass, config): - """Set up the HASSio component.""" + """Set up the Hass.io component.""" try: host = os.environ['HASSIO'] except KeyError: - _LOGGER.error("No HassIO supervisor detect!") + _LOGGER.error("No Hass.io supervisor detect") return False websession = hass.helpers.aiohttp_client.async_get_clientsession() hass.data[DOMAIN] = hassio = HassIO(hass.loop, websession, host) if not (yield from hassio.is_connected()): - _LOGGER.error("Not connected with HassIO!") + _LOGGER.error("Not connected with Hass.io") return False hass.http.register_view(HassIOView(hassio)) @@ -187,7 +188,7 @@ def async_setup(hass, config): @asyncio.coroutine def async_service_handler(service): - """Handle service calls for HassIO.""" + """Handle service calls for Hass.io.""" api_command = MAP_SERVICE_API[service.service][0] data = service.data.copy() addon = data.pop(ATTR_ADDON, None) @@ -215,7 +216,7 @@ def async_setup(hass, config): @asyncio.coroutine def update_homeassistant_version(now): - """Update last available HomeAssistant version.""" + """Update last available Home Assistant version.""" data = yield from hassio.get_homeassistant_info() if data: hass.data[DATA_HOMEASSISTANT_VERSION] = \ @@ -255,10 +256,10 @@ def async_setup(hass, config): def _api_bool(funct): - """API wrapper to return Boolean.""" + """Return a boolean.""" @asyncio.coroutine def _wrapper(*argv, **kwargs): - """Wrapper function.""" + """Wrap function.""" data = yield from funct(*argv, **kwargs) return data and data['result'] == "ok" @@ -266,24 +267,24 @@ def _api_bool(funct): class HassIO(object): - """Small API wrapper for HassIO.""" + """Small API wrapper for Hass.io.""" def __init__(self, loop, websession, ip): - """Initialze HassIO api.""" + """Initialize Hass.io API.""" self.loop = loop self.websession = websession self._ip = ip @_api_bool def is_connected(self): - """Return True if it connected to HassIO supervisor. + """Return true if it connected to Hass.io supervisor. This method return a coroutine. """ return self.send_command("/supervisor/ping", method="get") def get_homeassistant_info(self): - """Return data for HomeAssistant. + """Return data for Home Assistant. This method return a coroutine. """ @@ -291,7 +292,7 @@ class HassIO(object): @_api_bool def update_hass_api(self, http_config): - """Update Home-Assistant API data on HassIO. + """Update Home Assistant API data on Hass.io. This method return a coroutine. """ @@ -305,13 +306,13 @@ class HassIO(object): if CONF_SERVER_HOST in http_config: options['watchdog'] = False - _LOGGER.warning("Don't use 'server_host' options with Hass.io!") + _LOGGER.warning("Don't use 'server_host' options with Hass.io") return self.send_command("/homeassistant/options", payload=options) @_api_bool def update_hass_timezone(self, core_config): - """Update Home-Assistant timezone data on HassIO. + """Update Home-Assistant timezone data on Hass.io. This method return a coroutine. """ @@ -321,7 +322,7 @@ class HassIO(object): @asyncio.coroutine def send_command(self, command, method="post", payload=None, timeout=10): - """Send API command to HassIO. + """Send API command to Hass.io. This method is a coroutine. """ @@ -351,7 +352,7 @@ class HassIO(object): @asyncio.coroutine def command_proxy(self, path, request): - """Return a client request with proxy origin for HassIO supervisor. + """Return a client request with proxy origin for Hass.io supervisor. This method is a coroutine. """ @@ -376,28 +377,28 @@ class HassIO(object): return client except aiohttp.ClientError as err: - _LOGGER.error("Client error on api %s request %s.", path, err) + _LOGGER.error("Client error on api %s request %s", path, err) except asyncio.TimeoutError: - _LOGGER.error("Client timeout error on api request %s.", path) + _LOGGER.error("Client timeout error on API request %s", path) raise HTTPBadGateway() class HassIOView(HomeAssistantView): - """HassIO view to handle base part.""" + """Hass.io view to handle base part.""" name = "api:hassio" url = "/api/hassio/{path:.+}" requires_auth = False def __init__(self, hassio): - """Initialize a hassio base view.""" + """Initialize a Hass.io base view.""" self.hassio = hassio @asyncio.coroutine def _handle(self, request, path): - """Route data to hassio.""" + """Route data to Hass.io.""" if _need_auth(path) and not request[KEY_AUTHENTICATED]: return web.Response(status=401) @@ -434,7 +435,7 @@ def _create_response_log(client, data): def _get_timeout(path): - """Return timeout for a url path.""" + """Return timeout for a URL path.""" for re_path in NO_TIMEOUT: if re_path.match(path): return 0 @@ -442,7 +443,7 @@ def _get_timeout(path): def _need_auth(path): - """Return if a path need a auth.""" + """Return if a path need authentication.""" for re_path in NO_AUTH: if re_path.match(path): return False diff --git a/homeassistant/components/influxdb.py b/homeassistant/components/influxdb.py index d31d1e964310..82f98449411f 100644 --- a/homeassistant/components/influxdb.py +++ b/homeassistant/components/influxdb.py @@ -5,7 +5,7 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/influxdb/ """ from datetime import timedelta -from functools import wraps, partial +from functools import partial, wraps import logging import re @@ -13,13 +13,13 @@ import requests.exceptions import voluptuous as vol from homeassistant.const import ( - EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN, CONF_HOST, - CONF_PORT, CONF_SSL, CONF_VERIFY_SSL, CONF_USERNAME, CONF_PASSWORD, - CONF_EXCLUDE, CONF_INCLUDE, CONF_DOMAINS, CONF_ENTITIES) + CONF_DOMAINS, CONF_ENTITIES, CONF_EXCLUDE, CONF_HOST, CONF_INCLUDE, + CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, + EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN) from homeassistant.helpers import state as state_helper +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_values import EntityValues from homeassistant.util import utcnow -import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['influxdb==4.1.1'] @@ -227,6 +227,7 @@ def setup(hass, config): @RetryOnError(hass, retry_limit=max_tries, retry_delay=20, queue_limit=queue_limit) def _write_data(json_body): + """Write the data.""" try: influx.write_points(json_body) except exceptions.InfluxDBClientError: @@ -268,7 +269,7 @@ class RetryOnError(object): @wraps(method) def wrapper(*args, **kwargs): - """Wrapped method.""" + """Wrap method.""" # pylint: disable=protected-access if not hasattr(wrapper, "_retry_queue"): wrapper._retry_queue = [] diff --git a/homeassistant/components/insteon_local.py b/homeassistant/components/insteon_local.py index dbe8597be3da..a18d4e0aa147 100644 --- a/homeassistant/components/insteon_local.py +++ b/homeassistant/components/insteon_local.py @@ -11,7 +11,7 @@ import requests import voluptuous as vol from homeassistant.const import ( - CONF_PASSWORD, CONF_USERNAME, CONF_HOST, CONF_PORT, CONF_TIMEOUT) + CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_TIMEOUT, CONF_USERNAME) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform @@ -37,14 +37,15 @@ CONFIG_SCHEMA = vol.Schema({ vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int + vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, }) }, extra=vol.ALLOW_EXTRA) def setup(hass, config): - """Setup insteon hub.""" + """Set up the local Insteon hub.""" from insteonlocal.Hub import Hub + conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) @@ -62,20 +63,16 @@ def setup(hass, config): # Check for successful connection insteonhub.get_buffer_status() except requests.exceptions.ConnectTimeout: - _LOGGER.error( - "Could not connect. Check config", - exc_info=True) + _LOGGER.error("Could not connect", exc_info=True) return False except requests.exceptions.ConnectionError: - _LOGGER.error( - "Could not connect. Check config", - exc_info=True) + _LOGGER.error("Could not connect", exc_info=True) return False except requests.exceptions.RequestException: if insteonhub.http_code == 401: - _LOGGER.error("Bad user/pass for insteon_local hub") + _LOGGER.error("Bad username or password for Insteon_local hub") else: - _LOGGER.error("Error on insteon_local hub check", exc_info=True) + _LOGGER.error("Error on Insteon_local hub check", exc_info=True) return False linked = insteonhub.get_linked() diff --git a/homeassistant/components/kira.py b/homeassistant/components/kira.py index 98d1228d541d..3a5ee25f05eb 100644 --- a/homeassistant/components/kira.py +++ b/homeassistant/components/kira.py @@ -1,26 +1,23 @@ -"""KIRA interface to receive UDP packets from an IR-IP bridge.""" -# pylint: disable=import-error +""" +KIRA interface to receive UDP packets from an IR-IP bridge. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/kira/ +""" import logging import os -import yaml import voluptuous as vol from voluptuous.error import Error as VoluptuousError +import yaml +from homeassistant.const import ( + CONF_DEVICE, CONF_HOST, CONF_NAME, CONF_PORT, CONF_SENSORS, CONF_TYPE, + EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv -from homeassistant.const import ( - CONF_DEVICE, - CONF_HOST, - CONF_NAME, - CONF_PORT, - CONF_SENSORS, - CONF_TYPE, - EVENT_HOMEASSISTANT_STOP, - STATE_UNKNOWN) - -REQUIREMENTS = ["pykira==0.1.1"] +REQUIREMENTS = ['pykira==0.1.1'] DOMAIN = 'kira' @@ -67,7 +64,7 @@ CONFIG_SCHEMA = vol.Schema({ def load_codes(path): - """Load Kira codes from specified file.""" + """Load KIRA codes from specified file.""" codes = [] if os.path.exists(path): with open(path) as code_file: @@ -77,7 +74,7 @@ def load_codes(path): codes.append(CODE_SCHEMA(code)) except VoluptuousError as exception: # keep going - _LOGGER.warning('Kira Code Invalid Data: %s', exception) + _LOGGER.warning("KIRA code invalid data: %s", exception) else: with open(path, 'w') as code_file: code_file.write('') @@ -85,7 +82,7 @@ def load_codes(path): def setup(hass, config): - """Setup KIRA capability.""" + """Set up the KIRA component.""" import pykira sensors = config.get(DOMAIN, {}).get(CONF_SENSORS, []) @@ -99,10 +96,10 @@ def setup(hass, config): hass.data[DOMAIN] = { CONF_SENSOR: {}, CONF_REMOTE: {}, - } + } def load_module(platform, idx, module_conf): - """Set up Kira module and load platform.""" + """Set up the KIRA module and load platform.""" # note: module_name is not the HA device name. it's just a unique name # to ensure the component and platform can share information module_name = ("%s_%d" % (DOMAIN, idx)) if idx else DOMAIN @@ -133,6 +130,7 @@ def setup(hass, config): load_module(CONF_REMOTE, idx, module_conf) def _stop_kira(_event): + """Stop the KIRA receiver.""" for receiver in hass.data[DOMAIN][CONF_SENSOR].values(): receiver.stop() _LOGGER.info("Terminated receivers") diff --git a/homeassistant/components/knx.py b/homeassistant/components/knx.py index f9747351bdd7..eb5ae9a4590e 100644 --- a/homeassistant/components/knx.py +++ b/homeassistant/components/knx.py @@ -1,22 +1,21 @@ """ - Connects to KNX platform. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ - """ -import logging import asyncio +import logging import voluptuous as vol +from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv -from homeassistant.const import EVENT_HOMEASSISTANT_STOP, \ - CONF_HOST, CONF_PORT from homeassistant.helpers.script import Script +REQUIREMENTS = ['xknx==0.7.18'] + DOMAIN = "knx" DATA_KNX = "data_knx" CONF_KNX_CONFIG = "config_file" @@ -36,12 +35,10 @@ ATTR_DISCOVER_DEVICES = 'devices' _LOGGER = logging.getLogger(__name__) -REQUIREMENTS = ['xknx==0.7.18'] - TUNNELING_SCHEMA = vol.Schema({ vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_PORT): cv.port, vol.Required(CONF_KNX_LOCAL_IP): cv.string, + vol.Optional(CONF_PORT): cv.port, }) ROUTING_SCHEMA = vol.Schema({ @@ -57,9 +54,7 @@ CONFIG_SCHEMA = vol.Schema({ vol.Inclusive(CONF_KNX_FIRE_EVENT, 'fire_ev'): cv.boolean, vol.Inclusive(CONF_KNX_FIRE_EVENT_FILTER, 'fire_ev'): - vol.All( - cv.ensure_list, - [cv.string]), + vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_KNX_STATE_UPDATER, default=True): cv.boolean, }) }, extra=vol.ALLOW_EXTRA) @@ -73,7 +68,7 @@ SERVICE_KNX_SEND_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Set up knx component.""" + """Set up the KNX component.""" from xknx.exceptions import XKNXException try: hass.data[DATA_KNX] = KNXModule(hass, config) @@ -109,6 +104,7 @@ def async_setup(hass, config): def _get_devices(hass, discovery_type): + """Get the KNX devices.""" return list( map(lambda device: device.name, filter( @@ -120,7 +116,7 @@ class KNXModule(object): """Representation of KNX Object.""" def __init__(self, hass, config): - """Initialization of KNXModule.""" + """Initialize of KNX module.""" self.hass = hass self.config = config self.connected = False @@ -129,11 +125,9 @@ class KNXModule(object): self.register_callbacks() def init_xknx(self): - """Initialization of KNX object.""" + """Initialize of KNX object.""" from xknx import XKNX - self.xknx = XKNX( - config=self.config_file(), - loop=self.hass.loop) + self.xknx = XKNX(config=self.config_file(), loop=self.hass.loop) @asyncio.coroutine def start(self): @@ -189,10 +183,8 @@ class KNXModule(object): if gateway_port is None: gateway_port = DEFAULT_MCAST_PORT return ConnectionConfig( - connection_type=ConnectionType.TUNNELING, - gateway_ip=gateway_ip, - gateway_port=gateway_port, - local_ip=local_ip) + connection_type=ConnectionType.TUNNELING, gateway_ip=gateway_ip, + gateway_port=gateway_port, local_ip=local_ip) def connection_config_auto(self): """Return the connection_config if auto is configured.""" @@ -213,7 +205,7 @@ class KNXModule(object): @asyncio.coroutine def telegram_received_cb(self, telegram): - """Callback invoked after a KNX telegram was received.""" + """Call invoked after a KNX telegram was received.""" self.hass.bus.fire('knx_event', { 'address': telegram.group_address.str(), 'data': telegram.payload.value @@ -254,8 +246,6 @@ class KNXAutomation(): import xknx self.action = xknx.devices.ActionCallback( - hass.data[DATA_KNX].xknx, - self.script.async_run, - hook=hook, - counter=counter) + hass.data[DATA_KNX].xknx, self.script.async_run, + hook=hook, counter=counter) device.actions.append(self.action) diff --git a/homeassistant/components/light/__init__.py b/homeassistant/components/light/__init__.py index 3d333e229fac..b761b04c705b 100644 --- a/homeassistant/components/light/__init__.py +++ b/homeassistant/components/light/__init__.py @@ -5,33 +5,33 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/light/ """ import asyncio +import csv from datetime import timedelta import logging import os -import csv import voluptuous as vol -from homeassistant.core import callback -from homeassistant.loader import bind_hass from homeassistant.components import group from homeassistant.const import ( - STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE, - ATTR_ENTITY_ID) + ATTR_ENTITY_ID, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, + STATE_ON) +from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity_component import EntityComponent -from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa -import homeassistant.helpers.config_validation as cv +from homeassistant.loader import bind_hass import homeassistant.util.color as color_util -DOMAIN = "light" +DOMAIN = 'light' DEPENDENCIES = ['group'] SCAN_INTERVAL = timedelta(seconds=30) GROUP_NAME_ALL_LIGHTS = 'all lights' ENTITY_ID_ALL_LIGHTS = group.ENTITY_ID_FORMAT.format('all_lights') -ENTITY_ID_FORMAT = DOMAIN + ".{}" +ENTITY_ID_FORMAT = DOMAIN + '.{}' # Bitfield of features supported by the light entity SUPPORT_BRIGHTNESS = 1 @@ -220,7 +220,7 @@ def toggle(hass, entity_id=None, transition=None): def preprocess_turn_on_alternatives(params): - """Processing extra data for turn light on request.""" + """Process extra data for turn light on request.""" profile = Profiles.get(params.pop(ATTR_PROFILE, None)) if profile is not None: params.setdefault(ATTR_XY_COLOR, profile[:2]) @@ -242,7 +242,7 @@ def preprocess_turn_on_alternatives(params): @asyncio.coroutine def async_setup(hass, config): - """Expose light control via statemachine and services.""" + """Expose light control via state machine and services.""" component = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_LIGHTS) yield from component.async_setup(config) diff --git a/homeassistant/components/light/greenwave.py b/homeassistant/components/light/greenwave.py index 0e99a49eaa91..c8f06a3d0f88 100644 --- a/homeassistant/components/light/greenwave.py +++ b/homeassistant/components/light/greenwave.py @@ -9,28 +9,31 @@ import logging import voluptuous as vol from homeassistant.components.light import ( - ATTR_BRIGHTNESS, Light, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS) + ATTR_BRIGHTNESS, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, Light) from homeassistant.const import CONF_HOST import homeassistant.helpers.config_validation as cv -SUPPORTED_FEATURES = (SUPPORT_BRIGHTNESS) - REQUIREMENTS = ['greenwavereality==0.2.9'] + _LOGGER = logging.getLogger(__name__) +CONF_VERSION = 'version' + +SUPPORTED_FEATURES = (SUPPORT_BRIGHTNESS) + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, - vol.Required("version"): cv.positive_int, + vol.Required(CONF_VERSION): cv.positive_int, }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup Greenwave Reality Platform.""" + """Set up the Greenwave Reality Platform.""" import greenwavereality as greenwave import os host = config.get(CONF_HOST) tokenfile = hass.config.path('.greenwave') - if config.get("version") == 3: + if config.get(CONF_VERSION) == 3: if os.path.exists(tokenfile): tokenfile = open(tokenfile) token = tokenfile.read() diff --git a/homeassistant/components/light/hue.py b/homeassistant/components/light/hue.py index f4ea04240f14..cbabaafd3fb0 100644 --- a/homeassistant/components/light/hue.py +++ b/homeassistant/components/light/hue.py @@ -14,13 +14,12 @@ import socket import voluptuous as vol import homeassistant.components.hue as hue - from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_RGB_COLOR, ATTR_TRANSITION, ATTR_XY_COLOR, EFFECT_COLORLOOP, EFFECT_RANDOM, - FLASH_LONG, FLASH_SHORT, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, - SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_RGB_COLOR, SUPPORT_TRANSITION, - SUPPORT_XY_COLOR, Light, PLATFORM_SCHEMA) + FLASH_LONG, FLASH_SHORT, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, + SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_RGB_COLOR, + SUPPORT_TRANSITION, SUPPORT_XY_COLOR, Light) from homeassistant.const import CONF_FILENAME, CONF_HOST, DEVICE_DEFAULT_NAME import homeassistant.helpers.config_validation as cv import homeassistant.util as util @@ -114,7 +113,7 @@ def update_lights(hass, bridge, add_devices): def unthrottled_update_lights(hass, bridge, add_devices): - """Internal version of update_lights.""" + """Update the lights (Internal version of update_lights).""" import phue if not bridge.configured: @@ -123,14 +122,14 @@ def unthrottled_update_lights(hass, bridge, add_devices): try: api = bridge.get_api() except phue.PhueRequestTimeout: - _LOGGER.warning('Timeout trying to reach the bridge') + _LOGGER.warning("Timeout trying to reach the bridge") return except ConnectionRefusedError: - _LOGGER.error('The bridge refused the connection') + _LOGGER.error("The bridge refused the connection") return except socket.error: # socket.error when we cannot reach Hue - _LOGGER.exception('Cannot reach the bridge') + _LOGGER.exception("Cannot reach the bridge") return new_lights = process_lights( @@ -151,7 +150,7 @@ def process_lights(hass, api, bridge, update_lights_cb): api_lights = api.get('lights') if not isinstance(api_lights, dict): - _LOGGER.error('Got unexpected result from Hue API') + _LOGGER.error("Got unexpected result from Hue API") return [] new_lights = [] @@ -186,8 +185,8 @@ def process_groups(hass, api, bridge, update_lights_cb): for lightgroup_id, info in api_groups.items(): if 'state' not in info: - _LOGGER.warning('Group info does not contain state. ' - 'Please update your hub.') + _LOGGER.warning( + "Group info does not contain state. Please update your hub") return [] if lightgroup_id not in bridge.lightgroups: diff --git a/homeassistant/components/light/iglo.py b/homeassistant/components/light/iglo.py index 11366ffc45cf..a2eed36a089d 100644 --- a/homeassistant/components/light/iglo.py +++ b/homeassistant/components/light/iglo.py @@ -9,13 +9,10 @@ import math import voluptuous as vol -from homeassistant.const import (CONF_HOST, CONF_NAME, CONF_PORT) from homeassistant.components.light import ( - ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_COLOR_TEMP, - SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR, - Light, PLATFORM_SCHEMA -) - + ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_RGB_COLOR, PLATFORM_SCHEMA, + SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR, Light) +from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util diff --git a/homeassistant/components/light/knx.py b/homeassistant/components/light/knx.py index c1caf91db451..732cfe2a6442 100644 --- a/homeassistant/components/light/knx.py +++ b/homeassistant/components/light/knx.py @@ -5,11 +5,12 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES -from homeassistant.components.light import PLATFORM_SCHEMA, Light, \ - SUPPORT_BRIGHTNESS, ATTR_BRIGHTNESS +from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, Light) from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -32,20 +33,17 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): - """Set up light(s) for KNX platform.""" +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): + """Set up lights for KNX platform.""" if DATA_KNX not in hass.data \ or not hass.data[DATA_KNX].initialized: - return False + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): @@ -77,7 +75,7 @@ class KNXLight(Light): """Representation of a KNX light.""" def __init__(self, hass, device): - """Initialization of KNXLight.""" + """Initialize of KNX light.""" self.device = device self.hass = hass self.async_register_callbacks() @@ -87,7 +85,7 @@ class KNXLight(Light): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) diff --git a/homeassistant/components/light/lifx.py b/homeassistant/components/light/lifx.py index 22ec58f65cd8..090341e42556 100644 --- a/homeassistant/components/light/lifx.py +++ b/homeassistant/components/light/lifx.py @@ -4,29 +4,28 @@ Support for the LIFX platform that implements lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.lifx/ """ -import logging import asyncio -import sys -import math -from functools import partial from datetime import timedelta +from functools import partial +import logging +import math +import sys import voluptuous as vol +from homeassistant import util from homeassistant.components.light import ( - Light, DOMAIN, PLATFORM_SCHEMA, LIGHT_TURN_ON_SCHEMA, - ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_PCT, ATTR_COLOR_NAME, ATTR_RGB_COLOR, - ATTR_XY_COLOR, ATTR_COLOR_TEMP, ATTR_KELVIN, ATTR_TRANSITION, ATTR_EFFECT, - SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR, - SUPPORT_XY_COLOR, SUPPORT_TRANSITION, SUPPORT_EFFECT, - VALID_BRIGHTNESS, VALID_BRIGHTNESS_PCT, + ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_PCT, ATTR_COLOR_NAME, ATTR_COLOR_TEMP, + ATTR_EFFECT, ATTR_KELVIN, ATTR_RGB_COLOR, ATTR_TRANSITION, ATTR_XY_COLOR, + DOMAIN, LIGHT_TURN_ON_SCHEMA, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, + SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_RGB_COLOR, SUPPORT_TRANSITION, + SUPPORT_XY_COLOR, VALID_BRIGHTNESS, VALID_BRIGHTNESS_PCT, Light, preprocess_turn_on_alternatives) from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_STOP -from homeassistant import util from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.service import extract_entity_ids -import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util _LOGGER = logging.getLogger(__name__) @@ -296,12 +295,12 @@ class LIFXManager(object): @callback def register(self, device): - """Handler for newly detected bulb.""" + """Handle newly detected bulb.""" self.hass.async_add_job(self.async_register(device)) @asyncio.coroutine def async_register(self, device): - """Handler for newly detected bulb.""" + """Handle newly detected bulb.""" if device.mac_addr in self.entities: entity = self.entities[device.mac_addr] entity.registered = True diff --git a/homeassistant/components/light/mysensors.py b/homeassistant/components/light/mysensors.py index c41f480c67e1..9a48b13ed3b1 100644 --- a/homeassistant/components/light/mysensors.py +++ b/homeassistant/components/light/mysensors.py @@ -16,7 +16,7 @@ SUPPORT_MYSENSORS = (SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR | def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the mysensors platform for lights.""" + """Set up the MySensors platform for lights.""" device_class_map = { 'S_DIMMER': MySensorsLightDimmer, 'S_RGB_LIGHT': MySensorsLightRGB, diff --git a/homeassistant/components/light/osramlightify.py b/homeassistant/components/light/osramlightify.py index 5785f0f1fc79..ff526c4783d9 100644 --- a/homeassistant/components/light/osramlightify.py +++ b/homeassistant/components/light/osramlightify.py @@ -63,7 +63,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): setup_bridge(bridge, add_devices, add_groups) -def setup_bridge(bridge, add_devices_callback, add_groups): +def setup_bridge(bridge, add_devices, add_groups): """Set up the Lightify bridge.""" lights = {} @@ -100,7 +100,7 @@ def setup_bridge(bridge, add_devices_callback, add_groups): lights[group_name].group = group if new_lights: - add_devices_callback(new_lights) + add_devices(new_lights) update_lights() @@ -109,7 +109,7 @@ class Luminary(Light): """Representation of Luminary Lights and Groups.""" def __init__(self, luminary, update_lights): - """Initize a Luminary light.""" + """Initialize a Luminary light.""" self.update_lights = update_lights self._luminary = luminary self._brightness = None diff --git a/homeassistant/components/light/wink.py b/homeassistant/components/light/wink.py index 445fe8ceb25f..02605d24faf8 100644 --- a/homeassistant/components/light/wink.py +++ b/homeassistant/components/light/wink.py @@ -10,7 +10,7 @@ import colorsys from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_RGB_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR, Light) -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.util import color as color_util from homeassistant.util.color import \ color_temperature_mired_to_kelvin as mired_to_kelvin @@ -39,7 +39,7 @@ class WinkLight(WinkDevice, Light): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['light'].append(self) @property diff --git a/homeassistant/components/lock/nuki.py b/homeassistant/components/lock/nuki.py index 6efa3dcb80c8..4fe05279919a 100644 --- a/homeassistant/components/lock/nuki.py +++ b/homeassistant/components/lock/nuki.py @@ -10,10 +10,10 @@ import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.components.lock import (DOMAIN, LockDevice, PLATFORM_SCHEMA) +from homeassistant.components.lock import DOMAIN, PLATFORM_SCHEMA, LockDevice from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, CONF_PORT, CONF_TOKEN) +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.service import extract_entity_ids REQUIREMENTS = ['pynuki==1.3.1'] @@ -25,7 +25,12 @@ DEFAULT_PORT = 8080 ATTR_BATTERY_CRITICAL = 'battery_critical' ATTR_NUKI_ID = 'nuki_id' ATTR_UNLATCH = 'unlatch' + +MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5) +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=30) + NUKI_DATA = 'nuki' + SERVICE_LOCK_N_GO = 'nuki_lock_n_go' SERVICE_UNLATCH = 'nuki_unlatch' @@ -44,9 +49,6 @@ UNLATCH_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids }) -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=30) -MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=5) - # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): @@ -93,7 +95,7 @@ class NukiLock(LockDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" if NUKI_DATA not in self.hass.data: self.hass.data[NUKI_DATA] = {} if DOMAIN not in self.hass.data[NUKI_DATA]: diff --git a/homeassistant/components/lock/tesla.py b/homeassistant/components/lock/tesla.py index 80a35adb5fbf..4d24ed200035 100644 --- a/homeassistant/components/lock/tesla.py +++ b/homeassistant/components/lock/tesla.py @@ -7,7 +7,8 @@ https://home-assistant.io/components/lock.tesla/ import logging from homeassistant.components.lock import ENTITY_ID_FORMAT, LockDevice -from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN, TeslaDevice +from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN +from homeassistant.components.tesla import TeslaDevice from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED _LOGGER = logging.getLogger(__name__) @@ -26,7 +27,7 @@ class TeslaLock(TeslaDevice, LockDevice): """Representation of a Tesla door lock.""" def __init__(self, tesla_device, controller): - """Initialisation of the lock.""" + """Initialise of the lock.""" self._state = None super().__init__(tesla_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.tesla_id) @@ -47,7 +48,7 @@ class TeslaLock(TeslaDevice, LockDevice): return self._state == STATE_LOCKED def update(self): - """Updating state of the lock.""" + """Update state of the lock.""" _LOGGER.debug("Updating state for: %s", self._name) self.tesla_device.update() self._state = STATE_LOCKED if self.tesla_device.is_locked() \ diff --git a/homeassistant/components/lock/wink.py b/homeassistant/components/lock/wink.py index 118a8d8f6645..a5cd18454df5 100644 --- a/homeassistant/components/lock/wink.py +++ b/homeassistant/components/lock/wink.py @@ -10,9 +10,9 @@ import logging import voluptuous as vol from homeassistant.components.lock import LockDevice -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice +from homeassistant.const import ATTR_CODE, ATTR_ENTITY_ID, STATE_UNKNOWN import homeassistant.helpers.config_validation as cv -from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, ATTR_CODE DEPENDENCIES = ['wink'] @@ -30,13 +30,19 @@ ATTR_SENSITIVITY = 'sensitivity' ATTR_MODE = 'mode' ATTR_NAME = 'name' -ALARM_SENSITIVITY_MAP = {"low": 0.2, "medium_low": 0.4, - "medium": 0.6, "medium_high": 0.8, - "high": 1.0} +ALARM_SENSITIVITY_MAP = { + 'low': 0.2, + 'medium_low': 0.4, + 'medium': 0.6, + 'medium_high': 0.8, + 'high': 1.0, +} -ALARM_MODES_MAP = {"tamper": "tamper", - "activity": "alert", - "forced_entry": "forced_entry"} +ALARM_MODES_MAP = { + 'activity': 'alert', + 'forced_entry': 'forced_entry', + 'tamper': 'tamper', +} SET_ENABLED_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, @@ -70,7 +76,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): add_devices([WinkLockDevice(lock, hass)]) def service_handle(service): - """Handler for services.""" + """Handle for services.""" entity_ids = service.data.get('entity_id') all_locks = hass.data[DOMAIN]['entities']['lock'] locks_to_set = [] @@ -127,7 +133,7 @@ class WinkLockDevice(WinkDevice, LockDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['lock'].append(self) @property diff --git a/homeassistant/components/media_player/bluesound.py b/homeassistant/components/media_player/bluesound.py index 1f86056efb52..ca6b152a37ea 100644 --- a/homeassistant/components/media_player/bluesound.py +++ b/homeassistant/components/media_player/bluesound.py @@ -1,5 +1,5 @@ """ -Bluesound. +Support for Bluesound devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.bluesound/ @@ -16,14 +16,14 @@ import async_timeout import voluptuous as vol from homeassistant.components.media_player import ( - SUPPORT_PLAY, SUPPORT_SEEK, SUPPORT_STOP, SUPPORT_PAUSE, PLATFORM_SCHEMA, - MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PLAY_MEDIA, - SUPPORT_VOLUME_SET, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, - SUPPORT_SELECT_SOURCE, SUPPORT_CLEAR_PLAYLIST, SUPPORT_PREVIOUS_TRACK, + MEDIA_TYPE_MUSIC, PLATFORM_SCHEMA, SUPPORT_CLEAR_PLAYLIST, + SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, + SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_SELECT_SOURCE, SUPPORT_STOP, + SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, MediaPlayerDevice) from homeassistant.const import ( - CONF_HOST, CONF_NAME, CONF_PORT, CONF_HOSTS, STATE_IDLE, STATE_PAUSED, - STATE_PLAYING, EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START) + CONF_HOST, CONF_HOSTS, CONF_NAME, CONF_PORT, EVENT_HOMEASSISTANT_START, + EVENT_HOMEASSISTANT_STOP, STATE_IDLE, STATE_PAUSED, STATE_PLAYING) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -60,6 +60,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def _add_player(hass, async_add_devices, host, port=None, name=None): + """Add Bluesound players.""" if host in [x.host for x in hass.data[DATA_BLUESOUND]]: return @@ -108,8 +109,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): hass.data[DATA_BLUESOUND] = [] if discovery_info: - _add_player(hass, async_add_devices, discovery_info.get('host'), - discovery_info.get('port', None)) + _add_player(hass, async_add_devices, discovery_info.get(CONF_HOST), + discovery_info.get(CONF_PORT, None)) return hosts = config.get(CONF_HOSTS, None) @@ -117,11 +118,11 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): for host in hosts: _add_player( hass, async_add_devices, host.get(CONF_HOST), - host.get(CONF_PORT), host.get(CONF_NAME, None)) + host.get(CONF_PORT), host.get(CONF_NAME)) class BluesoundPlayer(MediaPlayerDevice): - """Bluesound Player Object.""" + """Represenatation of a Bluesound Player.""" def __init__(self, hass, host, port=None, name=None, init_callback=None): """Initialize the media player.""" @@ -150,6 +151,7 @@ class BluesoundPlayer(MediaPlayerDevice): @staticmethod def _try_get_index(string, seach_string): + """Get the index.""" try: return string.index(seach_string) except ValueError: @@ -158,6 +160,7 @@ class BluesoundPlayer(MediaPlayerDevice): @asyncio.coroutine def _internal_update_sync_status( self, on_updated_cb=None, raise_timeout=False): + """Update the internal status.""" resp = None try: resp = yield from self.send_bluesound_command( @@ -186,7 +189,7 @@ class BluesoundPlayer(MediaPlayerDevice): @asyncio.coroutine def _start_poll_command(self): - """"Loop which polls the status of the player.""" + """Loop which polls the status of the player.""" try: while True: yield from self.async_update_status() @@ -214,7 +217,7 @@ class BluesoundPlayer(MediaPlayerDevice): @asyncio.coroutine def async_init(self): - """Initiate the player async.""" + """Initialize the player async.""" try: if self._retry_remove is not None: self._retry_remove() @@ -284,7 +287,7 @@ class BluesoundPlayer(MediaPlayerDevice): @asyncio.coroutine def async_update_status(self): - """Using the poll session to always get the status of the player.""" + """Use the poll session to always get the status of the player.""" import xmltodict response = None diff --git a/homeassistant/components/media_player/monoprice.py b/homeassistant/components/media_player/monoprice.py index c95ddcab97e8..d26fce0ea88b 100644 --- a/homeassistant/components/media_player/monoprice.py +++ b/homeassistant/components/media_player/monoprice.py @@ -8,14 +8,13 @@ import logging import voluptuous as vol -from homeassistant.const import (ATTR_ENTITY_ID, CONF_NAME, CONF_PORT, - STATE_OFF, STATE_ON) -import homeassistant.helpers.config_validation as cv from homeassistant.components.media_player import ( - DOMAIN, MediaPlayerDevice, MEDIA_PLAYER_SCHEMA, PLATFORM_SCHEMA, - SUPPORT_VOLUME_MUTE, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_ON, - SUPPORT_TURN_OFF, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP) - + DOMAIN, MEDIA_PLAYER_SCHEMA, PLATFORM_SCHEMA, SUPPORT_SELECT_SOURCE, + SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, + SUPPORT_VOLUME_STEP, MediaPlayerDevice) +from homeassistant.const import ( + ATTR_ENTITY_ID, CONF_NAME, CONF_PORT, STATE_OFF, STATE_ON) +import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pymonoprice==0.3'] @@ -42,9 +41,9 @@ SERVICE_SNAPSHOT = 'snapshot' SERVICE_RESTORE = 'restore' # Valid zone ids: 11-16 or 21-26 or 31-36 -ZONE_IDS = vol.All(vol.Coerce(int), vol.Any(vol.Range(min=11, max=16), - vol.Range(min=21, max=26), - vol.Range(min=31, max=36))) +ZONE_IDS = vol.All(vol.Coerce(int), vol.Any( + vol.Range(min=11, max=16), vol.Range(min=21, max=26), + vol.Range(min=31, max=36))) # Valid source ids: 1-6 SOURCE_IDS = vol.All(vol.Coerce(int), vol.Range(min=1, max=6)) @@ -66,7 +65,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: monoprice = get_monoprice(port) except SerialException: - _LOGGER.error('Error connecting to Monoprice controller.') + _LOGGER.error("Error connecting to Monoprice controller") return sources = {source_id: extra[CONF_NAME] for source_id, extra @@ -75,9 +74,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): hass.data[DATA_MONOPRICE] = [] for zone_id, extra in config[CONF_ZONES].items(): _LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME]) - hass.data[DATA_MONOPRICE].append(MonopriceZone(monoprice, sources, - zone_id, - extra[CONF_NAME])) + hass.data[DATA_MONOPRICE].append(MonopriceZone( + monoprice, sources, zone_id, extra[CONF_NAME])) add_devices(hass.data[DATA_MONOPRICE], True) @@ -98,19 +96,15 @@ def setup_platform(hass, config, add_devices, discovery_info=None): device.restore() hass.services.register( - DOMAIN, SERVICE_SNAPSHOT, service_handle, - schema=MEDIA_PLAYER_SCHEMA) + DOMAIN, SERVICE_SNAPSHOT, service_handle, schema=MEDIA_PLAYER_SCHEMA) hass.services.register( - DOMAIN, SERVICE_RESTORE, service_handle, - schema=MEDIA_PLAYER_SCHEMA) + DOMAIN, SERVICE_RESTORE, service_handle, schema=MEDIA_PLAYER_SCHEMA) class MonopriceZone(MediaPlayerDevice): """Representation of a a Monoprice amplifier zone.""" - # pylint: disable=too-many-public-methods - def __init__(self, monoprice, sources, zone_id, zone_name): """Initialize new zone.""" self._monoprice = monoprice @@ -179,7 +173,7 @@ class MonopriceZone(MediaPlayerDevice): @property def source(self): - """"Return the current input source of the device.""" + """Return the current input source of the device.""" return self._source @property @@ -224,12 +218,10 @@ class MonopriceZone(MediaPlayerDevice): """Volume up the media player.""" if self._volume is None: return - self._monoprice.set_volume(self._zone_id, - min(self._volume + 1, 38)) + self._monoprice.set_volume(self._zone_id, min(self._volume + 1, 38)) def volume_down(self): """Volume down media player.""" if self._volume is None: return - self._monoprice.set_volume(self._zone_id, - max(self._volume - 1, 0)) + self._monoprice.set_volume(self._zone_id, max(self._volume - 1, 0)) diff --git a/homeassistant/components/media_player/mpd.py b/homeassistant/components/media_player/mpd.py index c661e2a3b58a..4307b68e709d 100644 --- a/homeassistant/components/media_player/mpd.py +++ b/homeassistant/components/media_player/mpd.py @@ -4,22 +4,22 @@ Support to interact with a Music Player Daemon. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.mpd/ """ +from datetime import timedelta import logging import os -from datetime import timedelta import voluptuous as vol from homeassistant.components.media_player import ( - MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, PLATFORM_SCHEMA, - SUPPORT_PREVIOUS_TRACK, SUPPORT_STOP, SUPPORT_PLAY, - SUPPORT_VOLUME_SET, SUPPORT_PLAY_MEDIA, MEDIA_TYPE_PLAYLIST, - SUPPORT_SELECT_SOURCE, SUPPORT_CLEAR_PLAYLIST, SUPPORT_SHUFFLE_SET, - SUPPORT_SEEK, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, - SUPPORT_TURN_OFF, SUPPORT_TURN_ON, MediaPlayerDevice) + MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, PLATFORM_SCHEMA, + SUPPORT_CLEAR_PLAYLIST, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, + SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, + SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, SUPPORT_TURN_OFF, + SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, + SUPPORT_VOLUME_STEP, MediaPlayerDevice) from homeassistant.const import ( - STATE_OFF, STATE_PAUSED, STATE_PLAYING, - CONF_PORT, CONF_PASSWORD, CONF_HOST, CONF_NAME) + CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, STATE_OFF, STATE_PAUSED, + STATE_PLAYING) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle @@ -116,7 +116,7 @@ class MpdDevice(MediaPlayerDevice): @property def available(self): - """True if MPD is available and connected.""" + """Return true if MPD is available and connected.""" return self._is_connected def update(self): diff --git a/homeassistant/components/media_player/nadtcp.py b/homeassistant/components/media_player/nadtcp.py index 707a0c29eafb..06ec3c04cbe5 100644 --- a/homeassistant/components/media_player/nadtcp.py +++ b/homeassistant/components/media_player/nadtcp.py @@ -5,14 +5,14 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.nadtcp/ """ import logging + import voluptuous as vol + from homeassistant.components.media_player import ( - SUPPORT_VOLUME_SET, - SUPPORT_VOLUME_MUTE, SUPPORT_TURN_ON, SUPPORT_TURN_OFF, - SUPPORT_VOLUME_STEP, SUPPORT_SELECT_SOURCE, MediaPlayerDevice, - PLATFORM_SCHEMA) -from homeassistant.const import ( - CONF_NAME, STATE_OFF, STATE_ON) + PLATFORM_SCHEMA, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, + SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, + MediaPlayerDevice) +from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['nad_receiver==0.0.9'] @@ -30,7 +30,6 @@ SUPPORT_NAD = SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_TURN_ON | \ CONF_MIN_VOLUME = 'min_volume' CONF_MAX_VOLUME = 'max_volume' CONF_VOLUME_STEP = 'volume_step' -CONF_HOST = 'host' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, @@ -42,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the NAD platform.""" + """Set up the NAD platform.""" from nad_receiver import NADReceiverTCP add_devices([NADtcp( NADReceiverTCP(config.get(CONF_HOST)), diff --git a/homeassistant/components/media_player/snapcast.py b/homeassistant/components/media_player/snapcast.py index 2413de136ab7..793800a3d225 100644 --- a/homeassistant/components/media_player/snapcast.py +++ b/homeassistant/components/media_player/snapcast.py @@ -11,11 +11,11 @@ import socket import voluptuous as vol from homeassistant.components.media_player import ( - SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_SELECT_SOURCE, - DOMAIN, PLATFORM_SCHEMA, MediaPlayerDevice) + DOMAIN, PLATFORM_SCHEMA, SUPPORT_SELECT_SOURCE, SUPPORT_VOLUME_MUTE, + SUPPORT_VOLUME_SET, MediaPlayerDevice) from homeassistant.const import ( - STATE_ON, STATE_OFF, STATE_IDLE, STATE_PLAYING, STATE_UNKNOWN, CONF_HOST, - CONF_PORT, ATTR_ENTITY_ID) + ATTR_ENTITY_ID, CONF_HOST, CONF_PORT, STATE_IDLE, STATE_OFF, STATE_ON, + STATE_PLAYING, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['snapcast==2.0.8'] @@ -42,14 +42,14 @@ SERVICE_SCHEMA = vol.Schema({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, - vol.Optional(CONF_PORT): cv.port + vol.Optional(CONF_PORT): cv.port, }) # pylint: disable=unused-argument @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the Snapcast platform.""" + """Set up the Snapcast platform.""" import snapcast.control from snapcast.control.server import CONTROL_PORT host = config.get(CONF_HOST) @@ -68,25 +68,23 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None): yield from device.async_restore() hass.services.async_register( - DOMAIN, SERVICE_SNAPSHOT, _handle_service, - schema=SERVICE_SCHEMA) + DOMAIN, SERVICE_SNAPSHOT, _handle_service, schema=SERVICE_SCHEMA) hass.services.async_register( - DOMAIN, SERVICE_RESTORE, _handle_service, - schema=SERVICE_SCHEMA) + DOMAIN, SERVICE_RESTORE, _handle_service, schema=SERVICE_SCHEMA) try: server = yield from snapcast.control.create_server( hass.loop, host, port, reconnect=True) except socket.gaierror: - _LOGGER.error('Could not connect to Snapcast server at %s:%d', + _LOGGER.error("Could not connect to Snapcast server at %s:%d", host, port) - return False + return + groups = [SnapcastGroupDevice(group) for group in server.groups] clients = [SnapcastClientDevice(client) for client in server.clients] devices = groups + clients hass.data[DATA_KEY] = devices async_add_devices(devices) - return True class SnapcastGroupDevice(MediaPlayerDevice): diff --git a/homeassistant/components/media_player/sonos.py b/homeassistant/components/media_player/sonos.py index 947b86ce2818..d4a7fd3adb58 100644 --- a/homeassistant/components/media_player/sonos.py +++ b/homeassistant/components/media_player/sonos.py @@ -14,14 +14,14 @@ import urllib import voluptuous as vol from homeassistant.components.media_player import ( - ATTR_MEDIA_ENQUEUE, DOMAIN, MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, - SUPPORT_PAUSE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, - SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_CLEAR_PLAYLIST, - SUPPORT_SELECT_SOURCE, MediaPlayerDevice, PLATFORM_SCHEMA, SUPPORT_STOP, - SUPPORT_PLAY, SUPPORT_SHUFFLE_SET) + ATTR_MEDIA_ENQUEUE, DOMAIN, MEDIA_TYPE_MUSIC, PLATFORM_SCHEMA, + SUPPORT_CLEAR_PLAYLIST, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, + SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, + SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, + SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, MediaPlayerDevice) from homeassistant.const import ( - STATE_IDLE, STATE_PAUSED, STATE_PLAYING, STATE_OFF, ATTR_ENTITY_ID, - CONF_HOSTS, ATTR_TIME) + ATTR_ENTITY_ID, ATTR_TIME, CONF_HOSTS, STATE_IDLE, STATE_OFF, STATE_PAUSED, + STATE_PLAYING) import homeassistant.helpers.config_validation as cv from homeassistant.util.dt import utcnow @@ -126,7 +126,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if discovery_info: player = soco.SoCo(discovery_info.get('host')) - # if device already exists by config + # If device already exists by config if player.uid in [x.unique_id for x in hass.data[DATA_SONOS]]: return @@ -167,7 +167,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): add_devices(coordinators, True) if slaves: add_devices(slaves, True) - _LOGGER.info("Added %s Sonos speakers", len(players)) + _LOGGER.debug("Added %s Sonos speakers", len(players)) def service_handle(service): """Handle for services.""" @@ -242,10 +242,11 @@ def _parse_timespan(timespan): reversed(timespan.split(':')))) -class _ProcessSonosEventQueue(): +class _ProcessSonosEventQueue(object): """Queue like object for dispatching sonos events.""" def __init__(self, sonos_device): + """Initialize Sonos event queue.""" self._sonos_device = sonos_device def put(self, item, block=True, timeout=None): @@ -266,7 +267,7 @@ def _get_entity_from_soco(hass, soco): def soco_error(errorcodes=None): """Filter out specified UPnP errors from logs and avoid exceptions.""" def decorator(funct): - """Decorator function.""" + """Decorate functions.""" @ft.wraps(funct) def wrapper(*args, **kwargs): """Wrap for all soco UPnP exception.""" diff --git a/homeassistant/components/media_player/vizio.py b/homeassistant/components/media_player/vizio.py index 5d6e6fcf6dde..64d1f642e6e7 100644 --- a/homeassistant/components/media_player/vizio.py +++ b/homeassistant/components/media_player/vizio.py @@ -1,36 +1,23 @@ """ Vizio SmartCast TV support. -Usually only 2016+ models come with SmartCast capabilities. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.vizio/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol -import homeassistant.util as util from homeassistant.components.media_player import ( - PLATFORM_SCHEMA, - SUPPORT_TURN_ON, - SUPPORT_TURN_OFF, - SUPPORT_SELECT_SOURCE, - SUPPORT_PREVIOUS_TRACK, - SUPPORT_NEXT_TRACK, - SUPPORT_VOLUME_MUTE, - SUPPORT_VOLUME_STEP, - MediaPlayerDevice -) + PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PREVIOUS_TRACK, + SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, + SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, MediaPlayerDevice) from homeassistant.const import ( - STATE_UNKNOWN, - STATE_OFF, - STATE_ON, - CONF_NAME, - CONF_HOST, - CONF_ACCESS_TOKEN -) + CONF_ACCESS_TOKEN, CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON, + STATE_UNKNOWN) from homeassistant.helpers import config_validation as cv +import homeassistant.util as util REQUIREMENTS = ['pyvizio==0.0.2'] @@ -39,13 +26,16 @@ _LOGGER = logging.getLogger(__name__) CONF_SUPPRESS_WARNING = 'suppress_warning' CONF_VOLUME_STEP = 'volume_step' -ICON = 'mdi:television' DEFAULT_NAME = 'Vizio SmartCast' DEFAULT_VOLUME_STEP = 1 -DEVICE_NAME = 'Python Vizio' DEVICE_ID = 'pyvizio' -MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) +DEVICE_NAME = 'Python Vizio' + +ICON = 'mdi:television' + MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1) +MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) + SUPPORTED_COMMANDS = SUPPORT_TURN_ON | SUPPORT_TURN_OFF \ | SUPPORT_SELECT_SOURCE \ | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK \ @@ -70,14 +60,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None): device = VizioDevice(host, token, name, volume_step) if device.validate_setup() is False: - _LOGGER.error('Failed to setup Vizio TV platform, ' - 'please check if host and API key are correct.') - return False + _LOGGER.error("Failed to setup Vizio TV platform, " + "please check if host and API key are correct") + return if config.get(CONF_SUPPRESS_WARNING): from requests.packages import urllib3 - _LOGGER.warning('InsecureRequestWarning is disabled ' - 'because of Vizio platform configuration.') + _LOGGER.warning("InsecureRequestWarning is disabled " + "because of Vizio platform configuration") urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) add_devices([device], True) @@ -184,5 +174,5 @@ class VizioDevice(MediaPlayerDevice): self._device.vol_down(num=self._volume_step) def validate_setup(self): - """Validating if host is available and key is correct.""" + """Validate if host is available and key is correct.""" return self._device.get_current_volume() is not None diff --git a/homeassistant/components/media_player/webostv.py b/homeassistant/components/media_player/webostv.py index 9d3e0b90fa44..55179ed60a91 100644 --- a/homeassistant/components/media_player/webostv.py +++ b/homeassistant/components/media_player/webostv.py @@ -4,30 +4,26 @@ Support for interface with an LG webOS Smart TV. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.webostv/ """ -import logging import asyncio from datetime import timedelta +import logging from urllib.parse import urlparse import voluptuous as vol -import homeassistant.util as util from homeassistant.components.media_player import ( - SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_PLAY, - SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, - SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, - SUPPORT_SELECT_SOURCE, SUPPORT_PLAY_MEDIA, MEDIA_TYPE_CHANNEL, - MediaPlayerDevice, PLATFORM_SCHEMA) + MEDIA_TYPE_CHANNEL, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, + SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, + SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, + SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, MediaPlayerDevice) from homeassistant.const import ( - CONF_HOST, CONF_CUSTOMIZE, CONF_TIMEOUT, STATE_OFF, - STATE_PLAYING, STATE_PAUSED, - STATE_UNKNOWN, CONF_NAME, CONF_FILENAME) + CONF_CUSTOMIZE, CONF_FILENAME, CONF_HOST, CONF_NAME, CONF_TIMEOUT, + STATE_OFF, STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.script import Script +import homeassistant.util as util -REQUIREMENTS = ['pylgtv==0.1.7', - 'websockets==3.2', - 'wakeonlan==0.2.2'] +REQUIREMENTS = ['pylgtv==0.1.7', 'websockets==3.2', 'wakeonlan==0.2.2'] _CONFIGURING = {} # type: Dict[str, str] _LOGGER = logging.getLogger(__name__) @@ -48,17 +44,16 @@ MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1) CUSTOMIZE_SCHEMA = vol.Schema({ - vol.Optional(CONF_SOURCES): - vol.All(cv.ensure_list, [cv.string]), + vol.Optional(CONF_SOURCES): vol.All(cv.ensure_list, [cv.string]), }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, - vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_CUSTOMIZE, default={}): CUSTOMIZE_SCHEMA, vol.Optional(CONF_FILENAME, default=WEBOSTV_CONFIG_FILE): cv.string, - vol.Optional(CONF_TIMEOUT, default=8): cv.positive_int, + vol.Optional(CONF_HOST): cv.string, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_ON_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_TIMEOUT, default=8): cv.positive_int, }) @@ -142,7 +137,7 @@ def request_configuration( # pylint: disable=unused-argument def lgtv_configuration_callback(data): - """The actions to do when our configuration callback is called.""" + """Handle actions when configuration callback is called.""" setup_tv(host, name, customize, config, timeout, hass, add_devices, turn_on_action) diff --git a/homeassistant/components/mychevy.py b/homeassistant/components/mychevy.py index 3a4894a2a663..678cdf10c567 100644 --- a/homeassistant/components/mychevy.py +++ b/homeassistant/components/mychevy.py @@ -4,16 +4,14 @@ MyChevy Component. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/mychevy/ """ - from datetime import timedelta import logging -import time import threading +import time import voluptuous as vol -from homeassistant.const import ( - CONF_USERNAME, CONF_PASSWORD) +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import config_validation as cv from homeassistant.helpers import discovery from homeassistant.util import Throttle @@ -38,16 +36,16 @@ ERROR_SLEEP_TIME = timedelta(minutes=30) CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, - vol.Required(CONF_PASSWORD): cv.string + vol.Required(CONF_PASSWORD): cv.string, }), }, extra=vol.ALLOW_EXTRA) class EVSensorConfig(object): - """EV Sensor Config.""" + """The EV sensor configuration.""" def __init__(self, name, attr, unit_of_measurement=None, icon=None): - """Create new Sensor Config.""" + """Create new sensor configuration.""" self.name = name self.attr = attr self.unit_of_measurement = unit_of_measurement @@ -55,17 +53,17 @@ class EVSensorConfig(object): class EVBinarySensorConfig(object): - """EV Binary Sensor Config.""" + """The EV binary sensor configuration.""" def __init__(self, name, attr, device_class=None): - """Create new Binary Sensor Config.""" + """Create new binary sensor configuration.""" self.name = name self.attr = attr self.device_class = device_class def setup(hass, base_config): - """Setup mychevy platform.""" + """Set up the mychevy component.""" import mychevy.mychevy as mc config = base_config.get(DOMAIN) diff --git a/homeassistant/components/mysensors.py b/homeassistant/components/mysensors.py index 71be416c59c8..91053b41bf6b 100644 --- a/homeassistant/components/mysensors.py +++ b/homeassistant/components/mysensors.py @@ -1,8 +1,8 @@ """ Connect to a MySensors gateway via pymysensors API. -For more details about this platform, please refer to the documentation at -https://home-assistant.io/components/sensor.mysensors/ +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/mysensors/ """ import asyncio from collections import defaultdict @@ -115,21 +115,20 @@ def is_serial_port(value): if value in ports: return value else: - raise vol.Invalid( - '{} is not a serial port'.format(value)) + raise vol.Invalid('{} is not a serial port'.format(value)) else: return cv.isdevice(value) def deprecated(key): - """Mark key as deprecated in config.""" + """Mark key as deprecated in configuration.""" def validator(config): """Check if key is in config, log warning and remove key.""" if key not in config: return config _LOGGER.warning( '%s option for %s is deprecated. Please remove %s from your ' - 'configuration file.', key, DOMAIN, key) + 'configuration file', key, DOMAIN, key) config.pop(key) return config return validator @@ -150,16 +149,13 @@ CONFIG_SCHEMA = vol.Schema({ vol.Any(MQTT_COMPONENT, is_socket_address, is_serial_port), vol.Optional(CONF_PERSISTENCE_FILE): vol.All(cv.string, is_persistence_file, has_parent_dir), - vol.Optional( - CONF_BAUD_RATE, - default=DEFAULT_BAUD_RATE): cv.positive_int, - vol.Optional( - CONF_TCP_PORT, - default=DEFAULT_TCP_PORT): cv.port, - vol.Optional( - CONF_TOPIC_IN_PREFIX, default=''): valid_subscribe_topic, - vol.Optional( - CONF_TOPIC_OUT_PREFIX, default=''): valid_publish_topic, + vol.Optional(CONF_BAUD_RATE, default=DEFAULT_BAUD_RATE): + cv.positive_int, + vol.Optional(CONF_TCP_PORT, default=DEFAULT_TCP_PORT): cv.port, + vol.Optional(CONF_TOPIC_IN_PREFIX, default=''): + valid_subscribe_topic, + vol.Optional(CONF_TOPIC_OUT_PREFIX, default=''): + valid_publish_topic, vol.Optional(CONF_NODES, default={}): NODE_SCHEMA, }] ), @@ -171,7 +167,7 @@ CONFIG_SCHEMA = vol.Schema({ }, extra=vol.ALLOW_EXTRA) -# mysensors const schemas +# MySensors const schemas BINARY_SENSOR_SCHEMA = {PLATFORM: 'binary_sensor', TYPE: 'V_TRIPPED'} CLIMATE_SCHEMA = {PLATFORM: 'climate', TYPE: 'V_HVAC_FLOW_STATE'} LIGHT_DIMMER_SCHEMA = { @@ -439,7 +435,7 @@ def validate_child(gateway, node_id, child): def discover_mysensors_platform(hass, platform, new_devices): - """Discover a mysensors platform.""" + """Discover a MySensors platform.""" discovery.load_platform( hass, platform, DOMAIN, {ATTR_DEVICES: new_devices, CONF_NAME: DOMAIN}) @@ -458,7 +454,7 @@ def discover_persistent_devices(hass, gateway): def get_mysensors_devices(hass, domain): - """Return mysensors devices for a platform.""" + """Return MySensors devices for a platform.""" if MYSENSORS_PLATFORM_DEVICES.format(domain) not in hass.data: hass.data[MYSENSORS_PLATFORM_DEVICES.format(domain)] = {} return hass.data[MYSENSORS_PLATFORM_DEVICES.format(domain)] @@ -467,15 +463,14 @@ def get_mysensors_devices(hass, domain): def gw_callback_factory(hass): """Return a new callback for the gateway.""" def mysensors_callback(msg): - """Default callback for a mysensors gateway.""" + """Handle messages from a MySensors gateway.""" start = timer() _LOGGER.debug( "Node update: node %s child %s", msg.node_id, msg.child_id) child = msg.gateway.sensors[msg.node_id].children.get(msg.child_id) if child is None: - _LOGGER.debug( - "Not a child update for node %s", msg.node_id) + _LOGGER.debug("Not a child update for node %s", msg.node_id) return signals = [] @@ -518,7 +513,7 @@ def get_mysensors_name(gateway, node_id, child_id): def get_mysensors_gateway(hass, gateway_id): - """Return gateway.""" + """Return MySensors gateway.""" if MYSENSORS_GATEWAYS not in hass.data: hass.data[MYSENSORS_GATEWAYS] = {} gateways = hass.data.get(MYSENSORS_GATEWAYS) @@ -528,8 +523,8 @@ def get_mysensors_gateway(hass, gateway_id): def setup_mysensors_platform( hass, domain, discovery_info, device_class, device_args=None, add_devices=None): - """Set up a mysensors platform.""" - # Only act if called via mysensors by discovery event. + """Set up a MySensors platform.""" + # Only act if called via MySensors by discovery event. # Otherwise gateway is not setup. if not discovery_info: return @@ -627,7 +622,7 @@ class MySensorsEntity(MySensorsDevice, Entity): @property def should_poll(self): - """Mysensor gateway pushes its state to HA.""" + """Return the polling state. The gateway pushes its states.""" return False @property diff --git a/homeassistant/components/notify/pushbullet.py b/homeassistant/components/notify/pushbullet.py index 359810bb6bce..13cb2fd579b1 100644 --- a/homeassistant/components/notify/pushbullet.py +++ b/homeassistant/components/notify/pushbullet.py @@ -129,7 +129,7 @@ class PushBulletNotificationService(BaseNotificationService): continue def _push_data(self, message, title, data, pusher, email=None): - """Helper for creating the message content.""" + """Create the message content.""" from pushbullet import PushError if data is None: data = {} diff --git a/homeassistant/components/python_script.py b/homeassistant/components/python_script.py index a56b40f30643..b49b280791af 100644 --- a/homeassistant/components/python_script.py +++ b/homeassistant/components/python_script.py @@ -12,11 +12,11 @@ import time import voluptuous as vol -import homeassistant.util.dt as dt_util from homeassistant.const import SERVICE_RELOAD from homeassistant.exceptions import HomeAssistantError from homeassistant.loader import bind_hass from homeassistant.util import sanitize_filename +import homeassistant.util.dt as dt_util REQUIREMENTS = ['restrictedpython==4.0b2'] @@ -185,7 +185,7 @@ class StubPrinter: class TimeWrapper: - """Wrapper of the time module.""" + """Wrap the time module.""" # Class variable, only going to warn once per Home Assistant run warned = False @@ -205,7 +205,7 @@ class TimeWrapper: attribute = getattr(time, attr) if callable(attribute): def wrapper(*args, **kw): - """Wrapper to return callable method if callable.""" + """Wrap to return callable method if callable.""" return attribute(*args, **kw) return wrapper else: diff --git a/homeassistant/components/raincloud.py b/homeassistant/components/raincloud.py index 1668fce0f45c..505c3a7b2b00 100644 --- a/homeassistant/components/raincloud.py +++ b/homeassistant/components/raincloud.py @@ -5,20 +5,19 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/raincloud/ """ import asyncio -import logging from datetime import timedelta +import logging +from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.const import ( - ATTR_ATTRIBUTION, CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL) -from homeassistant.helpers.event import track_time_interval -from homeassistant.helpers.entity import Entity + ATTR_ATTRIBUTION, CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME) +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, dispatcher_send) - -from requests.exceptions import HTTPError, ConnectTimeout +from homeassistant.helpers.entity import Entity +from homeassistant.helpers.event import track_time_interval REQUIREMENTS = ['raincloudy==0.0.4'] @@ -115,7 +114,7 @@ def setup(hass, config): def hub_refresh(event_time): """Call Raincloud hub to refresh information.""" - _LOGGER.debug("Updating RainCloud Hub component.") + _LOGGER.debug("Updating RainCloud Hub component") hass.data[DATA_RAINCLOUD].data.update() dispatcher_send(hass, SIGNAL_UPDATE_RAINCLOUD) @@ -156,7 +155,7 @@ class RainCloudEntity(Entity): self.hass, SIGNAL_UPDATE_RAINCLOUD, self._update_callback) def _update_callback(self): - """Callback update method.""" + """Call update method.""" self.schedule_update_ha_state(True) @property @@ -175,5 +174,5 @@ class RainCloudEntity(Entity): @property def icon(self): - """Icon to use in the frontend, if any.""" + """Return the icon to use in the frontend, if any.""" return ICON_MAP.get(self._sensor_type) diff --git a/homeassistant/components/raspihats.py b/homeassistant/components/raspihats.py index e9d65b85c81d..e3c1ab8ff88b 100644 --- a/homeassistant/components/raspihats.py +++ b/homeassistant/components/raspihats.py @@ -9,11 +9,9 @@ import threading import time from homeassistant.const import ( - EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP -) + EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) -REQUIREMENTS = ['raspihats==2.2.3', - 'smbus-cffi==0.5.1'] +REQUIREMENTS = ['raspihats==2.2.3', 'smbus-cffi==0.5.1'] _LOGGER = logging.getLogger(__name__) @@ -37,7 +35,7 @@ I2C_HATS_MANAGER = 'I2CH_MNG' # pylint: disable=unused-argument def setup(hass, config): - """Setup the raspihats component.""" + """Set up the raspihats component.""" hass.data[I2C_HATS_MANAGER] = I2CHatsManager() def start_i2c_hats_keep_alive(event): @@ -73,13 +71,13 @@ class I2CHatsDIScanner(object): _CALLBACKS = "callbacks" def setup(self, i2c_hat): - """Setup I2C-HAT instance for digital inputs scanner.""" + """Set up the I2C-HAT instance for digital inputs scanner.""" if hasattr(i2c_hat, self._DIGITAL_INPUTS): digital_inputs = getattr(i2c_hat, self._DIGITAL_INPUTS) old_value = None - # add old value attribute + # Add old value attribute setattr(digital_inputs, self._OLD_VALUE, old_value) - # add callbacks dict attribute {channel: callback} + # Add callbacks dict attribute {channel: callback} setattr(digital_inputs, self._CALLBACKS, {}) def register_callback(self, i2c_hat, channel, callback): @@ -141,17 +139,15 @@ class I2CHatsManager(threading.Thread): self._i2c_hats[address] = i2c_hat status_word = i2c_hat.status # read status_word to reset bits _LOGGER.info( - log_message(self, i2c_hat, "registered", status_word) - ) + log_message(self, i2c_hat, "registered", status_word)) def run(self): """Keep alive for I2C-HATs.""" # pylint: disable=import-error from raspihats.i2c_hats import ResponseException - _LOGGER.info( - log_message(self, "starting") - ) + _LOGGER.info(log_message(self, "starting")) + while self._run: with self._lock: for i2c_hat in list(self._i2c_hats.values()): @@ -176,17 +172,13 @@ class I2CHatsManager(threading.Thread): ) setattr(i2c_hat, self._EXCEPTION, ex) time.sleep(0.05) - _LOGGER.info( - log_message(self, "exiting") - ) + _LOGGER.info(log_message(self, "exiting")) def _read_status(self, i2c_hat): """Read I2C-HATs status.""" status_word = i2c_hat.status if status_word.value != 0x00: - _LOGGER.error( - log_message(self, i2c_hat, status_word) - ) + _LOGGER.error(log_message(self, i2c_hat, status_word)) def start_keep_alive(self): """Start keep alive mechanism.""" diff --git a/homeassistant/components/remember_the_milk/__init__.py b/homeassistant/components/remember_the_milk/__init__.py index 08c371fcf0ab..581380e36671 100644 --- a/homeassistant/components/remember_the_milk/__init__.py +++ b/homeassistant/components/remember_the_milk/__init__.py @@ -1,21 +1,17 @@ -"""Component to interact with Remember The Milk. +""" +Component to interact with Remember The Milk. For more details about this component, please refer to the documentation at https://home-assistant.io/components/remember_the_milk/ - -Minimum viable product, it currently only support creating new tasks in your -Remember The Milk (https://www.rememberthemilk.com/) account. - -This product uses the Remember The Milk API but is not endorsed or certified -by Remember The Milk. """ +import json import logging import os -import json + import voluptuous as vol -from homeassistant.const import (CONF_API_KEY, STATE_OK, CONF_TOKEN, - CONF_NAME, CONF_ID) +from homeassistant.const import ( + CONF_API_KEY, CONF_ID, CONF_NAME, CONF_TOKEN, STATE_OK) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent @@ -61,9 +57,9 @@ SERVICE_SCHEMA_COMPLETE_TASK = vol.Schema({ def setup(hass, config): - """Set up the remember_the_milk component.""" - component = EntityComponent(_LOGGER, DOMAIN, hass, - group_name=GROUP_NAME_RTM) + """Set up the Remember the milk component.""" + component = EntityComponent( + _LOGGER, DOMAIN, hass, group_name=GROUP_NAME_RTM) stored_rtm_config = RememberTheMilkConfiguration(hass) for rtm_config in config[DOMAIN]: @@ -107,21 +103,21 @@ def _register_new_account(hass, account_name, api_key, shared_secret, configurator = hass.components.configurator api = Rtm(api_key, shared_secret, "write", None) url, frob = api.authenticate_desktop() - _LOGGER.debug('sent authentication request to server') + _LOGGER.debug("Sent authentication request to server") def register_account_callback(_): - """Callback for configurator.""" + """Call for register the configurator.""" api.retrieve_token(frob) token = api.token if api.token is None: - _LOGGER.error('Failed to register, please try again.') + _LOGGER.error("Failed to register, please try again") configurator.notify_errors( request_id, 'Failed to register, please try again.') return stored_rtm_config.set_token(account_name, token) - _LOGGER.debug('retrieved new token from server') + _LOGGER.debug("Retrieved new token from server") _create_instance( hass, account_name, api_key, shared_secret, token, @@ -155,13 +151,13 @@ class RememberTheMilkConfiguration(object): self._config = dict() return try: - _LOGGER.debug('loading configuration from file: %s', + _LOGGER.debug("Loading configuration from file: %s", self._config_file_path) with open(self._config_file_path, 'r') as config_file: self._config = json.load(config_file) except ValueError: - _LOGGER.error('failed to load configuration file, creating a ' - 'new one: %s', self._config_file_path) + _LOGGER.error("Failed to load configuration file, creating a " + "new one: %s", self._config_file_path) self._config = dict() def save_config(self): @@ -197,9 +193,9 @@ class RememberTheMilkConfiguration(object): self._config[profile_name][CONF_ID_MAP] = dict() def get_rtm_id(self, profile_name, hass_id): - """Get the rtm ids for a home assistant task id. + """Get the RTM ids for a Home Assistant task ID. - The id of a rtm tasks consists of the tuple: + The id of a RTM tasks consists of the tuple: list id, timeseries id and the task id. """ self._initialize_profile(profile_name) @@ -210,7 +206,7 @@ class RememberTheMilkConfiguration(object): def set_rtm_id(self, profile_name, hass_id, list_id, time_series_id, rtm_task_id): - """Add/Update the rtm task id for a home assistant task id.""" + """Add/Update the RTM task ID for a Home Assistant task IS.""" self._initialize_profile(profile_name) id_tuple = { CONF_LIST_ID: list_id, @@ -229,7 +225,7 @@ class RememberTheMilkConfiguration(object): class RememberTheMilk(Entity): - """MVP implementation of an interface to Remember The Milk.""" + """Representation of an interface to Remember The Milk.""" def __init__(self, name, api_key, shared_secret, token, rtm_config): """Create new instance of Remember The Milk component.""" @@ -243,7 +239,7 @@ class RememberTheMilk(Entity): self._rtm_api = rtmapi.Rtm(api_key, shared_secret, "delete", token) self._token_valid = None self._check_token() - _LOGGER.debug("instance created for account %s", self._name) + _LOGGER.debug("Instance created for account %s", self._name) def _check_token(self): """Check if the API token is still valid. @@ -253,8 +249,8 @@ class RememberTheMilk(Entity): """ valid = self._rtm_api.token_valid() if not valid: - _LOGGER.error('Token for account %s is invalid. You need to ' - 'register again!', self.name) + _LOGGER.error("Token for account %s is invalid. You need to " + "register again!", self.name) self._rtm_config.delete_token(self._name) self._token_valid = False else: @@ -264,7 +260,7 @@ class RememberTheMilk(Entity): def create_task(self, call): """Create a new task on Remember The Milk. - You can use the smart syntax to define the attribues of a new task, + You can use the smart syntax to define the attributes of a new task, e.g. "my task #some_tag ^today" will add tag "some_tag" and set the due date to today. """ @@ -282,25 +278,20 @@ class RememberTheMilk(Entity): if hass_id is None or rtm_id is None: result = self._rtm_api.rtm.tasks.add( timeline=timeline, name=task_name, parse='1') - _LOGGER.debug('created new task "%s" in account %s', + _LOGGER.debug("Created new task '%s' in account %s", task_name, self.name) - self._rtm_config.set_rtm_id(self._name, - hass_id, - result.list.id, - result.list.taskseries.id, - result.list.taskseries.task.id) + self._rtm_config.set_rtm_id( + self._name, hass_id, result.list.id, + result.list.taskseries.id, result.list.taskseries.task.id) else: - self._rtm_api.rtm.tasks.setName(name=task_name, - list_id=rtm_id[0], - taskseries_id=rtm_id[1], - task_id=rtm_id[2], - timeline=timeline) - _LOGGER.debug('updated task with id "%s" in account ' - '%s to name %s', - hass_id, self.name, task_name) + self._rtm_api.rtm.tasks.setName( + name=task_name, list_id=rtm_id[0], taskseries_id=rtm_id[1], + task_id=rtm_id[2], timeline=timeline) + _LOGGER.debug("Updated task with id '%s' in account " + "%s to name %s", hass_id, self.name, task_name) except rtmapi.RtmRequestFailedException as rtm_exception: - _LOGGER.error('Error creating new Remember The Milk task for ' - 'account %s: %s', self._name, rtm_exception) + _LOGGER.error("Error creating new Remember The Milk task for " + "account %s: %s", self._name, rtm_exception) return False return True @@ -311,23 +302,21 @@ class RememberTheMilk(Entity): hass_id = call.data.get(CONF_ID) rtm_id = self._rtm_config.get_rtm_id(self._name, hass_id) if rtm_id is None: - _LOGGER.error('Could not find task with id %s in account %s. ' - 'So task could not be closed.', - hass_id, self._name) + _LOGGER.error("Could not find task with ID %s in account %s. " + "So task could not be closed", hass_id, self._name) return False try: result = self._rtm_api.rtm.timelines.create() timeline = result.timeline.value - self._rtm_api.rtm.tasks.complete(list_id=rtm_id[0], - taskseries_id=rtm_id[1], - task_id=rtm_id[2], - timeline=timeline) + self._rtm_api.rtm.tasks.complete( + list_id=rtm_id[0], taskseries_id=rtm_id[1], task_id=rtm_id[2], + timeline=timeline) self._rtm_config.delete_rtm_id(self._name, hass_id) - _LOGGER.debug('Completed task with id %s in account %s', + _LOGGER.debug("Completed task with id %s in account %s", hass_id, self._name) except rtmapi.RtmRequestFailedException as rtm_exception: - _LOGGER.error('Error creating new Remember The Milk task for ' - 'account %s: %s', self._name, rtm_exception) + _LOGGER.error("Error creating new Remember The Milk task for " + "account %s: %s", self._name, rtm_exception) return True @property @@ -339,5 +328,5 @@ class RememberTheMilk(Entity): def state(self): """Return the state of the device.""" if not self._token_valid: - return 'API token invalid' + return "API token invalid" return STATE_OK diff --git a/homeassistant/components/remote/harmony.py b/homeassistant/components/remote/harmony.py index 4d241ed5913a..89cdc7529cb3 100644 --- a/homeassistant/components/remote/harmony.py +++ b/homeassistant/components/remote/harmony.py @@ -4,19 +4,19 @@ Support for Harmony Hub devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/remote.harmony/ """ -import logging import asyncio +import logging import time import voluptuous as vol import homeassistant.components.remote as remote -import homeassistant.helpers.config_validation as cv -from homeassistant.const import ( - CONF_NAME, CONF_HOST, CONF_PORT, ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_STOP) from homeassistant.components.remote import ( - PLATFORM_SCHEMA, DOMAIN, ATTR_DEVICE, ATTR_ACTIVITY, ATTR_NUM_REPEATS, - ATTR_DELAY_SECS, DEFAULT_DELAY_SECS) + ATTR_ACTIVITY, ATTR_DELAY_SECS, ATTR_DEVICE, ATTR_NUM_REPEATS, + DEFAULT_DELAY_SECS, DOMAIN, PLATFORM_SCHEMA) +from homeassistant.const import ( + ATTR_ENTITY_ID, CONF_HOST, CONF_NAME, CONF_PORT, EVENT_HOMEASSISTANT_STOP) +import homeassistant.helpers.config_validation as cv from homeassistant.util import slugify REQUIREMENTS = ['pyharmony==1.0.18'] @@ -30,12 +30,12 @@ CONF_DEVICE_CACHE = 'harmony_device_cache' SERVICE_SYNC = 'harmony_sync' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Required(CONF_NAME): cv.string, - vol.Optional(CONF_HOST): cv.string, - vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Required(ATTR_ACTIVITY, default=None): cv.string, + vol.Required(CONF_NAME): cv.string, vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float), + vol.Optional(CONF_HOST): cv.string, + vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, }) HARMONY_SYNC_SCHEMA = vol.Schema({ @@ -182,7 +182,7 @@ class HarmonyRemote(remote.RemoteDevice): return self._current_activity not in [None, 'PowerOff'] def new_activity(self, activity_id): - """Callback for updating the current activity.""" + """Call for updating the current activity.""" import pyharmony activity_name = pyharmony.activity_name(self._config, activity_id) _LOGGER.debug("%s activity reported as: %s", self._name, activity_name) diff --git a/homeassistant/components/remote/kira.py b/homeassistant/components/remote/kira.py index c1a04718d33e..7a04949dbeb4 100644 --- a/homeassistant/components/remote/kira.py +++ b/homeassistant/components/remote/kira.py @@ -4,15 +4,13 @@ Support for Keene Electronics IR-IP devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/remote.kira/ """ -import logging import functools as ft +import logging import homeassistant.components.remote as remote +from homeassistant.const import CONF_DEVICE, CONF_NAME from homeassistant.helpers.entity import Entity -from homeassistant.const import ( - CONF_DEVICE, CONF_NAME) - DOMAIN = 'kira' _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/scene/wink.py b/homeassistant/components/scene/wink.py index 008edf6f1316..2d4a6d0621c5 100644 --- a/homeassistant/components/scene/wink.py +++ b/homeassistant/components/scene/wink.py @@ -8,10 +8,11 @@ import asyncio import logging from homeassistant.components.scene import Scene -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice + +_LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['wink'] -_LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): @@ -34,7 +35,7 @@ class WinkScene(WinkDevice, Scene): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['scene'].append(self) @property diff --git a/homeassistant/components/sensor/abode.py b/homeassistant/components/sensor/abode.py index 3a465db44880..1a700e24de67 100644 --- a/homeassistant/components/sensor/abode.py +++ b/homeassistant/components/sensor/abode.py @@ -47,8 +47,8 @@ class AbodeSensor(AbodeDevice): super().__init__(data, device) self._sensor_type = sensor_type self._icon = 'mdi:{}'.format(SENSOR_TYPES[self._sensor_type][1]) - self._name = '{0} {1}'.format(self._device.name, - SENSOR_TYPES[self._sensor_type][0]) + self._name = '{0} {1}'.format( + self._device.name, SENSOR_TYPES[self._sensor_type][0]) @property def icon(self): diff --git a/homeassistant/components/sensor/ads.py b/homeassistant/components/sensor/ads.py index 725cbb555f11..659ac6d7e5dc 100644 --- a/homeassistant/components/sensor/ads.py +++ b/homeassistant/components/sensor/ads.py @@ -3,33 +3,32 @@ Support for ADS sensors. For more details about this platform, please refer to the documentation. https://home-assistant.io/components/sensor.ads/ - """ import asyncio import logging + import voluptuous as vol + +from homeassistant.components import ads +from homeassistant.components.ads import ( + CONF_ADS_FACTOR, CONF_ADS_TYPE, CONF_ADS_VAR) from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT -from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv -from homeassistant.components import ads -from homeassistant.components.ads import CONF_ADS_VAR, CONF_ADS_TYPE, \ - CONF_ADS_FACTOR - +from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) -DEFAULT_NAME = 'ADS sensor' +DEFAULT_NAME = "ADS sensor" DEPENDENCIES = ['ads'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ADS_VAR): cv.string, + vol.Optional(CONF_ADS_FACTOR): cv.positive_int, + vol.Optional(CONF_ADS_TYPE, default=ads.ADSTYPE_INT): + vol.In([ads.ADSTYPE_INT, ads.ADSTYPE_UINT, ads.ADSTYPE_BYTE]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=''): cv.string, - vol.Optional(CONF_ADS_TYPE, default=ads.ADSTYPE_INT): vol.In( - [ads.ADSTYPE_INT, ads.ADSTYPE_UINT, ads.ADSTYPE_BYTE] - ), - vol.Optional(CONF_ADS_FACTOR): cv.positive_int, }) @@ -43,8 +42,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) factor = config.get(CONF_ADS_FACTOR) - entity = AdsSensor(ads_hub, ads_var, ads_type, name, - unit_of_measurement, factor) + entity = AdsSensor( + ads_hub, ads_var, ads_type, name, unit_of_measurement, factor) add_devices([entity]) @@ -68,9 +67,9 @@ class AdsSensor(Entity): """Register device notification.""" def update(name, value): """Handle device notifications.""" - _LOGGER.debug('Variable %s changed its value to %d', name, value) + _LOGGER.debug("Variable %s changed its value to %d", name, value) - # if factor is set use it otherwise not + # If factor is set use it otherwise not if self.factor is None: self._value = value else: @@ -99,5 +98,5 @@ class AdsSensor(Entity): @property def should_poll(self): - """Return False because entity pushes its state to HA.""" + """Return False because entity pushes its state.""" return False diff --git a/homeassistant/components/sensor/deconz.py b/homeassistant/components/sensor/deconz.py index b3118d3906d9..7c2c1e0895f2 100644 --- a/homeassistant/components/sensor/deconz.py +++ b/homeassistant/components/sensor/deconz.py @@ -86,12 +86,12 @@ class DeconzSensor(Entity): @property def unit_of_measurement(self): - """Unit of measurement of this sensor.""" + """Return the unit of measurement of this sensor.""" return self._sensor.sensor_unit @property def available(self): - """Return True if sensor is available.""" + """Return true if sensor is available.""" return self._sensor.reachable @property diff --git a/homeassistant/components/sensor/dyson.py b/homeassistant/components/sensor/dyson.py index 62c77bb768f9..91629a18f68b 100644 --- a/homeassistant/components/sensor/dyson.py +++ b/homeassistant/components/sensor/dyson.py @@ -1,23 +1,23 @@ -"""Support for Dyson Pure Cool Link Sensors. +""" +Support for Dyson Pure Cool Link Sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.dyson/ """ -import logging import asyncio +import logging -from homeassistant.const import TEMP_CELSIUS, STATE_OFF from homeassistant.components.dyson import DYSON_DEVICES - +from homeassistant.const import STATE_OFF, TEMP_CELSIUS from homeassistant.helpers.entity import Entity DEPENDENCIES = ['dyson'] SENSOR_UNITS = { - "filter_life": "hours", - "humidity": "%", - "dust": "level", - "air_quality": "level" + 'air_quality': 'level', + 'dust': 'level', + 'filter_life': 'hours', + 'humidity': '%', } _LOGGER = logging.getLogger(__name__) @@ -25,7 +25,7 @@ _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Dyson Sensors.""" - _LOGGER.info("Creating new Dyson fans") + _LOGGER.debug("Creating new Dyson fans") devices = [] unit = hass.config.units.temperature_unit # Get Dyson Devices from parent component @@ -52,12 +52,12 @@ class DysonSensor(Entity): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.async_add_job( self._device.add_message_listener, self.on_message) def on_message(self, message): - """Called when new messages received from the fan.""" + """Handle new messages which are received from the fan.""" # Prevent refreshing if not needed if self._old_value is None or self._old_value != self.state: _LOGGER.debug("Message received for %s device: %s", self.name, diff --git a/homeassistant/components/sensor/imap.py b/homeassistant/components/sensor/imap.py index 9f12353221d1..f0585228851e 100644 --- a/homeassistant/components/sensor/imap.py +++ b/homeassistant/components/sensor/imap.py @@ -4,19 +4,19 @@ IMAP sensor support. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.imap/ """ -import logging import asyncio -import async_timeout +import logging +import async_timeout import voluptuous as vol -from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( - CONF_NAME, CONF_PORT, CONF_USERNAME, CONF_PASSWORD, + CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) @@ -41,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): - """Setup the IMAP platform.""" + """Set up the IMAP platform.""" sensor = ImapSensor(config.get(CONF_NAME), config.get(CONF_USERNAME), config.get(CONF_PASSWORD), diff --git a/homeassistant/components/sensor/kira.py b/homeassistant/components/sensor/kira.py index 232e50b85edf..b5d3073ea9a0 100644 --- a/homeassistant/components/sensor/kira.py +++ b/homeassistant/components/sensor/kira.py @@ -1,12 +1,12 @@ -"""KIRA interface to receive UDP packets from an IR-IP bridge.""" -# pylint: disable=import-error +""" +KIRA interface to receive UDP packets from an IR-IP bridge. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sensor.kira/ +""" import logging -from homeassistant.const import ( - CONF_DEVICE, - CONF_NAME, - STATE_UNKNOWN) - +from homeassistant.const import CONF_DEVICE, CONF_NAME, STATE_UNKNOWN from homeassistant.helpers.entity import Entity DOMAIN = 'kira' @@ -15,17 +15,18 @@ _LOGGER = logging.getLogger(__name__) ICON = 'mdi:remote' -CONF_SENSOR = "sensor" +CONF_SENSOR = 'sensor' # pylint: disable=unused-argument, too-many-function-args -def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """Setup Kira sensor.""" +def setup_platform(hass, config, add_devices, discovery_info=None): + """Set up a Kira sensor.""" if discovery_info is not None: name = discovery_info.get(CONF_NAME) device = discovery_info.get(CONF_DEVICE) kira = hass.data[DOMAIN][CONF_SENSOR][name] - add_devices_callback([KiraReceiver(device, kira)]) + + add_devices([KiraReceiver(device, kira)]) class KiraReceiver(Entity): @@ -34,14 +35,14 @@ class KiraReceiver(Entity): def __init__(self, name, kira): """Initialize the sensor.""" self._name = name - self._state = STATE_UNKNOWN + self._state = None self._device = STATE_UNKNOWN kira.registerCallback(self._update_callback) def _update_callback(self, code): code_name, device = code - _LOGGER.info("Kira Code: %s", code_name) + _LOGGER.debug("Kira Code: %s", code_name) self._state = code_name self._device = device self.schedule_update_ha_state() @@ -64,9 +65,7 @@ class KiraReceiver(Entity): @property def device_state_attributes(self): """Return the state attributes of the device.""" - attr = {} - attr[CONF_DEVICE] = self._device - return attr + return {CONF_DEVICE: self._device} @property def should_poll(self) -> bool: diff --git a/homeassistant/components/sensor/knx.py b/homeassistant/components/sensor/knx.py index f803f406e1e9..0a455099597a 100644 --- a/homeassistant/components/sensor/knx.py +++ b/homeassistant/components/sensor/knx.py @@ -5,14 +5,15 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES -from homeassistant.helpers.entity import Entity +from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity CONF_ADDRESS = 'address' CONF_TYPE = 'type' @@ -28,20 +29,16 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up sensor(s) for KNX platform.""" - if DATA_KNX not in hass.data \ - or not hass.data[DATA_KNX].initialized: - return False + if DATA_KNX not in hass.data or not hass.data[DATA_KNX].initialized: + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): @@ -70,7 +67,7 @@ class KNXSensor(Entity): """Representation of a KNX sensor.""" def __init__(self, hass, device): - """Initialization of KNXSensor.""" + """Initialize of a KNX sensor.""" self.device = device self.hass = hass self.async_register_callbacks() @@ -80,7 +77,7 @@ class KNXSensor(Entity): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) diff --git a/homeassistant/components/sensor/lacrosse.py b/homeassistant/components/sensor/lacrosse.py index d284e3012dcd..b402fc5c70f3 100644 --- a/homeassistant/components/sensor/lacrosse.py +++ b/homeassistant/components/sensor/lacrosse.py @@ -4,17 +4,17 @@ Support for LaCrosse sensor components. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.lacrosse/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.core import callback -from homeassistant.components.sensor import (ENTITY_ID_FORMAT, PLATFORM_SCHEMA) +from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA from homeassistant.const import ( - EVENT_HOMEASSISTANT_STOP, CONF_DEVICE, CONF_NAME, CONF_ID, - CONF_SENSORS, CONF_TYPE, TEMP_CELSIUS) + CONF_DEVICE, CONF_ID, CONF_NAME, CONF_SENSORS, CONF_TYPE, + EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS) +from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity, async_generate_entity_id from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util import dt as dt_util @@ -147,7 +147,7 @@ class LaCrosseSensor(Entity): return attributes def _callback_lacrosse(self, lacrosse_sensor, user_data): - """Callback function that is called from pylacrosse with new values.""" + """Handle a function that is called from pylacrosse with new values.""" if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: diff --git a/homeassistant/components/sensor/london_air.py b/homeassistant/components/sensor/london_air.py index 848e1255833c..2ffbb9142756 100644 --- a/homeassistant/components/sensor/london_air.py +++ b/homeassistant/components/sensor/london_air.py @@ -4,22 +4,24 @@ Sensor for checking the status of London air. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.london_air/ """ -import logging from datetime import timedelta +import logging -import voluptuous as vol import requests +import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import STATE_UNKNOWN +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) CONF_LOCATIONS = 'locations' + SCAN_INTERVAL = timedelta(minutes=30) + AUTHORITIES = [ 'Barking and Dagenham', 'Bexley', @@ -48,6 +50,7 @@ AUTHORITIES = [ 'Tower Hamlets', 'Wandsworth', 'Westminster'] + URL = ('http://api.erg.kcl.ac.uk/AirQuality/Hourly/' 'MonitoringIndex/GroupName=London/Json') @@ -58,7 +61,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the Tube sensor.""" + """Set up the London Air sensor.""" data = APIData() data.update() sensors = [] @@ -199,7 +202,7 @@ def parse_site(entry_sites_data): def parse_api_response(response): - """API can return dict or list of data so need to check.""" + """Parse return dict or list of data from API.""" data = dict.fromkeys(AUTHORITIES) for authority in AUTHORITIES: for entry in response['HourlyAirQualityIndex']['LocalAuthority']: diff --git a/homeassistant/components/sensor/mopar.py b/homeassistant/components/sensor/mopar.py index fdf6c9132d56..99ea4ef6135a 100644 --- a/homeassistant/components/sensor/mopar.py +++ b/homeassistant/components/sensor/mopar.py @@ -4,33 +4,35 @@ Sensor for Mopar vehicles. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.mopar/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol from homeassistant.components.sensor import DOMAIN, PLATFORM_SCHEMA -from homeassistant.helpers.entity import Entity -from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD, CONF_PIN, - ATTR_ATTRIBUTION, ATTR_COMMAND, - LENGTH_KILOMETERS) -from homeassistant.util import Throttle +from homeassistant.const import ( + ATTR_ATTRIBUTION, ATTR_COMMAND, CONF_PASSWORD, CONF_PIN, CONF_USERNAME, + LENGTH_KILOMETERS) import homeassistant.helpers.config_validation as cv - +from homeassistant.helpers.entity import Entity +from homeassistant.util import Throttle REQUIREMENTS = ['motorparts==1.0.2'] _LOGGER = logging.getLogger(__name__) -MIN_TIME_BETWEEN_UPDATES = timedelta(days=7) ATTR_VEHICLE_INDEX = 'vehicle_index' -SERVICE_REMOTE_COMMAND = 'mopar_remote_command' + COOKIE_FILE = 'mopar_cookies.pickle' +MIN_TIME_BETWEEN_UPDATES = timedelta(days=7) + +SERVICE_REMOTE_COMMAND = 'mopar_remote_command' + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, - vol.Required(CONF_PIN): cv.positive_int + vol.Required(CONF_PIN): cv.positive_int, }) REMOTE_COMMAND_SCHEMA = vol.Schema({ @@ -41,17 +43,16 @@ REMOTE_COMMAND_SCHEMA = vol.Schema({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Mopar platform.""" + """Set up the Mopar platform.""" import motorparts cookie = hass.config.path(COOKIE_FILE) try: - session = motorparts.get_session(config.get(CONF_USERNAME), - config.get(CONF_PASSWORD), - config.get(CONF_PIN), - cookie_path=cookie) + session = motorparts.get_session( + config.get(CONF_USERNAME), config.get(CONF_PASSWORD), + config.get(CONF_PIN), cookie_path=cookie) except motorparts.MoparError: - _LOGGER.error("failed to login") - return False + _LOGGER.error("Failed to login") + return def _handle_service(service): """Handle service call.""" @@ -67,12 +68,9 @@ def setup_platform(hass, config, add_devices, discovery_info=None): data = MoparData(session) add_devices([MoparSensor(data, index) - for index, _ in enumerate(data.vehicles)], - True) - return True + for index, _ in enumerate(data.vehicles)], True) -# pylint: disable=too-few-public-methods class MoparData(object): """Container for Mopar vehicle data. @@ -91,11 +89,11 @@ class MoparData(object): def update(self, **kwargs): """Update data.""" import motorparts - _LOGGER.info("updating vehicle data") + _LOGGER.info("Updating vehicle data") try: self.vehicles = motorparts.get_summary(self._session)['vehicles'] except motorparts.MoparError: - _LOGGER.exception("failed to get summary") + _LOGGER.exception("Failed to get summary") return for index, _ in enumerate(self.vehicles): try: @@ -103,7 +101,7 @@ class MoparData(object): self.tow_guides[index] = motorparts.get_tow_guide( self._session, index) except motorparts.MoparError: - _LOGGER.warning("failed to update for vehicle index %s", index) + _LOGGER.warning("Failed to update for vehicle index %s", index) class MoparSensor(Entity): @@ -132,9 +130,9 @@ class MoparSensor(Entity): @property def name(self): """Return the name of the sensor.""" - return '{} {} {}'.format(self._vehicle['year'], - self._vehicle['make'], - self._vehicle['model']) + return '{} {} {}'.format( + self._vehicle['year'], self._vehicle['make'], + self._vehicle['model']) @property def state(self): diff --git a/homeassistant/components/sensor/nederlandse_spoorwegen.py b/homeassistant/components/sensor/nederlandse_spoorwegen.py index 3535e00d79b4..ec534047cccb 100644 --- a/homeassistant/components/sensor/nederlandse_spoorwegen.py +++ b/homeassistant/components/sensor/nederlandse_spoorwegen.py @@ -4,17 +4,16 @@ Support for Nederlandse Spoorwegen public transport. For more details on this platform, please refer to the documentation at https://home-assistant.io/components/sensor.nederlandse_spoorwegen/ """ -from datetime import datetime -from datetime import timedelta +from datetime import datetime, timedelta import logging -import voluptuous as vol import requests +import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import (CONF_EMAIL, CONF_NAME, - CONF_PASSWORD, ATTR_ATTRIBUTION) +from homeassistant.const import ( + ATTR_ATTRIBUTION, CONF_EMAIL, CONF_NAME, CONF_PASSWORD) +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -50,7 +49,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the departure sensor.""" + """Set up the departure sensor.""" import ns_api nsapi = ns_api.NSAPI( config.get(CONF_EMAIL), config.get(CONF_PASSWORD)) @@ -77,7 +76,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): def valid_stations(stations, given_stations): - """Verify the existance of the given station codes.""" + """Verify the existence of the given station codes.""" for station in given_stations: if station is None: continue diff --git a/homeassistant/components/sensor/openhardwaremonitor.py b/homeassistant/components/sensor/openhardwaremonitor.py index 54ce5dbd6da1..1b5867836bcf 100644 --- a/homeassistant/components/sensor/openhardwaremonitor.py +++ b/homeassistant/components/sensor/openhardwaremonitor.py @@ -1,16 +1,21 @@ -"""Support for Open Hardware Monitor Sensor Platform.""" +""" +Support for Open Hardware Monitor Sensor Platform. +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sensor.openhardwaremonitor/ +""" from datetime import timedelta import logging + import requests import voluptuous as vol -from homeassistant.util.dt import utcnow +from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_PORT import homeassistant.helpers.config_validation as cv -from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle +from homeassistant.util.dt import utcnow _LOGGER = logging.getLogger(__name__) @@ -37,7 +42,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Open Hardware Monitor platform.""" + """Set up the Open Hardware Monitor platform.""" data = OpenHardwareMonitorData(config, hass) add_devices(data.devices, True) @@ -124,9 +129,8 @@ class OpenHardwareMonitorData(object): def refresh(self): """Download and parse JSON from OHM.""" - data_url = "http://%s:%d/data.json" % ( - self._config.get(CONF_HOST), - self._config.get(CONF_PORT)) + data_url = "http://{}:{}/data.json".format( + self._config.get(CONF_HOST), self._config.get(CONF_PORT)) try: response = requests.get(data_url, timeout=30) @@ -135,7 +139,7 @@ class OpenHardwareMonitorData(object): _LOGGER.error("ConnectionError: Is OpenHardwareMonitor running?") def initialize(self, now): - """Initial parsing of the sensors and adding of devices.""" + """Parse of the sensors and adding of devices.""" self.refresh() if self.data is None: @@ -173,11 +177,7 @@ class OpenHardwareMonitorData(object): fullname = ' '.join(child_names) dev = OpenHardwareMonitorDevice( - self, - fullname, - path, - unit_of_measurement - ) + self, fullname, path, unit_of_measurement) result.append(dev) return result diff --git a/homeassistant/components/sensor/rfxtrx.py b/homeassistant/components/sensor/rfxtrx.py index 1c09bc019093..1696e8e37700 100644 --- a/homeassistant/components/sensor/rfxtrx.py +++ b/homeassistant/components/sensor/rfxtrx.py @@ -9,14 +9,14 @@ import logging import voluptuous as vol import homeassistant.components.rfxtrx as rfxtrx -import homeassistant.helpers.config_validation as cv +from homeassistant.components.rfxtrx import ( + ATTR_DATA_TYPE, ATTR_FIRE_EVENT, ATTR_NAME, CONF_AUTOMATIC_ADD, + CONF_DATA_TYPE, CONF_DEVICES, CONF_FIRE_EVENT, DATA_TYPES) +from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ENTITY_ID, CONF_NAME +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import slugify -from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.components.rfxtrx import ( - ATTR_NAME, ATTR_FIRE_EVENT, ATTR_DATA_TYPE, CONF_AUTOMATIC_ADD, - CONF_FIRE_EVENT, CONF_DEVICES, DATA_TYPES, CONF_DATA_TYPE) DEPENDENCIES = ['rfxtrx'] @@ -35,13 +35,13 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ }, extra=vol.ALLOW_EXTRA) -def setup_platform(hass, config, add_devices_callback, discovery_info=None): +def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the RFXtrx platform.""" from RFXtrx import SensorEvent sensors = [] for packet_id, entity_info in config[CONF_DEVICES].items(): event = rfxtrx.get_rfx_object(packet_id) - device_id = "sensor_" + slugify(event.device.id_string.lower()) + device_id = "sensor_{}".format(slugify(event.device.id_string.lower())) if device_id in rfxtrx.RFX_DEVICES: continue _LOGGER.info("Add %s rfxtrx.sensor", entity_info[ATTR_NAME]) @@ -60,7 +60,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): sensors.append(new_sensor) sub_sensors[_data_type] = new_sensor rfxtrx.RFX_DEVICES[device_id] = sub_sensors - add_devices_callback(sensors) + add_devices(sensors) def sensor_update(event): """Handle sensor updates from the RFXtrx gateway.""" @@ -78,8 +78,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): if sensors[key].should_fire_event: sensor.hass.bus.fire( "signal_received", { - ATTR_ENTITY_ID: - sensors[key].entity_id, + ATTR_ENTITY_ID: sensors[key].entity_id, } ) return @@ -100,7 +99,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None): sub_sensors = {} sub_sensors[new_sensor.data_type] = new_sensor rfxtrx.RFX_DEVICES[device_id] = sub_sensors - add_devices_callback([new_sensor]) + add_devices([new_sensor]) if sensor_update not in rfxtrx.RECEIVED_EVT_SUBSCRIBERS: rfxtrx.RECEIVED_EVT_SUBSCRIBERS.append(sensor_update) @@ -135,7 +134,7 @@ class RfxtrxSensor(Entity): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" if not self.event: return None return self.event.values diff --git a/homeassistant/components/sensor/tesla.py b/homeassistant/components/sensor/tesla.py index 3f36a1128d6d..4534c8d62035 100644 --- a/homeassistant/components/sensor/tesla.py +++ b/homeassistant/components/sensor/tesla.py @@ -4,12 +4,13 @@ Sensors for the Tesla sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.tesla/ """ -import logging from datetime import timedelta +import logging -from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.components.sensor import ENTITY_ID_FORMAT -from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN, TeslaDevice +from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN +from homeassistant.components.tesla import TeslaDevice +from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) @@ -37,7 +38,7 @@ class TeslaSensor(TeslaDevice, Entity): """Representation of Tesla sensors.""" def __init__(self, tesla_device, controller, sensor_type=None): - """Initialisation of the sensor.""" + """Initialize of the sensor.""" self.current_value = None self._unit = None self.last_changed_time = None diff --git a/homeassistant/components/sensor/usps.py b/homeassistant/components/sensor/usps.py index a789f5668963..6ca18442883b 100644 --- a/homeassistant/components/sensor/usps.py +++ b/homeassistant/components/sensor/usps.py @@ -21,13 +21,12 @@ STATUS_DELIVERED = 'delivered' def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the USPS platform.""" + """Set up the USPS platform.""" if discovery_info is None: return usps = hass.data[DATA_USPS] - add_devices([USPSPackageSensor(usps), - USPSMailSensor(usps)], True) + add_devices([USPSPackageSensor(usps), USPSMailSensor(usps)], True) class USPSPackageSensor(Entity): @@ -73,7 +72,7 @@ class USPSPackageSensor(Entity): @property def icon(self): - """Icon to use in the frontend.""" + """Return the icon to use in the frontend.""" return 'mdi:package-variant-closed' @property diff --git a/homeassistant/components/sensor/viaggiatreno.py b/homeassistant/components/sensor/viaggiatreno.py index 37e7e020cc9f..a7f4b070f2d4 100644 --- a/homeassistant/components/sensor/viaggiatreno.py +++ b/homeassistant/components/sensor/viaggiatreno.py @@ -4,17 +4,16 @@ Support for information about the Italian train system using ViaggiaTreno API. For more details about this platform please refer to the documentation at https://home-assistant.io/components/sensor.viaggiatreno """ +import asyncio import logging -import asyncio -import async_timeout import aiohttp - +import async_timeout import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) @@ -58,9 +57,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, - async_add_devices, discovery_info=None): - """Setup the ViaggiaTreno platform.""" +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): + """Set up the ViaggiaTreno platform.""" train_id = config.get(CONF_TRAIN_ID) station_id = config.get(CONF_STATION_ID) name = config.get(CONF_NAME) @@ -100,8 +98,7 @@ class ViaggiaTrenoSensor(Entity): self._name = name self.uri = VIAGGIATRENO_ENDPOINT.format( - station_id=station_id, - train_id=train_id) + station_id=station_id, train_id=train_id) @property def name(self): diff --git a/homeassistant/components/sensor/vultr.py b/homeassistant/components/sensor/vultr.py index 7a3db3895dc0..012c6eb7398f 100644 --- a/homeassistant/components/sensor/vultr.py +++ b/homeassistant/components/sensor/vultr.py @@ -5,29 +5,26 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/sensor.vultr/ """ import logging + import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.helpers.entity import Entity -from homeassistant.const import ( - CONF_MONITORED_CONDITIONS, CONF_NAME) from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.components.vultr import ( - CONF_SUBSCRIPTION, ATTR_CURRENT_BANDWIDTH_USED, ATTR_PENDING_CHARGES, + ATTR_CURRENT_BANDWIDTH_USED, ATTR_PENDING_CHARGES, CONF_SUBSCRIPTION, DATA_VULTR) - -# Name defaults to {subscription label} {sensor name} -DEFAULT_NAME = 'Vultr {} {}' -DEPENDENCIES = ['vultr'] +from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) -# Monitored conditions: name, units, icon +DEFAULT_NAME = 'Vultr {} {}' +DEPENDENCIES = ['vultr'] + MONITORED_CONDITIONS = { ATTR_CURRENT_BANDWIDTH_USED: ['Current Bandwidth Used', 'GB', 'mdi:chart-histogram'], - ATTR_PENDING_CHARGES: ['Pending Charges', 'US$', - 'mdi:currency-usd'] + ATTR_PENDING_CHARGES: ['Pending Charges', 'US$', 'mdi:currency-usd'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -48,15 +45,12 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) - return False + return sensors = [] for condition in monitored_conditions: - sensors.append(VultrSensor(vultr, - subscription, - condition, - name)) + sensors.append(VultrSensor(vultr, subscription, condition, name)) add_devices(sensors, True) @@ -84,21 +78,21 @@ class VultrSensor(Entity): """Return the name of the sensor.""" try: return self._name.format(self._condition_name) - except IndexError: # name contains more {} than fulfilled + except IndexError: try: - return self._name.format(self.data['label'], - self._condition_name) - except (KeyError, TypeError): # label key missing or data is None + return self._name.format( + self.data['label'], self._condition_name) + except (KeyError, TypeError): return self._name @property def icon(self): - """Icon used in the frontend if any.""" + """Return the icon used in the frontend if any.""" return self._icon @property def unit_of_measurement(self): - """The unit of measurement to present the value in.""" + """Return the unit of measurement to present the value in.""" return self._units @property diff --git a/homeassistant/components/sensor/whois.py b/homeassistant/components/sensor/whois.py index 771c4bc9d73b..21b1b99ca137 100644 --- a/homeassistant/components/sensor/whois.py +++ b/homeassistant/components/sensor/whois.py @@ -4,13 +4,13 @@ Get WHOIS information for a given host. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.whois/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol -from homeassistant.const import CONF_NAME from homeassistant.components.sensor import PLATFORM_SCHEMA +from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -22,10 +22,10 @@ CONF_DOMAIN = 'domain' DEFAULT_NAME = 'Whois' +ATTR_EXPIRES = 'expires' ATTR_NAME_SERVERS = 'name_servers' ATTR_REGISTRAR = 'registrar' ATTR_UPDATED = 'updated' -ATTR_EXPIRES = 'expires' SCAN_INTERVAL = timedelta(hours=24) @@ -79,12 +79,12 @@ class WhoisSensor(Entity): @property def icon(self): - """The icon to represent this sensor.""" + """Return the icon to represent this sensor.""" return 'mdi:calendar-clock' @property def unit_of_measurement(self): - """The unit of measurement to present the value in.""" + """Return the unit of measurement to present the value in.""" return 'days' @property diff --git a/homeassistant/components/sensor/wink.py b/homeassistant/components/sensor/wink.py index b8c2b8a6236b..75751bbbf8ac 100644 --- a/homeassistant/components/sensor/wink.py +++ b/homeassistant/components/sensor/wink.py @@ -7,12 +7,13 @@ at https://home-assistant.io/components/sensor.wink/ import asyncio import logging +from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.const import TEMP_CELSIUS from homeassistant.helpers.entity import Entity -from homeassistant.components.wink import WinkDevice, DOMAIN + +_LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['wink'] -_LOGGER = logging.getLogger(__name__) SENSOR_TYPES = ['temperature', 'humidity', 'balance', 'proximity'] @@ -61,7 +62,7 @@ class WinkSensorDevice(WinkDevice, Entity): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['sensor'].append(self) @property diff --git a/homeassistant/components/spc.py b/homeassistant/components/spc.py index c186559c91a4..141d06768e30 100644 --- a/homeassistant/components/spc.py +++ b/homeassistant/components/spc.py @@ -4,23 +4,22 @@ Support for Vanderbilt (formerly Siemens) SPC alarm systems. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/spc/ """ -import logging import asyncio import json +import logging from urllib.parse import urljoin import aiohttp import async_timeout import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.helpers import discovery from homeassistant.const import ( - STATE_UNKNOWN, STATE_ON, STATE_OFF, STATE_ALARM_ARMED_AWAY, - STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, - STATE_UNAVAILABLE) + STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, + STATE_ALARM_TRIGGERED, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, + STATE_UNKNOWN) +from homeassistant.helpers import discovery +import homeassistant.helpers.config_validation as cv -DOMAIN = 'spc' REQUIREMENTS = ['websockets==3.2'] _LOGGER = logging.getLogger(__name__) @@ -33,6 +32,7 @@ CONF_API_URL = 'api_url' DATA_REGISTRY = 'spc_registry' DATA_API = 'spc_api' +DOMAIN = 'spc' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ @@ -44,7 +44,7 @@ CONFIG_SCHEMA = vol.Schema({ @asyncio.coroutine def async_setup(hass, config): - """Setup the SPC platform.""" + """Set up the SPC platform.""" hass.data[DATA_REGISTRY] = SpcRegistry() api = SpcWebGateway(hass, @@ -96,29 +96,31 @@ def _async_process_message(sia_message, spc_registry): if len(data) == 3: extra['changed_by'] = data[1] else: - # change in zone status, notify sensor device + # Change in zone status, notify sensor device device = spc_registry.get_sensor_device(spc_id) - sia_code_to_state_map = {'BA': STATE_ALARM_TRIGGERED, - 'CG': STATE_ALARM_ARMED_AWAY, - 'NL': STATE_ALARM_ARMED_HOME, - 'OG': STATE_ALARM_DISARMED, - 'ZO': STATE_ON, - 'ZC': STATE_OFF, - 'ZX': STATE_UNKNOWN, - 'ZD': STATE_UNAVAILABLE} + sia_code_to_state_map = { + 'BA': STATE_ALARM_TRIGGERED, + 'CG': STATE_ALARM_ARMED_AWAY, + 'NL': STATE_ALARM_ARMED_HOME, + 'OG': STATE_ALARM_DISARMED, + 'ZO': STATE_ON, + 'ZC': STATE_OFF, + 'ZX': STATE_UNKNOWN, + 'ZD': STATE_UNAVAILABLE, + } new_state = sia_code_to_state_map.get(sia_code, None) if new_state and not device: - _LOGGER.warning("No device mapping found for SPC area/zone id %s.", - spc_id) + _LOGGER.warning( + "No device mapping found for SPC area/zone id %s", spc_id) elif new_state: yield from device.async_update_from_spc(new_state, extra) class SpcRegistry: - """Maintains mappings between SPC zones/areas and HA entities.""" + """Maintain mappings between SPC zones/areas and HA entities.""" def __init__(self): """Initialize the registry.""" @@ -145,12 +147,12 @@ class SpcRegistry: @asyncio.coroutine def _ws_process_message(message, async_callback, *args): if message.get('status', '') != 'success': - _LOGGER.warning("Unsuccessful websocket message " - "delivered, ignoring: %s", message) + _LOGGER.warning( + "Unsuccessful websocket message delivered, ignoring: %s", message) try: yield from async_callback(message['data']['sia'], *args) except: # pylint: disable=bare-except - _LOGGER.exception("Exception in callback, ignoring.") + _LOGGER.exception("Exception in callback, ignoring") class SpcWebGateway: @@ -180,8 +182,8 @@ class SpcWebGateway: @asyncio.coroutine def send_area_command(self, area_id, command): """Send an area command.""" - _LOGGER.debug("Sending SPC area command '%s' to area %s.", - command, area_id) + _LOGGER.debug( + "Sending SPC area command '%s' to area %s", command, area_id) resource = "area/{}/{}".format(area_id, command) return (yield from self._call_web_gateway(resource, use_get=False)) @@ -199,37 +201,39 @@ class SpcWebGateway: @asyncio.coroutine def _get_data(self, resource): + """Get the data from the resource.""" data = yield from self._call_web_gateway(resource) if not data: return False if data['status'] != 'success': - _LOGGER.error("SPC Web Gateway call unsuccessful " - "for resource '%s'.", resource) + _LOGGER.error( + "SPC Web Gateway call unsuccessful for resource: %s", resource) return False return [item for item in data['data'][resource]] @asyncio.coroutine def _call_web_gateway(self, resource, use_get=True): + """Call web gateway for data.""" response = None session = None url = self._build_url(resource) try: - _LOGGER.debug("Attempting to retrieve SPC data from %s.", url) + _LOGGER.debug("Attempting to retrieve SPC data from %s", url) session = aiohttp.ClientSession() with async_timeout.timeout(10, loop=self._hass.loop): action = session.get if use_get else session.put response = yield from action(url) if response.status != 200: - _LOGGER.error("SPC Web Gateway returned http " - "status %d, response %s.", - response.status, (yield from response.text())) + _LOGGER.error( + "SPC Web Gateway returned http status %d, response %s", + response.status, (yield from response.text())) return False result = yield from response.json() except asyncio.TimeoutError: - _LOGGER.error("Timeout getting SPC data from %s.", url) + _LOGGER.error("Timeout getting SPC data from %s", url) return False except aiohttp.ClientError: - _LOGGER.exception("Error getting SPC data from %s.", url) + _LOGGER.exception("Error getting SPC data from %s", url) return False finally: if session: @@ -241,12 +245,13 @@ class SpcWebGateway: @asyncio.coroutine def _ws_read(self): + """Read from websocket.""" import websockets as wslib try: if not self._ws: self._ws = yield from wslib.connect(self._ws_url) - _LOGGER.info("Connected to websocket at %s.", self._ws_url) + _LOGGER.info("Connected to websocket at %s", self._ws_url) except Exception as ws_exc: # pylint: disable=broad-except _LOGGER.error("Failed to connect to websocket: %s", ws_exc) return @@ -267,15 +272,16 @@ class SpcWebGateway: @asyncio.coroutine def _ws_listen(self, async_callback, *args): + """Listen on websocket.""" try: while True: result = yield from self._ws_read() if result: - yield from _ws_process_message(json.loads(result), - async_callback, *args) + yield from _ws_process_message( + json.loads(result), async_callback, *args) else: - _LOGGER.info("Trying again in 30 seconds.") + _LOGGER.info("Trying again in 30 seconds") yield from asyncio.sleep(30) finally: diff --git a/homeassistant/components/switch/ads.py b/homeassistant/components/switch/ads.py index f4abf2391e2a..b58c4d325e72 100644 --- a/homeassistant/components/switch/ads.py +++ b/homeassistant/components/switch/ads.py @@ -3,21 +3,24 @@ Support for ADS switch platform. For more details about this platform, please refer to the documentation. https://home-assistant.io/components/switch.ads/ - """ import asyncio import logging + import voluptuous as vol + +from homeassistant.components.ads import CONF_ADS_VAR, DATA_ADS from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME -from homeassistant.components.ads import DATA_ADS, CONF_ADS_VAR -from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv - +from homeassistant.helpers.entity import ToggleEntity _LOGGER = logging.getLogger(__name__) + DEPENDENCIES = ['ads'] + DEFAULT_NAME = 'ADS Switch' + PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ADS_VAR): cv.string, vol.Optional(CONF_NAME): cv.string, @@ -49,15 +52,13 @@ class AdsSwitch(ToggleEntity): """Register device notification.""" def update(name, value): """Handle device notification.""" - _LOGGER.debug('Variable %s changed its value to %d', - name, value) + _LOGGER.debug('Variable %s changed its value to %d', name, value) self._on_state = value self.schedule_update_ha_state() self.hass.async_add_job( self._ads_hub.add_device_notification, - self.ads_var, self._ads_hub.PLCTYPE_BOOL, update - ) + self.ads_var, self._ads_hub.PLCTYPE_BOOL, update) @property def is_on(self): @@ -76,10 +77,10 @@ class AdsSwitch(ToggleEntity): def turn_on(self, **kwargs): """Turn the switch on.""" - self._ads_hub.write_by_name(self.ads_var, True, - self._ads_hub.PLCTYPE_BOOL) + self._ads_hub.write_by_name( + self.ads_var, True, self._ads_hub.PLCTYPE_BOOL) def turn_off(self, **kwargs): """Turn the switch off.""" - self._ads_hub.write_by_name(self.ads_var, False, - self._ads_hub.PLCTYPE_BOOL) + self._ads_hub.write_by_name( + self.ads_var, False, self._ads_hub.PLCTYPE_BOOL) diff --git a/homeassistant/components/switch/broadlink.py b/homeassistant/components/switch/broadlink.py index bd2ebc1704f2..5841642cc009 100644 --- a/homeassistant/components/switch/broadlink.py +++ b/homeassistant/components/switch/broadlink.py @@ -4,24 +4,23 @@ Support for Broadlink RM devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.broadlink/ """ -from datetime import timedelta -from base64 import b64encode, b64decode import asyncio +from base64 import b64decode, b64encode import binascii +from datetime import timedelta import logging import socket import voluptuous as vol -from homeassistant.util.dt import utcnow -from homeassistant.util import Throttle from homeassistant.components.switch import ( - SwitchDevice, DOMAIN, PLATFORM_SCHEMA) + DOMAIN, PLATFORM_SCHEMA, SwitchDevice) from homeassistant.const import ( - CONF_FRIENDLY_NAME, CONF_SWITCHES, - CONF_COMMAND_OFF, CONF_COMMAND_ON, - CONF_TIMEOUT, CONF_HOST, CONF_MAC, CONF_TYPE) + CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_FRIENDLY_NAME, CONF_HOST, CONF_MAC, + CONF_SWITCHES, CONF_TIMEOUT, CONF_TYPE) import homeassistant.helpers.config_validation as cv +from homeassistant.util import Throttle +from homeassistant.util.dt import utcnow REQUIREMENTS = ['broadlink==0.5'] @@ -41,7 +40,7 @@ RM_TYPES = ['rm', 'rm2', 'rm_mini', 'rm_pro_phicomm', 'rm2_home_plus', 'rm2_pro_plus_bl', 'rm_mini_shate'] SP1_TYPES = ['sp1'] SP2_TYPES = ['sp2', 'honeywell_sp2', 'sp3', 'spmini2', 'spminiplus'] -MP1_TYPES = ["mp1"] +MP1_TYPES = ['mp1'] SWITCH_TYPES = RM_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES @@ -71,7 +70,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up Broadlink switches.""" + """Set up the Broadlink switches.""" import broadlink devices = config.get(CONF_SWITCHES) slots = config.get('slots', {}) @@ -83,6 +82,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): @asyncio.coroutine def _learn_command(call): + """Handle a learn command.""" try: auth = yield from hass.async_add_job(broadlink_device.auth) except socket.timeout: @@ -94,7 +94,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): yield from hass.async_add_job(broadlink_device.enter_learning) - _LOGGER.info("Press the key you want HASS to learn") + _LOGGER.info("Press the key you want Home Assistant to learn") start_time = utcnow() while (utcnow() - start_time) < timedelta(seconds=20): packet = yield from hass.async_add_job( @@ -113,6 +113,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): @asyncio.coroutine def _send_packet(call): + """Send a packet.""" packets = call.data.get('packet', []) for packet in packets: for retry in range(DEFAULT_RETRY): @@ -133,6 +134,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): _LOGGER.error("Failed to send packet to device") def _get_mp1_slot_name(switch_friendly_name, slot): + """Get slot name.""" if not slots['slot_{}'.format(slot)]: return '{} slot {}'.format(switch_friendly_name, slot) return slots['slot_{}'.format(slot)] @@ -288,6 +290,7 @@ class BroadlinkSP2Switch(BroadlinkSP1Switch): self._update() def _update(self, retry=2): + """Update the state of the device.""" try: state = self._device.check_power() except (socket.timeout, ValueError) as error: @@ -333,7 +336,7 @@ class BroadlinkMP1Slot(BroadlinkRMSwitch): @property def should_poll(self): - """Polling needed.""" + """Return the polling state.""" return True def update(self): @@ -360,6 +363,7 @@ class BroadlinkMP1Switch(object): self._update() def _update(self, retry=2): + """Update the state of the device.""" try: states = self._device.check_power() except (socket.timeout, ValueError) as error: @@ -374,6 +378,7 @@ class BroadlinkMP1Switch(object): self._states = states def _auth(self, retry=2): + """Authenticate the device.""" try: auth = self._device.auth() except socket.timeout: diff --git a/homeassistant/components/switch/doorbird.py b/homeassistant/components/switch/doorbird.py index 66c3bf731164..4ab8eea6ec4b 100644 --- a/homeassistant/components/switch/doorbird.py +++ b/homeassistant/components/switch/doorbird.py @@ -1,10 +1,11 @@ """Support for powering relays in a DoorBird video doorbell.""" import datetime import logging + import voluptuous as vol from homeassistant.components.doorbird import DOMAIN as DOORBIRD_DOMAIN -from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA +from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_SWITCHES import homeassistant.helpers.config_validation as cv @@ -62,12 +63,12 @@ class DoorBirdSwitch(SwitchDevice): @property def name(self): - """Get the name of the switch.""" + """Return the name of the switch.""" return SWITCHES[self._switch]["name"] @property def icon(self): - """Get an icon to display.""" + """Return the icon to display.""" return "mdi:{}".format(SWITCHES[self._switch]["icon"][self._state]) @property @@ -86,9 +87,9 @@ class DoorBirdSwitch(SwitchDevice): self._assume_off = now + SWITCHES[self._switch]["time"] def turn_off(self, **kwargs): - """The relays are time-based.""" - raise NotImplementedError("DoorBird relays cannot be manually turned " - "off.") + """Turn off the relays is not needed. They are time-based.""" + raise NotImplementedError( + "DoorBird relays cannot be manually turned off.") def update(self): """Wait for the correct amount of assumed time to pass.""" diff --git a/homeassistant/components/switch/knx.py b/homeassistant/components/switch/knx.py index d1c6d717945a..e0b656aafe98 100644 --- a/homeassistant/components/switch/knx.py +++ b/homeassistant/components/switch/knx.py @@ -5,9 +5,10 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.knx/ """ import asyncio + import voluptuous as vol -from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES +from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_NAME from homeassistant.core import callback @@ -27,20 +28,16 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @asyncio.coroutine -def async_setup_platform(hass, config, async_add_devices, - discovery_info=None): +def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up switch(es) for KNX platform.""" - if DATA_KNX not in hass.data \ - or not hass.data[DATA_KNX].initialized: - return False + if DATA_KNX not in hass.data or not hass.data[DATA_KNX].initialized: + return if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) - return True - @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): @@ -69,7 +66,7 @@ class KNXSwitch(SwitchDevice): """Representation of a KNX switch.""" def __init__(self, hass, device): - """Initialization of KNXSwitch.""" + """Initialize of KNX switch.""" self.device = device self.hass = hass self.async_register_callbacks() @@ -79,7 +76,7 @@ class KNXSwitch(SwitchDevice): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): - """Callback after device was updated.""" + """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) @@ -91,12 +88,12 @@ class KNXSwitch(SwitchDevice): @property def available(self): - """Return True if entity is available.""" + """Return true if entity is available.""" return self.hass.data[DATA_KNX].connected @property def should_poll(self): - """No polling needed within KNX.""" + """Return the polling state. Not needed within KNX.""" return False @property diff --git a/homeassistant/components/switch/rachio.py b/homeassistant/components/switch/rachio.py index c9b6011bcbdf..a1ce83b597ad 100644 --- a/homeassistant/components/switch/rachio.py +++ b/homeassistant/components/switch/rachio.py @@ -1,20 +1,27 @@ -"""Integration with the Rachio Iro sprinkler system controller.""" -import logging +""" +Integration with the Rachio Iro sprinkler system controller. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/switch.rachio/ +""" from datetime import timedelta +import logging + import voluptuous as vol +from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice +from homeassistant.const import CONF_ACCESS_TOKEN import homeassistant.helpers.config_validation as cv import homeassistant.util as util -from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA -from homeassistant.const import CONF_ACCESS_TOKEN REQUIREMENTS = ['rachiopy==0.1.2'] _LOGGER = logging.getLogger(__name__) +CONF_MANUAL_RUN_MINS = 'manual_run_mins' + DATA_RACHIO = 'rachio' -CONF_MANUAL_RUN_MINS = 'manual_run_mins' DEFAULT_MANUAL_RUN_MINS = 10 MIN_UPDATE_INTERVAL = timedelta(seconds=30) @@ -23,50 +30,49 @@ MIN_FORCED_UPDATE_INTERVAL = timedelta(seconds=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ACCESS_TOKEN): cv.string, vol.Optional(CONF_MANUAL_RUN_MINS, default=DEFAULT_MANUAL_RUN_MINS): - cv.positive_int + cv.positive_int, }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the component.""" + """Set up the Rachio switches.""" + from rachiopy import Rachio + # Get options manual_run_mins = config.get(CONF_MANUAL_RUN_MINS) _LOGGER.debug("Rachio run time is %d min", manual_run_mins) - # Get access token - _LOGGER.debug("Getting Rachio access token...") access_token = config.get(CONF_ACCESS_TOKEN) # Configure API - _LOGGER.debug("Configuring Rachio API...") - from rachiopy import Rachio + _LOGGER.debug("Configuring Rachio API") rachio = Rachio(access_token) + person = None try: person = _get_person(rachio) except KeyError: - _LOGGER.error("Could not reach the Rachio API. " - "Is your access token valid?") - return False + _LOGGER.error( + "Could not reach the Rachio API. Is your access token valid?") + return # Get and persist devices devices = _list_devices(rachio, manual_run_mins) if not devices: - _LOGGER.error("No Rachio devices found in account " + - person['username']) - return False + _LOGGER.error( + "No Rachio devices found in account %s", person['username']) + return hass.data[DATA_RACHIO] = devices[0] if len(devices) > 1: _LOGGER.warning("Multiple Rachio devices found in account, " - "using " + hass.data[DATA_RACHIO].device_id) + "using %s", hass.data[DATA_RACHIO].device_id) else: - _LOGGER.info("Found Rachio device") + _LOGGER.debug("Found Rachio device") hass.data[DATA_RACHIO].update() add_devices(hass.data[DATA_RACHIO].list_zones()) - return True def _get_person(rachio): @@ -82,10 +88,10 @@ def _list_devices(rachio, manual_run_mins): class RachioIro(object): - """Represents one Rachio Iro.""" + """Representation of a Rachio Iro.""" def __init__(self, rachio, device_id, manual_run_mins): - """Initialize a new device.""" + """Initialize a Rachio device.""" self.rachio = rachio self._device_id = device_id self.manual_run_mins = manual_run_mins @@ -95,40 +101,40 @@ class RachioIro(object): def __str__(self): """Display the device as a string.""" - return "Rachio Iro " + self.serial_number + return "Rachio Iro {}".format(self.serial_number) @property def device_id(self): - """How the Rachio API refers to the device.""" + """Return the Rachio API device ID.""" return self._device['id'] @property def status(self): - """The current status of the device.""" + """Return the current status of the device.""" return self._device['status'] @property def serial_number(self): - """The serial number of the device.""" + """Return the serial number of the device.""" return self._device['serialNumber'] @property def is_paused(self): - """Whether the device is temporarily disabled.""" + """Return whether the device is temporarily disabled.""" return self._device['paused'] @property def is_on(self): - """Whether the device is powered on and connected.""" + """Return whether the device is powered on and connected.""" return self._device['on'] @property def current_schedule(self): - """The schedule that the device is running right now.""" + """Return the schedule that the device is running right now.""" return self._running def list_zones(self, include_disabled=False): - """A list of the zones connected to the device and their data.""" + """Return alist of the zones connected to the device, incl. data.""" if not self._zones: self._zones = [RachioZone(self.rachio, self, zone['id'], self.manual_run_mins) @@ -155,7 +161,7 @@ class RachioIro(object): class RachioZone(SwitchDevice): - """Represents one zone of sprinklers connected to the Rachio Iro.""" + """Representation of one zone of sprinklers connected to the Rachio Iro.""" def __init__(self, rachio, device, zone_id, manual_run_mins): """Initialize a new Rachio Zone.""" @@ -167,7 +173,7 @@ class RachioZone(SwitchDevice): def __str__(self): """Display the zone as a string.""" - return "Rachio Zone " + self.name + return "Rachio Zone {}".format(self.name) @property def zone_id(self): @@ -176,29 +182,28 @@ class RachioZone(SwitchDevice): @property def unique_id(self): - """Generate a unique string ID for the zone.""" + """Return the unique string ID for the zone.""" return '{iro}-{zone}'.format( - iro=self._device.device_id, - zone=self.zone_id) + iro=self._device.device_id, zone=self.zone_id) @property def number(self): - """The physical connection of the zone pump.""" + """Return the physical connection of the zone pump.""" return self._zone['zoneNumber'] @property def name(self): - """The friendly name of the zone.""" + """Return the friendly name of the zone.""" return self._zone['name'] @property def is_enabled(self): - """Whether the zone is allowed to run.""" + """Return whether the zone is allowed to run.""" return self._zone['enabled'] @property def is_on(self): - """Whether the zone is currently running.""" + """Return whether the zone is currently running.""" schedule = self._device.current_schedule return self.zone_id == schedule.get('zoneId') diff --git a/homeassistant/components/switch/raspihats.py b/homeassistant/components/switch/raspihats.py index 145697ef7c50..183ee6edb774 100644 --- a/homeassistant/components/switch/raspihats.py +++ b/homeassistant/components/switch/raspihats.py @@ -5,18 +5,17 @@ For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.raspihats/ """ import logging + import voluptuous as vol -from homeassistant.const import ( - CONF_NAME, DEVICE_DEFAULT_NAME -) -import homeassistant.helpers.config_validation as cv -from homeassistant.components.switch import PLATFORM_SCHEMA -from homeassistant.helpers.entity import ToggleEntity + from homeassistant.components.raspihats import ( - CONF_I2C_HATS, CONF_BOARD, CONF_ADDRESS, CONF_CHANNELS, CONF_INDEX, - CONF_INVERT_LOGIC, CONF_INITIAL_STATE, I2C_HAT_NAMES, I2C_HATS_MANAGER, - I2CHatsException -) + CONF_ADDRESS, CONF_BOARD, CONF_CHANNELS, CONF_I2C_HATS, CONF_INDEX, + CONF_INITIAL_STATE, CONF_INVERT_LOGIC, I2C_HAT_NAMES, I2C_HATS_MANAGER, + I2CHatsException) +from homeassistant.components.switch import PLATFORM_SCHEMA +from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import ToggleEntity _LOGGER = logging.getLogger(__name__) @@ -32,7 +31,7 @@ _CHANNELS_SCHEMA = vol.Schema([{ _I2C_HATS_SCHEMA = vol.Schema([{ vol.Required(CONF_BOARD): vol.In(I2C_HAT_NAMES), vol.Required(CONF_ADDRESS): vol.Coerce(int), - vol.Required(CONF_CHANNELS): _CHANNELS_SCHEMA + vol.Required(CONF_CHANNELS): _CHANNELS_SCHEMA, }]) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -42,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the raspihats switch devices.""" + """Set up the raspihats switch devices.""" I2CHatSwitch.I2C_HATS_MANAGER = hass.data[I2C_HATS_MANAGER] switches = [] i2c_hat_configs = config.get(CONF_I2C_HATS) @@ -54,9 +53,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): for channel_config in i2c_hat_config[CONF_CHANNELS]: switches.append( I2CHatSwitch( - board, - address, - channel_config[CONF_INDEX], + board, address, channel_config[CONF_INDEX], channel_config[CONF_NAME], channel_config[CONF_INVERT_LOGIC], channel_config[CONF_INITIAL_STATE] @@ -64,25 +61,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None): ) except I2CHatsException as ex: _LOGGER.error( - "Failed to register " + board + "I2CHat@" + hex(address) + " " - + str(ex) - ) + "Failed to register %s I2CHat@%s %s", board, hex(address), + str(ex)) add_devices(switches) class I2CHatSwitch(ToggleEntity): - """Represents a switch that uses a I2C-HAT digital output.""" + """Representation a switch that uses a I2C-HAT digital output.""" I2C_HATS_MANAGER = None - def __init__( - self, - board, - address, - channel, - name, - invert_logic, - initial_state): + def __init__(self, board, address, channel, name, invert_logic, + initial_state): """Initialize switch.""" self._board = board self._address = address @@ -95,22 +85,17 @@ class I2CHatSwitch(ToggleEntity): else: state = initial_state self.I2C_HATS_MANAGER.write_dq( - self._address, - self._channel, - state - ) + self._address, self._channel, state) def online_callback(): - """Callback fired when board is online.""" + """Call fired when board is online.""" self.schedule_update_ha_state() self.I2C_HATS_MANAGER.register_online_callback( - self._address, - self._channel, - online_callback - ) + self._address, self._channel, online_callback) def _log_message(self, message): + """Create log message.""" string = self._name + " " string += self._board + "I2CHat@" + hex(self._address) + " " string += "channel:" + str(self._channel) + message @@ -123,50 +108,34 @@ class I2CHatSwitch(ToggleEntity): @property def should_poll(self): - """Polling not needed.""" + """Return the polling state.""" return False @property def is_on(self): """Return true if device is on.""" try: - state = self.I2C_HATS_MANAGER.read_dq( - self._address, - self._channel - ) + state = self.I2C_HATS_MANAGER.read_dq(self._address, self._channel) return state != self._invert_logic except I2CHatsException as ex: - _LOGGER.error( - self._log_message("Is ON check failed, " + str(ex)) - ) + _LOGGER.error(self._log_message("Is ON check failed, " + str(ex))) return False def turn_on(self): """Turn the device on.""" try: state = True if self._invert_logic is False else False - self.I2C_HATS_MANAGER.write_dq( - self._address, - self._channel, - state - ) + self.I2C_HATS_MANAGER.write_dq(self._address, self._channel, state) self.schedule_update_ha_state() except I2CHatsException as ex: - _LOGGER.error( - self._log_message("Turn ON failed, " + str(ex)) - ) + _LOGGER.error(self._log_message("Turn ON failed, " + str(ex))) def turn_off(self): """Turn the device off.""" try: state = False if self._invert_logic is False else True - self.I2C_HATS_MANAGER.write_dq( - self._address, - self._channel, - state - ) + self.I2C_HATS_MANAGER.write_dq(self._address, self._channel, state) self.schedule_update_ha_state() except I2CHatsException as ex: _LOGGER.error( - self._log_message("Turn OFF failed, " + str(ex)) - ) + self._log_message("Turn OFF failed:, " + str(ex))) diff --git a/homeassistant/components/switch/rpi_pfio.py b/homeassistant/components/switch/rpi_pfio.py index 6e50725b564a..a493a8e95895 100644 --- a/homeassistant/components/switch/rpi_pfio.py +++ b/homeassistant/components/switch/rpi_pfio.py @@ -8,11 +8,11 @@ import logging import voluptuous as vol -from homeassistant.components.switch import PLATFORM_SCHEMA import homeassistant.components.rpi_pfio as rpi_pfio +from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.const import DEVICE_DEFAULT_NAME -from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import ToggleEntity _LOGGER = logging.getLogger(__name__) @@ -20,24 +20,25 @@ DEPENDENCIES = ['rpi_pfio'] ATTR_INVERT_LOGIC = 'invert_logic' ATTR_NAME = 'name' + CONF_PORTS = 'ports' DEFAULT_INVERT_LOGIC = False PORT_SCHEMA = vol.Schema({ vol.Optional(ATTR_NAME, default=None): cv.string, - vol.Optional(ATTR_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean + vol.Optional(ATTR_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_PORTS, default={}): vol.Schema({ - cv.positive_int: PORT_SCHEMA + cv.positive_int: PORT_SCHEMA, }) }) def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the PiFace Digital Output devices.""" + """Set up the PiFace Digital Output devices.""" switches = [] ports = config.get(CONF_PORTS) for port, port_entity in ports.items(): @@ -66,7 +67,7 @@ class RPiPFIOSwitch(ToggleEntity): @property def should_poll(self): - """No polling needed.""" + """Return the polling state.""" return False @property diff --git a/homeassistant/components/switch/telnet.py b/homeassistant/components/switch/telnet.py index 4d3db97f56e2..7c69b31aa00a 100644 --- a/homeassistant/components/switch/telnet.py +++ b/homeassistant/components/switch/telnet.py @@ -4,17 +4,17 @@ Support for switch controlled using a telnet connection. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.telnet/ """ +from datetime import timedelta import logging import telnetlib -from datetime import timedelta import voluptuous as vol -from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA, - ENTITY_ID_FORMAT) +from homeassistant.components.switch import ( + ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchDevice) from homeassistant.const import ( - CONF_RESOURCE, CONF_NAME, CONF_SWITCHES, CONF_VALUE_TEMPLATE, - CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_PORT) + CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_NAME, + CONF_PORT, CONF_RESOURCE, CONF_SWITCHES, CONF_VALUE_TEMPLATE) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -22,13 +22,13 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_PORT = 23 SWITCH_SCHEMA = vol.Schema({ - vol.Required(CONF_COMMAND_ON): cv.string, vol.Required(CONF_COMMAND_OFF): cv.string, + vol.Required(CONF_COMMAND_ON): cv.string, + vol.Required(CONF_RESOURCE): cv.string, + vol.Required(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_COMMAND_STATE): cv.string, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, - vol.Required(CONF_RESOURCE): cv.string, - vol.Required(CONF_VALUE_TEMPLATE): cv.template, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ @@ -66,7 +66,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): if not switches: _LOGGER.error("No switches added") - return False + return add_devices(switches) @@ -117,7 +117,7 @@ class TelnetSwitch(SwitchDevice): @property def assumed_state(self): - """Default ist true if no state command is defined, false otherwise.""" + """Return true if no state command is defined, false otherwise.""" return self._command_state is None def update(self): diff --git a/homeassistant/components/switch/tesla.py b/homeassistant/components/switch/tesla.py index 7de0c417d566..2f105a709adf 100644 --- a/homeassistant/components/switch/tesla.py +++ b/homeassistant/components/switch/tesla.py @@ -7,8 +7,9 @@ https://home-assistant.io/components/switch.tesla/ import logging from homeassistant.components.switch import ENTITY_ID_FORMAT, SwitchDevice -from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN, TeslaDevice -from homeassistant.const import STATE_ON, STATE_OFF +from homeassistant.components.tesla import DOMAIN as TESLA_DOMAIN +from homeassistant.components.tesla import TeslaDevice +from homeassistant.const import STATE_OFF, STATE_ON _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['tesla'] @@ -25,7 +26,7 @@ class ChargerSwitch(TeslaDevice, SwitchDevice): """Representation of a Tesla charger switch.""" def __init__(self, tesla_device, controller): - """Initialisation of the switch.""" + """Initialise of the switch.""" self._state = None super().__init__(tesla_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.tesla_id) @@ -46,7 +47,7 @@ class ChargerSwitch(TeslaDevice, SwitchDevice): return self._state == STATE_ON def update(self): - """Updating state of the switch.""" + """Update the state of the switch.""" _LOGGER.debug("Updating state for: %s", self._name) self.tesla_device.update() self._state = STATE_ON if self.tesla_device.is_charging() \ diff --git a/homeassistant/components/switch/toon.py b/homeassistant/components/switch/toon.py index d5f50be0befe..09dc45c6587b 100644 --- a/homeassistant/components/switch/toon.py +++ b/homeassistant/components/switch/toon.py @@ -6,20 +6,20 @@ https://home-assistant.io/components/switch.toon/ """ import logging -import homeassistant.components.toon as toon_main from homeassistant.components.switch import SwitchDevice +import homeassistant.components.toon as toon_main _LOGGER = logging.getLogger(__name__) -def setup_platform(hass, config, add_devices_callback, discovery_info=None): +def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the discovered Toon Smart Plugs.""" _toon_main = hass.data[toon_main.TOON_HANDLE] switch_items = [] for plug in _toon_main.toon.smartplugs: switch_items.append(EnecoSmartPlug(hass, plug)) - add_devices_callback(switch_items) + add_devices(switch_items) class EnecoSmartPlug(SwitchDevice): @@ -42,12 +42,12 @@ class EnecoSmartPlug(SwitchDevice): @property def current_power_w(self): - """Current power usage in W.""" + """Return the current power usage in W.""" return self.toon_data_store.get_data('current_power', self.name) @property def today_energy_kwh(self): - """Today total energy usage in kWh.""" + """Return the today total energy usage in kWh.""" return self.toon_data_store.get_data('today_energy', self.name) @property @@ -57,7 +57,7 @@ class EnecoSmartPlug(SwitchDevice): @property def available(self): - """True if switch is available.""" + """Return true if switch is available.""" return self.smartplug.can_toggle def turn_on(self, **kwargs): diff --git a/homeassistant/components/switch/vultr.py b/homeassistant/components/switch/vultr.py index 888db754f012..a044fca29728 100644 --- a/homeassistant/components/switch/vultr.py +++ b/homeassistant/components/switch/vultr.py @@ -24,7 +24,7 @@ DEPENDENCIES = ['vultr'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_SUBSCRIPTION): cv.string, - vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) diff --git a/homeassistant/components/switch/wink.py b/homeassistant/components/switch/wink.py index 8bd4c9fa53bc..5a43de9425c2 100644 --- a/homeassistant/components/switch/wink.py +++ b/homeassistant/components/switch/wink.py @@ -7,7 +7,7 @@ https://home-assistant.io/components/switch.wink/ import asyncio import logging -from homeassistant.components.wink import WinkDevice, DOMAIN +from homeassistant.components.wink import DOMAIN, WinkDevice from homeassistant.helpers.entity import ToggleEntity DEPENDENCIES = ['wink'] @@ -42,7 +42,7 @@ class WinkToggleDevice(WinkDevice, ToggleEntity): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['switch'].append(self) @property diff --git a/homeassistant/components/tesla.py b/homeassistant/components/tesla.py index 64ffe40d428b..4f76b70432e9 100644 --- a/homeassistant/components/tesla.py +++ b/homeassistant/components/tesla.py @@ -6,12 +6,13 @@ https://home-assistant.io/components/tesla/ """ from collections import defaultdict import logging + import voluptuous as vol from homeassistant.const import ( - ATTR_BATTERY_LEVEL, CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL) -from homeassistant.helpers import discovery + ATTR_BATTERY_LEVEL, CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME) from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import discovery from homeassistant.helpers.entity import Entity from homeassistant.util import slugify @@ -42,7 +43,7 @@ TESLA_COMPONENTS = [ def setup(hass, base_config): - """Set up of Tesla platform.""" + """Set up of Tesla component.""" from teslajsonpy import Controller as teslaAPI, TeslaException config = base_config.get(DOMAIN) @@ -53,8 +54,7 @@ def setup(hass, base_config): if hass.data.get(DOMAIN) is None: try: hass.data[DOMAIN] = { - 'controller': teslaAPI( - email, password, update_interval), + 'controller': teslaAPI(email, password, update_interval), 'devices': defaultdict(list) } _LOGGER.debug("Connected to the Tesla API.") @@ -95,7 +95,7 @@ class TeslaDevice(Entity): """Representation of a Tesla device.""" def __init__(self, tesla_device, controller): - """Initialisation of the Tesla device.""" + """Initialise of the Tesla device.""" self.tesla_device = tesla_device self.controller = controller self._name = self.tesla_device.name @@ -108,7 +108,7 @@ class TeslaDevice(Entity): @property def should_poll(self): - """Get polling requirement from tesla device.""" + """Return the polling state.""" return self.tesla_device.should_poll @property diff --git a/homeassistant/components/vacuum/dyson.py b/homeassistant/components/vacuum/dyson.py index 476e347055a2..aa05d004a35f 100644 --- a/homeassistant/components/vacuum/dyson.py +++ b/homeassistant/components/vacuum/dyson.py @@ -8,25 +8,23 @@ import asyncio import logging from homeassistant.components.dyson import DYSON_DEVICES -from homeassistant.components.vacuum import (SUPPORT_BATTERY, - SUPPORT_FAN_SPEED, SUPPORT_PAUSE, - SUPPORT_RETURN_HOME, - SUPPORT_STATUS, SUPPORT_STOP, - SUPPORT_TURN_OFF, SUPPORT_TURN_ON, - VacuumDevice) +from homeassistant.components.vacuum import ( + SUPPORT_BATTERY, SUPPORT_FAN_SPEED, SUPPORT_PAUSE, SUPPORT_RETURN_HOME, + SUPPORT_STATUS, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, + VacuumDevice) from homeassistant.helpers.icon import icon_for_battery_level -ATTR_FULL_CLEAN_TYPE = "full_clean_type" -ATTR_CLEAN_ID = "clean_id" -ATTR_POSITION = "position" - -DEPENDENCIES = ['dyson'] - _LOGGER = logging.getLogger(__name__) +ATTR_CLEAN_ID = 'clean_id' +ATTR_FULL_CLEAN_TYPE = 'full_clean_type' +ATTR_POSITION = 'position' + +DEPENDENCIES = ['dyson'] + DYSON_360_EYE_DEVICES = "dyson_360_eye_devices" -ICON = "mdi:roomba" +ICON = 'mdi:roomba' SUPPORT_DYSON = SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PAUSE | \ SUPPORT_RETURN_HOME | SUPPORT_FAN_SPEED | SUPPORT_STATUS | \ @@ -35,12 +33,13 @@ SUPPORT_DYSON = SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PAUSE | \ def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Dyson 360 Eye robot vacuum platform.""" - _LOGGER.info("Creating new Dyson 360 Eye robot vacuum") + from libpurecoollink.dyson_360_eye import Dyson360Eye + + _LOGGER.debug("Creating new Dyson 360 Eye robot vacuum") if DYSON_360_EYE_DEVICES not in hass.data: hass.data[DYSON_360_EYE_DEVICES] = [] # Get Dyson Devices from parent component - from libpurecoollink.dyson_360_eye import Dyson360Eye for device in [d for d in hass.data[DYSON_DEVICES] if isinstance(d, Dyson360Eye)]: dyson_entity = Dyson360EyeDevice(device) @@ -55,18 +54,18 @@ class Dyson360EyeDevice(VacuumDevice): def __init__(self, device): """Dyson 360 Eye robot vacuum device.""" - _LOGGER.info("Creating device %s", device.name) + _LOGGER.debug("Creating device %s", device.name) self._device = device self._icon = ICON @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.async_add_job( self._device.add_message_listener, self.on_message) def on_message(self, message): - """Called when new messages received from the vacuum.""" + """Handle a new messages that was received from the vacuum.""" _LOGGER.debug("Message received for %s device: %s", self.name, message) self.schedule_update_ha_state() @@ -105,8 +104,8 @@ class Dyson360EyeDevice(VacuumDevice): Dyson360EyeMode.FULL_CLEAN_FINISHED: "Finished", Dyson360EyeMode.FULL_CLEAN_NEEDS_CHARGE: "Need charging" } - return dyson_labels.get(self._device.state.state, - self._device.state.state) + return dyson_labels.get( + self._device.state.state, self._device.state.state) @property def battery_level(self): @@ -139,6 +138,7 @@ class Dyson360EyeDevice(VacuumDevice): def is_on(self) -> bool: """Return True if entity is on.""" from libpurecoollink.const import Dyson360EyeMode + return self._device.state.state in [ Dyson360EyeMode.FULL_CLEAN_INITIATED, Dyson360EyeMode.FULL_CLEAN_ABORTED, @@ -159,6 +159,7 @@ class Dyson360EyeDevice(VacuumDevice): def battery_icon(self): """Return the battery icon for the vacuum cleaner.""" from libpurecoollink.const import Dyson360EyeMode + charging = self._device.state.state in [ Dyson360EyeMode.INACTIVE_CHARGING] return icon_for_battery_level( @@ -166,8 +167,9 @@ class Dyson360EyeDevice(VacuumDevice): def turn_on(self, **kwargs): """Turn the vacuum on.""" - _LOGGER.debug("Turn on device %s", self.name) from libpurecoollink.const import Dyson360EyeMode + + _LOGGER.debug("Turn on device %s", self.name) if self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]: self._device.resume() else: @@ -185,8 +187,9 @@ class Dyson360EyeDevice(VacuumDevice): def set_fan_speed(self, fan_speed, **kwargs): """Set fan speed.""" - _LOGGER.debug("Set fan speed %s on device %s", fan_speed, self.name) from libpurecoollink.const import PowerMode + + _LOGGER.debug("Set fan speed %s on device %s", fan_speed, self.name) power_modes = { "Quiet": PowerMode.QUIET, "Max": PowerMode.MAX @@ -196,6 +199,7 @@ class Dyson360EyeDevice(VacuumDevice): def start_pause(self, **kwargs): """Start, pause or resume the cleaning task.""" from libpurecoollink.const import Dyson360EyeMode + if self._device.state.state in [Dyson360EyeMode.FULL_CLEAN_PAUSED]: _LOGGER.debug("Resume device %s", self.name) self._device.resume() diff --git a/homeassistant/components/vacuum/mqtt.py b/homeassistant/components/vacuum/mqtt.py index 54aea793a22b..f4c640f1fc73 100644 --- a/homeassistant/components/vacuum/mqtt.py +++ b/homeassistant/components/vacuum/mqtt.py @@ -10,7 +10,6 @@ import logging import voluptuous as vol import homeassistant.components.mqtt as mqtt -import homeassistant.helpers.config_validation as cv from homeassistant.components.mqtt import MqttAvailability from homeassistant.components.vacuum import ( DEFAULT_ICON, SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_FAN_SPEED, @@ -19,6 +18,7 @@ from homeassistant.components.vacuum import ( VacuumDevice) from homeassistant.const import ATTR_SUPPORTED_FEATURES, CONF_NAME from homeassistant.core import callback +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.icon import icon_for_battery_level _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/vacuum/neato.py b/homeassistant/components/vacuum/neato.py index e1c4a5952af1..29099db5cd55 100644 --- a/homeassistant/components/vacuum/neato.py +++ b/homeassistant/components/vacuum/neato.py @@ -24,7 +24,7 @@ SUPPORT_NEATO = SUPPORT_BATTERY | SUPPORT_PAUSE | SUPPORT_RETURN_HOME | \ SUPPORT_STOP | SUPPORT_TURN_OFF | SUPPORT_TURN_ON | \ SUPPORT_STATUS | SUPPORT_MAP -ICON = "mdi:roomba" +ICON = 'mdi:roomba' ATTR_CLEAN_START = 'clean_start' ATTR_CLEAN_STOP = 'clean_stop' @@ -45,10 +45,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): class NeatoConnectedVacuum(VacuumDevice): - """Neato Connected Vacuums.""" + """Representation of a Neato Connected Vacuum.""" def __init__(self, hass, robot): - """Initialize the Neato Connected Vacuums.""" + """Initialize the Neato Connected Vacuum.""" self.robot = robot self.neato = hass.data[NEATO_LOGIN] self._name = '{}'.format(self.robot.name) @@ -66,7 +66,7 @@ class NeatoConnectedVacuum(VacuumDevice): def update(self): """Update the states of Neato Vacuums.""" - _LOGGER.debug("Running Vacuums update") + _LOGGER.debug("Running Neato Vacuums update") self.neato.update_robots() try: self._state = self.robot.state diff --git a/homeassistant/components/weather/yweather.py b/homeassistant/components/weather/yweather.py index 20ed97ec249d..bbf9f1ae5908 100644 --- a/homeassistant/components/weather/yweather.py +++ b/homeassistant/components/weather/yweather.py @@ -4,16 +4,15 @@ Support for the Yahoo! Weather service. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/weather.yweather/ """ -import logging from datetime import timedelta +import logging import voluptuous as vol -import homeassistant.helpers.config_validation as cv from homeassistant.components.weather import ( - WeatherEntity, PLATFORM_SCHEMA, - ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME) -from homeassistant.const import (TEMP_CELSIUS, CONF_NAME, STATE_UNKNOWN) + ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME, PLATFORM_SCHEMA, WeatherEntity) +from homeassistant.const import CONF_NAME, STATE_UNKNOWN, TEMP_CELSIUS +import homeassistant.helpers.config_validation as cv REQUIREMENTS = ["yahooweather==0.10"] @@ -57,7 +56,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ def setup_platform(hass, config, add_devices, discovery_info=None): - """Setup the Yahoo! weather platform.""" + """Set up the Yahoo! weather platform.""" from yahooweather import get_woeid, UNIT_C, UNIT_F unit = hass.config.units.temperature_unit diff --git a/homeassistant/components/wink/__init__.py b/homeassistant/components/wink/__init__.py index c903b5a0ddf3..476f089b5926 100644 --- a/homeassistant/components/wink/__init__.py +++ b/homeassistant/components/wink/__init__.py @@ -5,26 +5,25 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/wink/ """ import asyncio -import logging -import time -import json -import os from datetime import timedelta +import json +import logging +import os +import time import voluptuous as vol -from homeassistant.core import callback from homeassistant.components.http import HomeAssistantView -from homeassistant.helpers import discovery -from homeassistant.helpers.event import track_time_interval from homeassistant.const import ( - ATTR_BATTERY_LEVEL, CONF_EMAIL, CONF_PASSWORD, - EVENT_HOMEASSISTANT_START, - EVENT_HOMEASSISTANT_STOP, __version__, ATTR_ENTITY_ID, - STATE_ON, STATE_OFF) + ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, CONF_EMAIL, CONF_PASSWORD, + EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, STATE_OFF, STATE_ON, + __version__) +from homeassistant.core import callback +from homeassistant.helpers import discovery +import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent -import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.event import track_time_interval from homeassistant.util.json import load_json, save_json REQUIREMENTS = ['python-wink==1.7.1', 'pubnubsub-handler==1.0.2'] @@ -54,7 +53,7 @@ ATTR_HUB_NAME = 'hub_name' WINK_AUTH_CALLBACK_PATH = '/auth/wink/callback' WINK_AUTH_START = '/auth/wink' WINK_CONFIG_FILE = '.wink.conf' -USER_AGENT = "Manufacturer/Home-Assistant%s python/3 Wink/3" % (__version__) +USER_AGENT = "Manufacturer/Home-Assistant%s python/3 Wink/3" % __version__ DEFAULT_CONFIG = { 'client_id': 'CLIENT_ID_HERE', @@ -175,7 +174,7 @@ def _request_app_setup(hass, config): setup(hass, config) return else: - error_msg = ("Your input was invalid. Please try again.") + error_msg = "Your input was invalid. Please try again." _configurator = hass.data[DOMAIN]['configuring'][DOMAIN] configurator.notify_errors(_configurator, error_msg) @@ -221,9 +220,7 @@ def _request_oauth_completion(hass, config): description = "Please authorize Wink by visiting {}".format(start_url) hass.data[DOMAIN]['configuring'][DOMAIN] = configurator.request_config( - DOMAIN, wink_configuration_callback, - description=description - ) + DOMAIN, wink_configuration_callback, description=description) def setup(hass, config): @@ -255,7 +252,7 @@ def setup(hass, config): local_control = None hass.data[DOMAIN]['configurator'] = True if None not in [client_id, client_secret]: - _LOGGER.info("Using legacy oauth authentication") + _LOGGER.info("Using legacy OAuth authentication") if not local_control: pywink.disable_local_control() hass.data[DOMAIN]["oauth"]["client_id"] = client_id @@ -265,7 +262,7 @@ def setup(hass, config): pywink.legacy_set_wink_credentials(email, password, client_id, client_secret) else: - _LOGGER.info("Using oauth authentication") + _LOGGER.info("Using OAuth authentication") if not local_control: pywink.disable_local_control() config_path = hass.config.path(WINK_CONFIG_FILE) @@ -296,18 +293,17 @@ def setup(hass, config): access_token=access_token, refresh_token=refresh_token) # This is called to create the redirect so the user can Authorize - # Home-Assistant + # Home . else: - redirect_uri = '{}{}'.format(hass.config.api.base_url, - WINK_AUTH_CALLBACK_PATH) + redirect_uri = '{}{}'.format( + hass.config.api.base_url, WINK_AUTH_CALLBACK_PATH) wink_auth_start_url = pywink.get_authorization_url( config_file.get(ATTR_CLIENT_ID), redirect_uri) hass.http.register_redirect(WINK_AUTH_START, wink_auth_start_url) - hass.http.register_view(WinkAuthCallbackView(config, - config_file, - pywink.request_token)) + hass.http.register_view(WinkAuthCallbackView( + config, config_file, pywink.request_token)) _request_oauth_completion(hass, config) return True @@ -327,7 +323,7 @@ def setup(hass, config): def keep_alive_call(event_time): """Call the Wink API endpoints to keep PubNub working.""" - _LOGGER.info("Polling the Wink API to keep PubNub updates flowing.") + _LOGGER.info("Polling the Wink API to keep PubNub updates flowing") pywink.set_user_agent(str(int(time.time()))) _temp_response = pywink.get_user() _LOGGER.debug(str(json.dumps(_temp_response))) @@ -340,20 +336,20 @@ def setup(hass, config): track_time_interval(hass, keep_alive_call, timedelta(minutes=60)) def start_subscription(event): - """Start the pubnub subscription.""" + """Start the PubNub subscription.""" _subscribe() hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription) def stop_subscription(event): - """Stop the pubnub subscription.""" + """Stop the PubNub subscription.""" hass.data[DOMAIN]['pubnub'].unsubscribe() hass.data[DOMAIN]['pubnub'] = None hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription) def save_credentials(event): - """Save currently set oauth credentials.""" + """Save currently set OAuth credentials.""" if hass.data[DOMAIN]["oauth"].get("email") is None: config_path = hass.config.path(WINK_CONFIG_FILE) _config = pywink.get_current_oauth_credentials() @@ -387,8 +383,7 @@ def setup(hass, config): kidde_code = call.data.get('kidde_radio_code') for hub in WINK_HUBS: if hub.name() == hub_name: - hub.pair_new_device(pairing_mode, - kidde_radio_code=kidde_code) + hub.pair_new_device(pairing_mode, kidde_radio_code=kidde_code) def rename_device(call): """Set specified device's name.""" @@ -436,7 +431,7 @@ def setup(hass, config): schema=SET_PAIRING_MODE_SCHEMA) def service_handle(service): - """Handler for services.""" + """Handle services.""" entity_ids = service.data.get('entity_id') all_sirens = [] for switch in hass.data[DOMAIN]['entities']['switch']: @@ -455,7 +450,7 @@ def setup(hass, config): if (service.service != SERVICE_SET_AUTO_SHUTOFF and service.service != SERVICE_ENABLE_SIREN and (_man != 'dome' and _man != 'wink')): - _LOGGER.error("Service only valid for Dome or Wink sirens.") + _LOGGER.error("Service only valid for Dome or Wink sirens") return if service.service == SERVICE_ENABLE_SIREN: @@ -564,17 +559,16 @@ class WinkAuthCallbackView(HomeAssistantView):

{}

""" if data.get('code') is not None: - response = self.request_token(data.get('code'), - self.config_file["client_secret"]) + response = self.request_token( + data.get('code'), self.config_file['client_secret']) config_contents = { ATTR_ACCESS_TOKEN: response['access_token'], ATTR_REFRESH_TOKEN: response['refresh_token'], - ATTR_CLIENT_ID: self.config_file["client_id"], - ATTR_CLIENT_SECRET: self.config_file["client_secret"] + ATTR_CLIENT_ID: self.config_file['client_id'], + ATTR_CLIENT_SECRET: self.config_file['client_secret'] } - save_json(hass.config.path(WINK_CONFIG_FILE), - config_contents) + save_json(hass.config.path(WINK_CONFIG_FILE), config_contents) hass.async_add_job(setup, hass, self.config) @@ -695,7 +689,7 @@ class WinkSirenDevice(WinkDevice): @asyncio.coroutine def async_added_to_hass(self): - """Callback when entity is added to hass.""" + """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['switch'].append(self) @property @@ -712,7 +706,7 @@ class WinkSirenDevice(WinkDevice): @property def device_state_attributes(self): - """Return the state attributes.""" + """Return the device state attributes.""" attributes = super(WinkSirenDevice, self).device_state_attributes auto_shutoff = self.wink.auto_shutoff() diff --git a/homeassistant/components/xiaomi_aqara.py b/homeassistant/components/xiaomi_aqara.py index 6a76ed48fd89..2aa56f7957fd 100644 --- a/homeassistant/components/xiaomi_aqara.py +++ b/homeassistant/components/xiaomi_aqara.py @@ -1,40 +1,51 @@ -"""Support for Xiaomi Gateways.""" +""" +Support for Xiaomi Gateways. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/xiaomi_aqara/ +""" import asyncio import logging + import voluptuous as vol -import homeassistant.helpers.config_validation as cv -from homeassistant.helpers import discovery -from homeassistant.helpers.entity import Entity + from homeassistant.components.discovery import SERVICE_XIAOMI_GW -from homeassistant.const import (ATTR_BATTERY_LEVEL, EVENT_HOMEASSISTANT_STOP, - CONF_MAC, CONF_HOST, CONF_PORT) +from homeassistant.const import ( + ATTR_BATTERY_LEVEL, CONF_HOST, CONF_MAC, CONF_PORT, + EVENT_HOMEASSISTANT_STOP) +from homeassistant.helpers import discovery +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity REQUIREMENTS = ['PyXiaomiGateway==0.7.1'] +_LOGGER = logging.getLogger(__name__) + ATTR_GW_MAC = 'gw_mac' ATTR_RINGTONE_ID = 'ringtone_id' ATTR_RINGTONE_VOL = 'ringtone_vol' ATTR_DEVICE_ID = 'device_id' + CONF_DISCOVERY_RETRY = 'discovery_retry' CONF_GATEWAYS = 'gateways' CONF_INTERFACE = 'interface' CONF_KEY = 'key' + DOMAIN = 'xiaomi_aqara' -PY_XIAOMI_GATEWAY = "xiaomi_gw" + +PY_XIAOMI_GATEWAY = 'xiaomi_gw' SERVICE_PLAY_RINGTONE = 'play_ringtone' SERVICE_STOP_RINGTONE = 'stop_ringtone' SERVICE_ADD_DEVICE = 'add_device' SERVICE_REMOVE_DEVICE = 'remove_device' - GW_MAC = vol.All( cv.string, lambda value: value.replace(':', '').lower(), vol.Length(min=12, max=12) ) - SERVICE_SCHEMA_PLAY_RINGTONE = vol.Schema({ vol.Required(ATTR_RINGTONE_ID): vol.All(vol.Coerce(int), vol.NotIn([9, 14, 15, 16, 17, 18, 19])), @@ -58,13 +69,13 @@ GATEWAY_CONFIG = vol.Schema({ def _fix_conf_defaults(config): - """Update some config defaults.""" + """Update some configuration defaults.""" config['sid'] = config.pop(CONF_MAC, None) if config.get(CONF_KEY) is None: _LOGGER.warning( 'Key is not provided for gateway %s. Controlling the gateway ' - 'will not be possible.', config['sid']) + 'will not be possible', config['sid']) if config.get(CONF_HOST) is None: config.pop(CONF_PORT) @@ -83,8 +94,6 @@ CONFIG_SCHEMA = vol.Schema({ }) }, extra=vol.ALLOW_EXTRA) -_LOGGER = logging.getLogger(__name__) - def setup(hass, config): """Set up the Xiaomi component.""" @@ -98,8 +107,8 @@ def setup(hass, config): @asyncio.coroutine def xiaomi_gw_discovered(service, discovery_info): - """Called when Xiaomi Gateway device(s) has been found.""" - # We don't need to do anything here, the purpose of HA's + """Perform action when Xiaomi Gateway device(s) has been found.""" + # We don't need to do anything here, the purpose of Home Assistant's # discovery service is to just trigger loading of this # component, and then its own discovery process kicks in. @@ -111,7 +120,7 @@ def setup(hass, config): _LOGGER.debug("Expecting %s gateways", len(gateways)) for k in range(discovery_retry): - _LOGGER.info('Discovering Xiaomi Gateways (Try %s)', k + 1) + _LOGGER.info("Discovering Xiaomi Gateways (Try %s)", k + 1) xiaomi.discover_gateways() if len(xiaomi.gateways) >= len(gateways): break @@ -127,7 +136,7 @@ def setup(hass, config): def stop_xiaomi(event): """Stop Xiaomi Socket.""" - _LOGGER.info("Shutting down Xiaomi Hub.") + _LOGGER.info("Shutting down Xiaomi Hub") xiaomi.stop_listen() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi) @@ -190,7 +199,7 @@ class XiaomiDevice(Entity): """Representation a base Xiaomi device.""" def __init__(self, device, name, xiaomi_hub): - """Initialize the xiaomi device.""" + """Initialize the Xiaomi device.""" self._state = None self._sid = device['sid'] self._name = '{}_{}'.format(name, self._sid) @@ -208,7 +217,7 @@ class XiaomiDevice(Entity): @property def should_poll(self): - """No polling needed.""" + """Return the polling state. No polling needed.""" return False @property diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index 6268b3cb9f7a..0cf9d83863f4 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -113,7 +113,7 @@ class IntentHandler: raise NotImplementedError() def __repr__(self): - """String representation of intent handler.""" + """Represent a string of an intent handler.""" return '<{} - {}>'.format(self.__class__.__name__, self.intent_type) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index d56cef1dd831..7eb0a6021398 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2,22 +2,24 @@ from datetime import datetime import json import logging +import math import random import re -import math import jinja2 from jinja2 import contextfilter from jinja2.sandbox import ImmutableSandboxedEnvironment from homeassistant.const import ( - STATE_UNKNOWN, ATTR_LATITUDE, ATTR_LONGITUDE, MATCH_ALL, - ATTR_UNIT_OF_MEASUREMENT) + ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_UNIT_OF_MEASUREMENT, MATCH_ALL, + STATE_UNKNOWN) from homeassistant.core import State from homeassistant.exceptions import TemplateError from homeassistant.helpers import location as loc_helper -from homeassistant.loader import get_component, bind_hass -from homeassistant.util import convert, dt as dt_util, location as loc_util +from homeassistant.loader import bind_hass, get_component +from homeassistant.util import convert +from homeassistant.util import dt as dt_util +from homeassistant.util import location as loc_util from homeassistant.util.async import run_callback_threadsafe _LOGGER = logging.getLogger(__name__) @@ -279,7 +281,7 @@ class TemplateState(State): def _wrap_state(state): - """Helper function to wrap a state.""" + """Wrap a state.""" return None if state is None else TemplateState(state) diff --git a/homeassistant/loader.py b/homeassistant/loader.py index e7a0854f047e..ac20f94d243c 100644 --- a/homeassistant/loader.py +++ b/homeassistant/loader.py @@ -1,5 +1,5 @@ """ -Provides methods for loading Home Assistant components. +The methods for loading Home Assistant components. This module has quite some complex parts. I have tried to add as much documentation as possible to keep it understandable. @@ -16,10 +16,10 @@ import logging import os import pkgutil import sys - from types import ModuleType + # pylint: disable=unused-import -from typing import Optional, Sequence, Set, Dict # NOQA +from typing import Dict, Optional, Sequence, Set # NOQA from homeassistant.const import PLATFORM_FORMAT from homeassistant.util import OrderedSet @@ -224,7 +224,7 @@ class ModuleWrapper: def bind_hass(func): - """Decorator to indicate that first argument is hass.""" + """Decorate function to indicate that first argument is hass.""" # pylint: disable=protected-access func.__bind_hass = True return func @@ -290,4 +290,4 @@ def _check_prepared() -> None: if not PREPARED: _LOGGER.warning(( "You did not call loader.prepare() yet. " - "Certain functionality might not be working.")) + "Certain functionality might not be working")) diff --git a/homeassistant/scripts/benchmark/__init__.py b/homeassistant/scripts/benchmark/__init__.py index 100d3aa35085..470040b8295c 100644 --- a/homeassistant/scripts/benchmark/__init__.py +++ b/homeassistant/scripts/benchmark/__init__.py @@ -1,21 +1,21 @@ """Script to run benchmarks.""" -import asyncio import argparse +import asyncio from contextlib import suppress from datetime import datetime import logging from timeit import default_timer as timer -from homeassistant.const import ( - EVENT_TIME_CHANGED, ATTR_NOW, EVENT_STATE_CHANGED) from homeassistant import core +from homeassistant.const import ( + ATTR_NOW, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED) from homeassistant.util import dt as dt_util BENCHMARKS = {} def run(args): - """Handle ensure config commandline script.""" + """Handle ensure configuration commandline script.""" # Disable logging logging.getLogger('homeassistant.core').setLevel(logging.CRITICAL) @@ -44,7 +44,7 @@ def run(args): def benchmark(func): - """Decorator to mark a benchmark.""" + """Decorate to mark a benchmark.""" BENCHMARKS[func.__name__] = func return func diff --git a/tests/components/sensor/test_vultr.py b/tests/components/sensor/test_vultr.py index c5222ab55431..6b2e2341c521 100644 --- a/tests/components/sensor/test_vultr.py +++ b/tests/components/sensor/test_vultr.py @@ -70,10 +70,8 @@ class TestVultrSensorSetup(unittest.TestCase): base_vultr.setup(self.hass, VALID_CONFIG) for config in self.configs: - setup = vultr.setup_platform(self.hass, - config, - self.add_devices, - None) + setup = vultr.setup_platform( + self.hass, config, self.add_devices, None) self.assertIsNone(setup) @@ -161,10 +159,8 @@ class TestVultrSensorSetup(unittest.TestCase): CONF_MONITORED_CONDITIONS: vultr.MONITORED_CONDITIONS, } # No subs at all - no_sub_setup = vultr.setup_platform(self.hass, - bad_conf, - self.add_devices, - None) + no_sub_setup = vultr.setup_platform( + self.hass, bad_conf, self.add_devices, None) - self.assertIsNotNone(no_sub_setup) + self.assertIsNone(no_sub_setup) self.assertEqual(0, len(self.DEVICES))