当前位置: 首页>>代码示例>>Python>>正文


Python HomeAssistantType.async_create_task方法代码示例

本文整理汇总了Python中homeassistant.helpers.typing.HomeAssistantType.async_create_task方法的典型用法代码示例。如果您正苦于以下问题:Python HomeAssistantType.async_create_task方法的具体用法?Python HomeAssistantType.async_create_task怎么用?Python HomeAssistantType.async_create_task使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在homeassistant.helpers.typing.HomeAssistantType的用法示例。


在下文中一共展示了HomeAssistantType.async_create_task方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType,
                            entry: ConfigType) -> bool:
    """Set up Toon from a config entry."""
    from toonapilib import Toon

    conf = hass.data.get(DATA_TOON_CONFIG)

    toon = await hass.async_add_executor_job(partial(
        Toon, entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD],
        conf[CONF_CLIENT_ID], conf[CONF_CLIENT_SECRET],
        tenant_id=entry.data[CONF_TENANT],
        display_common_name=entry.data[CONF_DISPLAY]))

    hass.data.setdefault(DATA_TOON_CLIENT, {})[entry.entry_id] = toon

    # Register device for the Meter Adapter, since it will have no entities.
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={
            (DOMAIN, toon.agreement.id, 'meter_adapter'),
        },
        manufacturer='Eneco',
        name="Meter Adapter",
        via_hub=(DOMAIN, toon.agreement.id)
    )

    for component in 'binary_sensor', 'climate', 'sensor':
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
开发者ID:chilicheech,项目名称:home-assistant,代码行数:34,代码来源:__init__.py

示例2: async_publish

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
def async_publish(hass: HomeAssistantType, topic: Any, payload, qos=None,
                  retain=None) -> None:
    """Publish message to an MQTT topic."""
    data = _build_publish_data(topic, qos, retain)
    data[ATTR_PAYLOAD] = payload
    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))
开发者ID:boced66,项目名称:home-assistant,代码行数:9,代码来源:__init__.py

示例3: async_migrate_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_migrate_entry(hass: HomeAssistantType, entry: ConfigEntry):
    """Handle migration of a previous version config entry.

    A config entry created under a previous version must go through the
    integration setup again so we can properly retrieve the needed data
    elements. Force this by removing the entry and triggering a new flow.
    """
    from pysmartthings import SmartThings

    # Remove the installed_app, which if already removed raises a 403 error.
    api = SmartThings(async_get_clientsession(hass),
                      entry.data[CONF_ACCESS_TOKEN])
    installed_app_id = entry.data[CONF_INSTALLED_APP_ID]
    try:
        await api.delete_installed_app(installed_app_id)
    except ClientResponseError as ex:
        if ex.status == 403:
            _LOGGER.exception("Installed app %s has already been removed",
                              installed_app_id)
        else:
            raise
    _LOGGER.debug("Removed installed app %s", installed_app_id)

    # Delete the entry
    hass.async_create_task(
        hass.config_entries.async_remove(entry.entry_id))
    # only create new flow if there isn't a pending one for SmartThings.
    flows = hass.config_entries.flow.async_progress()
    if not [flow for flow in flows if flow['handler'] == DOMAIN]:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={'source': 'import'}))

    # Return False because it could not be migrated.
    return False
开发者ID:chilicheech,项目名称:home-assistant,代码行数:37,代码来源:__init__.py

