Beispiel #1
0
def setup(opp, config):
    """Establish connection to MAX! Cube."""

    if DATA_KEY not in opp.data:
        opp.data[DATA_KEY] = {}

    connection_failed = 0
    gateways = config[DOMAIN][CONF_GATEWAYS]
    for gateway in gateways:
        host = gateway[CONF_HOST]
        port = gateway[CONF_PORT]
        scan_interval = gateway[CONF_SCAN_INTERVAL].total_seconds()

        try:
            cube = MaxCube(host, port, now=now)
            opp.data[DATA_KEY][host] = MaxCubeHandle(cube, scan_interval)
        except timeout as ex:
            _LOGGER.error("Unable to connect to Max!Cube gateway: %s", str(ex))
            opp.components.persistent_notification.create(
                f"Error: {ex}<br />You will need to restart Open Peer Power after fixing.",
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID,
            )
            connection_failed += 1

    if connection_failed >= len(gateways):
        return False

    load_platform(opp, "climate", DOMAIN, {}, config)
    load_platform(opp, "binary_sensor", DOMAIN, {}, config)

    return True
Beispiel #2
0
def autosetup_ihc_products(opp: OpenPeerPower, config, ihc_controller, controller_id):
    """Auto setup of IHC products from the IHC project file."""
    project_xml = ihc_controller.get_project()
    if not project_xml:
        _LOGGER.error("Unable to read project from IHC controller")
        return False
    project = ElementTree.fromstring(project_xml)

    # If an auto setup file exist in the configuration it will override
    yaml_path = opp.config.path(AUTO_SETUP_YAML)
    if not os.path.isfile(yaml_path):
        yaml_path = os.path.join(os.path.dirname(__file__), AUTO_SETUP_YAML)
    yaml = load_yaml_config_file(yaml_path)
    try:
        auto_setup_conf = AUTO_SETUP_SCHEMA(yaml)
    except vol.Invalid as exception:
        _LOGGER.error("Invalid IHC auto setup data: %s", exception)
        return False

    groups = project.findall(".//group")
    for platform in PLATFORMS:
        platform_setup = auto_setup_conf[platform]
        discovery_info = get_discovery_info(platform_setup, groups, controller_id)
        if discovery_info:
            discovery.load_platform(opp, platform, DOMAIN, discovery_info, config)

    return True
Beispiel #3
0
def setup(opp, base_config):
    """Set up the Fibaro Component."""
    gateways = base_config[DOMAIN][CONF_GATEWAYS]
    opp.data[FIBARO_CONTROLLERS] = {}

    def stop_fibaro(event):
        """Stop Fibaro Thread."""
        _LOGGER.info("Shutting down Fibaro connection")
        for controller in opp.data[FIBARO_CONTROLLERS].values():
            controller.disable_state_handler()

    opp.data[FIBARO_DEVICES] = {}
    for platform in PLATFORMS:
        opp.data[FIBARO_DEVICES][platform] = []

    for gateway in gateways:
        controller = FibaroController(gateway)
        if controller.connect():
            opp.data[FIBARO_CONTROLLERS][controller.hub_serial] = controller
            for platform in PLATFORMS:
                opp.data[FIBARO_DEVICES][platform].extend(
                    controller.fibaro_devices[platform])

    if opp.data[FIBARO_CONTROLLERS]:
        for platform in PLATFORMS:
            discovery.load_platform(opp, platform, DOMAIN, {}, base_config)
        for controller in opp.data[FIBARO_CONTROLLERS].values():
            controller.enable_state_handler()
        opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, stop_fibaro)
        return True

    return False
