Exemple #1
0
async def async_setup(opp, config):
    """Try to start embedded Lightwave broker."""
    host = config[DOMAIN][CONF_HOST]
    lwlink = LWLink(host)
    opp.data[LIGHTWAVE_LINK] = lwlink

    lights = config[DOMAIN][CONF_LIGHTS]
    if lights:
        opp.async_create_task(
            async_load_platform(opp, "light", DOMAIN, lights, config))

    switches = config[DOMAIN][CONF_SWITCHES]
    if switches:
        opp.async_create_task(
            async_load_platform(opp, "switch", DOMAIN, switches, config))

    trv = config[DOMAIN][CONF_TRV]
    if trv:
        trvs = trv[CONF_TRVS]
        proxy_ip = trv[CONF_PROXY_IP]
        proxy_port = trv[CONF_PROXY_PORT]
        lwlink.set_trv_proxy(proxy_ip, proxy_port)

        platforms = [CLIMATE_DOMAIN, SENSOR_DOMAIN]
        for platform in platforms:
            opp.async_create_task(
                async_load_platform(opp, platform, DOMAIN, trvs, config))

    return True
Exemple #2
0
async def async_setup(opp, config):
    """Set up an Utility Meter."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    opp.data[DATA_UTILITY] = {}
    register_services = False

    for meter, conf in config.get(DOMAIN).items():
        _LOGGER.debug("Setup %s.%s", DOMAIN, meter)

        opp.data[DATA_UTILITY][meter] = conf

        if not conf[CONF_TARIFFS]:
            # only one entity is required
            opp.async_create_task(
                discovery.async_load_platform(
                    opp,
                    SENSOR_DOMAIN,
                    DOMAIN,
                    [{
                        CONF_METER: meter,
                        CONF_NAME: meter
                    }],
                    config,
                ))
        else:
            # create tariff selection
            await component.async_add_entities(
                [TariffSelect(meter, list(conf[CONF_TARIFFS]))])
            opp.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] = "{}.{}".format(
                DOMAIN, meter)

            # add one meter for each tariff
            tariff_confs = []
            for tariff in conf[CONF_TARIFFS]:
                tariff_confs.append({
                    CONF_METER: meter,
                    CONF_NAME: f"{meter} {tariff}",
                    CONF_TARIFF: tariff,
                })
            opp.async_create_task(
                discovery.async_load_platform(opp, SENSOR_DOMAIN, DOMAIN,
                                              tariff_confs, config))
            register_services = True

    if register_services:
        component.async_register_entity_service(SERVICE_RESET, {},
                                                "async_reset_meters")

        component.async_register_entity_service(
            SERVICE_SELECT_TARIFF,
            {vol.Required(ATTR_TARIFF): cv.string},
            "async_select_tariff",
        )

        component.async_register_entity_service(SERVICE_SELECT_NEXT_TARIFF, {},
                                                "async_next_tariff")

    return True
Exemple #3
0
    async def add_table(host, name=None):
        """Add platforms for a single table with the given hostname."""
        tables[host] = TableHolder(opp, session, host, name)

        opp.async_create_task(
            async_load_platform(opp, "light", DOMAIN, {CONF_HOST: host},
                                config))
        opp.async_create_task(
            async_load_platform(opp, "media_player", DOMAIN, {CONF_HOST: host},
                                config))
async def async_setup(opp: OpenPeerPowerType, config: ConfigType):
    """Set up the mobile app component."""
    store = opp.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_SENSOR: {},
        }

    opp.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,
    }

    opp.http.register_view(RegistrationsView())

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

    opp.async_create_task(
        discovery.async_load_platform(opp, "notify", DOMAIN, {}, config)
    )

    return True
Exemple #5
0
async def async_setup(opp, config):
    """Set the tankerkoenig component up."""
    if DOMAIN not in config:
        return True

    conf = config[DOMAIN]

    _LOGGER.debug("Setting up integration")

    tankerkoenig = TankerkoenigData(opp, conf)

    latitude = conf.get(CONF_LATITUDE, opp.config.latitude)
    longitude = conf.get(CONF_LONGITUDE, opp.config.longitude)
    radius = conf[CONF_RADIUS]
    additional_stations = conf[CONF_STATIONS]

    setup_ok = await opp.async_add_executor_job(tankerkoenig.setup, latitude,
                                                longitude, radius,
                                                additional_stations)
    if not setup_ok:
        _LOGGER.error("Could not setup integration")
        return False

    opp.data[DOMAIN] = tankerkoenig

    opp.async_create_task(
        async_load_platform(
            opp,
            SENSOR_DOMAIN,
            DOMAIN,
            discovered=tankerkoenig.stations,
            opp_config=conf,
        ))

    return True
Exemple #6
0
async def async_setup(opp, opp_config):
    """Create an Intergas InComfort/Intouch system."""
    incomfort_data = opp.data[DOMAIN] = {}

    credentials = dict(opp_config[DOMAIN])
    hostname = credentials.pop(CONF_HOST)

    client = incomfort_data["client"] = InComfortGateway(
        hostname, **credentials, session=async_get_clientsession(opp)
    )

    try:
        heaters = incomfort_data["heaters"] = list(await client.heaters)
    except ClientResponseError as err:
        _LOGGER.warning("Setup failed, check your configuration, message is: %s", err)
        return False

    for heater in heaters:
        await heater.update()

    for platform in ["water_heater", "binary_sensor", "sensor", "climate"]:
        opp.async_create_task(
            async_load_platform(opp, platform, DOMAIN, {}, opp_config)
        )

    return True
Exemple #7
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Create a Genius Hub system."""
    opp.data[DOMAIN] = {}

    kwargs = dict(config[DOMAIN])
    if CONF_HOST in kwargs:
        args = (kwargs.pop(CONF_HOST),)
    else:
        args = (kwargs.pop(CONF_TOKEN),)
    hub_uid = kwargs.pop(CONF_MAC, None)

    client = GeniusHub(*args, **kwargs, session=async_get_clientsession(opp))

    broker = opp.data[DOMAIN]["broker"] = GeniusBroker(opp, client, hub_uid)

    try:
        await client.update()
    except aiohttp.ClientResponseError as err:
        _LOGGER.error("Setup failed, check your configuration, %s", err)
        return False
    broker.make_debug_log_entries()

    async_track_time_interval(opp, broker.async_update, SCAN_INTERVAL)

    for platform in ["climate", "water_heater", "sensor", "binary_sensor", "switch"]:
        opp.async_create_task(async_load_platform(opp, platform, DOMAIN, {}, config))

    setup_service_functions(opp, broker)

    return True