示例4: async_setup_scanner_platform

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
                                 scanner: Any, async_see_device: Callable,
                                 platform: str):
    """Set up the connect scanner-based platform to device tracker.

    This method must be run in the event loop.
    """
    interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
    update_lock = asyncio.Lock(loop=hass.loop)
    scanner.hass = hass

    # Initial scan of each mac we also tell about host name for config
    seen = set()  # type: Any

    async def async_device_tracker_scan(now: dt_util.dt.datetime):
        """Handle interval matches."""
        if update_lock.locked():
            _LOGGER.warning(
                "Updating device list from %s took longer than the scheduled "
                "scan interval %s", platform, interval)
            return

        async with update_lock:
            found_devices = await scanner.async_scan_devices()

        for mac in found_devices:
            if mac in seen:
                host_name = None
            else:
                host_name = await scanner.async_get_device_name(mac)
                seen.add(mac)

            try:
                extra_attributes = \
                    await scanner.async_get_extra_attributes(mac)
            except NotImplementedError:
                extra_attributes = dict()

            kwargs = {
                'mac': mac,
                'host_name': host_name,
                'source_type': SOURCE_TYPE_ROUTER,
                'attributes': {
                    'scanner': scanner.__class__.__name__,
                    **extra_attributes
                }
            }

            zone_home = hass.states.get(zone.ENTITY_ID_HOME)
            if zone_home:
                kwargs['gps'] = [zone_home.attributes[ATTR_LATITUDE],
                                 zone_home.attributes[ATTR_LONGITUDE]]
                kwargs['gps_accuracy'] = 0

            hass.async_create_task(async_see_device(**kwargs))

    async_track_time_interval(hass, async_device_tracker_scan, interval)
    hass.async_create_task(async_device_tracker_scan(None))
开发者ID:boced66,项目名称:home-assistant,代码行数:60,代码来源:__init__.py

示例5: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
    """Initialize config entry which represents the HEOS controller."""
    from pyheos import Heos, CommandError
    host = entry.data[CONF_HOST]
    # Setting all_progress_events=False ensures that we only receive a
    # media position update upon start of playback or when media changes
    controller = Heos(host, all_progress_events=False)
    try:
        await controller.connect(auto_reconnect=True)
    # Auto reconnect only operates if initial connection was successful.
    except (asyncio.TimeoutError, ConnectionError, CommandError) as error:
        await controller.disconnect()
        _LOGGER.debug("Unable to connect to controller %s: %s", host, error)
        raise ConfigEntryNotReady

    # Disconnect when shutting down
    async def disconnect_controller(event):
        await controller.disconnect()
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, disconnect_controller)

    # Get players and sources
    try:
        players = await controller.get_players()
        favorites = {}
        if controller.is_signed_in:
            favorites = await controller.get_favorites()
        else:
            _LOGGER.warning(
                "%s is not logged in to a HEOS account and will be unable "
                "to retrieve HEOS favorites: Use the 'heos.sign_in' service "
                "to sign-in to a HEOS account", host)
        inputs = await controller.get_input_sources()
    except (asyncio.TimeoutError, ConnectionError, CommandError) as error:
        await controller.disconnect()
        _LOGGER.debug("Unable to retrieve players and sources: %s", error,
                      exc_info=isinstance(error, CommandError))
        raise ConfigEntryNotReady

    controller_manager = ControllerManager(hass, controller)
    await controller_manager.connect_listeners()

    source_manager = SourceManager(favorites, inputs)
    source_manager.connect_update(hass, controller)

    hass.data[DOMAIN] = {
        DATA_CONTROLLER_MANAGER: controller_manager,
        DATA_SOURCE_MANAGER: source_manager,
        MEDIA_PLAYER_DOMAIN: players
    }

    services.register(hass, controller)

    hass.async_create_task(hass.config_entries.async_forward_entry_setup(
        entry, MEDIA_PLAYER_DOMAIN))
    return True
开发者ID:home-assistant,项目名称:home-assistant,代码行数:57,代码来源:__init__.py