Beispiel #4
0
def setup(opp, config):
    """Set up Eufy devices."""

    if CONF_USERNAME in config[DOMAIN] and CONF_PASSWORD in config[DOMAIN]:
        data = lakeside.get_devices(config[DOMAIN][CONF_USERNAME],
                                    config[DOMAIN][CONF_PASSWORD])
        for device in data:
            kind = device["type"]
            if kind not in EUFY_DISPATCH:
                continue
            discovery.load_platform(opp, EUFY_DISPATCH[kind], DOMAIN, device,
                                    config)

    for device_info in config[DOMAIN][CONF_DEVICES]:
        kind = device_info["type"]
        if kind not in EUFY_DISPATCH:
            continue
        device = {}
        device["address"] = device_info["address"]
        device["code"] = device_info["access_token"]
        device["type"] = device_info["type"]
        device["name"] = device_info["name"]
        discovery.load_platform(opp, EUFY_DISPATCH[kind], DOMAIN, device,
                                config)

    return True
Beispiel #5
0
    def _load_entities(self):
        sensor_info = []
        for pidx, printer in enumerate(self.printers):
            for sensor_type in self.sensors:
                info = {}
                info["sensor_type"] = sensor_type
                info["printer_id"] = pidx
                info["name"] = printer.slug
                info["printer_name"] = self.conf_name

                known = f"{printer.slug}-{sensor_type}"
                if known in self._known_entities:
                    continue

                methods = API_PRINTER_METHODS[sensor_type]
                if "temp_data" in methods["state"].values():
                    prop_data = getattr(printer, methods["attribute"])
                    if prop_data is None:
                        continue
                    for idx, _ in enumerate(prop_data):
                        prop_info = info.copy()
                        prop_info["temp_id"] = idx
                        sensor_info.append(prop_info)
                else:
                    info["temp_id"] = None
                    sensor_info.append(info)
                self._known_entities.add(known)

        if not sensor_info:
            return
        load_platform(self._opp, "sensor", DOMAIN, sensor_info, self.config)
Beispiel #6
0
def setup(opp, opp_config):
    """Set up global ECoalController instance same for sensors and switches."""

    conf = opp_config[DOMAIN]
    host = conf[CONF_HOST]
    username = conf[CONF_USERNAME]
    passwd = conf[CONF_PASSWORD]
    # Creating ECoalController instance makes HTTP request to controller.
    ecoal_contr = ECoalController(host, username, passwd)
    if ecoal_contr.version is None:
        # Wrong credentials nor network config
        _LOGGER.error(
            "Unable to read controller status from %s@%s (wrong host/credentials)",
            username,
            host,
        )
        return False
    _LOGGER.debug("Detected controller version: %r @%s", ecoal_contr.version,
                  host)
    opp.data[DATA_ECOAL_BOILER] = ecoal_contr
    # Setup switches
    switches = conf[CONF_SWITCHES][CONF_MONITORED_CONDITIONS]
    load_platform(opp, "switch", DOMAIN, switches, opp_config)
    # Setup temp sensors
    sensors = conf[CONF_SENSORS][CONF_MONITORED_CONDITIONS]
    load_platform(opp, "sensor", DOMAIN, sensors, opp_config)
    return True
Beispiel #7
0
def setup(opp, base_config):
    """Start Homeworks controller."""
    def hw_callback(msg_type, values):
        """Dispatch state changes."""
        _LOGGER.debug("callback: %s, %s", msg_type, values)
        addr = values[0]
        signal = f"homeworks_entity_{addr}"
        dispatcher_send(opp, signal, msg_type, values)

    config = base_config.get(DOMAIN)
    controller = Homeworks(config[CONF_HOST], config[CONF_PORT], hw_callback)
    opp.data[HOMEWORKS_CONTROLLER] = controller

    def cleanup(event):
        controller.close()

    opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, cleanup)

    dimmers = config[CONF_DIMMERS]
    load_platform(opp, "light", DOMAIN, {CONF_DIMMERS: dimmers}, base_config)

    for key_config in config[CONF_KEYPADS]:
        addr = key_config[CONF_ADDR]
        name = key_config[CONF_NAME]
        HomeworksKeypadEvent(opp, addr, name)

    return True
