Example #1
0
async def local_impl(hass):
    """Local implementation."""
    assert await setup.async_setup_component(hass, "http", {})
    return config_entry_oauth2_flow.LocalOAuth2Implementation(
        hass, TEST_DOMAIN, CLIENT_ID, CLIENT_SECRET, AUTHORIZE_URL, TOKEN_URL)
Example #2
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """
    Set up Strava Home Assistant config entry initiated through the HASS-UI.
    """

    hass.data.setdefault(DOMAIN, {})

    # OAuth Stuff
    try:
        implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass=hass, config_entry=entry)
    except ValueError:
        implementation = config_entry_oauth2_flow.LocalOAuth2Implementation(
            hass,
            DOMAIN,
            entry.data[CONF_CLIENT_ID],
            entry.data[CONF_CLIENT_SECRET],
            OAUTH2_AUTHORIZE,
            OAUTH2_TOKEN,
        )

        OAuth2FlowHandler.async_register_implementation(hass, implementation)

    oauth_websession = config_entry_oauth2_flow.OAuth2Session(
        hass, entry, implementation)

    await oauth_websession.async_ensure_token_valid()

    # webhook view to get notifications for strava activity updates
    def strava_update_event_factory(data,
                                    event_type=CONF_STRAVA_DATA_UPDATE_EVENT):
        hass.bus.fire(event_type, data)

    strava_webhook_view = StravaWebhookView(
        oauth_websession=oauth_websession,
        event_factory=strava_update_event_factory,
        host=get_url(hass, allow_internal=False, allow_ip=False),
        hass=hass,
    )

    hass.http.register_view(strava_webhook_view)

    # event listeners
    async def strava_startup_functions():
        await renew_webhook_subscription(hass=hass,
                                         entry=entry,
                                         webhook_view=strava_webhook_view)
        await strava_webhook_view.fetch_strava_data()
        return True

    def ha_start_handler(event):
        """
        called when HA rebooted
        i.e. after all webhook views have been registered and are available
        """
        hass.async_create_task(strava_startup_functions())

    def component_reload_handler(event):
        """called when the component reloads"""
        hass.async_create_task(strava_startup_functions())

    async def async_strava_config_update_handler():
        """called when user changes sensor configs"""
        await strava_webhook_view.fetch_strava_data()
        return

    def strava_config_update_handler(event):
        hass.async_create_task(async_strava_config_update_handler())

    def core_config_update_handler(event):
        """
        handles relevant changes to the HA core config.
        In particular, for URL and Unit System changes
        """
        if "external_url" in event.data.keys():
            hass.async_create_task(
                renew_webhook_subscription(hass=hass,
                                           entry=entry,
                                           webhook_view=strava_webhook_view))
        if "unit_system" in event.data.keys():
            hass.async_create_task(strava_webhook_view.fetch_strava_data())

    # register event listeners
    hass.data[DOMAIN]["remove_update_listener"] = []

    # if hass.bus.async_listeners().get(EVENT_HOMEASSISTANT_START, 0) < 1:
    hass.data[DOMAIN]["remove_update_listener"].append(
        hass.bus.async_listen(EVENT_HOMEASSISTANT_START, ha_start_handler))

    # if hass.bus.async_listeners().get(EVENT_CORE_CONFIG_UPDATE, 0) < 1:
    hass.data[DOMAIN]["remove_update_listener"].append(
        hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE,
                              core_config_update_handler))

    if hass.bus.async_listeners().get(CONF_STRAVA_RELOAD_EVENT, 0) < 1:
        hass.data[DOMAIN]["remove_update_listener"].append(
            hass.bus.async_listen(CONF_STRAVA_RELOAD_EVENT,
                                  component_reload_handler))

    if hass.bus.async_listeners().get(CONF_STRAVA_CONFIG_UPDATE_EVENT, 0) < 1:
        hass.data[DOMAIN]["remove_update_listener"].append(
            hass.bus.async_listen(CONF_STRAVA_CONFIG_UPDATE_EVENT,
                                  strava_config_update_handler))

    hass.data[DOMAIN]["remove_update_listener"] = [
        entry.add_update_listener(strava_config_update_helper)
    ]

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Example #3
0
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
    """Set up Home Connect component."""
    hass.data[DOMAIN] = {}

    if DOMAIN not in config:
        return True

    config_flow.OAuth2FlowHandler.async_register_implementation(
        hass,
        config_entry_oauth2_flow.LocalOAuth2Implementation(
            hass,
            DOMAIN,
            config[DOMAIN][CONF_CLIENT_ID],
            config[DOMAIN][CONF_CLIENT_SECRET],
            OAUTH2_AUTHORIZE,
            OAUTH2_TOKEN,
        ),
    )

    async def _async_service_program(call, method):
        """Generic callback for services taking a program."""
        program = call.data[ATTR_PROGRAM]
        entity_id = call.data[ATTR_ENTITY_ID]
        option_key = call.data.get(ATTR_OPTION_KEY, None)
        option_value = call.data.get(ATTR_OPTION_VALUE, None)
        option_unit = call.data.get(ATTR_OPTION_UNIT, None)
        if option_key is not None and option_value is not None:
            _options = {"key": option_key, "value": option_value}
            if option_unit is not None:
                _options["unit"] = option_unit
            options = [_options]
        else:
            options = None
        appliance = _get_appliance_by_entity_id(hass, entity_id)
        if appliance is not None:
            await hass.async_add_executor_job(getattr(appliance, method),
                                              program, options)

    async def _async_service_command(call, command):
        """Generic callback for services executing a command."""
        entity_id = call.data[ATTR_ENTITY_ID]
        appliance = _get_appliance_by_entity_id(hass, entity_id)
        if appliance is not None:
            await hass.async_add_executor_job(appliance.execute_command,
                                              command)

    async def _async_service_key_value(call, method):
        """Generic callback for services taking a key and value."""
        key = call.data[ATTR_KEY]
        value = call.data[ATTR_VALUE]
        entity_id = call.data[ATTR_ENTITY_ID]
        appliance = _get_appliance_by_entity_id(hass, entity_id)
        if appliance is not None:
            await hass.async_add_executor_job(
                getattr(appliance, method),
                key,
                value,
            )

    async def async_service_option_active(call):
        """Service for setting an option for an active program."""
        await _async_service_key_value(call, "set_options_active_program")

    async def async_service_option_selected(call):
        """Service for setting an option for a selected program."""
        await _async_service_key_value(call, "set_options_selected_program")

    async def async_service_pause(call):
        """Service for pausing a program."""
        await _async_service_command(call, BSH_PAUSE)

    async def async_service_resume(call):
        """Service for resuming a paused program."""
        await _async_service_command(call, BSH_RESUME)

    async def async_service_select(call):
        """Service for selecting a program."""
        await _async_service_program(call, "select_program")

    async def async_service_setting(call):
        """Service for changing a setting."""
        await _async_service_key_value(call, "set_setting")

    async def async_service_start(call):
        """Service for starting a program."""
        await _async_service_program(call, "start_program")

    hass.services.async_register(
        DOMAIN,
        SERVICE_OPTION_ACTIVE,
        async_service_option_active,
        schema=SERVICE_SETTING_SCHEMA,
    )
    hass.services.async_register(
        DOMAIN,
        SERVICE_OPTION_SELECTED,
        async_service_option_selected,
        schema=SERVICE_SETTING_SCHEMA,
    )
    hass.services.async_register(DOMAIN,
                                 SERVICE_SETTING,
                                 async_service_setting,
                                 schema=SERVICE_SETTING_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 SERVICE_PAUSE,
                                 async_service_pause,
                                 schema=SERVICE_COMMAND_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 SERVICE_RESUME,
                                 async_service_resume,
                                 schema=SERVICE_COMMAND_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 SERVICE_SELECT,
                                 async_service_select,
                                 schema=SERVICE_PROGRAM_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 SERVICE_START,
                                 async_service_start,
                                 schema=SERVICE_PROGRAM_SCHEMA)

    return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up TDAmeritrade from a config entry."""
    _LOGGER.debug("Setting up entry")
    config_flow.OAuth2FlowHandler.async_register_implementation(
        hass,
        config_entry_oauth2_flow.LocalOAuth2Implementation(
            hass,
            entry.domain,
            entry.data["consumer_key"],
            None,
            OAUTH2_AUTHORIZE,
            OAUTH2_TOKEN,
        ),
    )

    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))

    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)

    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session)

    client = AmeritradeAPI(auth)

    async def place_order_service(call):
        """Handle a place trade service call."""

        price = call.data["price"]
        instruction = call.data["instruction"]
        quantity = call.data["quantity"]
        symbol = call.data["symbol"]
        account_id = call.data["account_id"]
        order_type = call.data["order_type"]
        session = call.data["session"]
        duration = call.data["duration"]
        order_strategy_type = call.data["orderStrategyType"]
        asset_type = call.data["assetType"]

        return await client.async_place_order(
            price,
            instruction,
            quantity,
            symbol,
            account_id,
            order_type=order_type,
            session=session,
            duration=duration,
            orderStrategyType=order_strategy_type,
            assetType=asset_type,
        )

    async def get_quote_service(call):
        """Handle a place trade service call."""
        symbol = call.data["symbol"]
        res = await client.async_get_quote(ticker=symbol)

        hass.states.async_set(
            f"get_quote_service.{symbol}",
            res[symbol]["lastPrice"],
            attributes=res[symbol],
        )

        return True

    _LOGGER.debug("Registering Services")
    hass.services.async_register(DOMAIN, "place_order", place_order_service)
    hass.services.async_register(DOMAIN, "get_quote", get_quote_service)

    hass.data.setdefault(DOMAIN, {})
    hass_data = dict(entry.data)
    entry.update_listeners = []
    hass_data["unsub"] = entry.add_update_listener(options_update_listener)
    hass_data["client"] = AmeritradeAPI(auth)
    hass.data[DOMAIN][entry.entry_id] = hass_data
    if entry.state in [
            ConfigEntryState.NOT_LOADED, ConfigEntryState.SETUP_IN_PROGRESS
    ]:
        for component in PLATFORMS:
            _LOGGER.debug("Setting up %s component", component)
            hass.async_create_task(
                hass.config_entries.async_forward_entry_setup(
                    entry, component))
    return True
Example #5
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Home Connect from a config entry."""

    hass.data[DOMAIN] = {}

    async def async_get_appliance(name: str):
        """Retrieve appliance from device name."""
        registry = await device_registry.async_get_registry(hass)

        haId = None
        for device in registry.devices.values():
            for identifier in device.identifiers:
                if identifier[0] == DOMAIN and device.name == name:
                    haId = identifier[1]
                    break
            else:
                continue
            break

        appliance = None
        if haId is not None:
            for hc in hass.data[DOMAIN].values():
                for dev_dict in hc.devices:
                    if dev_dict.appliance.haId == haId:
                        appliance = dev_dict.appliance
                        break
                else:
                    continue
                break

        return appliance

    async def async_service_program(call):
        """Service call for program selection."""
        device_name = call.data["device_name"]
        program_key = call.data["key"]
        appliance = await async_get_appliance(device_name)
        if appliance is not None:
            await hass.async_add_executor_job(
                getattr(appliance, "set_programs_selected"), program_key)

    async def async_service_option(call):
        """Service call for option selection."""
        device_name = call.data["device_name"]
        option_key = call.data["key"]
        value = call.data["value"]
        appliance = await async_get_appliance(device_name)
        if appliance is not None:
            await hass.async_add_executor_job(
                getattr(appliance, "set_programs_active_options_with_key"),
                option_key, value)

    async def async_service_setting(call):
        """Service call to set settings."""
        device_name = call.data["device_name"]
        setting_key = call.data["key"]
        value = call.data["value"]
        appliance = await async_get_appliance(device_name)
        if appliance is not None:
            await hass.async_add_executor_job(
                getattr(appliance, "set_setting_with_key"), setting_key, value)

    async def async_service_command(call):
        """Service call to execute command."""
        device_name = call.data["device_name"]
        command_key = call.data["key"]
        appliance = await async_get_appliance(device_name)
        if appliance is not None:
            await hass.async_add_executor_job(
                getattr(appliance, "set_command"), command_key)

    hass.services.async_register(DOMAIN,
                                 "program",
                                 async_service_program,
                                 schema=SERVICE_PROGRAM_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 "option",
                                 async_service_option,
                                 schema=SERVICE_OPTION_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 "setting",
                                 async_service_setting,
                                 schema=SERVICE_SETTING_SCHEMA)
    hass.services.async_register(DOMAIN,
                                 "command",
                                 async_service_command,
                                 schema=SERVICE_COMMAND_SCHEMA)

    client_id = entry.data.get(CONF_CLIENT_ID)
    client_secret = entry.data.get(CONF_CLIENT_SECRET)
    authorize_url = f"{BASE_URL}{ENDPOINT_AUTHORIZE}"
    token_url = f"{BASE_URL}{ENDPOINT_TOKEN}"
    OAuth2FlowHandler.async_register_implementation(
        hass,
        config_entry_oauth2_flow.LocalOAuth2Implementation(
            hass, DOMAIN, client_id, client_secret, authorize_url, token_url))

    implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
        hass, entry)

    # session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    # hass.data[DOMAIN][entry.entry_id] = ConfigEntryAuth(hass, entry, session)

    hass.data[DOMAIN][entry.entry_id] = ConfigEntryAuth(
        hass, entry, implementation)

    # Get the Home Connect interface
    home_connect = hass.data[DOMAIN][entry.entry_id]

    # Get a list of all Home Connect appliances like washer, dryer, oven.
    appliances = await hass.async_add_executor_job(home_connect.get_appliances)

    # Get a list of Home Connect devices and it's entities
    devices = []
    for appliance in appliances:
        if appliance.type == "Washer":
            device = Washer(hass, appliance)
            _LOGGER.info("Washer detected")
        elif appliance.type == "Dryer":
            device = Dryer(hass, appliance)
            _LOGGER.info("Dryer detected")
        elif appliance.type == "WasherDryer":
            device = WasherDryer(hass, appliance)
            _LOGGER.info("Washer Dryer detected")
        elif appliance.type == "Refrigerator":
            device = Refrigerator(hass, appliance)
            _LOGGER.info("Refrigerator detected")
        elif appliance.type == "WineCooler":
            device = WineCooler(hass, appliance)
            _LOGGER.info("Wine Cooler detected")
        elif appliance.type == "Freezer":
            device = Freezer(hass, appliance)
            _LOGGER.info("Freezer detected")
        elif appliance.type == "Dishwasher":
            device = Dishwasher(hass, appliance)
            _LOGGER.info("Dishwasher detected")
        elif appliance.type == "FridgeFreezer":
            device = FridgeFreezer(hass, appliance)
            _LOGGER.info("Fridge Freezer detected")
        elif appliance.type == "Oven":
            device = Oven(hass, appliance)
            _LOGGER.info("Oven detected")
        elif appliance.type == "CoffeeMaker":
            device = CoffeeMaker(hass, appliance)
            _LOGGER.info("Coffee Maker detected")
        elif appliance.type == "Hood":
            device = Hood(hass, appliance)
            _LOGGER.info("Hood detected")
        elif appliance.type == "Hob":
            device = Hob(hass, appliance)
            _LOGGER.info("Hob detected")
        else:
            _LOGGER.warning("Appliance type %s not implemented",
                            appliance.type)
            continue

        # Initialize Home Connect device
        await hass.async_add_executor_job(device.initialize)

        # Put the device into the list of devices
        devices.append(device)

    # Save all found devices in home connect object
    home_connect.devices = devices

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True