示例6: async_setup

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Start the MQTT protocol service."""
    conf = config.get(DOMAIN)  # type: Optional[ConfigType]

    # We need this because discovery can cause components to be set up and
    # otherwise it will not load the users config.
    # This needs a better solution.
    hass.data[DATA_MQTT_HASS_CONFIG] = config

    if conf is None:
        # If we have a config entry, setup is done by that config entry.
        # If there is no config entry, this should fail.
        return bool(hass.config_entries.async_entries(DOMAIN))

    conf = dict(conf)

    if CONF_EMBEDDED in conf or CONF_BROKER not in conf:
        if (conf.get(CONF_PASSWORD) is None and
                config.get('http', {}).get('api_password') is not None):
            _LOGGER.error(
                "Starting from release 0.76, the embedded MQTT broker does not"
                " use api_password as default password anymore. Please set"
                " password configuration. See https://home-assistant.io/docs/"
                "mqtt/broker#embedded-broker for details")
            return False

        broker_config = await _async_setup_server(hass, config)

        if broker_config is None:
            _LOGGER.error("Unable to start embedded MQTT broker")
            return False

        conf.update({
            CONF_BROKER: broker_config[0],
            CONF_PORT: broker_config[1],
            CONF_USERNAME: broker_config[2],
            CONF_PASSWORD: broker_config[3],
            CONF_CERTIFICATE: broker_config[4],
            CONF_PROTOCOL: broker_config[5],
            CONF_CLIENT_KEY: None,
            CONF_CLIENT_CERT: None,
            CONF_TLS_INSECURE: None,
        })

    hass.data[DATA_MQTT_CONFIG] = conf

    # Only import if we haven't before.
    if not hass.config_entries.async_entries(DOMAIN):
        hass.async_create_task(hass.config_entries.flow.async_init(
            DOMAIN, context={'source': config_entries.SOURCE_IMPORT},
            data={}
        ))

    return True
开发者ID:arsaboo,项目名称:home-assistant,代码行数:56,代码来源:__init__.py

示例7: async_setup

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Start the MQTT protocol service."""
    conf = config.get(DOMAIN)  # type: Optional[ConfigType]

    # We need this because discovery can cause components to be set up and
    # otherwise it will not load the users config.
    # This needs a better solution.
    hass.data[DATA_MQTT_HASS_CONFIG] = config

    websocket_api.async_register_command(hass, websocket_subscribe)

    if conf is None:
        # If we have a config entry, setup is done by that config entry.
        # If there is no config entry, this should fail.
        return bool(hass.config_entries.async_entries(DOMAIN))

    conf = dict(conf)

    if CONF_EMBEDDED in conf or CONF_BROKER not in conf:

        broker_config = await _async_setup_server(hass, config)

        if broker_config is None:
            _LOGGER.error("Unable to start embedded MQTT broker")
            return False

        conf.update({
            CONF_BROKER: broker_config[0],
            CONF_PORT: broker_config[1],
            CONF_USERNAME: broker_config[2],
            CONF_PASSWORD: broker_config[3],
            CONF_CERTIFICATE: broker_config[4],
            CONF_PROTOCOL: broker_config[5],
            CONF_CLIENT_KEY: None,
            CONF_CLIENT_CERT: None,
            CONF_TLS_INSECURE: None,
        })

    hass.data[DATA_MQTT_CONFIG] = conf

    # Only import if we haven't before.
    if not hass.config_entries.async_entries(DOMAIN):
        hass.async_create_task(hass.config_entries.flow.async_init(
            DOMAIN, context={'source': config_entries.SOURCE_IMPORT},
            data={}
        ))

    return True
开发者ID:boced66,项目名称:home-assistant,代码行数:50,代码来源:__init__.py

示例8: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType,
                            config_entry: ConfigEntry):
    """Set up UPnP/IGD-device from a config entry."""
    await async_ensure_domain_data(hass)
    data = config_entry.data

    # build UPnP/IGD device
    ssdp_description = data[CONF_SSDP_DESCRIPTION]
    try:
        device = await Device.async_create_device(hass, ssdp_description)
    except (asyncio.TimeoutError, aiohttp.ClientError):
        _LOGGER.error('Unable to create upnp-device')
        return False

    hass.data[DOMAIN]['devices'][device.udn] = device

    # port mapping
    if data.get(CONF_ENABLE_PORT_MAPPING):
        local_ip = hass.data[DOMAIN]['local_ip']
        ports = hass.data[DOMAIN]['auto_config']['ports']
        _LOGGER.debug('Enabling port mappings: %s', ports)

        hass_port = None
        if hasattr(hass, 'http'):
            hass_port = hass.http.server_port
        ports = _substitute_hass_ports(ports, hass_port=hass_port)
        await device.async_add_port_mappings(ports, local_ip)

    # sensors
    if data.get(CONF_ENABLE_SENSORS):
        _LOGGER.debug('Enabling sensors')

        # register sensor setup handlers
        hass.async_create_task(hass.config_entries.async_forward_entry_setup(
            config_entry, 'sensor'))

    async def delete_port_mapping(event):
        """Delete port mapping on quit."""
        if data.get(CONF_ENABLE_PORT_MAPPING):
            _LOGGER.debug('Deleting port mappings')
            await device.async_delete_port_mappings()
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, delete_port_mapping)

    return True