Beispiel #8
0
def setup(opp, config):
    """Set up the ComfoConnect bridge."""

    conf = config[DOMAIN]
    host = conf[CONF_HOST]
    name = conf[CONF_NAME]
    token = conf[CONF_TOKEN]
    user_agent = conf[CONF_USER_AGENT]
    pin = conf[CONF_PIN]

    # Run discovery on the configured ip
    bridges = Bridge.discover(host)
    if not bridges:
        _LOGGER.error("Could not connect to ComfoConnect bridge on %s", host)
        return False
    bridge = bridges[0]
    _LOGGER.info("Bridge found: %s (%s)", bridge.uuid.hex(), bridge.host)

    # Setup ComfoConnect Bridge
    ccb = ComfoConnectBridge(opp, bridge, name, token, user_agent, pin)
    opp.data[DOMAIN] = ccb

    # Start connection with bridge
    ccb.connect()

    # Schedule disconnect on shutdown
    def _shutdown(_event):
        ccb.disconnect()

    opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, _shutdown)

    # Load platforms
    discovery.load_platform(opp, "fan", DOMAIN, {}, config)

    return True
Beispiel #9
0
    def load_module(platform, idx, module_conf):
        """Set up the KIRA module and load platform."""
        # note: module_name is not the OPP device name. it's just a unique name
        # to ensure the component and platform can share information
        module_name = ("%s_%d" % (DOMAIN, idx)) if idx else DOMAIN
        device_name = module_conf.get(CONF_NAME, DOMAIN)
        port = module_conf.get(CONF_PORT, DEFAULT_PORT)
        host = module_conf.get(CONF_HOST, DEFAULT_HOST)

        if platform == CONF_SENSOR:
            module = pykira.KiraReceiver(host, port)
            module.start()
        else:
            module = pykira.KiraModule(host, port)

        opp.data[DOMAIN][platform][module_name] = module
        for code in codes:
            code_tuple = (code.get(CONF_NAME),
                          code.get(CONF_DEVICE, STATE_UNKNOWN))
            module.registerCode(code_tuple, code.get(CONF_CODE))

        discovery.load_platform(opp, platform, DOMAIN, {
            "name": module_name,
            "device": device_name
        }, config)
Beispiel #10
0
def setup(opp, config):
    """Set up the Coinbase component.

    Will automatically setup sensors to support
    wallets discovered on the network.
    """
    api_key = config[DOMAIN][CONF_API_KEY]
    api_secret = config[DOMAIN][CONF_API_SECRET]
    account_currencies = config[DOMAIN].get(CONF_ACCOUNT_CURRENCIES)
    exchange_currencies = config[DOMAIN][CONF_EXCHANGE_CURRENCIES]

    opp.data[DATA_COINBASE] = coinbase_data = CoinbaseData(api_key, api_secret)

    if not hasattr(coinbase_data, "accounts"):
        return False
    for account in coinbase_data.accounts:
        if account_currencies is None or account.currency in account_currencies:
            load_platform(opp, "sensor", DOMAIN, {"account": account}, config)
    for currency in exchange_currencies:
        if currency not in coinbase_data.exchange_rates.rates:
            _LOGGER.warning("Currency %s not found", currency)
            continue
        native = coinbase_data.exchange_rates.currency
        load_platform(
            opp,
            "sensor",
            DOMAIN,
            {
                "native_currency": native,
                "exchange_currency": currency
            },
            config,
        )

    return True
Beispiel #11
0
def setup(opp, config):
    """Set up the eBusd component."""
    _LOGGER.debug("Integration setup started")
    conf = config[DOMAIN]
    name = conf[CONF_NAME]
    circuit = conf[CONF_CIRCUIT]
    monitored_conditions = conf.get(CONF_MONITORED_CONDITIONS)
    server_address = (conf.get(CONF_HOST), conf.get(CONF_PORT))

    try:

        ebusdpy.init(server_address)
        opp.data[DOMAIN] = EbusdData(server_address, circuit)

        sensor_config = {
            CONF_MONITORED_CONDITIONS: monitored_conditions,
            "client_name": name,
            "sensor_types": SENSOR_TYPES[circuit],
        }
        load_platform(opp, "sensor", DOMAIN, sensor_config, config)

        opp.services.register(DOMAIN, SERVICE_EBUSD_WRITE,
                              opp.data[DOMAIN].write)

        _LOGGER.debug("Ebusd integration setup completed")
        return True
    except (socket.timeout, OSError):
        return False