Exemple #8
0
async def async_setup(opp, config):
    """Set up the Kaiterra integration."""

    conf = config[DOMAIN]
    scan_interval = conf[CONF_SCAN_INTERVAL]
    devices = conf[CONF_DEVICES]
    session = async_get_clientsession(opp)
    api = opp.data[DOMAIN] = KaiterraApiData(opp, conf, session)

    await api.async_update()

    async def _update(now=None):
        """Periodic update."""
        await api.async_update()

    async_track_time_interval(opp, _update, scan_interval)

    # Load platforms for each device
    for device in devices:
        device_name, device_id = (
            device.get(CONF_NAME) or device[CONF_TYPE],
            device[CONF_DEVICE_ID],
        )
        for platform in PLATFORMS:
            opp.async_create_task(
                async_load_platform(
                    opp,
                    platform,
                    DOMAIN,
                    {CONF_NAME: device_name, CONF_DEVICE_ID: device_id},
                    config,
                )
            )

    return True
Exemple #9
0
async def async_setup(opp: OpenPeerPower, config: ConfigType):
    """Set up the mobile app component."""
    store = opp.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
    app_config = await store.async_load()
    if app_config is None:
        app_config = {
            DATA_CONFIG_ENTRIES: {},
            DATA_DELETED_IDS: [],
        }

    opp.data[DOMAIN] = {
        DATA_CONFIG_ENTRIES: {},
        DATA_DELETED_IDS: app_config.get(DATA_DELETED_IDS, []),
        DATA_DEVICES: {},
        DATA_PUSH_CHANNEL: {},
        DATA_STORE: store,
    }

    opp.http.register_view(RegistrationsView())

    for deleted_id in opp.data[DOMAIN][DATA_DELETED_IDS]:
        with suppress(ValueError):
            webhook_register(opp, DOMAIN, "Deleted Webhook", deleted_id,
                             handle_webhook)

    opp.async_create_task(
        discovery.async_load_platform(opp, "notify", DOMAIN, {}, config))

    websocket_api.async_register_command(opp, handle_push_notification_channel)

    return True
