Esempio n. 1
0
async def async_setup_entry(opp: OpenPeerPower, config_entry: ConfigEntry):
    """Set up AEMET OpenData as config entry."""
    name = config_entry.data[CONF_NAME]
    api_key = config_entry.data[CONF_API_KEY]
    latitude = config_entry.data[CONF_LATITUDE]
    longitude = config_entry.data[CONF_LONGITUDE]
    station_updates = config_entry.options.get(CONF_STATION_UPDATES, True)

    aemet = AEMET(api_key)
    weather_coordinator = WeatherUpdateCoordinator(opp, aemet, latitude,
                                                   longitude, station_updates)

    await weather_coordinator.async_config_entry_first_refresh()

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][config_entry.entry_id] = {
        ENTRY_NAME: name,
        ENTRY_WEATHER_COORDINATOR: weather_coordinator,
    }

    opp.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    config_entry.async_on_unload(
        config_entry.add_update_listener(async_update_options))

    return True
Esempio n. 2
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Plum Lightpad from a config entry."""
    _LOGGER.debug("Setting up config entry with ID = %s", entry.unique_id)

    username = entry.data.get(CONF_USERNAME)
    password = entry.data.get(CONF_PASSWORD)

    try:
        plum = await load_plum(username, password, opp)
    except ContentTypeError as ex:
        _LOGGER.error("Unable to authenticate to Plum cloud: %s", ex)
        return False
    except (ConnectTimeout, HTTPError) as ex:
        _LOGGER.error("Unable to connect to Plum cloud: %s", ex)
        raise ConfigEntryNotReady from ex

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = plum

    for platform in PLATFORMS:
        opp.async_create_task(
            opp.config_entries.async_forward_entry_setup(entry, platform))

    def cleanup(event):
        """Clean up resources."""
        plum.cleanup()

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, cleanup))
    return True
Esempio n. 3
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up ONVIF from a config entry."""
    if DOMAIN not in opp.data:
        opp.data[DOMAIN] = {}

    if not entry.options:
        await async_populate_options(opp, entry)

    device = ONVIFDevice(opp, entry)

    if not await device.async_setup():
        await device.device.close()
        return False

    if not device.available:
        raise ConfigEntryNotReady()

    if not entry.data.get(CONF_SNAPSHOT_AUTH):
        await async_populate_snapshot_auth(opp, device, entry)

    opp.data[DOMAIN][entry.unique_id] = device

    platforms = ["camera"]

    if device.capabilities.events:
        platforms += ["binary_sensor", "sensor"]

    opp.config_entries.async_setup_platforms(entry, platforms)

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, device.async_stop)
    )

    return True
Esempio n. 4
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Freebox entry."""
    router = FreeboxRouter(opp, entry)
    await router.setup()

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.unique_id] = router

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    # Services
    async def async_reboot(call):
        """Handle reboot service call."""
        await router.reboot()

    opp.services.async_register(DOMAIN, SERVICE_REBOOT, async_reboot)

    async def async_close_connection(event):
        """Close Freebox connection on OPP Stop."""
        await router.close()

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP,
                                  async_close_connection))

    return True
Esempio n. 5
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up a wemo config entry."""
    config = opp.data[DOMAIN].pop("config")

    # Keep track of WeMo device subscriptions for push updates
    registry = opp.data[DOMAIN]["registry"] = pywemo.SubscriptionRegistry()
    await opp.async_add_executor_job(registry.start)
    static_conf = config.get(CONF_STATIC, [])
    wemo_dispatcher = WemoDispatcher(entry)
    wemo_discovery = WemoDiscovery(opp, wemo_dispatcher, static_conf)

    async def async_stop_wemo(event):
        """Shutdown Wemo subscriptions and subscription thread on exit."""
        _LOGGER.debug("Shutting down WeMo event subscriptions")
        await opp.async_add_executor_job(registry.stop)
        wemo_discovery.async_stop_discovery()

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, async_stop_wemo))

    # Need to do this at least once in case statics are defined and discovery is disabled
    await wemo_discovery.discover_statics()

    if config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY):
        await wemo_discovery.async_discover_and_schedule()

    return True