Beispiel #12
0
def get_manual_configuration(opp, config, conf, ihc_controller, controller_id):
    """Get manual configuration for IHC devices."""
    for platform in PLATFORMS:
        discovery_info = {}
        if platform in conf:
            platform_setup = conf.get(platform)
            for sensor_cfg in platform_setup:
                name = sensor_cfg[CONF_NAME]
                device = {
                    "ihc_id": sensor_cfg[CONF_ID],
                    "ctrl_id": controller_id,
                    "product": {
                        "name": name,
                        "note": sensor_cfg.get(CONF_NOTE) or "",
                        "position": sensor_cfg.get(CONF_POSITION) or "",
                    },
                    "product_cfg": {
                        "type": sensor_cfg.get(CONF_TYPE),
                        "inverting": sensor_cfg.get(CONF_INVERTING),
                        "off_id": sensor_cfg.get(CONF_OFF_ID),
                        "on_id": sensor_cfg.get(CONF_ON_ID),
                        "dimmable": sensor_cfg.get(CONF_DIMMABLE),
                        "unit_of_measurement": sensor_cfg.get(CONF_UNIT_OF_MEASUREMENT),
                    },
                }
                discovery_info[name] = device
        if discovery_info:
            discovery.load_platform(opp, platform, DOMAIN, discovery_info, config)
Beispiel #13
0
def setup(opp, config):
    """Set up the Nextcloud integration."""
    # Fetch Nextcloud Monitor api data
    conf = config[DOMAIN]

    try:
        ncm = NextcloudMonitor(conf[CONF_URL], conf[CONF_USERNAME], conf[CONF_PASSWORD])
    except NextcloudMonitorError:
        _LOGGER.error("Nextcloud setup failed - Check configuration")

    opp.data[DOMAIN] = get_data_points(ncm.data)
    opp.data[DOMAIN]["instance"] = conf[CONF_URL]

    def nextcloud_update(event_time):
        """Update data from nextcloud api."""
        try:
            ncm.update()
        except NextcloudMonitorError:
            _LOGGER.error("Nextcloud update failed")
            return False

        opp.data[DOMAIN] = get_data_points(ncm.data)
        opp.data[DOMAIN]["instance"] = conf[CONF_URL]

    # Update sensors on time interval
    track_time_interval(opp, nextcloud_update, conf[CONF_SCAN_INTERVAL])

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, config)

    return True
Beispiel #14
0
async def async_setup(opp, config):
    """Set up the iOS component."""
    conf = config.get(DOMAIN)

    ios_config = await opp.async_add_executor_job(
        load_json, opp.config.path(CONFIGURATION_FILE))

    if ios_config == {}:
        ios_config[ATTR_DEVICES] = {}

    ios_config[CONF_USER] = conf or {}

    if CONF_PUSH not in ios_config[CONF_USER]:
        ios_config[CONF_USER][CONF_PUSH] = {}

    opp.data[DOMAIN] = ios_config

    # No entry support for notify component yet
    discovery.load_platform(opp, "notify", DOMAIN, {}, config)

    if conf is not None:
        opp.async_create_task(
            opp.config_entries.flow.async_init(
                DOMAIN, context={"source": config_entries.SOURCE_IMPORT}))

    return True