开发者ID:ManHammer,项目名称:home-assistant,代码行数:46,代码来源:__init__.py

示例9: async_setup

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the HEOS component."""
    if DOMAIN not in config:
        return True
    host = config[DOMAIN][CONF_HOST]
    entries = hass.config_entries.async_entries(DOMAIN)
    if not entries:
        # Create new entry based on config
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={'source': 'import'},
                data={CONF_HOST: host}))
    else:
        # Check if host needs to be updated
        entry = entries[0]
        if entry.data[CONF_HOST] != host:
            entry.data[CONF_HOST] = host
            entry.title = format_title(host)
            hass.config_entries.async_update_entry(entry)

    return True
开发者ID:home-assistant,项目名称:home-assistant,代码行数:23,代码来源:__init__.py

示例10: async_get_registry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_get_registry(hass: HomeAssistantType) -> ZhaDeviceStorage:
    """Return zha device storage instance."""
    task = hass.data.get(DATA_REGISTRY)

    if task is None:
        async def _load_reg() -> ZhaDeviceStorage:
            registry = ZhaDeviceStorage(hass)
            await registry.async_load()
            return registry

        task = hass.data[DATA_REGISTRY] = hass.async_create_task(_load_reg())

    return cast(ZhaDeviceStorage, await task)
开发者ID:boced66,项目名称:home-assistant,代码行数:15,代码来源:store.py

示例11: async_setup

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the mobile app component."""
    store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
    app_config = await store.async_load()
    if app_config is None:
        app_config = {
            DATA_BINARY_SENSOR: {},
            DATA_CONFIG_ENTRIES: {},
            DATA_DELETED_IDS: [],
            DATA_DEVICES: {},
            DATA_SENSOR: {}
        }

    hass.data[DOMAIN] = {
        DATA_BINARY_SENSOR: app_config.get(DATA_BINARY_SENSOR, {}),
        DATA_CONFIG_ENTRIES: {},
        DATA_DELETED_IDS: app_config.get(DATA_DELETED_IDS, []),
        DATA_DEVICES: {},
        DATA_SENSOR: app_config.get(DATA_SENSOR, {}),
        DATA_STORE: store,
    }

    hass.http.register_view(RegistrationsView())
    register_websocket_handlers(hass)

    for deleted_id in hass.data[DOMAIN][DATA_DELETED_IDS]:
        try:
            webhook_register(hass, DOMAIN, "Deleted Webhook", deleted_id,
                             handle_webhook)
        except ValueError:
            pass

    hass.async_create_task(discovery.async_load_platform(
        hass, 'notify', DOMAIN, {}, config))

    return True
开发者ID:fbradyirl,项目名称:home-assistant,代码行数:38,代码来源:__init__.py

