Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Use bind_hass for helpers #9745

Merged
merged 2 commits into from
Oct 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions homeassistant/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@

import voluptuous as vol

import homeassistant.components as core_components
from homeassistant import (
core, config as conf_util, loader, components as core_components)
from homeassistant.components import persistent_notification
import homeassistant.config as conf_util
import homeassistant.core as core
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
from homeassistant.setup import async_setup_component
import homeassistant.loader as loader
from homeassistant.util.logging import AsyncHandler
from homeassistant.util.package import async_get_user_site, get_user_site
from homeassistant.util.yaml import clear_secret_cache
Expand Down
5 changes: 3 additions & 2 deletions homeassistant/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
EVENT_SERVICE_EXECUTED, EVENT_SERVICE_REGISTERED, EVENT_STATE_CHANGED,
EVENT_TIME_CHANGED, MATCH_ALL, EVENT_HOMEASSISTANT_CLOSE,
EVENT_SERVICE_REMOVED, __version__)
from homeassistant.loader import Components
from homeassistant import loader
from homeassistant.exceptions import (
HomeAssistantError, InvalidEntityFormatError)
from homeassistant.util.async import (
Expand Down Expand Up @@ -129,7 +129,8 @@ def __init__(self, loop=None):
self.services = ServiceRegistry(self)
self.states = StateMachine(self.bus, self.loop)
self.config = Config() # type: Config
self.components = Components(self)
self.components = loader.Components(self)
self.helpers = loader.Helpers(self)
# This is a dictionary that any component can store any data on.
self.data = {}
self.state = CoreState.not_running
Expand Down
8 changes: 6 additions & 2 deletions homeassistant/helpers/aiohttp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import async_timeout

from homeassistant.core import callback
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
from homeassistant.const import __version__
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE, __version__
from homeassistant.loader import bind_hass

DATA_CONNECTOR = 'aiohttp_connector'
DATA_CONNECTOR_NOTVERIFY = 'aiohttp_connector_notverify'
Expand All @@ -21,6 +21,7 @@


@callback
@bind_hass
def async_get_clientsession(hass, verify_ssl=True):
"""Return default aiohttp ClientSession.

Expand All @@ -45,6 +46,7 @@ def async_get_clientsession(hass, verify_ssl=True):


@callback
@bind_hass
def async_create_clientsession(hass, verify_ssl=True, auto_cleanup=True,
**kwargs):
"""Create a new ClientSession with kwargs, i.e. for cookies.
Expand All @@ -71,6 +73,7 @@ def async_create_clientsession(hass, verify_ssl=True, auto_cleanup=True,


@asyncio.coroutine
@bind_hass
def async_aiohttp_proxy_web(hass, request, web_coro, buffer_size=102400,
timeout=10):
"""Stream websession request to aiohttp web response."""
Expand Down Expand Up @@ -102,6 +105,7 @@ def async_aiohttp_proxy_web(hass, request, web_coro, buffer_size=102400,


@asyncio.coroutine
@bind_hass
def async_aiohttp_proxy_stream(hass, request, stream, content_type,
buffer_size=102400, timeout=10):
"""Stream a stream to aiohttp web response."""
Expand Down
9 changes: 9 additions & 0 deletions homeassistant/helpers/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import asyncio

from homeassistant import setup, core
from homeassistant.loader import bind_hass
from homeassistant.const import (
ATTR_DISCOVERED, ATTR_SERVICE, EVENT_PLATFORM_DISCOVERED)
from homeassistant.exceptions import HomeAssistantError
Expand All @@ -18,6 +19,7 @@
ATTR_PLATFORM = 'platform'


@bind_hass
def listen(hass, service, callback):
"""Set up listener for discovery of specific service.

Expand All @@ -28,6 +30,7 @@ def listen(hass, service, callback):


@core.callback
@bind_hass
def async_listen(hass, service, callback):
"""Set up listener for discovery of specific service.

Expand All @@ -48,13 +51,15 @@ def discovery_event_listener(event):
hass.bus.async_listen(EVENT_PLATFORM_DISCOVERED, discovery_event_listener)


@bind_hass
def discover(hass, service, discovered=None, component=None, hass_config=None):
"""Fire discovery event. Can ensure a component is loaded."""
hass.add_job(
async_discover(hass, service, discovered, component, hass_config))


@asyncio.coroutine
@bind_hass
def async_discover(hass, service, discovered=None, component=None,
hass_config=None):
"""Fire discovery event. Can ensure a component is loaded."""
Expand All @@ -76,13 +81,15 @@ def async_discover(hass, service, discovered=None, component=None,
hass.bus.async_fire(EVENT_PLATFORM_DISCOVERED, data)


@bind_hass
def listen_platform(hass, component, callback):
"""Register a platform loader listener."""
run_callback_threadsafe(
hass.loop, async_listen_platform, hass, component, callback
).result()


@bind_hass
def async_listen_platform(hass, component, callback):
"""Register a platform loader listener.

Expand All @@ -109,6 +116,7 @@ def discovery_platform_listener(event):
EVENT_PLATFORM_DISCOVERED, discovery_platform_listener)


@bind_hass
def load_platform(hass, component, platform, discovered=None,
hass_config=None):
"""Load a component and platform dynamically.
Expand All @@ -127,6 +135,7 @@ def load_platform(hass, component, platform, discovered=None,


@asyncio.coroutine
@bind_hass
def async_load_platform(hass, component, platform, discovered=None,
hass_config=None):
"""Load a component and platform dynamically.
Expand Down
5 changes: 5 additions & 0 deletions homeassistant/helpers/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
import logging

from homeassistant.core import callback
from homeassistant.loader import bind_hass
from homeassistant.util.async import run_callback_threadsafe


_LOGGER = logging.getLogger(__name__)
DATA_DISPATCHER = 'dispatcher'


@bind_hass
def dispatcher_connect(hass, signal, target):
"""Connect a callable function to a signal."""
async_unsub = run_callback_threadsafe(
Expand All @@ -22,6 +24,7 @@ def remove_dispatcher():


@callback
@bind_hass
def async_dispatcher_connect(hass, signal, target):
"""Connect a callable function to a signal.

Expand Down Expand Up @@ -49,12 +52,14 @@ def async_remove_dispatcher():
return async_remove_dispatcher


@bind_hass
def dispatcher_send(hass, signal, *args):
"""Send signal and data."""
hass.loop.call_soon_threadsafe(async_dispatcher_send, hass, signal, *args)


@callback
@bind_hass
def async_dispatcher_send(hass, signal, *args):
"""Send signal and data.

Expand Down
11 changes: 11 additions & 0 deletions homeassistant/helpers/event.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Helpers for listening to events."""
import functools as ft

from homeassistant.loader import bind_hass
from homeassistant.helpers.sun import get_astral_event_next
from ..core import HomeAssistant, callback
from ..const import (
Expand Down Expand Up @@ -35,6 +36,7 @@ def remove():


@callback
@bind_hass
def async_track_state_change(hass, entity_ids, action, from_state=None,
to_state=None):
"""Track specific state changes.
Expand Down Expand Up @@ -86,6 +88,7 @@ def state_change_listener(event):


@callback
@bind_hass
def async_track_template(hass, template, action, variables=None):
"""Add a listener that track state changes with template condition."""
from . import condition
Expand Down Expand Up @@ -114,6 +117,7 @@ def template_condition_listener(entity_id, from_s, to_s):


@callback
@bind_hass
def async_track_same_state(hass, orig_value, period, action,
async_check_func=None, entity_ids=MATCH_ALL):
"""Track the state of entities for a period and run a action.
Expand Down Expand Up @@ -170,6 +174,7 @@ def state_for_cancel_listener(entity, from_state, to_state):


@callback
@bind_hass
def async_track_point_in_time(hass, action, point_in_time):
"""Add a listener that fires once after a specific point in time."""
utc_point_in_time = dt_util.as_utc(point_in_time)
Expand All @@ -187,6 +192,7 @@ def utc_converter(utc_now):


@callback
@bind_hass
def async_track_point_in_utc_time(hass, action, point_in_time):
"""Add a listener that fires once after a specific point in UTC time."""
# Ensure point_in_time is UTC
Expand Down Expand Up @@ -221,6 +227,7 @@ def point_in_time_listener(event):


@callback
@bind_hass
def async_track_time_interval(hass, action, interval):
"""Add a listener that fires repetitively at every timedelta interval."""
remove = None
Expand Down Expand Up @@ -251,6 +258,7 @@ def remove_listener():


@callback
@bind_hass
def async_track_sunrise(hass, action, offset=None):
"""Add a listener that will fire a specified offset from sunrise daily."""
remove = None
Expand Down Expand Up @@ -279,6 +287,7 @@ def remove_listener():


@callback
@bind_hass
def async_track_sunset(hass, action, offset=None):
"""Add a listener that will fire a specified offset from sunset daily."""
remove = None
Expand Down Expand Up @@ -307,6 +316,7 @@ def remove_listener():


@callback
@bind_hass
def async_track_utc_time_change(hass, action, year=None, month=None, day=None,
hour=None, minute=None, second=None,
local=False):
Expand Down Expand Up @@ -352,6 +362,7 @@ def pattern_time_change_listener(event):


@callback
@bind_hass
def async_track_time_change(hass, action, year=None, month=None, day=None,
hour=None, minute=None, second=None):
"""Add a listener that will fire if UTC time matches a pattern."""
Expand Down
3 changes: 3 additions & 0 deletions homeassistant/helpers/intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import bind_hass


DATA_KEY = 'intent'
Expand All @@ -19,6 +20,7 @@


@callback
@bind_hass
def async_register(hass, handler):
"""Register an intent with Home Assistant."""
intents = hass.data.get(DATA_KEY)
Expand All @@ -33,6 +35,7 @@ def async_register(hass, handler):


@asyncio.coroutine
@bind_hass
def async_handle(hass, platform, intent_type, slots=None, text_input=None):
"""Handle an intent."""
handler = hass.data.get(DATA_KEY, {}).get(intent_type)
Expand Down
2 changes: 2 additions & 0 deletions homeassistant/helpers/restore_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from homeassistant.core import HomeAssistant, CoreState, callback
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.loader import bind_hass
from homeassistant.components.history import get_states, last_recorder_run
from homeassistant.components.recorder import (
wait_connection_ready, DOMAIN as _RECORDER)
Expand Down Expand Up @@ -49,6 +50,7 @@ def remove_cache(event):


@asyncio.coroutine
@bind_hass
def async_get_last_state(hass, entity_id: str):
"""Restore state."""
if DATA_RESTORE_CACHE in hass.data:
Expand Down
5 changes: 4 additions & 1 deletion homeassistant/helpers/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant # NOQA
from homeassistant.exceptions import TemplateError
from homeassistant.loader import get_component
from homeassistant.loader import get_component, bind_hass
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async import run_coroutine_threadsafe

Expand All @@ -22,6 +22,7 @@
_LOGGER = logging.getLogger(__name__)


@bind_hass
def call_from_config(hass, config, blocking=False, variables=None,
validate_config=True):
"""Call a service based on a config hash."""
Expand All @@ -31,6 +32,7 @@ def call_from_config(hass, config, blocking=False, variables=None,


@asyncio.coroutine
@bind_hass
def async_call_from_config(hass, config, blocking=False, variables=None,
validate_config=True):
"""Call a service based on a config hash."""
Expand Down Expand Up @@ -80,6 +82,7 @@ def _data_template_creator(value):
domain, service_name, service_data, blocking)


@bind_hass
def extract_entity_ids(hass, service_call, expand_group=True):
"""Extract a list of entity ids from a service call.

Expand Down
2 changes: 2 additions & 0 deletions homeassistant/helpers/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@

from homeassistant.core import callback
from homeassistant.const import RESTART_EXIT_CODE
from homeassistant.loader import bind_hass

_LOGGER = logging.getLogger(__name__)


@callback
@bind_hass
def async_register_signal_handling(hass):
"""Register system signal handler for core."""
if sys.platform != 'win32':
Expand Down
3 changes: 3 additions & 0 deletions homeassistant/helpers/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging
from collections import defaultdict

from homeassistant.loader import bind_hass
import homeassistant.util.dt as dt_util
from homeassistant.components.media_player import (
ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_SEEK_POSITION,
Expand Down Expand Up @@ -120,13 +121,15 @@ def get_changed_since(states, utc_point_in_time):
if state.last_updated >= utc_point_in_time]


@bind_hass
def reproduce_state(hass, states, blocking=False):
"""Reproduce given state."""
return run_coroutine_threadsafe(
async_reproduce_state(hass, states, blocking), hass.loop).result()


@asyncio.coroutine
@bind_hass
def async_reproduce_state(hass, states, blocking=False):
"""Reproduce given state."""
if isinstance(states, State):
Expand Down
Loading