Exemple #10
0
async def async_setup(opp, config):
    """Set up the iperf3 component."""
    opp.data[DOMAIN] = {}

    conf = config[DOMAIN]
    for host in conf[CONF_HOSTS]:
        data = opp.data[DOMAIN][host[CONF_HOST]] = Iperf3Data(opp, host)

        if not conf[CONF_MANUAL]:
            async_track_time_interval(opp, data.update,
                                      conf[CONF_SCAN_INTERVAL])

    def update(call):
        """Service call to manually update the data."""
        called_host = call.data[ATTR_HOST]
        if called_host in opp.data[DOMAIN]:
            opp.data[DOMAIN][called_host].update()
        else:
            for iperf3_host in opp.data[DOMAIN].values():
                iperf3_host.update()

    opp.services.async_register(DOMAIN,
                                "speedtest",
                                update,
                                schema=SERVICE_SCHEMA)

    opp.async_create_task(
        async_load_platform(opp, SENSOR_DOMAIN, DOMAIN,
                            conf[CONF_MONITORED_CONDITIONS], config))

    return True
Exemple #11
0
async def async_setup(opp, config):
    """Set up the Unify Circuit component."""
    webhooks = config[DOMAIN][CONF_WEBHOOK]

    for webhook_conf in webhooks:
        opp.async_create_task(
            discovery.async_load_platform(opp, "notify", DOMAIN, webhook_conf, config)
        )

    return True
Exemple #12
0
async def async_setup(opp, config):
    """Set up the Melissa Climate component."""
    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)
    api = melissa.AsyncMelissa(username=username, password=password)
    await api.async_connect()
    opp.data[DATA_MELISSA] = api

    opp.async_create_task(async_load_platform(opp, "climate", DOMAIN, {}, config))
    return True
Exemple #13
0
async def async_setup(opp, config):
    """Set up the SPC component."""
    async def async_upate_callback(spc_object):

        if isinstance(spc_object, Area):
            async_dispatcher_send(opp,
                                  SIGNAL_UPDATE_ALARM.format(spc_object.id))
        elif isinstance(spc_object, Zone):
            async_dispatcher_send(opp,
                                  SIGNAL_UPDATE_SENSOR.format(spc_object.id))

    session = aiohttp_client.async_get_clientsession(opp)

    spc = SpcWebGateway(
        loop=opp.loop,
        session=session,
        api_url=config[DOMAIN].get(CONF_API_URL),
        ws_url=config[DOMAIN].get(CONF_WS_URL),
        async_callback=async_upate_callback,
    )

    opp.data[DATA_API] = spc

    if not await spc.async_load_parameters():
        _LOGGER.error("Failed to load area/zone information from SPC")
        return False

    # add sensor devices for each zone (typically motion/fire/door sensors)
    opp.async_create_task(
        discovery.async_load_platform(opp, "binary_sensor", DOMAIN, {},
                                      config))

    # create a separate alarm panel for each area
    opp.async_create_task(
        discovery.async_load_platform(opp, "alarm_control_panel", DOMAIN, {},
                                      config))

    # start listening for incoming events over websocket
    spc.start()

    return True