示例12: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
    """Initialize config entry which represents an installed SmartApp."""
    from pysmartthings import SmartThings

    if not hass.config.api.base_url.lower().startswith('https://'):
        _LOGGER.warning("The 'base_url' of the 'http' component must be "
                        "configured and start with 'https://'")
        return False

    api = SmartThings(async_get_clientsession(hass),
                      entry.data[CONF_ACCESS_TOKEN])

    remove_entry = False
    try:
        # See if the app is already setup. This occurs when there are
        # installs in multiple SmartThings locations (valid use-case)
        manager = hass.data[DOMAIN][DATA_MANAGER]
        smart_app = manager.smartapps.get(entry.data[CONF_APP_ID])
        if not smart_app:
            # Validate and setup the app.
            app = await api.app(entry.data[CONF_APP_ID])
            smart_app = setup_smartapp(hass, app)

        # Validate and retrieve the installed app.
        installed_app = await validate_installed_app(
            api, entry.data[CONF_INSTALLED_APP_ID])

        # Get devices and their current status
        devices = await api.devices(
            location_ids=[installed_app.location_id])

        async def retrieve_device_status(device):
            try:
                await device.status.refresh()
            except ClientResponseError:
                _LOGGER.debug("Unable to update status for device: %s (%s), "
                              "the device will be ignored",
                              device.label, device.device_id, exc_info=True)
                devices.remove(device)

        await asyncio.gather(*[retrieve_device_status(d)
                               for d in devices.copy()])

        # Setup device broker
        broker = DeviceBroker(hass, devices,
                              installed_app.installed_app_id)
        broker.event_handler_disconnect = \
            smart_app.connect_event(broker.event_handler)
        hass.data[DOMAIN][DATA_BROKERS][entry.entry_id] = broker

    except ClientResponseError as ex:
        if ex.status in (401, 403):
            _LOGGER.exception("Unable to setup config entry '%s' - please "
                              "reconfigure the integration", entry.title)
            remove_entry = True
        else:
            _LOGGER.debug(ex, exc_info=True)
            raise ConfigEntryNotReady
    except (ClientConnectionError, RuntimeWarning) as ex:
        _LOGGER.debug(ex, exc_info=True)
        raise ConfigEntryNotReady

    if remove_entry:
        hass.async_create_task(
            hass.config_entries.async_remove(entry.entry_id))
        # only create new flow if there isn't a pending one for SmartThings.
        flows = hass.config_entries.flow.async_progress()
        if not [flow for flow in flows if flow['handler'] == DOMAIN]:
            hass.async_create_task(
                hass.config_entries.flow.async_init(
                    DOMAIN, context={'source': 'import'}))
        return False

    for component in SUPPORTED_PLATFORMS:
        hass.async_create_task(hass.config_entries.async_forward_entry_setup(
            entry, component))
    return True
开发者ID:arsaboo,项目名称:home-assistant,代码行数:79,代码来源:__init__.py

示例13: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType,
                            config_entry: ConfigEntry):
    """Set up UPnP/IGD device from a config entry."""
    domain_data = hass.data[DOMAIN]
    conf = domain_data['config']

    # discover and construct
    device = await async_discover_and_construct(hass,
                                                config_entry.data.get('udn'))
    if not device:
        _LOGGER.info('Unable to create UPnP/IGD, aborting')
        return False

    # 'register'/save UDN
    config_entry.data['udn'] = device.udn
    hass.data[DOMAIN]['devices'][device.udn] = device
    hass.config_entries.async_update_entry(entry=config_entry,
                                           data=config_entry.data)

    # create device registry entry
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={
            (dr.CONNECTION_UPNP, device.udn)
        },
        identifiers={
            (DOMAIN, device.udn)
        },
        name=device.name,
        manufacturer=device.manufacturer,
    )

    # set up sensors
    if conf.get(CONF_ENABLE_SENSORS):
        _LOGGER.debug('Enabling sensors')

        # register sensor setup handlers
        hass.async_create_task(hass.config_entries.async_forward_entry_setup(
            config_entry, 'sensor'))

    # set up port mapping
    if conf.get(CONF_ENABLE_PORT_MAPPING):
        _LOGGER.debug('Enabling port mapping')
        local_ip = domain_data['local_ip']
        ports = conf.get('ports', {})

        hass_port = None
        if hasattr(hass, 'http'):
            hass_port = hass.http.server_port

        ports = _substitute_hass_ports(ports, hass_port=hass_port)
        await device.async_add_port_mappings(ports, local_ip)

    # set up port mapping deletion on stop-hook
    async def delete_port_mapping(event):
        """Delete port mapping on quit."""
        _LOGGER.debug('Deleting port mappings')
        await device.async_delete_port_mappings()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, delete_port_mapping)

    return True