Beispiel #15
0
def setup(opp, config):
    """Set up the QVR Pro component."""
    conf = config[DOMAIN]
    user = conf[CONF_USERNAME]
    password = conf[CONF_PASSWORD]
    host = conf[CONF_HOST]
    port = conf[CONF_PORT]
    excluded_channels = conf[CONF_EXCLUDE_CHANNELS]

    try:
        qvrpro = Client(user, password, host, port=port)

        channel_resp = qvrpro.get_channel_list()

    except InsufficientPermissionsError:
        _LOGGER.error("User must have Surveillance Management permission")
        return False
    except AuthenticationError:
        _LOGGER.error("Authentication failed")
        return False
    except RequestsConnectionError:
        _LOGGER.error("Error connecting to QVR server")
        return False

    channels = []

    for channel in channel_resp["channels"]:
        if channel["channel_index"] + 1 in excluded_channels:
            continue

        channels.append(channel)

    opp.data[DOMAIN] = {"channels": channels, "client": qvrpro}

    load_platform(opp, CAMERA_DOMAIN, DOMAIN, {}, config)

    # Register services
    def handle_start_record(call):
        guid = call.data[SERVICE_CHANNEL_GUID]
        qvrpro.start_recording(guid)

    def handle_stop_record(call):
        guid = call.data[SERVICE_CHANNEL_GUID]
        qvrpro.stop_recording(guid)

    opp.services.register(
        DOMAIN,
        SERVICE_START_RECORD,
        handle_start_record,
        schema=SERVICE_CHANNEL_RECORD_SCHEMA,
    )
    opp.services.register(
        DOMAIN,
        SERVICE_STOP_RECORD,
        handle_stop_record,
        schema=SERVICE_CHANNEL_RECORD_SCHEMA,
    )

    return True
Beispiel #16
0
def setup(opp, config):
    """Set up the IOTA component."""
    iota_config = config[DOMAIN]

    for platform in IOTA_PLATFORMS:
        load_platform(opp, platform, DOMAIN, iota_config, config)

    return True
Beispiel #17
0
    def test_platform(self, mock_setup_component):
        """Test discover platform method."""
        calls = []

        @callback
        def platform_callback(platform, info):
            """Platform callback method."""
            calls.append((platform, info))

        run_callback_threadsafe(
            self.opp.loop,
            discovery.async_listen_platform,
            self.opp,
            "test_component",
            platform_callback,
        ).result()

        discovery.load_platform(
            self.opp,
            "test_component",
            "test_platform",
            "discovery info",
            {"test_component": {}},
        )
        self.opp.block_till_done()
        assert mock_setup_component.called
        assert mock_setup_component.call_args[0] == (
            self.opp,
            "test_component",
            {
                "test_component": {}
            },
        )
        self.opp.block_till_done()

        discovery.load_platform(
            self.opp,
            "test_component_2",
            "test_platform",
            "discovery info",
            {"test_component": {}},
        )
        self.opp.block_till_done()

        assert len(calls) == 1
        assert calls[0] == ("test_platform", "discovery info")

        dispatcher_send(
            self.opp,
            discovery.SIGNAL_PLATFORM_DISCOVERED,
            {
                "service":
                discovery.EVENT_LOAD_PLATFORM.format("test_component")
            },
        )
        self.opp.block_till_done()

        assert len(calls) == 1
