From d0275c80754ac4a73d453d4fce0ad6d755d46e3a Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sun, 16 Jul 2017 12:39:38 -0700 Subject: [PATCH] Persistent notification import (#8507) * Rewrite persistent notification creation * Update components.is_on to use auto loading * Fix two hass parameters --- homeassistant/components/__init__.py | 30 ++++++++--------- .../alarm_control_panel/simplisafe.py | 6 ++-- homeassistant/components/amcrest.py | 6 ++-- homeassistant/components/apple_tv.py | 14 +++----- homeassistant/components/arlo.py | 6 ++-- homeassistant/components/axis.py | 14 ++++---- homeassistant/components/configurator.py | 2 ++ homeassistant/components/cover/myq.py | 6 ++-- homeassistant/components/demo.py | 9 +++--- .../components/device_tracker/unifi.py | 6 ++-- homeassistant/components/google.py | 32 +++++++++---------- homeassistant/components/media_player/roku.py | 6 ++-- homeassistant/components/ring.py | 6 ++-- homeassistant/components/sensor/qnap.py | 9 +++--- homeassistant/components/switch/broadlink.py | 11 +++---- homeassistant/components/upnp.py | 8 ++--- 16 files changed, 70 insertions(+), 101 deletions(-) diff --git a/homeassistant/components/__init__.py b/homeassistant/components/__init__.py index ecbb8036464..1d437d35da7 100644 --- a/homeassistant/components/__init__.py +++ b/homeassistant/components/__init__.py @@ -15,7 +15,6 @@ import homeassistant.core as ha import homeassistant.config as conf_util from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.service import extract_entity_ids -from homeassistant.loader import get_component from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE, SERVICE_HOMEASSISTANT_STOP, SERVICE_HOMEASSISTANT_RESTART, @@ -33,25 +32,27 @@ def is_on(hass, entity_id=None): If there is no entity id given we will check all. """ if entity_id: - group = get_component('group') - - entity_ids = group.expand_entity_ids(hass, [entity_id]) + entity_ids = hass.components.group.expand_entity_ids([entity_id]) else: entity_ids = hass.states.entity_ids() for ent_id in entity_ids: domain = ha.split_entity_id(ent_id)[0] - module = get_component(domain) - try: - if module.is_on(hass, ent_id): - return True + component = getattr(hass.components, domain) - except AttributeError: - # module is None or method is_on does not exist - _LOGGER.exception("Failed to call %s.is_on for %s", - module, ent_id) + except ImportError: + _LOGGER.error('Failed to call %s.is_on: component not found', + domain) + continue + + if not hasattr(component, 'is_on'): + _LOGGER.warning("Component %s has no is_on method.", domain) + continue + + if component.is_on(ent_id): + return True return False @@ -161,10 +162,9 @@ def async_setup(hass, config): return if errors: - notif = get_component('persistent_notification') _LOGGER.error(errors) - notif.async_create( - hass, "Config error. See dev-info panel for details.", + hass.components.persistent_notification.async_create( + "Config error. See dev-info panel for details.", "Config validating", "{0}.check_config".format(ha.DOMAIN)) return diff --git a/homeassistant/components/alarm_control_panel/simplisafe.py b/homeassistant/components/alarm_control_panel/simplisafe.py index fadfbc41a6f..913a3abb616 100644 --- a/homeassistant/components/alarm_control_panel/simplisafe.py +++ b/homeassistant/components/alarm_control_panel/simplisafe.py @@ -15,7 +15,6 @@ from homeassistant.const import ( STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, EVENT_HOMEASSISTANT_STOP) import homeassistant.helpers.config_validation as cv -import homeassistant.loader as loader REQUIREMENTS = ['simplisafe-python==1.0.2'] @@ -42,7 +41,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None): username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) - persistent_notification = loader.get_component('persistent_notification') simplisafe = SimpliSafeApiInterface() status = simplisafe.set_credentials(username, password) if status: @@ -53,8 +51,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): else: message = 'Failed to log into SimpliSafe. Check credentials.' _LOGGER.error(message) - persistent_notification.create( - hass, message, + hass.components.persistent_notification.create( + message, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False diff --git a/homeassistant/components/amcrest.py b/homeassistant/components/amcrest.py index 8a40c790c12..9760ee5d607 100644 --- a/homeassistant/components/amcrest.py +++ b/homeassistant/components/amcrest.py @@ -11,7 +11,6 @@ import aiohttp import voluptuous as vol from requests.exceptions import HTTPError, ConnectTimeout -import homeassistant.loader as loader from homeassistant.const import ( CONF_NAME, CONF_HOST, CONF_PORT, CONF_USERNAME, CONF_PASSWORD, CONF_SENSORS, CONF_SCAN_INTERVAL, HTTP_BASIC_AUTHENTICATION) @@ -92,7 +91,6 @@ def setup(hass, config): amcrest_cams = config[DOMAIN] - persistent_notification = loader.get_component('persistent_notification') for device in amcrest_cams: camera = AmcrestCamera(device.get(CONF_HOST), device.get(CONF_PORT), @@ -103,8 +101,8 @@ def setup(hass, config): except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Amcrest camera: %s", str(ex)) - persistent_notification.create( - hass, 'Error: {}
' + hass.components.persistent_notification.create( + 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, diff --git a/homeassistant/components/apple_tv.py b/homeassistant/components/apple_tv.py index 17cc46f3318..948caa27538 100644 --- a/homeassistant/components/apple_tv.py +++ b/homeassistant/components/apple_tv.py @@ -15,7 +15,6 @@ from homeassistant.config import load_yaml_config_file from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers import discovery from homeassistant.components.discovery import SERVICE_APPLE_TV -from homeassistant.loader import get_component import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pyatv==0.3.2'] @@ -66,27 +65,24 @@ APPLE_TV_AUTHENTICATE_SCHEMA = vol.Schema({ def request_configuration(hass, config, atv, credentials): """Request configuration steps from the user.""" - configurator = get_component('configurator') + configurator = hass.components.configurator @asyncio.coroutine def configuration_callback(callback_data): """Handle the submitted configuration.""" from pyatv import exceptions pin = callback_data.get('pin') - notification = get_component('persistent_notification') try: yield from atv.airplay.finish_authentication(pin) - notification.async_create( - hass, + hass.components.persistent_notification.async_create( 'Authentication succeeded!

Add the following ' 'to credentials: in your apple_tv configuration:

' '{0}'.format(credentials), title=NOTIFICATION_AUTH_TITLE, notification_id=NOTIFICATION_AUTH_ID) except exceptions.DeviceAuthenticationError as ex: - notification.async_create( - hass, + hass.components.persistent_notification.async_create( 'Authentication failed! Did you enter correct PIN?

' 'Details: {0}'.format(ex), title=NOTIFICATION_AUTH_TITLE, @@ -119,9 +115,7 @@ def scan_for_apple_tvs(hass): if not devices: devices = ['No device(s) found'] - notification = get_component('persistent_notification') - notification.async_create( - hass, + hass.components.persistent_notification.async_create( 'The following devices were found:

' + '

'.join(devices), title=NOTIFICATION_SCAN_TITLE, diff --git a/homeassistant/components/arlo.py b/homeassistant/components/arlo.py index 630420bd3e5..1ba2acb4fe0 100644 --- a/homeassistant/components/arlo.py +++ b/homeassistant/components/arlo.py @@ -9,7 +9,6 @@ import logging import voluptuous as vol from requests.exceptions import HTTPError, ConnectTimeout -import homeassistant.loader as loader from homeassistant.helpers import config_validation as cv from homeassistant.const import CONF_USERNAME, CONF_PASSWORD @@ -40,7 +39,6 @@ def setup(hass, config): username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) - persistent_notification = loader.get_component('persistent_notification') try: from pyarlo import PyArlo @@ -50,8 +48,8 @@ def setup(hass, config): hass.data[DATA_ARLO] = arlo except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Netgar Arlo: %s", str(ex)) - persistent_notification.create( - hass, 'Error: {}
' + hass.components.persistent_notification.create( + 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, diff --git a/homeassistant/components/axis.py b/homeassistant/components/axis.py index bb1ec05496a..d83e07989e6 100644 --- a/homeassistant/components/axis.py +++ b/homeassistant/components/axis.py @@ -21,7 +21,6 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers import discovery from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.entity import Entity -from homeassistant.loader import get_component REQUIREMENTS = ['axis==8'] @@ -79,7 +78,7 @@ SERVICE_SCHEMA = vol.Schema({ def request_configuration(hass, name, host, serialnumber): """Request configuration steps from the user.""" - configurator = get_component('configurator') + configurator = hass.components.configurator def configuration_callback(callback_data): """Called when config is submitted.""" @@ -242,12 +241,11 @@ def setup_device(hass, config): if enable_metadatastream: device.initialize_new_event = event_initialized if not device.initiate_metadatastream(): - notification = get_component('persistent_notification') - notification.create(hass, - 'Dependency missing for sensors, ' - 'please check documentation', - title=DOMAIN, - notification_id='axis_notification') + hass.components.persistent_notification.create( + 'Dependency missing for sensors, ' + 'please check documentation', + title=DOMAIN, + notification_id='axis_notification') AXIS_DEVICES[device.serial_number] = device diff --git a/homeassistant/components/configurator.py b/homeassistant/components/configurator.py index e502e0a0253..660a62a5b89 100644 --- a/homeassistant/components/configurator.py +++ b/homeassistant/components/configurator.py @@ -12,6 +12,7 @@ import logging from homeassistant.core import callback as async_callback from homeassistant.const import EVENT_TIME_CHANGED, ATTR_FRIENDLY_NAME, \ ATTR_ENTITY_PICTURE +from homeassistant.loader import bind_hass from homeassistant.helpers.entity import generate_entity_id from homeassistant.util.async import run_callback_threadsafe @@ -37,6 +38,7 @@ STATE_CONFIGURE = 'configure' STATE_CONFIGURED = 'configured' +@bind_hass def request_config( hass, name, callback, description=None, description_image=None, submit_caption=None, fields=None, link_name=None, link_url=None, diff --git a/homeassistant/components/cover/myq.py b/homeassistant/components/cover/myq.py index 4c862f8c8b8..8d59a90278c 100644 --- a/homeassistant/components/cover/myq.py +++ b/homeassistant/components/cover/myq.py @@ -12,7 +12,6 @@ from homeassistant.components.cover import CoverDevice from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_TYPE, STATE_CLOSED) import homeassistant.helpers.config_validation as cv -import homeassistant.loader as loader REQUIREMENTS = ['pymyq==0.0.8'] @@ -37,7 +36,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None): username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) brand = config.get(CONF_TYPE) - persistent_notification = loader.get_component('persistent_notification') myq = pymyq(username, password, brand) try: @@ -52,8 +50,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): except (TypeError, KeyError, NameError, ValueError) as ex: _LOGGER.error("%s", ex) - persistent_notification.create( - hass, 'Error: {}
' + hass.components.persistent_notification.create( + 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, diff --git a/homeassistant/components/demo.py b/homeassistant/components/demo.py index 222a031d380..27bb1bbb8d1 100644 --- a/homeassistant/components/demo.py +++ b/homeassistant/components/demo.py @@ -9,7 +9,6 @@ import time import homeassistant.bootstrap as bootstrap import homeassistant.core as ha -import homeassistant.loader as loader from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM DEPENDENCIES = ['conversation', 'introduction', 'zone'] @@ -38,9 +37,9 @@ COMPONENTS_WITH_DEMO_PLATFORM = [ @asyncio.coroutine def async_setup(hass, config): """Set up the demo environment.""" - group = loader.get_component('group') - configurator = loader.get_component('configurator') - persistent_notification = loader.get_component('persistent_notification') + group = hass.components.group + configurator = hass.components.configurator + persistent_notification = hass.components.persistent_notification config.setdefault(ha.DOMAIN, {}) config.setdefault(DOMAIN, {}) @@ -206,7 +205,7 @@ def async_setup(hass, config): def setup_configurator(): """Set up a configurator.""" request_id = configurator.request_config( - hass, "Philips Hue", hue_configuration_callback, + "Philips Hue", hue_configuration_callback, description=("Press the button on the bridge to register Philips " "Hue with Home Assistant."), description_image="/static/images/config_philips_hue.jpg", diff --git a/homeassistant/components/device_tracker/unifi.py b/homeassistant/components/device_tracker/unifi.py index 29c997b4dac..a471ca5c96a 100644 --- a/homeassistant/components/device_tracker/unifi.py +++ b/homeassistant/components/device_tracker/unifi.py @@ -8,7 +8,6 @@ import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv -import homeassistant.loader as loader from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD @@ -48,14 +47,13 @@ def get_scanner(hass, config): port = config[DOMAIN].get(CONF_PORT) verify_ssl = config[DOMAIN].get(CONF_VERIFY_SSL) - persistent_notification = loader.get_component('persistent_notification') try: ctrl = Controller(host, username, password, port, version='v4', site_id=site_id, ssl_verify=verify_ssl) except APIError as ex: _LOGGER.error("Failed to connect to Unifi: %s", ex) - persistent_notification.create( - hass, 'Failed to connect to Unifi. ' + hass.components.persistent_notification.create( + 'Failed to connect to Unifi. ' 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(ex), diff --git a/homeassistant/components/google.py b/homeassistant/components/google.py index f7f8e63167f..e99c4095f22 100644 --- a/homeassistant/components/google.py +++ b/homeassistant/components/google.py @@ -17,7 +17,6 @@ import voluptuous as vol from voluptuous.error import Error as VoluptuousError import homeassistant.helpers.config_validation as cv -import homeassistant.loader as loader from homeassistant.setup import setup_component from homeassistant.helpers import discovery from homeassistant.helpers.entity import generate_entity_id @@ -106,32 +105,31 @@ def do_authentication(hass, config): 'Home-Assistant.io', ) - persistent_notification = loader.get_component('persistent_notification') try: dev_flow = oauth.step1_get_device_and_user_codes() except OAuth2DeviceCodeError as err: - persistent_notification.create( - hass, 'Error: {}
You will need to restart hass after fixing.' - ''.format(err), + hass.components.persistent_notification.create( + 'Error: {}
You will need to restart hass after fixing.' + ''.format(err), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False - persistent_notification.create( - hass, 'In order to authorize Home-Assistant to view your calendars ' - 'you must visit: {} and enter ' - 'code: {}'.format(dev_flow.verification_url, - dev_flow.verification_url, - dev_flow.user_code), + hass.components.persistent_notification.create( + 'In order to authorize Home-Assistant to view your calendars ' + 'you must visit: {} and enter ' + 'code: {}'.format(dev_flow.verification_url, + dev_flow.verification_url, + dev_flow.user_code), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID ) def step2_exchange(now): """Keep trying to validate the user_code until it expires.""" if now >= dt.as_local(dev_flow.user_code_expiry): - persistent_notification.create( - hass, 'Authenication code expired, please restart ' - 'Home-Assistant and try again', + hass.components.persistent_notification.create( + 'Authenication code expired, please restart ' + 'Home-Assistant and try again', title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) listener() @@ -146,9 +144,9 @@ def do_authentication(hass, config): storage.put(credentials) do_setup(hass, config) listener() - persistent_notification.create( - hass, 'We are all setup now. Check {} for calendars that have ' - 'been found'.format(YAML_DEVICES), + hass.components.persistent_notification.create( + 'We are all setup now. Check {} for calendars that have ' + 'been found'.format(YAML_DEVICES), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) listener = track_time_change(hass, step2_exchange, diff --git a/homeassistant/components/media_player/roku.py b/homeassistant/components/media_player/roku.py index aac6b1a228d..5917f1e3083 100644 --- a/homeassistant/components/media_player/roku.py +++ b/homeassistant/components/media_player/roku.py @@ -15,7 +15,6 @@ from homeassistant.components.media_player import ( from homeassistant.const import ( CONF_HOST, STATE_IDLE, STATE_PLAYING, STATE_UNKNOWN, STATE_HOME) import homeassistant.helpers.config_validation as cv -import homeassistant.loader as loader REQUIREMENTS = ['python-roku==3.1.3'] @@ -52,7 +51,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None): elif CONF_HOST in config: hosts.append(config.get(CONF_HOST)) - persistent_notification = loader.get_component('persistent_notification') rokus = [] for host in hosts: new_roku = RokuDevice(host) @@ -66,8 +64,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None): except AttributeError: _LOGGER.error("Unable to initialize roku at %s", host) - persistent_notification.create( - hass, 'Error: Unable to initialize roku at {}
' + hass.components.persistent_notification.create( + 'Error: Unable to initialize roku at {}
' 'Check its network connection or consider ' 'using auto discovery.
' 'You will need to restart hass after fixing.' diff --git a/homeassistant/components/ring.py b/homeassistant/components/ring.py index 450ef6b1978..a1529fddbd6 100644 --- a/homeassistant/components/ring.py +++ b/homeassistant/components/ring.py @@ -9,7 +9,6 @@ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_USERNAME, CONF_PASSWORD -import homeassistant.loader as loader from requests.exceptions import HTTPError, ConnectTimeout @@ -40,7 +39,6 @@ def setup(hass, config): username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) - persistent_notification = loader.get_component('persistent_notification') try: from ring_doorbell import Ring @@ -51,8 +49,8 @@ def setup(hass, config): hass.data['ring'] = ring except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Ring service: %s", str(ex)) - persistent_notification.create( - hass, 'Error: {}
' + hass.components.persistent_notification.create( + 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, diff --git a/homeassistant/components/sensor/qnap.py b/homeassistant/components/sensor/qnap.py index 42f68a1967a..20460f9063c 100644 --- a/homeassistant/components/sensor/qnap.py +++ b/homeassistant/components/sensor/qnap.py @@ -110,11 +110,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): api.update() if not api.data: - import homeassistant.loader as loader - loader.get_component('persistent_notification').create( - hass, 'Error: Failed to set up QNAP sensor.
' - 'Check the logs for additional information. ' - 'You will need to restart hass after fixing.', + hass.components.persistent_notification.create( + 'Error: Failed to set up QNAP sensor.
' + 'Check the logs for additional information. ' + 'You will need to restart hass after fixing.', title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False diff --git a/homeassistant/components/switch/broadlink.py b/homeassistant/components/switch/broadlink.py index 3a7f3ee0c80..6ea738d82bc 100644 --- a/homeassistant/components/switch/broadlink.py +++ b/homeassistant/components/switch/broadlink.py @@ -13,7 +13,6 @@ import socket import voluptuous as vol -import homeassistant.loader as loader from homeassistant.util.dt import utcnow from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) from homeassistant.const import ( @@ -67,8 +66,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None): config.get(CONF_MAC).encode().replace(b':', b'')) switch_type = config.get(CONF_TYPE) - persistent_notification = loader.get_component('persistent_notification') - @asyncio.coroutine def _learn_command(call): try: @@ -91,13 +88,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None): log_msg = "Recieved packet is: {}".\ format(b64encode(packet).decode('utf8')) _LOGGER.info(log_msg) - persistent_notification.async_create( - hass, log_msg, title='Broadlink switch') + hass.components.persistent_notification.async_create( + log_msg, title='Broadlink switch') return yield from asyncio.sleep(1, loop=hass.loop) _LOGGER.error("Did not received any signal") - persistent_notification.async_create( - hass, "Did not received any signal", title='Broadlink switch') + hass.components.persistent_notification.async_create( + "Did not received any signal", title='Broadlink switch') @asyncio.coroutine def _send_packet(call): diff --git a/homeassistant/components/upnp.py b/homeassistant/components/upnp.py index 355a6d0a648..9e45def63db 100644 --- a/homeassistant/components/upnp.py +++ b/homeassistant/components/upnp.py @@ -9,8 +9,6 @@ from urllib.parse import urlsplit import voluptuous as vol -import homeassistant.loader as loader - from homeassistant.const import (EVENT_HOMEASSISTANT_STOP) from homeassistant.helpers import config_validation as cv from homeassistant.helpers import discovery @@ -78,8 +76,6 @@ def setup(hass, config): if external_port == 0: external_port = internal_port - persistent_notification = loader.get_component('persistent_notification') - try: upnp.addportmapping( external_port, 'TCP', host, internal_port, 'Home Assistant', '') @@ -92,8 +88,8 @@ def setup(hass, config): except Exception as ex: _LOGGER.error("UPnP failed to configure port mapping: %s", str(ex)) - persistent_notification.create( - hass, 'ERROR: tcp port {} is already mapped in your router.' + hass.components.persistent_notification.create( + 'ERROR: tcp port {} is already mapped in your router.' '
Please disable port_mapping in the upnp ' 'configuration section.
' 'You will need to restart hass after fixing.'