开发者ID:boced66,项目名称:home-assistant,代码行数:65,代码来源:__init__.py

示例14: async_setup_entry

# 需要导入模块: from homeassistant.helpers.typing import HomeAssistantType [as 别名]
# 或者: from homeassistant.helpers.typing.HomeAssistantType import async_create_task [as 别名]
async def async_setup_entry(hass: HomeAssistantType,
                            entry: ConfigEntry) -> bool:
    """Set up the esphome component."""
    # pylint: disable=redefined-outer-name
    from aioesphomeapi import APIClient, APIConnectionError

    hass.data.setdefault(DOMAIN, {})

    host = entry.data[CONF_HOST]
    port = entry.data[CONF_PORT]
    password = entry.data[CONF_PASSWORD]

    cli = APIClient(hass.loop, host, port, password,
                    client_info="Home Assistant {}".format(const.__version__))

    # Store client in per-config-entry hass.data
    store = Store(hass, STORAGE_VERSION, STORAGE_KEY.format(entry.entry_id),
                  encoder=JSONEncoder)
    entry_data = hass.data[DOMAIN][entry.entry_id] = RuntimeEntryData(
        client=cli,
        entry_id=entry.entry_id,
        store=store,
    )

    async def on_stop(event: Event) -> None:
        """Cleanup the socket client on HA stop."""
        await _cleanup_instance(hass, entry)

    entry_data.cleanup_callbacks.append(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_stop)
    )

    @callback
    def async_on_state(state: 'EntityState') -> None:
        """Send dispatcher updates when a new state is received."""
        entry_data.async_update_state(hass, state)

    @callback
    def async_on_service_call(service: 'ServiceCall') -> None:
        """Call service when user automation in ESPHome config is triggered."""
        domain, service_name = service.service.split('.', 1)
        service_data = service.data

        if service.data_template:
            try:
                data_template = {key: Template(value) for key, value in
                                 service.data_template.items()}
                template.attach(hass, data_template)
                service_data.update(template.render_complex(
                    data_template, service.variables))
            except TemplateError as ex:
                _LOGGER.error('Error rendering data template: %s', ex)
                return

        hass.async_create_task(hass.services.async_call(
            domain, service_name, service_data, blocking=True))

    async def send_home_assistant_state(entity_id: str, _,
                                        new_state: Optional[State]) -> None:
        """Forward Home Assistant states to ESPHome."""
        if new_state is None:
            return
        await cli.send_home_assistant_state(entity_id, new_state.state)

    @callback
    def async_on_state_subscription(entity_id: str) -> None:
        """Subscribe and forward states for requested entities."""
        unsub = async_track_state_change(
            hass, entity_id, send_home_assistant_state)
        entry_data.disconnect_callbacks.append(unsub)
        # Send initial state
        hass.async_create_task(send_home_assistant_state(
            entity_id, None, hass.states.get(entity_id)))

    async def on_login() -> None:
        """Subscribe to states and list entities on successful API login."""
        try:
            entry_data.device_info = await cli.device_info()
            entry_data.available = True
            await _async_setup_device_registry(hass, entry,
                                               entry_data.device_info)
            entry_data.async_update_device_state(hass)

            entity_infos = await cli.list_entities()
            entry_data.async_update_static_infos(hass, entity_infos)
            await cli.subscribe_states(async_on_state)
            await cli.subscribe_service_calls(async_on_service_call)
            await cli.subscribe_home_assistant_states(
                async_on_state_subscription)

            hass.async_create_task(entry_data.async_save_to_store())
        except APIConnectionError as err:
            _LOGGER.warning("Error getting initial data: %s", err)
            # Re-connection logic will trigger after this
            await cli.disconnect()

    try_connect = await _setup_auto_reconnect_logic(hass, cli, entry, host,
                                                    on_login)

    # This is a bit of a hack: We schedule complete_setup into the
#.........这里部分代码省略.........
开发者ID:Martwall,项目名称:home-assistant,代码行数:103,代码来源:__init__.py


注:本文中的homeassistant.helpers.typing.HomeAssistantType.async_create_task方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。