From b534244e404498c4fd7f5f084a2072597ccdd403 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Tue, 8 Mar 2016 17:55:57 +0100 Subject: [PATCH] Fix PEEP257 issues --- homeassistant/components/__init__.py | 30 +++-- homeassistant/components/alexa.py | 15 ++- homeassistant/components/apcupsd.py | 13 ++- homeassistant/components/api.py | 37 +++--- homeassistant/components/arduino.py | 6 +- homeassistant/components/bloomsky.py | 13 +-- homeassistant/components/browser.py | 4 +- homeassistant/components/configurator.py | 7 +- homeassistant/components/conversation.py | 10 +- .../components/device_sun_light_trigger.py | 29 ++--- homeassistant/components/discovery.py | 6 +- homeassistant/components/downloader.py | 6 +- homeassistant/components/ecobee.py | 10 +- homeassistant/components/graphite.py | 7 +- homeassistant/components/group.py | 20 ++-- homeassistant/components/history.py | 14 +-- homeassistant/components/http.py | 36 +++--- homeassistant/components/input_boolean.py | 5 +- homeassistant/components/input_select.py | 5 +- homeassistant/components/insteon_hub.py | 10 +- homeassistant/components/isy994.py | 12 +- homeassistant/components/keyboard.py | 2 +- homeassistant/components/logbook.py | 9 +- homeassistant/components/logger.py | 2 + homeassistant/components/modbus.py | 12 +- homeassistant/components/mqtt_eventstream.py | 5 +- homeassistant/components/mysensors.py | 1 + homeassistant/components/proximity.py | 10 +- homeassistant/components/recorder.py | 41 ++++--- homeassistant/components/rpi_gpio.py | 2 +- homeassistant/components/script.py | 26 +++-- homeassistant/components/scsgate.py | 25 ++-- homeassistant/components/shell_command.py | 2 +- homeassistant/components/splunk.py | 5 +- homeassistant/components/sun.py | 14 ++- homeassistant/components/tellduslive.py | 6 +- homeassistant/components/verisure.py | 16 +-- homeassistant/components/weblink.py | 4 +- homeassistant/components/wink.py | 8 +- homeassistant/components/zigbee.py | 110 +++++++++--------- homeassistant/components/zone.py | 8 +- homeassistant/components/zwave.py | 40 ++++--- 42 files changed, 335 insertions(+), 308 deletions(-) diff --git a/homeassistant/components/__init__.py b/homeassistant/components/__init__.py index 0d82e1d2882..f2696bbbd1a 100644 --- a/homeassistant/components/__init__.py +++ b/homeassistant/components/__init__.py @@ -1,16 +1,11 @@ """ -homeassistant.components -~~~~~~~~~~~~~~~~~~~~~~~~ This package contains components that can be plugged into Home Assistant. Component design guidelines: - -Each component defines a constant DOMAIN that is equal to its filename. - -Each component that tracks states should create state entity names in the -format ".". - -Each component should publish services only under its own domain. +- Each component defines a constant DOMAIN that is equal to its filename. +- Each component that tracks states should create state entity names in the + format ".". +- Each component should publish services only under its own domain. """ import itertools as it import logging @@ -26,8 +21,10 @@ _LOGGER = logging.getLogger(__name__) def is_on(hass, entity_id=None): - """ Loads up the module to call the is_on method. - If there is no entity id given we will check all. """ + """Load up the module to call the is_on method. + + If there is no entity id given we will check all. + """ if entity_id: group = get_component('group') @@ -53,7 +50,7 @@ def is_on(hass, entity_id=None): def turn_on(hass, entity_id=None, **service_data): - """ Turns specified entity on if possible. """ + """Turn specified entity on if possible.""" if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id @@ -61,7 +58,7 @@ def turn_on(hass, entity_id=None, **service_data): def turn_off(hass, entity_id=None, **service_data): - """ Turns specified entity off. """ + """Turn specified entity off.""" if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id @@ -69,7 +66,7 @@ def turn_off(hass, entity_id=None, **service_data): def toggle(hass, entity_id=None, **service_data): - """ Toggles specified entity. """ + """Toggle specified entity.""" if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id @@ -77,10 +74,9 @@ def toggle(hass, entity_id=None, **service_data): def setup(hass, config): - """ Setup general services related to homeassistant. """ - + """Setup general services related to Home Assistant.""" def handle_turn_service(service): - """ Method to handle calls to homeassistant.turn_on/off. """ + """Method to handle calls to homeassistant.turn_on/off.""" entity_ids = extract_entity_ids(hass, service) # Generic turn on/off method requires entity id diff --git a/homeassistant/components/alexa.py b/homeassistant/components/alexa.py index 65d26a2360e..806d6874a8d 100644 --- a/homeassistant/components/alexa.py +++ b/homeassistant/components/alexa.py @@ -97,21 +97,24 @@ def _handle_alexa(handler, path_match, data): class SpeechType(enum.Enum): - """Alexa speech types.""" + """The Alexa speech types.""" + plaintext = "PlainText" ssml = "SSML" class CardType(enum.Enum): - """Alexa card types.""" + """The Alexa card types.""" + simple = "Simple" link_account = "LinkAccount" class AlexaResponse(object): - """Helps generating the response for Alexa.""" + """Help generating the response for Alexa.""" def __init__(self, hass, intent=None): + """Initialize the response.""" self.hass = hass self.speech = None self.card = None @@ -125,7 +128,7 @@ class AlexaResponse(object): self.variables = {} def add_card(self, card_type, title, content): - """ Add a card to the response. """ + """Add a card to the response.""" assert self.card is None card = { @@ -141,7 +144,7 @@ class AlexaResponse(object): self.card = card def add_speech(self, speech_type, text): - """ Add speech to the response. """ + """Add speech to the response.""" assert self.speech is None key = 'ssml' if speech_type == SpeechType.ssml else 'text' @@ -163,7 +166,7 @@ class AlexaResponse(object): } def as_dict(self): - """Returns response in an Alexa valid dict.""" + """Return response in an Alexa valid dict.""" response = { 'shouldEndSession': self.should_end_session } diff --git a/homeassistant/components/apcupsd.py b/homeassistant/components/apcupsd.py index ab49243267c..fd064075458 100644 --- a/homeassistant/components/apcupsd.py +++ b/homeassistant/components/apcupsd.py @@ -51,11 +51,14 @@ def setup(hass, config): class APCUPSdData(object): + """Stores the data retrieved from APCUPSd. + + For each entity to use, acts as the single point responsible for fetching + updates from the server. """ - Stores the data retrieved from APCUPSd for each entity to use, acts as the - single point responsible for fetching updates from the server. - """ + def __init__(self, host, port): + """Initialize the data oject.""" from apcaccess import status self._host = host self._port = port @@ -75,7 +78,5 @@ class APCUPSdData(object): @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self, **kwargs): - """ - Fetch the latest status from APCUPSd and store it in self._status. - """ + """Fetch the latest status from APCUPSd.""" self._status = self._get_status() diff --git a/homeassistant/components/api.py b/homeassistant/components/api.py index 6f785f19896..65ef2d84cfd 100644 --- a/homeassistant/components/api.py +++ b/homeassistant/components/api.py @@ -34,7 +34,6 @@ _LOGGER = logging.getLogger(__name__) def setup(hass, config): """Register the API with the HTTP interface.""" - # /api - for validation purposes hass.http.register_path('GET', URL_API, _handle_get_api) @@ -96,7 +95,7 @@ def setup(hass, config): def _handle_get_api(handler, path_match, data): - """Renders the debug interface.""" + """Render the debug interface.""" handler.write_json_message("API running.") @@ -114,7 +113,7 @@ def _handle_get_api_stream(handler, path_match, data): restrict = restrict.split(',') def write_message(payload): - """Writes a message to the output.""" + """Write a message to the output.""" with write_lock: msg = "data: {}\n\n".format(payload) @@ -127,7 +126,7 @@ def _handle_get_api_stream(handler, path_match, data): block.set() def forward_events(event): - """Forwards events to the open request.""" + """Forward events to the open request.""" nonlocal gracefully_closed if block.is_set() or event.event_type == EVENT_TIME_CHANGED: @@ -171,17 +170,17 @@ def _handle_get_api_stream(handler, path_match, data): def _handle_get_api_config(handler, path_match, data): - """Returns the Home Assistant configuration.""" + """Return the Home Assistant configuration.""" handler.write_json(handler.server.hass.config.as_dict()) def _handle_get_api_states(handler, path_match, data): - """Returns a dict containing all entity ids and their state.""" + """Return a dict containing all entity ids and their state.""" handler.write_json(handler.server.hass.states.all()) def _handle_get_api_states_entity(handler, path_match, data): - """Returns the state of a specific entity.""" + """Return the state of a specific entity.""" entity_id = path_match.group('entity_id') state = handler.server.hass.states.get(entity_id) @@ -193,7 +192,7 @@ def _handle_get_api_states_entity(handler, path_match, data): def _handle_post_state_entity(handler, path_match, data): - """Handles updating the state of an entity. + """Handle updating the state of an entity. This handles the following paths: /api/states/ @@ -240,15 +239,14 @@ def _handle_delete_state_entity(handler, path_match, data): def _handle_get_api_events(handler, path_match, data): - """Handles getting overview of event listeners.""" + """Handle getting overview of event listeners.""" handler.write_json(events_json(handler.server.hass)) def _handle_api_post_events_event(handler, path_match, event_data): - """Handles firing of an event. + """Handle firing of an event. - This handles the following paths: - /api/events/ + This handles the following paths: /api/events/ Events from /api are threated as remote events. """ @@ -276,16 +274,15 @@ def _handle_api_post_events_event(handler, path_match, event_data): def _handle_get_api_services(handler, path_match, data): - """Handles getting overview of services.""" + """Handle getting overview of services.""" handler.write_json(services_json(handler.server.hass)) # pylint: disable=invalid-name def _handle_post_api_services_domain_service(handler, path_match, data): - """Handles calling a service. + """Handle calling a service. - This handles the following paths: - /api/services// + This handles the following paths: /api/services// """ domain = path_match.group('domain') service = path_match.group('service') @@ -298,7 +295,7 @@ def _handle_post_api_services_domain_service(handler, path_match, data): # pylint: disable=invalid-name def _handle_post_api_event_forward(handler, path_match, data): - """Handles adding an event forwarding target.""" + """Handle adding an event forwarding target.""" try: host = data['host'] api_password = data['api_password'] @@ -331,7 +328,7 @@ def _handle_post_api_event_forward(handler, path_match, data): def _handle_delete_api_event_forward(handler, path_match, data): - """Handles deleting an event forwarding target.""" + """Handle deleting an event forwarding target.""" try: host = data['host'] except KeyError: @@ -354,12 +351,12 @@ def _handle_delete_api_event_forward(handler, path_match, data): def _handle_get_api_components(handler, path_match, data): - """Returns all the loaded components.""" + """Return all the loaded components.""" handler.write_json(handler.server.hass.config.components) def _handle_get_api_error_log(handler, path_match, data): - """Returns the logged errors for this session.""" + """Return the logged errors for this session.""" handler.write_file(handler.server.hass.config.path(ERROR_LOG_FILENAME), False) diff --git a/homeassistant/components/arduino.py b/homeassistant/components/arduino.py index 2055ed4564f..767d5c491cf 100644 --- a/homeassistant/components/arduino.py +++ b/homeassistant/components/arduino.py @@ -49,8 +49,10 @@ def setup(hass, config): class ArduinoBoard(object): - """Represents an Arduino board.""" + """Representation of an Arduino board.""" + def __init__(self, port): + """Initialize the board.""" from PyMata.pymata import PyMata self._port = port self._board = PyMata(self._port, verbose=False) @@ -104,6 +106,6 @@ class ArduinoBoard(object): return self._board.get_firmata_version() def disconnect(self): - """Disconnects the board and closes the serial connection.""" + """Disconnect the board and close the serial connection.""" self._board.reset() self._board.close() diff --git a/homeassistant/components/bloomsky.py b/homeassistant/components/bloomsky.py index ffaeee8abc3..de9f4a18b91 100644 --- a/homeassistant/components/bloomsky.py +++ b/homeassistant/components/bloomsky.py @@ -30,7 +30,7 @@ DISCOVER_CAMERAS = 'bloomsky.camera' # pylint: disable=unused-argument,too-few-public-methods def setup(hass, config): - """ Setup BloomSky component. """ + """Setup BloomSky component.""" if not validate_config( config, {DOMAIN: [CONF_API_KEY]}, @@ -55,13 +55,13 @@ def setup(hass, config): class BloomSky(object): - """ Handle all communication with the BloomSky API. """ + """Handle all communication with the BloomSky API.""" # API documentation at http://weatherlution.com/bloomsky-api/ - API_URL = "https://api.bloomsky.com/api/skydata" def __init__(self, api_key): + """Initialize the BookSky.""" self._api_key = api_key self.devices = {} _LOGGER.debug("Initial bloomsky device load...") @@ -69,10 +69,7 @@ class BloomSky(object): @Throttle(MIN_TIME_BETWEEN_UPDATES) def refresh_devices(self): - """ - Uses the API to retreive a list of devices associated with an - account along with all the sensors on the device. - """ + """Use the API to retreive a list of devices.""" _LOGGER.debug("Fetching bloomsky update") response = requests.get(self.API_URL, headers={"Authorization": self._api_key}, @@ -82,7 +79,7 @@ class BloomSky(object): elif response.status_code != 200: _LOGGER.error("Invalid HTTP response: %s", response.status_code) return - # create dictionary keyed off of the device unique id + # Create dictionary keyed off of the device unique id self.devices.update({ device["DeviceID"]: device for device in response.json() }) diff --git a/homeassistant/components/browser.py b/homeassistant/components/browser.py index d171e4b5901..edfe1008c6e 100644 --- a/homeassistant/components/browser.py +++ b/homeassistant/components/browser.py @@ -10,9 +10,7 @@ SERVICE_BROWSE_URL = "browse_url" def setup(hass, config): - """ - Listen for browse_url events and open the url in the default web browser. - """ + """Listen for browse_url events.""" import webbrowser hass.services.register(DOMAIN, SERVICE_BROWSE_URL, diff --git a/homeassistant/components/configurator.py b/homeassistant/components/configurator.py index ce4ec8fed4f..aecaa1cfadc 100644 --- a/homeassistant/components/configurator.py +++ b/homeassistant/components/configurator.py @@ -36,6 +36,7 @@ def request_config( hass, name, callback, description=None, description_image=None, submit_caption=None, fields=None): """Create a new request for configuration. + Will return an ID to be used for sequent calls. """ instance = _get_instance(hass) @@ -86,8 +87,10 @@ def _get_instance(hass): class Configurator(object): - """Class to keep track of current configuration requests.""" + """The class to keep track of current configuration requests.""" + def __init__(self, hass): + """Initialize the configurator.""" self.hass = hass self._cur_id = 0 self._requests = {} @@ -173,7 +176,7 @@ class Configurator(object): callback(call.data.get(ATTR_FIELDS, {})) def _generate_unique_id(self): - """Generates a unique configurator ID.""" + """Generate a unique configurator ID.""" self._cur_id += 1 return "{}-{}".format(id(self), self._cur_id) diff --git a/homeassistant/components/conversation.py b/homeassistant/components/conversation.py index 17e1506c530..74ba0648c74 100644 --- a/homeassistant/components/conversation.py +++ b/homeassistant/components/conversation.py @@ -23,19 +23,18 @@ REQUIREMENTS = ['fuzzywuzzy==0.8.0'] def setup(hass, config): - """Registers the process service.""" + """Register the process service.""" from fuzzywuzzy import process as fuzzyExtract logger = logging.getLogger(__name__) def process(service): - """Parses text into commands.""" + """Parse text into commands.""" if ATTR_TEXT not in service.data: logger.error("Received process service call without a text") return text = service.data[ATTR_TEXT].lower() - match = REGEX_TURN_COMMAND.match(text) if not match: @@ -43,11 +42,8 @@ def setup(hass, config): return name, command = match.groups() - entities = {state.entity_id: state.name for state in hass.states.all()} - - entity_ids = fuzzyExtract.extractOne(name, - entities, + entity_ids = fuzzyExtract.extractOne(name, entities, score_cutoff=65)[2] if not entity_ids: diff --git a/homeassistant/components/device_sun_light_trigger.py b/homeassistant/components/device_sun_light_trigger.py index 2386dba7fd2..a954ae8fd0f 100644 --- a/homeassistant/components/device_sun_light_trigger.py +++ b/homeassistant/components/device_sun_light_trigger.py @@ -1,6 +1,5 @@ """ -Provides functionality to turn on lights based on the state of the sun and -devices home. +Provides functionality to turn on lights based on the states. For more details about this component, please refer to the documentation at https://home-assistant.io/components/device_sun_light_trigger/ @@ -29,7 +28,7 @@ CONF_DEVICE_GROUP = 'device_group' # pylint: disable=too-many-locals def setup(hass, config): - """Triggers to turn lights on or off based on device presence.""" + """The triggers to turn lights on or off based on device presence.""" logger = logging.getLogger(__name__) device_tracker = get_component('device_tracker') group = get_component('group') @@ -57,16 +56,20 @@ def setup(hass, config): return False def calc_time_for_light_when_sunset(): - """ Calculates the time when to start fading lights in when sun sets. - Returns None if no next_setting data available. """ + """Calculate the time when to start fading lights in when sun sets. + + Returns None if no next_setting data available. + """ next_setting = sun.next_setting(hass) if not next_setting: return None return next_setting - LIGHT_TRANSITION_TIME * len(light_ids) def turn_light_on_before_sunset(light_id): - """ Helper function to turn on lights slowly if there - are devices home and the light is not on yet. """ + """Helper function to turn on lights. + + Speed is slow if there are devices home and the light is not on yet. + """ if not device_tracker.is_on(hass) or light.is_on(hass, light_id): return light.turn_on(hass, light_id, @@ -78,8 +81,8 @@ def setup(hass, config): @track_state_change(sun.ENTITY_ID, sun.STATE_BELOW_HORIZON, sun.STATE_ABOVE_HORIZON) def schedule_lights_at_sun_set(hass, entity, old_state, new_state): - """ - The moment sun sets we want to have all the lights on. + """The moment sun sets we want to have all the lights on. + We will schedule to have each light start after one another and slowly transition in. """ @@ -88,10 +91,10 @@ def setup(hass, config): return def turn_on(light_id): - """ - Lambda can keep track of function parameters but not local - parameters. If we put the lambda directly in the below statement - only the last light will be turned on. + """Lambda can keep track of function parameters. + + No local parameters. If we put the lambda directly in the below + statement only the last light will be turned on. """ return lambda now: turn_light_on_before_sunset(light_id) diff --git a/homeassistant/components/discovery.py b/homeassistant/components/discovery.py index a08b167f87f..79a152e5848 100644 --- a/homeassistant/components/discovery.py +++ b/homeassistant/components/discovery.py @@ -37,8 +37,8 @@ SERVICE_HANDLERS = { def listen(hass, service, callback): - """ - Setup listener for discovery of specific service. + """Setup listener for discovery of specific service. + Service can be a string or a list/tuple. """ if isinstance(service, str): @@ -70,7 +70,7 @@ def discover(hass, service, discovered=None, component=None, hass_config=None): def setup(hass, config): - """Starts a discovery service.""" + """Start a discovery service.""" logger = logging.getLogger(__name__) from netdisco.service import DiscoveryService diff --git a/homeassistant/components/downloader.py b/homeassistant/components/downloader.py index c9f2f44d691..c425d9cbb23 100644 --- a/homeassistant/components/downloader.py +++ b/homeassistant/components/downloader.py @@ -26,7 +26,7 @@ CONF_DOWNLOAD_DIR = 'download_dir' # pylint: disable=too-many-branches def setup(hass, config): - """Listens for download events to download files.""" + """Listen for download events to download files.""" logger = logging.getLogger(__name__) if not validate_config(config, {DOMAIN: [CONF_DOWNLOAD_DIR]}, logger): @@ -47,13 +47,13 @@ def setup(hass, config): return False def download_file(service): - """Starts thread to download file specified in the URL.""" + """Start thread to download file specified in the URL.""" if ATTR_URL not in service.data: logger.error("Service called but 'url' parameter not specified.") return def do_download(): - """Downloads the file.""" + """Download the file.""" try: url = service.data[ATTR_URL] diff --git a/homeassistant/components/ecobee.py b/homeassistant/components/ecobee.py index 31a534f1d83..21dd73ea6e6 100644 --- a/homeassistant/components/ecobee.py +++ b/homeassistant/components/ecobee.py @@ -44,7 +44,7 @@ def request_configuration(network, hass, config): # pylint: disable=unused-argument def ecobee_configuration_callback(callback_data): - """Actions to do when our configuration callback is called.""" + """The actions to do when our configuration callback is called.""" network.request_tokens() network.update() setup_ecobee(hass, network, config) @@ -91,8 +91,10 @@ def setup_ecobee(hass, network, config): # pylint: disable=too-few-public-methods class EcobeeData(object): - """Gets the latest data and update the states.""" + """Get the latest data and update the states.""" + def __init__(self, config_file): + """Initialize the Ecobee data object.""" from pyecobee import Ecobee self.ecobee = Ecobee(config_file) @@ -104,8 +106,8 @@ class EcobeeData(object): def setup(hass, config): - """ - Setup Ecobee. + """Setup Ecobee. + Will automatically load thermostat and sensor components to support devices discovered on the network. """ diff --git a/homeassistant/components/graphite.py b/homeassistant/components/graphite.py index 4e726f06bb5..c262443a94d 100644 --- a/homeassistant/components/graphite.py +++ b/homeassistant/components/graphite.py @@ -1,6 +1,5 @@ """ -Component that records all events and state changes and feeds the data to -a Graphite installation. +Component that sends data to aGraphite installation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/graphite/ @@ -35,8 +34,10 @@ def setup(hass, config): class GraphiteFeeder(threading.Thread): - """Feeds data to Graphite.""" + """Feed data to Graphite.""" + def __init__(self, hass, host, port, prefix): + """Initialize the feeder.""" super(GraphiteFeeder, self).__init__(daemon=True) self._hass = hass self._host = host diff --git a/homeassistant/components/group.py b/homeassistant/components/group.py index b1ad9f478cc..028222e0e76 100644 --- a/homeassistant/components/group.py +++ b/homeassistant/components/group.py @@ -106,7 +106,7 @@ def get_entity_ids(hass, entity_id, domain_filter=None): def setup(hass, config): - """Set up all groups found definded in the configuration.""" + """Setup all groups found definded in the configuration.""" for object_id, conf in config.get(DOMAIN, {}).items(): if not isinstance(conf, dict): conf = {CONF_ENTITIES: conf} @@ -129,7 +129,6 @@ class Group(Entity): """Track a group of entity ids.""" # pylint: disable=too-many-instance-attributes, too-many-arguments - def __init__(self, hass, name, entity_ids=None, user_defined=True, icon=None, view=False, object_id=None): """Initialize a group.""" @@ -160,30 +159,27 @@ class Group(Entity): @property def name(self): - """Name of the group.""" + """Return the name of the group.""" return self._name @property def state(self): - """State of the group.""" + """Return the state of the group.""" return self._state @property def icon(self): - """Icon of the group.""" + """Return the icon of the group.""" return self._icon @property def hidden(self): - """If group should be hidden or not. - - true if group is a view or not user defined. - """ + """If group should be hidden or not.""" return not self._user_defined or self._view @property def state_attributes(self): - """State attributes for the group.""" + """Return the state attributes for the group.""" data = { ATTR_ENTITY_ID: self.tracking, ATTR_ORDER: self._order, @@ -215,7 +211,7 @@ class Group(Entity): self.hass, self.tracking, self._state_changed_listener) def stop(self): - """Unregisters the group from Home Assistant.""" + """Unregister the group from Home Assistant.""" self.hass.states.remove(self.entity_id) self.hass.bus.remove_listener( @@ -233,7 +229,7 @@ class Group(Entity): @property def _tracking_states(self): - """States that the group is tracking.""" + """The states that the group is tracking.""" states = [] for entity_id in self.tracking: diff --git a/homeassistant/components/history.py b/homeassistant/components/history.py index b29a1254f14..9151406c388 100644 --- a/homeassistant/components/history.py +++ b/homeassistant/components/history.py @@ -70,9 +70,7 @@ def get_significant_states(start_time, end_time=None, entity_id=None): def state_changes_during_period(start_time, end_time=None, entity_id=None): - """ - Return states changes during UTC period start_time - end_time. - """ + """Return states changes during UTC period start_time - end_time.""" where = "last_changed=last_updated AND last_changed > ? " data = [start_time] @@ -93,7 +91,7 @@ def state_changes_during_period(start_time, end_time=None, entity_id=None): def get_states(utc_point_in_time, entity_ids=None, run=None): - """Returns the states at a specific point in time.""" + """Return the states at a specific point in time.""" if run is None: run = recorder.run_information(utc_point_in_time) @@ -122,8 +120,7 @@ def get_states(utc_point_in_time, entity_ids=None, run=None): def states_to_json(states, start_time, entity_id): - """ - Converts SQL results into JSON friendly data structure. + """Convert SQL results into JSON friendly data structure. This takes our state list and turns it into a JSON friendly data structure {'entity_id': [list of states], 'entity_id2': [list of states]} @@ -157,7 +154,7 @@ def get_state(utc_point_in_time, entity_id, run=None): # pylint: disable=unused-argument def setup(hass, config): - """Setup history hooks.""" + """Setup the history hooks.""" hass.http.register_path( 'GET', re.compile( @@ -204,8 +201,7 @@ def _api_history_period(handler, path_match, data): def _is_significant(state): - """ - Test if state is significant for history charts. + """Test if state is significant for history charts. Will only test for things that are not filtered out in SQL. """ diff --git a/homeassistant/components/http.py b/homeassistant/components/http.py index 7f0342d019d..90d43d38818 100644 --- a/homeassistant/components/http.py +++ b/homeassistant/components/http.py @@ -50,7 +50,7 @@ _LOGGER = logging.getLogger(__name__) def setup(hass, config): - """Sets up the HTTP API and debug interface.""" + """Set up the HTTP API and debug interface.""" conf = config.get(DOMAIN, {}) api_password = util.convert(conf.get(CONF_API_PASSWORD), str) @@ -86,6 +86,7 @@ def setup(hass, config): # pylint: disable=too-many-instance-attributes class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer): """Handle HTTP requests in a threaded fashion.""" + # pylint: disable=too-few-public-methods allow_reuse_address = True daemon_threads = True @@ -93,6 +94,7 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer): # pylint: disable=too-many-arguments def __init__(self, server_address, request_handler_class, hass, api_password, development, ssl_certificate, ssl_key): + """Initialize the server.""" super().__init__(server_address, request_handler_class) self.server_address = server_address @@ -116,9 +118,9 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer): self.socket = context.wrap_socket(self.socket, server_side=True) def start(self): - """Starts the HTTP server.""" + """Start the HTTP server.""" def stop_http(event): - """Stops the HTTP server.""" + """Stop the HTTP server.""" self.shutdown() self.hass.bus.listen_once(ha.EVENT_HOMEASSISTANT_STOP, stop_http) @@ -137,7 +139,7 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer): self.serve_forever() def register_path(self, method, url, callback, require_auth=True): - """Registers a path with the server.""" + """Register a path with the server.""" self.paths.append((method, url, callback, require_auth)) def log_message(self, fmt, *args): @@ -148,16 +150,16 @@ class HomeAssistantHTTPServer(ThreadingMixIn, HTTPServer): # pylint: disable=too-many-public-methods,too-many-locals class RequestHandler(SimpleHTTPRequestHandler): - """ - Handles incoming HTTP requests + """Handle incoming HTTP requests. We extend from SimpleHTTPRequestHandler instead of Base so we can use the guess content type methods. """ + server_version = "HomeAssistant/1.0" def __init__(self, req, client_addr, server): - """Contructor, call the base constructor and set up session.""" + """Constructor, call the base constructor and set up session.""" # Track if this was an authenticated request self.authenticated = False SimpleHTTPRequestHandler.__init__(self, req, client_addr, server) @@ -172,7 +174,7 @@ class RequestHandler(SimpleHTTPRequestHandler): if isinstance(arg, str) else arg for arg in arguments)) def _handle_request(self, method): # pylint: disable=too-many-branches - """Does some common checks and calls appropriate method.""" + """Perform some common checks and call appropriate method.""" url = urlparse(self.path) # Read query input. parse_qs gives a list for each value, we want last @@ -302,7 +304,7 @@ class RequestHandler(SimpleHTTPRequestHandler): self.wfile.write(message.encode("UTF-8")) def write_file(self, path, cache_headers=True): - """Returns a file to the user.""" + """Return a file to the user.""" try: with open(path, 'rb') as inp: self.write_file_pointer(self.guess_type(path), inp, @@ -314,10 +316,7 @@ class RequestHandler(SimpleHTTPRequestHandler): _LOGGER.exception("Unable to serve %s", path) def write_file_pointer(self, content_type, inp, cache_headers=True): - """ - Helper function to write a file pointer to the user. - Does not do error handling. - """ + """Helper function to write a file pointer to the user.""" do_gzip = 'gzip' in self.headers.get(HTTP_HEADER_ACCEPT_ENCODING, '') self.send_response(HTTP_OK) @@ -387,9 +386,9 @@ class RequestHandler(SimpleHTTPRequestHandler): return self.get_cookie_session_id() is not None def get_cookie_session_id(self): - """ - Extracts the current session id from the cookie or returns None if not - set or invalid. + """Extract the current session ID from the cookie. + + Return None if not set or invalid. """ if 'Cookie' not in self.headers: return None @@ -413,7 +412,7 @@ class RequestHandler(SimpleHTTPRequestHandler): return None def destroy_session(self): - """Destroys session.""" + """Destroy the session.""" session_id = self.get_cookie_session_id() if session_id is None: @@ -430,6 +429,7 @@ def session_valid_time(): class SessionStore(object): """Responsible for storing and retrieving HTTP sessions.""" + def __init__(self): """Setup the session store.""" self._sessions = {} @@ -464,7 +464,7 @@ class SessionStore(object): self._sessions.pop(key, None) def create(self): - """Creates a new session.""" + """Create a new session.""" with self._lock: session_id = util.get_random_string(20) diff --git a/homeassistant/components/input_boolean.py b/homeassistant/components/input_boolean.py index 65d6730cfde..75d5d940f47 100644 --- a/homeassistant/components/input_boolean.py +++ b/homeassistant/components/input_boolean.py @@ -84,9 +84,10 @@ def setup(hass, config): class InputBoolean(ToggleEntity): - """Represent a boolean input.""" + """Representation of a boolean input.""" + def __init__(self, object_id, name, state, icon): - """ Initialize a boolean input. """ + """Initialize a boolean input.""" self.entity_id = ENTITY_ID_FORMAT.format(object_id) self._name = name self._state = state diff --git a/homeassistant/components/input_select.py b/homeassistant/components/input_select.py index ad1cb64257c..e7c6e280386 100644 --- a/homeassistant/components/input_select.py +++ b/homeassistant/components/input_select.py @@ -90,10 +90,11 @@ def setup(hass, config): class InputSelect(Entity): - """Represent a select input.""" + """Representation of a select input.""" + # pylint: disable=too-many-arguments def __init__(self, object_id, name, state, options, icon): - """ Initialize a select input. """ + """Initialize a select input.""" self.entity_id = ENTITY_ID_FORMAT.format(object_id) self._name = name self._current_option = state diff --git a/homeassistant/components/insteon_hub.py b/homeassistant/components/insteon_hub.py index 5311cd270d8..00f7bb5b143 100644 --- a/homeassistant/components/insteon_hub.py +++ b/homeassistant/components/insteon_hub.py @@ -22,8 +22,8 @@ _LOGGER = logging.getLogger(__name__) def setup(hass, config): - """ - Setup Insteon Hub component. + """Setup Insteon Hub component. + This will automatically import associated lights. """ if not validate_config( @@ -56,8 +56,10 @@ def setup(hass, config): class InsteonToggleDevice(ToggleEntity): - """ An abstract Class for an Insteon node.""" + """An abstract Class for an Insteon node.""" + def __init__(self, node): + """Initialize the device.""" self.node = node self._value = 0 @@ -85,7 +87,9 @@ class InsteonToggleDevice(ToggleEntity): return self._value != 0 def turn_on(self, **kwargs): + """Turn device on.""" self.node.send_command('on') def turn_off(self, **kwargs): + """Turn device off.""" self.node.send_command('off') diff --git a/homeassistant/components/isy994.py b/homeassistant/components/isy994.py index c221a8d011f..697aa4e8ea6 100644 --- a/homeassistant/components/isy994.py +++ b/homeassistant/components/isy994.py @@ -29,8 +29,8 @@ _LOGGER = logging.getLogger(__name__) def setup(hass, config): - """ - Setup ISY994 component. + """Setup ISY994 component. + This will automatically import associated lights, switches, and sensors. """ import PyISY @@ -97,6 +97,7 @@ def stop(event): class ISYDeviceABC(ToggleEntity): """An abstract Class for an ISY device.""" + _attrs = {} _onattrs = [] _states = [] @@ -105,6 +106,7 @@ class ISYDeviceABC(ToggleEntity): _name = None def __init__(self, node): + """Initialize the device.""" # setup properties self.node = node @@ -182,7 +184,7 @@ class ISYDeviceABC(ToggleEntity): pass def on_update(self, event): - """Handles the update received event.""" + """Handle the update received event.""" self.update_ha_state() @property @@ -203,7 +205,7 @@ class ISYDeviceABC(ToggleEntity): return self.value def turn_on(self, **kwargs): - """Turns the device on.""" + """Turn the device on.""" if self.domain is not 'sensor': attrs = [kwargs.get(name) for name in self._onattrs] self.node.on(*attrs) @@ -211,7 +213,7 @@ class ISYDeviceABC(ToggleEntity): _LOGGER.error('ISY cannot turn on sensors.') def turn_off(self, **kwargs): - """Turns the device off.""" + """Turn the device off.""" if self.domain is not 'sensor': self.node.off() else: diff --git a/homeassistant/components/keyboard.py b/homeassistant/components/keyboard.py index dfbfd0e1124..eb801fae252 100644 --- a/homeassistant/components/keyboard.py +++ b/homeassistant/components/keyboard.py @@ -39,7 +39,7 @@ def media_next_track(hass): def media_prev_track(hass): - """Press the keyboard button for prev track. """ + """Press the keyboard button for prev track.""" hass.services.call(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK) diff --git a/homeassistant/components/logbook.py b/homeassistant/components/logbook.py index ebc4dc25b7c..d26b3373cb8 100644 --- a/homeassistant/components/logbook.py +++ b/homeassistant/components/logbook.py @@ -41,7 +41,7 @@ ATTR_ENTITY_ID = 'entity_id' def log_entry(hass, name, message, domain=None, entity_id=None): - """Adds an entry to the logbook.""" + """Add an entry to the logbook.""" data = { ATTR_NAME: name, ATTR_MESSAGE: message @@ -55,7 +55,7 @@ def log_entry(hass, name, message, domain=None, entity_id=None): def setup(hass, config): - """Listens for download events to download files.""" + """Listen for download events to download files.""" def log_message(service): """Handle sending notification message service calls.""" message = service.data.get(ATTR_MESSAGE) @@ -100,9 +100,11 @@ def _handle_get_logbook(handler, path_match, data): class Entry(object): """A human readable version of the log.""" + # pylint: disable=too-many-arguments, too-few-public-methods def __init__(self, when=None, name=None, message=None, domain=None, entity_id=None): + """Initialize the entry.""" self.when = when self.name = name self.message = message @@ -121,8 +123,7 @@ class Entry(object): def humanify(events): - """ - Generator that converts a list of events into Entry objects. + """Generator that converts a list of events into Entry objects. Will try to group events if possible: - if 2+ sensor updates in GROUP_BY_MINUTES, show last diff --git a/homeassistant/components/logger.py b/homeassistant/components/logger.py index 5805760fd5c..ed17e7520d0 100644 --- a/homeassistant/components/logger.py +++ b/homeassistant/components/logger.py @@ -26,8 +26,10 @@ LOGGER_LOGS = 'logs' class HomeAssistantLogFilter(logging.Filter): """A log filter.""" + # pylint: disable=no-init,too-few-public-methods def __init__(self, logfilter): + """Initialize the filter.""" super().__init__() self.logfilter = logfilter diff --git a/homeassistant/components/modbus.py b/homeassistant/components/modbus.py index 0c625968f14..01f4e72ca0d 100644 --- a/homeassistant/components/modbus.py +++ b/homeassistant/components/modbus.py @@ -1,7 +1,5 @@ """ -homeassistant.components.modbus -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Modbus component, using pymodbus (python3 branch). +Support for Modbus. For more details about this component, please refer to the documentation at https://home-assistant.io/components/modbus/ @@ -38,8 +36,7 @@ TYPE = None def setup(hass, config): - """ Setup Modbus component. """ - + """Setup Modbus component.""" # Modbus connection type # pylint: disable=global-statement, import-error global TYPE @@ -69,15 +66,14 @@ def setup(hass, config): return False def stop_modbus(event): - """ Stop Modbus service. """ + """Stop Modbus service.""" NETWORK.close() def start_modbus(event): - """ Start Modbus service. """ + """Start Modbus service.""" NETWORK.connect() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_modbus) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_modbus) - # Tells the bootstrapper that the component was successfully initialized return True diff --git a/homeassistant/components/mqtt_eventstream.py b/homeassistant/components/mqtt_eventstream.py index fe4c8c546ca..a807487c90f 100644 --- a/homeassistant/components/mqtt_eventstream.py +++ b/homeassistant/components/mqtt_eventstream.py @@ -62,10 +62,7 @@ def setup(hass, config): # Process events from a remote server that are received on a queue. def _event_receiver(topic, payload, qos): - """ - Receive events published by the other HA instance and fire them on - this hass instance. - """ + """Receive events published by and fire them on this hass instance.""" event = json.loads(payload) event_type = event.get('event_type') event_data = event.get('event_data') diff --git a/homeassistant/components/mysensors.py b/homeassistant/components/mysensors.py index 77ba85b4233..2d3c8eb1f53 100644 --- a/homeassistant/components/mysensors.py +++ b/homeassistant/components/mysensors.py @@ -157,6 +157,7 @@ def pf_callback_factory(map_sv_types, devices, add_devices, entity_class): class GatewayWrapper(object): """Gateway wrapper class.""" + def __init__(self, gateway, version, optimistic): """Setup class attributes on instantiation. diff --git a/homeassistant/components/proximity.py b/homeassistant/components/proximity.py index c2646096b44..5880df639bd 100644 --- a/homeassistant/components/proximity.py +++ b/homeassistant/components/proximity.py @@ -1,4 +1,6 @@ """ +Support for tracking the proximity of a device. + Component to monitor the proximity of devices to a particular zone and the direction of travel. @@ -77,11 +79,13 @@ def setup(hass, config): # pylint: disable=too-many-locals,too-many-statements class Proximity(Entity): # pylint: disable=too-many-instance-attributes - """Represents a Proximity.""" + """Representation of a Proximity.""" + + # pylint: disable=too-many-arguments def __init__(self, hass, zone_friendly_name, dist_to, dir_of_travel, nearest, ignored_zones, proximity_devices, tolerance, proximity_zone): - # pylint: disable=too-many-arguments + """Initialize the proximity.""" self.hass = hass self.friendly_name = zone_friendly_name self.dist_to = dist_to @@ -115,8 +119,8 @@ class Proximity(Entity): # pylint: disable=too-many-instance-attributes ATTR_NEAREST: self.nearest, } + # pylint: disable=too-many-branches,too-many-statements,too-many-locals def check_proximity_state_change(self, entity, old_state, new_state): - # pylint: disable=too-many-branches,too-many-statements,too-many-locals """Function to perform the proximity checking.""" entity_name = new_state.name devices_to_calculate = False diff --git a/homeassistant/components/recorder.py b/homeassistant/components/recorder.py index 84ac0851cb8..07825821880 100644 --- a/homeassistant/components/recorder.py +++ b/homeassistant/components/recorder.py @@ -1,4 +1,6 @@ """ +Support for recording details. + Component that records all events and state changes. Allows other components to query this database. @@ -80,8 +82,9 @@ def row_to_event(row): def run_information(point_in_time=None): - """ - Returns information about current run or the run that covers point_in_time. + """Return information about current run. + + There is also the run that covers point_in_time. """ _verify_instance() @@ -106,8 +109,10 @@ def setup(hass, config): class RecorderRun(object): - """Represents a recorder run.""" + """Representation of arecorder run.""" + def __init__(self, row=None): + """Initialize the recorder run.""" self.end = None if row is None: @@ -122,8 +127,8 @@ class RecorderRun(object): self.closed_incorrect = bool(row[3]) def entity_ids(self, point_in_time=None): - """ - Return the entity ids that existed in this run. + """Return the entity ids that existed in this run. + Specify point_in_time if you want to know which existed at that point in time inside the run. """ @@ -140,15 +145,18 @@ class RecorderRun(object): @property def where_after_start_run(self): - """ - Returns SQL WHERE clause to select rows created after the start of the - run. + """Return SQL WHERE clause. + + Selection of the rows created after the start of the run. """ return "created >= {} ".format(_adapt_datetime(self.start)) @property def where_limit_to_run(self): - """ Return a SQL WHERE clause to limit results to this run. """ + """Return a SQL WHERE clause. + + For limiting the results to this run. + """ where = self.where_after_start_run if self.end is not None: @@ -159,7 +167,9 @@ class RecorderRun(object): class Recorder(threading.Thread): """A threaded recorder class.""" + def __init__(self, hass): + """Initialize the recorder.""" threading.Thread.__init__(self) self.hass = hass @@ -206,14 +216,11 @@ class Recorder(threading.Thread): self.queue.task_done() def event_listener(self, event): - """ - Listens for new events on the EventBus and puts them in the process - queue. - """ + """Listen for new events and put them in the process queue.""" self.queue.put(event) def shutdown(self, event): - """Tells the recorder to shut down.""" + """Tell the recorder to shut down.""" self.queue.put(self.quit_object) self.block_till_done() @@ -262,7 +269,7 @@ class Recorder(threading.Thread): ") VALUES (?, ?, ?, ?, ?, ?)", info, RETURN_LASTROWID) def query(self, sql_query, data=None, return_value=None): - """ Query the database. """ + """Query the database.""" try: with self.conn, self.lock: _LOGGER.debug("Running query %s", sql_query) @@ -290,7 +297,7 @@ class Recorder(threading.Thread): return [] def block_till_done(self): - """Blocks till all events processed.""" + """Block till all events processed.""" self.queue.join() def _setup_connection(self): @@ -474,6 +481,6 @@ def _adapt_datetime(datetimestamp): def _verify_instance(): - """Throws error if recorder not initialized.""" + """Throw error if recorder not initialized.""" if _INSTANCE is None: raise RuntimeError("Recorder not initialized.") diff --git a/homeassistant/components/rpi_gpio.py b/homeassistant/components/rpi_gpio.py index 1110088dc38..1b302eb1839 100644 --- a/homeassistant/components/rpi_gpio.py +++ b/homeassistant/components/rpi_gpio.py @@ -59,7 +59,7 @@ def read_input(port): def edge_detect(port, event_callback, bounce): - """Adds detection for RISING and FALLING events.""" + """Add detection for RISING and FALLING events.""" import RPi.GPIO as GPIO GPIO.add_event_detect( port, diff --git a/homeassistant/components/script.py b/homeassistant/components/script.py index 86e9626a49b..071921426bb 100644 --- a/homeassistant/components/script.py +++ b/homeassistant/components/script.py @@ -1,4 +1,6 @@ """ +Support for scripts. + Scripts are a sequence of actions that can be triggered manually by the user or automatically based upon automation events, etc. @@ -43,7 +45,7 @@ _LOGGER = logging.getLogger(__name__) def is_on(hass, entity_id): - """Returns if the switch is on based on the statemachine.""" + """Return if the switch is on based on the statemachine.""" return hass.states.is_state(entity_id, STATE_ON) @@ -60,7 +62,7 @@ def turn_off(hass, entity_id): def toggle(hass, entity_id): - """Toggles script.""" + """Toggle the script.""" hass.services.call(DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: entity_id}) @@ -69,7 +71,7 @@ def setup(hass, config): component = EntityComponent(_LOGGER, DOMAIN, hass) def service_handler(service): - """ Execute a service call to script.