Exemple #14
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
Exemple #15
0
async def async_setup(opp, config):
    """Set up the Compensation sensor."""
    opp.data[DATA_COMPENSATION] = {}

    for compensation, conf in config.get(DOMAIN).items():
        _LOGGER.debug("Setup %s.%s", DOMAIN, compensation)

        degree = conf[CONF_DEGREE]

        # get x values and y values from the x,y point pairs
        x_values, y_values = zip(*conf[CONF_DATAPOINTS])

        # try to get valid coefficients for a polynomial
        coefficients = None
        with np.errstate(all="raise"):
            with warnings.catch_warnings(record=True) as all_warnings:
                warnings.simplefilter("always")
                try:
                    coefficients = np.polyfit(x_values, y_values, degree)
                except FloatingPointError as error:
                    _LOGGER.error(
                        "Setup of %s encountered an error, %s",
                        compensation,
                        error,
                    )
                for warning in all_warnings:
                    _LOGGER.warning(
                        "Setup of %s encountered a warning, %s",
                        compensation,
                        str(warning.message).lower(),
                    )

        if coefficients is not None:
            data = {
                k: v for k, v in conf.items() if k not in [CONF_DEGREE, CONF_DATAPOINTS]
            }
            data[CONF_POLYNOMIAL] = np.poly1d(coefficients)

            opp.data[DATA_COMPENSATION][compensation] = data

            opp.async_create_task(
                async_load_platform(
                    opp,
                    SENSOR_DOMAIN,
                    DOMAIN,
                    {CONF_COMPENSATION: compensation},
                    config,
                )
            )

    return True
def discover_mysensors_platform(opp, opp_config, platform, new_devices):
    """Discover a MySensors platform."""
    task = opp.async_create_task(
        discovery.async_load_platform(
            opp,
            platform,
            DOMAIN,
            {
                ATTR_DEVICES: new_devices,
                CONF_NAME: DOMAIN
            },
            opp_config,
        ))
    return task
Exemple #17
0
async def async_setup_entry(opp, entry):
    """Load a config entry.

    Validate and save sessions per aws credential.
    """
    config = opp.data.get(DATA_OPP_CONFIG)
    conf = opp.data.get(DATA_CONFIG)

    if entry.source == config_entries.SOURCE_IMPORT:
        if conf is None:
            # user removed config from configuration.yaml, abort setup
            opp.async_create_task(
                opp.config_entries.async_remove(entry.entry_id))
            return False

        if conf != entry.data:
            # user changed config from configuration.yaml, use conf to setup
            opp.config_entries.async_update_entry(entry, data=conf)

    if conf is None:
        conf = CONFIG_SCHEMA({DOMAIN: entry.data})[DOMAIN]

    # validate credentials and create sessions
    validation = True
    tasks = []
    for cred in conf[ATTR_CREDENTIALS]:
        tasks.append(_validate_aws_credentials(opp, cred))
    if tasks:
        results = await asyncio.gather(*tasks, return_exceptions=True)
        for index, result in enumerate(results):
            name = conf[ATTR_CREDENTIALS][index][CONF_NAME]
            if isinstance(result, Exception):
                _LOGGER.error(
                    "Validating credential [%s] failed: %s",
                    name,
                    result,
                    exc_info=result,
                )
                validation = False
            else:
                opp.data[DATA_SESSIONS][name] = result

    # set up notify platform, no entry support for notify component yet,
    # have to use discovery to load platform.
    for notify_config in conf[CONF_NOTIFY]:
        opp.async_create_task(
            discovery.async_load_platform(opp, "notify", DOMAIN, notify_config,
                                          config))

    return validation
Exemple #18
0
async def async_setup(opp, config):
    """Set up the client and boot the platforms."""
    conf = config[DOMAIN]
    host = conf.get(CONF_HOST)
    name = conf.get(CONF_NAME)

    client = Vallox(host)
    state_proxy = ValloxStateProxy(opp, client)
    service_handler = ValloxServiceHandler(client, state_proxy)

    opp.data[DOMAIN] = {
        "client": client,
        "state_proxy": state_proxy,
        "name": name
    }

    for vallox_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[vallox_service]["schema"]
        opp.services.async_register(DOMAIN,
                                    vallox_service,
                                    service_handler.async_handle,
                                    schema=schema)

    # The vallox hardware expects quite strict timings for websocket
    # requests. Timings that machines with less processing power, like
    # Raspberries, cannot live up to during the busy start phase of Home
    # Asssistant. Hence, async_add_entities() for fan and sensor in respective
    # code will be called with update_before_add=False to intentionally delay
    # the first request, increasing chance that it is issued only when the
    # machine is less busy again.
    opp.async_create_task(
        async_load_platform(opp, "sensor", DOMAIN, {}, config))
    opp.async_create_task(async_load_platform(opp, "fan", DOMAIN, {}, config))

    async_track_time_interval(opp, state_proxy.async_update, SCAN_INTERVAL)

    return True