Esempio n. 6
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up HomeKit from a config entry."""
    _async_import_options_from_data_if_missing(opp, entry)

    conf = entry.data
    options = entry.options

    name = conf[CONF_NAME]
    port = conf[CONF_PORT]
    _LOGGER.debug("Begin setup HomeKit for %s", name)

    # ip_address and advertise_ip are yaml only
    ip_address = conf.get(CONF_IP_ADDRESS)
    advertise_ip = conf.get(CONF_ADVERTISE_IP)
    # exclude_accessory_mode is only used for config flow
    # to indicate that the config entry was setup after
    # we started creating config entries for entities that
    # to run in accessory mode and that we should never include
    # these entities on the bridge. For backwards compatibility
    # with users who have not migrated yet we do not do exclude
    # these entities by default as we cannot migrate automatically
    # since it requires a re-pairing.
    exclude_accessory_mode = conf.get(CONF_EXCLUDE_ACCESSORY_MODE,
                                      DEFAULT_EXCLUDE_ACCESSORY_MODE)
    homekit_mode = options.get(CONF_HOMEKIT_MODE, DEFAULT_HOMEKIT_MODE)
    entity_config = options.get(CONF_ENTITY_CONFIG, {}).copy()
    auto_start = options.get(CONF_AUTO_START, DEFAULT_AUTO_START)
    entity_filter = FILTER_SCHEMA(options.get(CONF_FILTER, {}))

    homekit = HomeKit(
        opp,
        name,
        port,
        ip_address,
        entity_filter,
        exclude_accessory_mode,
        entity_config,
        homekit_mode,
        advertise_ip,
        entry.entry_id,
        entry.title,
    )

    entry.async_on_unload(entry.add_update_listener(_async_update_listener))
    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP,
                                  homekit.async_stop))

    opp.data[DOMAIN][entry.entry_id] = {HOMEKIT: homekit}

    if opp.state == CoreState.running:
        await homekit.async_start()
    elif auto_start:
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STARTED,
                                  homekit.async_start)

    return True
Esempio n. 7
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up AccuWeather as config entry."""
    api_key: str = entry.data[CONF_API_KEY]
    assert entry.unique_id is not None
    location_key = entry.unique_id
    forecast: bool = entry.options.get(CONF_FORECAST, False)

    _LOGGER.debug("Using location_key: %s, get forecast: %s", location_key,
                  forecast)

    websession = async_get_clientsession(opp)

    coordinator = AccuWeatherDataUpdateCoordinator(opp, websession, api_key,
                                                   location_key, forecast)
    await coordinator.async_config_entry_first_refresh()

    undo_listener = entry.add_update_listener(update_listener)

    opp.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        COORDINATOR: coordinator,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 8
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Monoprice 6-Zone Amplifier from a config entry."""
    port = entry.data[CONF_PORT]

    try:
        monoprice = await opp.async_add_executor_job(get_monoprice, port)
    except SerialException as err:
        _LOGGER.error("Error connecting to Monoprice controller at %s", port)
        raise ConfigEntryNotReady from err

    # double negative to handle absence of value
    first_run = not bool(entry.data.get(CONF_NOT_FIRST_RUN))

    if first_run:
        opp.config_entries.async_update_entry(
            entry, data={**entry.data, CONF_NOT_FIRST_RUN: True}
        )

    undo_listener = entry.add_update_listener(_update_listener)

    opp.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        MONOPRICE_OBJECT: monoprice,
        UNDO_UPDATE_LISTENER: undo_listener,
        FIRST_RUN: first_run,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 9
0
async def async_setup_entry(opp: core.OpenPeerPower,
                            entry: config_entries.ConfigEntry):
    """Set up the denonavr components from a config entry."""
    opp.data.setdefault(DOMAIN, {})

    # Connect to receiver
    connect_denonavr = ConnectDenonAVR(
        entry.data[CONF_HOST],
        DEFAULT_TIMEOUT,
        entry.options.get(CONF_SHOW_ALL_SOURCES, DEFAULT_SHOW_SOURCES),
        entry.options.get(CONF_ZONE2, DEFAULT_ZONE2),
        entry.options.get(CONF_ZONE3, DEFAULT_ZONE3),
        lambda: get_async_client(opp),
    )
    try:
        await connect_denonavr.async_connect_receiver()
    except (AvrNetworkError, AvrTimoutError) as ex:
        raise ConfigEntryNotReady from ex
    receiver = connect_denonavr.receiver

    undo_listener = entry.add_update_listener(update_listener)

    opp.data[DOMAIN][entry.entry_id] = {
        CONF_RECEIVER: receiver,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 10
0
async def async_setup_entry(opp: OpenPeerPower, config_entry: ConfigEntry):
    """Set up OpenWeatherMap as config entry."""
    name = config_entry.data[CONF_NAME]
    api_key = config_entry.data[CONF_API_KEY]
    latitude = config_entry.data.get(CONF_LATITUDE, opp.config.latitude)
    longitude = config_entry.data.get(CONF_LONGITUDE, opp.config.longitude)
    forecast_mode = _get_config_value(config_entry, CONF_MODE)
    language = _get_config_value(config_entry, CONF_LANGUAGE)

    config_dict = _get_owm_config(language)

    owm = OWM(api_key, config_dict).weather_manager()
    weather_coordinator = WeatherUpdateCoordinator(owm, latitude, longitude,
                                                   forecast_mode, opp)

    await weather_coordinator.async_config_entry_first_refresh()

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][config_entry.entry_id] = {
        ENTRY_NAME: name,
        ENTRY_WEATHER_COORDINATOR: weather_coordinator,
    }

    opp.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    update_listener = config_entry.add_update_listener(async_update_options)
    opp.data[DOMAIN][config_entry.entry_id][UPDATE_LISTENER] = update_listener

    return True
Esempio n. 11
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up NZBGet from a config entry."""
    if not entry.options:
        options = {
            CONF_SCAN_INTERVAL: entry.data.get(
                CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
            ),
        }
        opp.config_entries.async_update_entry(entry, options=options)

    coordinator = NZBGetDataUpdateCoordinator(
        opp,
        config=entry.data,
        options=entry.options,
    )

    await coordinator.async_config_entry_first_refresh()

    undo_listener = entry.add_update_listener(_async_update_listener)

    opp.data[DOMAIN][entry.entry_id] = {
        DATA_COORDINATOR: coordinator,
        DATA_UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    _async_register_services(opp, coordinator)

    return True
Esempio n. 12
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up a bridge from a config entry."""
    LOGGER.debug("Setting up entry %s", entry.data)
    bridge = DynaliteBridge(opp, entry.data)
    # need to do it before the listener
    opp.data[DOMAIN][entry.entry_id] = bridge
    entry.async_on_unload(entry.add_update_listener(async_entry_changed))

    if not await bridge.async_setup():
        LOGGER.error("Could not set up bridge for entry %s", entry.data)
        opp.data[DOMAIN][entry.entry_id] = None
        raise ConfigEntryNotReady

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 13
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up Canary from a config entry."""
    if not entry.options:
        options = {
            CONF_FFMPEG_ARGUMENTS:
            entry.data.get(CONF_FFMPEG_ARGUMENTS, DEFAULT_FFMPEG_ARGUMENTS),
            CONF_TIMEOUT:
            entry.data.get(CONF_TIMEOUT, DEFAULT_TIMEOUT),
        }
        opp.config_entries.async_update_entry(entry, options=options)

    try:
        canary_api = await opp.async_add_executor_job(_get_canary_api_instance,
                                                      entry)
    except (ConnectTimeout, HTTPError) as error:
        _LOGGER.error("Unable to connect to Canary service: %s", str(error))
        raise ConfigEntryNotReady from error

    coordinator = CanaryDataUpdateCoordinator(opp, api=canary_api)
    await coordinator.async_config_entry_first_refresh()

    undo_listener = entry.add_update_listener(_async_update_listener)

    opp.data[DOMAIN][entry.entry_id] = {
        DATA_COORDINATOR: coordinator,
        DATA_UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 14
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry,
                            async_add_entities) -> None:
    """Set up device tracker for FRITZ!Box component."""
    _LOGGER.debug("Starting FRITZ!Box device tracker")
    router = opp.data[DOMAIN][entry.entry_id]
    data_fritz = opp.data[DATA_FRITZ]

    @callback
    def update_router():
        """Update the values of the router."""
        _async_add_entities(router, async_add_entities, data_fritz)

    entry.async_on_unload(
        async_dispatcher_connect(opp, router.signal_device_new, update_router))

    update_router()
Esempio n. 15
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up AsusWrt platform."""

    # import options from yaml if empty
    yaml_options = opp.data.get(DOMAIN, {}).pop("yaml_options", {})
    if not entry.options and yaml_options:
        opp.config_entries.async_update_entry(entry, options=yaml_options)

    router = AsusWrtRouter(opp, entry)
    await router.setup()

    router.async_on_close(entry.add_update_listener(update_listener))

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    async def async_close_connection(event):
        """Close AsusWrt connection on OPP Stop."""
        await router.close()

    stop_listener = opp.bus.async_listen_once(
        EVENT_OPENPEERPOWER_STOP, async_close_connection
    )

    opp.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        DATA_ASUSWRT: router,
        "stop_listener": stop_listener,
    }

    return True
Esempio n. 16
0
async def async_setup_entry(
    opp: OpenPeerPower, config_entry: config_entries.ConfigEntry
) -> bool:
    """Set up a Firmata board for a config entry."""
    if DOMAIN not in opp.data:
        opp.data[DOMAIN] = {}

    _LOGGER.debug(
        "Setting up Firmata id %s, name %s, config %s",
        config_entry.entry_id,
        config_entry.data[CONF_NAME],
        config_entry.data,
    )

    board = FirmataBoard(config_entry.data)

    if not await board.async_setup():
        return False

    opp.data[DOMAIN][config_entry.entry_id] = board

    async def handle_shutdown(event) -> None:
        """Handle shutdown of board when Open Peer Power shuts down."""
        # Ensure board was not already removed previously before shutdown
        if config_entry.entry_id in opp.data[DOMAIN]:
            await board.async_reset()

    config_entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, handle_shutdown)
    )

    device_registry = await dr.async_get_registry(opp)
    device_registry.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={},
        identifiers={(DOMAIN, board.name)},
        manufacturer=FIRMATA_MANUFACTURER,
        name=board.name,
        sw_version=board.firmware_version,
    )

    for (conf, platform) in CONF_PLATFORM_MAP.items():
        if conf in config_entry.data:
            opp.async_create_task(
                opp.config_entries.async_forward_entry_setup(config_entry, platform)
            )
    return True
Esempio n. 17
0
async def _async_initialize(
    opp: OpenPeerPower,
    entry: ConfigEntry,
    host: str,
    device: YeelightDevice | None = None,
) -> None:
    entry_data = opp.data[DOMAIN][DATA_CONFIG_ENTRIES][entry.entry_id] = {
        DATA_PLATFORMS_LOADED: False
    }
    entry.async_on_unload(entry.add_update_listener(_async_update_listener))

    @callback
    def _async_load_platforms():
        if entry_data[DATA_PLATFORMS_LOADED]:
            return
        entry_data[DATA_PLATFORMS_LOADED] = True
        opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    if not device:
        device = await _async_get_device(opp, host, entry)
    entry_data[DATA_DEVICE] = device

    entry.async_on_unload(
        async_dispatcher_connect(
            opp,
            DEVICE_INITIALIZED.format(host),
            _async_load_platforms,
        ))

    entry.async_on_unload(device.async_unload)
    await device.async_setup()
Esempio n. 18
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up DoorBird from a config entry."""

    _async_import_options_from_data_if_missing(opp, entry)

    doorstation_config = entry.data
    doorstation_options = entry.options
    config_entry_id = entry.entry_id

    device_ip = doorstation_config[CONF_HOST]
    username = doorstation_config[CONF_USERNAME]
    password = doorstation_config[CONF_PASSWORD]

    device = DoorBird(device_ip, username, password)
    try:
        status, info = await opp.async_add_executor_job(
            _init_doorbird_device, device)
    except requests.exceptions.HTTPError as err:
        if err.response.status_code == HTTP_UNAUTHORIZED:
            _LOGGER.error("Authorization rejected by DoorBird for %s@%s",
                          username, device_ip)
            return False
        raise ConfigEntryNotReady from err
    except OSError as oserr:
        _LOGGER.error("Failed to setup doorbird at %s: %s", device_ip, oserr)
        raise ConfigEntryNotReady from oserr

    if not status[0]:
        _LOGGER.error(
            "Could not connect to DoorBird as %s@%s: Error %s",
            username,
            device_ip,
            str(status[1]),
        )
        raise ConfigEntryNotReady

    token = doorstation_config.get(CONF_TOKEN, config_entry_id)
    custom_url = doorstation_config.get(CONF_CUSTOM_URL)
    name = doorstation_config.get(CONF_NAME)
    events = doorstation_options.get(CONF_EVENTS, [])
    doorstation = ConfiguredDoorBird(device, name, custom_url, token)
    doorstation.update_events(events)
    # Subscribe to doorbell or motion events
    if not await _async_register_events(opp, doorstation):
        raise ConfigEntryNotReady

    undo_listener = entry.add_update_listener(_update_listener)

    opp.data[DOMAIN][config_entry_id] = {
        DOOR_STATION: doorstation,
        DOOR_STATION_INFO: info,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 19
0
async def async_migrate_entry(opp: OpenPeerPower, config_entry: ConfigEntry) -> bool:
    """Migrate config entry to new version."""
    if config_entry.version == 1:
        options = dict(config_entry.options)
        recipient = options.get(CONF_RECIPIENT)
        if isinstance(recipient, str):
            options[CONF_RECIPIENT] = [x.strip() for x in recipient.split(",")]
        config_entry.version = 2
        opp.config_entries.async_update_entry(config_entry, options=options)
        _LOGGER.info("Migrated config entry to version %d", config_entry.version)
    return True
Esempio n. 20
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up DSMR from a config entry."""
    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = {}

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    listener = entry.add_update_listener(async_update_options)
    opp.data[DOMAIN][entry.entry_id][DATA_LISTENER] = listener

    return True
Esempio n. 21
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up Verisure from a config entry."""
    coordinator = VerisureDataUpdateCoordinator(opp, entry=entry)

    if not await coordinator.async_login():
        raise ConfigEntryAuthFailed

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP,
                                  coordinator.async_logout))

    await coordinator.async_config_entry_first_refresh()

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = coordinator

    # Set up all platforms for this device/entry.
    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 22
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up fritzboxtools from config entry."""
    _LOGGER.debug("Setting up FRITZ!Box Tools component")
    fritz_tools = FritzBoxTools(
        opp=opp,
        host=entry.data[CONF_HOST],
        port=entry.data[CONF_PORT],
        username=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await fritz_tools.async_setup()
        await fritz_tools.async_start(entry.options)
    except FritzSecurityError as ex:
        raise ConfigEntryAuthFailed from ex
    except FritzConnectionException as ex:
        raise ConfigEntryNotReady from ex

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = fritz_tools

    if DATA_FRITZ not in opp.data:
        opp.data[DATA_FRITZ] = FritzData()

    @callback
    def _async_unload(event):
        fritz_tools.async_unload()

    entry.async_on_unload(
        opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, _async_unload)
    )
    entry.async_on_unload(entry.add_update_listener(update_listener))

    # Load the other platforms like switch
    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    await async_setup_services(opp)

    return True
Esempio n. 23
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up BMW Connected Drive from a config entry."""
    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN].setdefault(DATA_ENTRIES, {})

    _async_migrate_options_from_data_if_missing(opp, entry)

    try:
        account = await opp.async_add_executor_job(setup_account, entry, opp,
                                                   entry.data[CONF_USERNAME])
    except OSError as ex:
        raise ConfigEntryNotReady from ex

    async def _async_update_all(service_call=None):
        """Update all BMW accounts."""
        await opp.async_add_executor_job(_update_all)

    def _update_all() -> None:
        """Update all BMW accounts."""
        for entry in opp.data[DOMAIN][DATA_ENTRIES].copy().values():
            entry[CONF_ACCOUNT].update()

    # Add update listener for config entry changes (options)
    undo_listener = entry.add_update_listener(update_listener)

    opp.data[DOMAIN][DATA_ENTRIES][entry.entry_id] = {
        CONF_ACCOUNT: account,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    # Service to manually trigger updates for all accounts.
    opp.services.async_register(DOMAIN, SERVICE_UPDATE_STATE,
                                _async_update_all)

    await _async_update_all()

    opp.config_entries.async_setup_platforms(
        entry,
        [platform for platform in PLATFORMS if platform != NOTIFY_DOMAIN])

    # set up notify platform, no entry support for notify platform yet,
    # have to use discovery to load platform.
    opp.async_create_task(
        discovery.async_load_platform(
            opp,
            NOTIFY_DOMAIN,
            DOMAIN,
            {CONF_NAME: DOMAIN},
            opp.data[DOMAIN][DATA_OPP_CONFIG],
        ))

    return True
Esempio n. 24
0
async def async_migrate_entry(opp, config_entry: ConfigEntry):
    """Migrate old entry."""
    LOGGER.debug("Migrating from version %s", config_entry.version)

    if config_entry.version == 1:
        # Change unique id
        @callback
        def update_unique_id(entry):
            return {"new_unique_id": config_entry.entry_id}

        await async_migrate_entries(opp, config_entry.entry_id,
                                    update_unique_id)

        config_entry.unique_id = None

        # Get RTSP port from the camera or use the fallback one and store it in data
        camera = FoscamCamera(
            config_entry.data[CONF_HOST],
            config_entry.data[CONF_PORT],
            config_entry.data[CONF_USERNAME],
            config_entry.data[CONF_PASSWORD],
            verbose=False,
        )

        ret, response = await opp.async_add_executor_job(camera.get_port_info)

        rtsp_port = DEFAULT_RTSP_PORT

        if ret != 0:
            rtsp_port = response.get("rtspPort") or response.get("mediaPort")

        config_entry.data = {**config_entry.data, CONF_RTSP_PORT: rtsp_port}

        # Change entry version
        config_entry.version = 2

    LOGGER.info("Migration to version %s successful", config_entry.version)

    return True
Esempio n. 25
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Tado from a config entry."""

    _async_import_options_from_data_if_missing(opp, entry)

    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]
    fallback = entry.options.get(CONF_FALLBACK, True)

    tadoconnector = TadoConnector(opp, username, password, fallback)

    try:
        await opp.async_add_executor_job(tadoconnector.setup)
    except KeyError:
        _LOGGER.error("Failed to login to tado")
        return False
    except RuntimeError as exc:
        _LOGGER.error("Failed to setup tado: %s", exc)
        return ConfigEntryNotReady
    except requests.exceptions.Timeout as ex:
        raise ConfigEntryNotReady from ex
    except requests.exceptions.HTTPError as ex:
        if ex.response.status_code > 400 and ex.response.status_code < 500:
            _LOGGER.error("Failed to login to tado: %s", ex)
            return False
        raise ConfigEntryNotReady from ex

    # Do first update
    await opp.async_add_executor_job(tadoconnector.update)

    # Poll for updates in the background
    update_track = async_track_time_interval(
        opp,
        lambda now: tadoconnector.update(),
        SCAN_INTERVAL,
    )

    update_listener = entry.add_update_listener(_async_update_listener)

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = {
        DATA: tadoconnector,
        UPDATE_TRACK: update_track,
        UPDATE_LISTENER: update_listener,
    }

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 26
0
async def async_setup_entry(opp: OpenPeerPower, config_entry: ConfigEntry):
    """Set up wiffi from a config entry, config_entry contains data from config entry database."""
    if not config_entry.update_listeners:
        config_entry.add_update_listener(async_update_options)

    # create api object
    api = WiffiIntegrationApi(opp)
    api.async_setup(config_entry)

    # store api object
    opp.data.setdefault(DOMAIN, {})[config_entry.entry_id] = api

    try:
        await api.server.start_server()
    except OSError as exc:
        if exc.errno != errno.EADDRINUSE:
            _LOGGER.error("Start_server failed, errno: %d", exc.errno)
            return False
        _LOGGER.error("Port %s already in use", config_entry.data[CONF_PORT])
        raise ConfigEntryNotReady from exc

    opp.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    return True
Esempio n. 27
0
async def setup_platform(opp, platform: str, *, devices=None, scenes=None):
    """Set up the SmartThings platform and prerequisites."""
    opp.config.components.add(DOMAIN)
    config_entry = ConfigEntry(
        2,
        DOMAIN,
        "Test",
        {CONF_INSTALLED_APP_ID: str(uuid4())},
        SOURCE_USER,
    )
    broker = DeviceBroker(opp, config_entry, Mock(), Mock(), devices or [],
                          scenes or [])

    opp.data[DOMAIN] = {DATA_BROKERS: {config_entry.entry_id: broker}}
    await opp.config_entries.async_forward_entry_setup(config_entry, platform)
    await opp.async_block_till_done()
    return config_entry
Esempio n. 28
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up panel from a config entry."""
    client = AlarmPanel(opp, entry)
    # creates a panel data store in opp.data[DOMAIN][CONF_DEVICES]
    await client.async_save_data()

    # if the cfg entry was created we know we could connect to the panel at some point
    # async_connect will handle retries until it establishes a connection
    await client.async_connect()

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    # config entry specific data to enable unload
    opp.data[DOMAIN][entry.entry_id] = {
        UNDO_UPDATE_LISTENER: entry.add_update_listener(async_entry_updated)
    }
    return True
Esempio n. 29
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
    """Set up Dexcom from a config entry."""
    try:
        dexcom = await opp.async_add_executor_job(
            Dexcom,
            entry.data[CONF_USERNAME],
            entry.data[CONF_PASSWORD],
            entry.data[CONF_SERVER] == SERVER_OUS,
        )
    except AccountError:
        return False
    except SessionError as error:
        raise ConfigEntryNotReady from error

    if not entry.options:
        opp.config_entries.async_update_entry(
            entry, options={CONF_UNIT_OF_MEASUREMENT: MG_DL})

    async def async_update_data():
        try:
            return await opp.async_add_executor_job(
                dexcom.get_current_glucose_reading)
        except SessionError as error:
            raise UpdateFailed(error) from error

    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = {
        COORDINATOR:
        DataUpdateCoordinator(
            opp,
            _LOGGER,
            name=DOMAIN,
            update_method=async_update_data,
            update_interval=SCAN_INTERVAL,
        ),
        UNDO_UPDATE_LISTENER:
        entry.add_update_listener(update_listener),
    }

    await opp.data[DOMAIN][entry.entry_id
                           ][COORDINATOR].async_config_entry_first_refresh()

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 30
0
async def async_setup_entry(opp: OpenPeerPower,
                            config_entry: ConfigEntry) -> bool:
    """Set up the component."""
    opp.data.setdefault(DOMAIN, {})
    async_add_defaults(opp, config_entry)

    router = KeeneticRouter(opp, config_entry)
    await router.async_setup()

    undo_listener = config_entry.add_update_listener(update_listener)

    opp.data[DOMAIN][config_entry.entry_id] = {
        ROUTER: router,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    opp.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    return True