Beispiel #18
0
def setup(opp, config):
    """Set up the Egardia platform."""

    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)
    host = conf.get(CONF_HOST)
    port = conf.get(CONF_PORT)
    version = conf.get(CONF_VERSION)
    rs_enabled = conf.get(CONF_REPORT_SERVER_ENABLED)
    rs_port = conf.get(CONF_REPORT_SERVER_PORT)
    try:
        device = opp.data[EGARDIA_DEVICE] = egardiadevice.EgardiaDevice(
            host, port, username, password, "", version)
    except requests.exceptions.RequestException:
        _LOGGER.error("An error occurred accessing your Egardia device. "
                      "Please check configuration")
        return False
    except egardiadevice.UnauthorizedError:
        _LOGGER.error("Unable to authorize. Wrong password or username")
        return False
    # Set up the egardia server if enabled
    if rs_enabled:
        _LOGGER.debug("Setting up EgardiaServer")
        try:
            if EGARDIA_SERVER not in opp.data:
                server = egardiaserver.EgardiaServer("", rs_port)
                bound = server.bind()
                if not bound:
                    raise OSError(
                        "Binding error occurred while starting EgardiaServer.")
                opp.data[EGARDIA_SERVER] = server
                server.start()

            def handle_stop_event(event):
                """Handle Open Peer Power stop event."""
                server.stop()

            # listen to Open Peer Power stop event
            opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, handle_stop_event)

        except OSError:
            _LOGGER.error(
                "Binding error occurred while starting EgardiaServer")
            return False

    discovery.load_platform(opp,
                            "alarm_control_panel",
                            DOMAIN,
                            discovered=conf,
                            opp_config=config)

    # Get the sensors from the device and add those
    sensors = device.getsensors()
    discovery.load_platform(opp, "binary_sensor", DOMAIN,
                            {ATTR_DISCOVER_DEVICES: sensors}, config)

    return True
Beispiel #19
0
def setup(opp, base_config):
    """Set up the Lutron integration."""
    opp.data[LUTRON_BUTTONS] = []
    opp.data[LUTRON_CONTROLLER] = None
    opp.data[LUTRON_DEVICES] = {
        "light": [],
        "cover": [],
        "switch": [],
        "scene": [],
        "binary_sensor": [],
    }

    config = base_config.get(DOMAIN)
    opp.data[LUTRON_CONTROLLER] = Lutron(config[CONF_HOST],
                                         config[CONF_USERNAME],
                                         config[CONF_PASSWORD])

    opp.data[LUTRON_CONTROLLER].load_xml_db()
    opp.data[LUTRON_CONTROLLER].connect()
    _LOGGER.info("Connected to main repeater at %s", config[CONF_HOST])

    # Sort our devices into types
    for area in opp.data[LUTRON_CONTROLLER].areas:
        for output in area.outputs:
            if output.type == "SYSTEM_SHADE":
                opp.data[LUTRON_DEVICES]["cover"].append((area.name, output))
            elif output.is_dimmable:
                opp.data[LUTRON_DEVICES]["light"].append((area.name, output))
            else:
                opp.data[LUTRON_DEVICES]["switch"].append((area.name, output))
        for keypad in area.keypads:
            for button in keypad.buttons:
                # If the button has a function assigned to it, add it as a scene
                if button.name != "Unknown Button" and button.button_type in (
                        "SingleAction",
                        "Toggle",
                        "SingleSceneRaiseLower",
                        "MasterRaiseLower",
                ):
                    # Associate an LED with a button if there is one
                    led = next(
                        (led for led in keypad.leds
                         if led.number == button.number),
                        None,
                    )
                    opp.data[LUTRON_DEVICES]["scene"].append(
                        (area.name, keypad.name, button, led))

                opp.data[LUTRON_BUTTONS].append(
                    LutronButton(opp, area.name, keypad, button))
        if area.occupancy_group is not None:
            opp.data[LUTRON_DEVICES]["binary_sensor"].append(
                (area.name, area.occupancy_group))

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, base_config)
    return True
Beispiel #20
0
def setup(opp, config):
    """Set up the PCA switch platform."""

    for platform in ELV_PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN,
                                {"device": config[DOMAIN][CONF_DEVICE]},
                                config)

    return True
Beispiel #21
0
def setup(opp, config):
    """Set up the Danfoss Air component."""
    conf = config[DOMAIN]

    opp.data[DOMAIN] = DanfossAir(conf[CONF_HOST])

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, config)

    return True
Beispiel #22
0
 def _new_device(device):
     """Handle new devices which are detected by HDMI network."""
     key = f"{DOMAIN}.{device.name}"
     opp.data[key] = device
     ent_platform = base_config[DOMAIN][CONF_TYPES].get(key, platform)
     discovery.load_platform(
         opp,
         ent_platform,
         DOMAIN,
         discovered={ATTR_NEW: [key]},
         opp_config=base_config,
     )