Exemple #19
0
async def async_setup(opp, config):
    """Set up the velux component."""
    try:
        opp.data[DATA_VELUX] = VeluxModule(opp, config[DOMAIN])
        opp.data[DATA_VELUX].setup()
        await opp.data[DATA_VELUX].async_start()

    except PyVLXException as ex:
        _LOGGER.exception("Can't connect to velux interface: %s", ex)
        return False

    for platform in PLATFORMS:
        opp.async_create_task(
            discovery.async_load_platform(opp, platform, DOMAIN, {}, config)
        )
    return True
Exemple #20
0
async def async_setup(opp, config):
    """Check connectivity and version of KEBA charging station."""
    host = config[DOMAIN][CONF_HOST]
    rfid = config[DOMAIN][CONF_RFID]
    refresh_interval = config[DOMAIN][CONF_FS_INTERVAL]
    keba = KebaHandler(opp, host, rfid, refresh_interval)
    opp.data[DOMAIN] = keba

    # Wait for KebaHandler setup complete (initial values loaded)
    if not await keba.setup():
        _LOGGER.error("Could not find a charging station at %s", host)
        return False

    # Set failsafe mode at start up of Open Peer Power
    failsafe = config[DOMAIN][CONF_FS]
    timeout = config[DOMAIN][CONF_FS_TIMEOUT] if failsafe else 0
    fallback = config[DOMAIN][CONF_FS_FALLBACK] if failsafe else 0
    persist = config[DOMAIN][CONF_FS_PERSIST] if failsafe else 0
    try:
        opp.loop.create_task(keba.set_failsafe(timeout, fallback, persist))
    except ValueError as ex:
        _LOGGER.warning("Could not set failsafe mode %s", ex)

    # Register services to opp
    async def execute_service(call):
        """Execute a service to KEBA charging station.

        This must be a member function as we need access to the keba
        object here.
        """
        function_name = _SERVICE_MAP[call.service]
        function_call = getattr(keba, function_name)
        await function_call(call.data)

    for service in _SERVICE_MAP:
        opp.services.async_register(DOMAIN, service, execute_service)

    # Load components
    for domain in SUPPORTED_COMPONENTS:
        opp.async_create_task(
            discovery.async_load_platform(opp, domain, DOMAIN, {}, config))

    # Start periodic polling of charging station data
    keba.start_periodic_request()

    return True
Exemple #21
0
def setup(opp, config):
    """Set up the ZoneMinder component."""

    opp.data[DOMAIN] = {}

    success = True

    for conf in config[DOMAIN]:
        protocol = "https" if conf[CONF_SSL] else "http"

        host_name = conf[CONF_HOST]
        server_origin = f"{protocol}://{host_name}"
        zm_client = ZoneMinder(
            server_origin,
            conf.get(CONF_USERNAME),
            conf.get(CONF_PASSWORD),
            conf.get(CONF_PATH),
            conf.get(CONF_PATH_ZMS),
            conf.get(CONF_VERIFY_SSL),
        )
        opp.data[DOMAIN][host_name] = zm_client

        success = zm_client.login() and success

    def set_active_state(call):
        """Set the ZoneMinder run state to the given state name."""
        zm_id = call.data[ATTR_ID]
        state_name = call.data[ATTR_NAME]
        if zm_id not in opp.data[DOMAIN]:
            _LOGGER.error("Invalid ZoneMinder host provided: %s", zm_id)
        if not opp.data[DOMAIN][zm_id].set_active_state(state_name):
            _LOGGER.error(
                "Unable to change ZoneMinder state. Host: %s, state: %s",
                zm_id,
                state_name,
            )

    opp.services.register(DOMAIN,
                          SERVICE_SET_RUN_STATE,
                          set_active_state,
                          schema=SET_RUN_STATE_SCHEMA)

    opp.async_create_task(
        async_load_platform(opp, "binary_sensor", DOMAIN, {}, config))

    return success
