Persistent notification import (#8507)

* Rewrite persistent notification creation

* Update components.is_on to use auto loading

* Fix two hass parameters
This commit is contained in:
Paulus Schoutsen 2017-07-16 12:39:38 -07:00 committed by Pascal Vizeli
parent f6c3832e90
commit d0275c8075
16 changed files with 70 additions and 101 deletions

View File

@ -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

View File

@ -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

View File

@ -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: {}<br />'
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,

View File

@ -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!<br /><br />Add the following '
'to credentials: in your apple_tv configuration:<br /><br />'
'{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?<br /><br />'
'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:<br /><br />' +
'<br /><br />'.join(devices),
title=NOTIFICATION_SCAN_TITLE,

View File

@ -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: {}<br />'
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,

View File

@ -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

View File

@ -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,

View File

@ -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: {}<br />'
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,

View File

@ -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",

View File

@ -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: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),

View File

@ -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: {}<br />You will need to restart hass after fixing.'
''.format(err),
hass.components.persistent_notification.create(
'Error: {}<br />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: <a href="{}" target="_blank">{}</a> 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: <a href="{}" target="_blank">{}</a> 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,

View File

@ -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 {}<br />'
hass.components.persistent_notification.create(
'Error: Unable to initialize roku at {}<br />'
'Check its network connection or consider '
'using auto discovery.<br />'
'You will need to restart hass after fixing.'

View File

@ -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: {}<br />'
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(ex),
title=NOTIFICATION_TITLE,

View File

@ -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.<br />'
'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.<br />'
'Check the logs for additional information. '
'You will need to restart hass after fixing.',
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID)
return False

View File

@ -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):

View File

@ -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, '<b>ERROR: tcp port {} is already mapped in your router.'
hass.components.persistent_notification.create(
'<b>ERROR: tcp port {} is already mapped in your router.'
'</b><br />Please disable port_mapping in the <i>upnp</i> '
'configuration section.<br />'
'You will need to restart hass after fixing.'