async def test_setup_does_discovery(mock_setup_component, mock_setup, opp):
    """Test setup for discovery."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)

    component.setup({})

    discovery.load_platform(
        opp, DOMAIN, "platform_test", {"msg": "discovery_info"}, {DOMAIN: {}}
    )

    await opp.async_block_till_done()

    assert mock_setup.called
    assert ("platform_test", {}, {"msg": "discovery_info"}) == mock_setup.call_args[0]
Beispiel #24
0
def setup(opp, config):
    """Set up the Ecovacs component."""
    _LOGGER.debug("Creating new Ecovacs component")

    opp.data[ECOVACS_DEVICES] = []

    ecovacs_api = EcoVacsAPI(
        ECOVACS_API_DEVICEID,
        config[DOMAIN].get(CONF_USERNAME),
        EcoVacsAPI.md5(config[DOMAIN].get(CONF_PASSWORD)),
        config[DOMAIN].get(CONF_COUNTRY),
        config[DOMAIN].get(CONF_CONTINENT),
    )

    devices = ecovacs_api.devices()
    _LOGGER.debug("Ecobot devices: %s", devices)

    for device in devices:
        _LOGGER.info(
            "Discovered Ecovacs device on account: %s with nickname %s",
            device["did"],
            device["nick"],
        )
        vacbot = VacBot(
            ecovacs_api.uid,
            ecovacs_api.REALM,
            ecovacs_api.resource,
            ecovacs_api.user_access_token,
            device,
            config[DOMAIN].get(CONF_CONTINENT).lower(),
            monitor=True,
        )
        opp.data[ECOVACS_DEVICES].append(vacbot)

    def stop(event: object) -> None:
        """Shut down open connections to Ecovacs XMPP server."""
        for device in opp.data[ECOVACS_DEVICES]:
            _LOGGER.info(
                "Shutting down connection to Ecovacs device %s", device.vacuum["did"]
            )
            device.disconnect()

    # Listen for OPP stop to disconnect.
    opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, stop)

    if opp.data[ECOVACS_DEVICES]:
        _LOGGER.debug("Starting vacuum components")
        discovery.load_platform(opp, "vacuum", DOMAIN, {}, config)

    return True
Beispiel #25
0
def setup(opp, config):
    """Set up the streamlabs water integration."""

    conf = config[DOMAIN]
    api_key = conf.get(CONF_API_KEY)
    location_id = conf.get(CONF_LOCATION_ID)

    client = streamlabswater.StreamlabsClient(api_key)
    locations = client.get_locations().get("locations")

    if locations is None:
        _LOGGER.error("Unable to retrieve locations. Verify API key")
        return False

    if location_id is None:
        location = locations[0]
        location_id = location["locationId"]
        _LOGGER.info("Streamlabs Water Monitor auto-detected location_id=%s",
                     location_id)
    else:
        location = next(
            (loc for loc in locations if location_id == loc["locationId"]),
            None)
        if location is None:
            _LOGGER.error("Supplied location_id is invalid")
            return False

    location_name = location["name"]

    opp.data[DOMAIN] = {
        "client": client,
        "location_id": location_id,
        "location_name": location_name,
    }

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, config)

    def set_away_mode(service):
        """Set the StreamLabsWater Away Mode."""
        away_mode = service.data.get(ATTR_AWAY_MODE)
        client.update_location(location_id, away_mode)

    opp.services.register(DOMAIN,
                          SERVICE_SET_AWAY_MODE,
                          set_away_mode,
                          schema=SET_AWAY_MODE_SCHEMA)

    return True
 def test_discover_notify(self, mock_demo_get_service):
     """Test discovery of notify demo platform."""
     assert notify.DOMAIN not in self.opp.config.components
     discovery.load_platform(self.opp, "notify", "demo",
                             {"test_key": "test_val"}, {"notify": {}})
     self.opp.block_till_done()
     assert notify.DOMAIN in self.opp.config.components
     assert mock_demo_get_service.called
     assert mock_demo_get_service.mock_calls[0][1] == (
         self.opp,
         {},
         {
             "test_key": "test_val"
         },
     )
Beispiel #27
0
def setup(opp, config):
    """Set up the BloomSky integration."""
    api_key = config[DOMAIN][CONF_API_KEY]

    try:
        bloomsky = BloomSky(api_key, opp.config.units.is_metric)
    except RuntimeError:
        return False

    opp.data[DOMAIN] = bloomsky

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, config)

    return True
Beispiel #28
0
def setup(opp, config):
    """Set up the STIEBEL ELTRON unit.

    Will automatically load climate platform.
    """
    name = config[DOMAIN][CONF_NAME]
    modbus_client = opp.data[MODBUS_DOMAIN][config[DOMAIN][CONF_HUB]]

    opp.data[DOMAIN] = {
        "name": name,
        "ste_data": StiebelEltronData(name, modbus_client),
    }

    discovery.load_platform(opp, "climate", DOMAIN, {}, config)
    return True
Beispiel #29
0
def setup(opp, config):
    """Set up the OctoPrint component."""
    printers = opp.data[DOMAIN] = {}
    success = False

    if DOMAIN not in config:
        # Skip the setup if there is no configuration present
        return True

    for printer in config[DOMAIN]:
        name = printer[CONF_NAME]
        protocol = "https" if printer[CONF_SSL] else "http"
        base_url = (
            f"{protocol}://{printer[CONF_HOST]}:{printer[CONF_PORT]}"
            f"{printer[CONF_PATH]}api/"
        )
        api_key = printer[CONF_API_KEY]
        number_of_tools = printer[CONF_NUMBER_OF_TOOLS]
        bed = printer[CONF_BED]
        try:
            octoprint_api = OctoPrintAPI(base_url, api_key, bed, number_of_tools)
            printers[base_url] = octoprint_api
            octoprint_api.get("printer")
            octoprint_api.get("job")
        except requests.exceptions.RequestException as conn_err:
            _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
            continue

        sensors = printer[CONF_SENSORS][CONF_MONITORED_CONDITIONS]
        load_platform(
            opp,
            "sensor",
            DOMAIN,
            {"name": name, "base_url": base_url, "sensors": sensors},
            config,
        )
        b_sensors = printer[CONF_BINARY_SENSORS][CONF_MONITORED_CONDITIONS]
        load_platform(
            opp,
            "binary_sensor",
            DOMAIN,
            {"name": name, "base_url": base_url, "sensors": b_sensors},
            config,
        )
        success = True

    return success
Beispiel #30
0
def setup(opp, config):
    """Set up Tahoma integration."""

    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)
    exclude = conf.get(CONF_EXCLUDE)
    try:
        api = TahomaApi(username, password)
    except RequestException:
        _LOGGER.exception("Error when trying to log in to the Tahoma API")
        return False

    try:
        api.get_setup()
        devices = api.get_devices()
        scenes = api.get_action_groups()
    except RequestException:
        _LOGGER.exception("Error when getting devices from the Tahoma API")
        return False

    opp.data[DOMAIN] = {
        "controller": api,
        "devices": defaultdict(list),
        "scenes": []
    }

    for device in devices:
        _device = api.get_device(device)
        if all(ext not in _device.type for ext in exclude):
            device_type = map_tahoma_device(_device)
            if device_type is None:
                _LOGGER.warning(
                    "Unsupported type %s for Tahoma device %s",
                    _device.type,
                    _device.label,
                )
                continue
            opp.data[DOMAIN]["devices"][device_type].append(_device)

    for scene in scenes:
        opp.data[DOMAIN]["scenes"].append(scene)

    for platform in PLATFORMS:
        discovery.load_platform(opp, platform, DOMAIN, {}, config)

    return True