Exemple #22
0
async def _async_process_config(opp, config) -> bool:
    """Process rest configuration."""
    if DOMAIN not in config:
        return True

    refresh_tasks = []
    load_tasks = []
    for rest_idx, conf in enumerate(config[DOMAIN]):
        scan_interval = conf.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
        resource_template = conf.get(CONF_RESOURCE_TEMPLATE)
        rest = create_rest_data_from_config(opp, conf)
        coordinator = _rest_coordinator(opp, rest, resource_template,
                                        scan_interval)
        refresh_tasks.append(coordinator.async_refresh())
        opp.data[DOMAIN][REST_DATA].append({
            REST: rest,
            COORDINATOR: coordinator
        })

        for platform_domain in COORDINATOR_AWARE_PLATFORMS:
            if platform_domain not in conf:
                continue

            for platform_conf in conf[platform_domain]:
                opp.data[DOMAIN][platform_domain].append(platform_conf)
                platform_idx = len(opp.data[DOMAIN][platform_domain]) - 1

                load = discovery.async_load_platform(
                    opp,
                    platform_domain,
                    DOMAIN,
                    {
                        REST_IDX: rest_idx,
                        PLATFORM_IDX: platform_idx
                    },
                    config,
                )
                load_tasks.append(load)

    if refresh_tasks:
        await asyncio.gather(*refresh_tasks)

    if load_tasks:
        await asyncio.gather(*load_tasks)

    return True
Exemple #23
0
async def async_setup(opp, config):
    """Set up the Fast.com component."""
    conf = config[DOMAIN]
    data = opp.data[DOMAIN] = SpeedtestData(opp)

    if not conf[CONF_MANUAL]:
        async_track_time_interval(opp, data.update, conf[CONF_SCAN_INTERVAL])

    def update(call=None):
        """Service call to manually update the data."""
        data.update()

    opp.services.async_register(DOMAIN, "speedtest", update)

    opp.async_create_task(
        async_load_platform(opp, "sensor", DOMAIN, {}, config))

    return True
Exemple #24
0
def async_setup_sabnzbd(opp, sab_api, config, name):
    """Set up SABnzbd sensors and services."""
    sab_api_data = SabnzbdApiData(sab_api, name, config.get(CONF_SENSORS, {}))

    if config.get(CONF_SENSORS):
        opp.data[DATA_SABNZBD] = sab_api_data
        opp.async_create_task(
            discovery.async_load_platform(opp, "sensor", DOMAIN, {}, config))

    async def async_service_handler(service):
        """Handle service calls."""
        if service.service == SERVICE_PAUSE:
            await sab_api_data.async_pause_queue()
        elif service.service == SERVICE_RESUME:
            await sab_api_data.async_resume_queue()
        elif service.service == SERVICE_SET_SPEED:
            speed = service.data.get(ATTR_SPEED)
            await sab_api_data.async_set_queue_speed(speed)

    opp.services.async_register(DOMAIN,
                                SERVICE_PAUSE,
                                async_service_handler,
                                schema=vol.Schema({}))

    opp.services.async_register(DOMAIN,
                                SERVICE_RESUME,
                                async_service_handler,
                                schema=vol.Schema({}))

    opp.services.async_register(DOMAIN,
                                SERVICE_SET_SPEED,
                                async_service_handler,
                                schema=SPEED_LIMIT_SCHEMA)

    async def async_update_sabnzbd(now):
        """Refresh SABnzbd queue data."""

        try:
            await sab_api.refresh_data()
            async_dispatcher_send(opp, SIGNAL_SABNZBD_UPDATED, None)
        except SabnzbdApiException as err:
            _LOGGER.error(err)

    async_track_time_interval(opp, async_update_sabnzbd, UPDATE_INTERVAL)
Exemple #25
0
async def async_setup(opp, config):
    """Set up TP-Link LTE component."""
    if DATA_KEY not in opp.data:
        websession = async_create_clientsession(
            opp, cookie_jar=aiohttp.CookieJar(unsafe=True))
        opp.data[DATA_KEY] = LTEData(websession)

    domain_config = config.get(DOMAIN, [])

    tasks = [_setup_lte(opp, conf) for conf in domain_config]
    if tasks:
        await asyncio.wait(tasks)

    for conf in domain_config:
        for notify_conf in conf.get(CONF_NOTIFY, []):
            opp.async_create_task(
                discovery.async_load_platform(opp, "notify", DOMAIN,
                                              notify_conf, config))

    return True
Exemple #26
0
    async def async_setup(self, opp_config):
        """Set up the trigger and create entities."""
        if self.opp.state == CoreState.running:
            await self._attach_triggers()
        else:
            self._unsub_start = self.opp.bus.async_listen_once(
                EVENT_OPENPEERPOWER_START, self._attach_triggers)

        for platform_domain in PLATFORMS:
            if platform_domain in self.config:
                self.opp.async_create_task(
                    discovery.async_load_platform(
                        self.opp,
                        platform_domain,
                        DOMAIN,
                        {
                            "coordinator": self,
                            "entities": self.config[platform_domain]
                        },
                        opp_config,
                    ))
Exemple #27
0
async def _process_config(opp, opp_config):
    """Process config."""
    coordinators: list[TriggerUpdateCoordinator] | None = opp.data.pop(
        DOMAIN, None)

    # Remove old ones
    if coordinators:
        for coordinator in coordinators:
            coordinator.async_remove()

    async def init_coordinator(opp, conf_section):
        coordinator = TriggerUpdateCoordinator(opp, conf_section)
        await coordinator.async_setup(opp_config)
        return coordinator

    coordinator_tasks = []

    for conf_section in opp_config[DOMAIN]:
        if CONF_TRIGGER in conf_section:
            coordinator_tasks.append(init_coordinator(opp, conf_section))
            continue

        for platform_domain in PLATFORMS:
            if platform_domain in conf_section:
                opp.async_create_task(
                    discovery.async_load_platform(
                        opp,
                        platform_domain,
                        DOMAIN,
                        {
                            "unique_id": conf_section.get(CONF_UNIQUE_ID),
                            "entities": conf_section[platform_domain],
                        },
                        opp_config,
                    ))

    if coordinator_tasks:
        opp.data[DOMAIN] = await asyncio.gather(*coordinator_tasks)
Exemple #28
0
    def discover_vehicle(vehicle):
        """Load relevant platforms."""
        data.vehicles.add(vehicle.vin)

        dashboard = vehicle.dashboard(
            mutable=config[DOMAIN][CONF_MUTABLE],
            scandinavian_miles=config[DOMAIN][CONF_SCANDINAVIAN_MILES],
        )

        for instrument in (instrument for instrument in dashboard.instruments
                           if instrument.component in PLATFORMS
                           and is_enabled(instrument.slug_attr)):

            data.instruments.add(instrument)

            opp.async_create_task(
                discovery.async_load_platform(
                    opp,
                    PLATFORMS[instrument.component],
                    DOMAIN,
                    (vehicle.vin, instrument.component, instrument.attr),
                    config,
                ))
Exemple #29
0
async def async_setup_entry(opp, entry):
    """Set up a config entry."""

    tibber_connection = tibber.Tibber(
        access_token=entry.data[CONF_ACCESS_TOKEN],
        websession=async_get_clientsession(opp),
        time_zone=dt_util.DEFAULT_TIME_ZONE,
    )
    opp.data[DOMAIN] = tibber_connection

    async def _close(event):
        await tibber_connection.rt_disconnect()

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

    try:
        await tibber_connection.update_info()
    except asyncio.TimeoutError as err:
        raise ConfigEntryNotReady from err
    except aiohttp.ClientError as err:
        _LOGGER.error("Error connecting to Tibber: %s ", err)
        return False
    except tibber.InvalidLogin as exp:
        _LOGGER.error("Failed to login. %s", exp)
        return False

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    # set up notify platform, no entry support for notify component yet,
    # have to use discovery to load platform.
    opp.async_create_task(
        discovery.async_load_platform(opp, "notify", DOMAIN,
                                      {CONF_NAME: DOMAIN},
                                      opp.data[DATA_OPP_CONFIG]))
    return True
Exemple #30
0
def _load_platform(opp, config, entity_type, entity_info_list):
    """Load platform with list of entity info."""
    opp.async_create_task(
        async_load_platform(opp, entity_type, DOMAIN, entity_info_list,
                            config))