async def async_step_init(self,
                              user_input: Dict[str,
                                               str] = None) -> Dict[str, str]:
        """Manage the options for the custom component."""
        errors: Dict[str, str] = {}

        # Grab all devices from the entity registry so we can populate the
        # dropdown list that will allow a user to configure a device.
        entity_registry = await async_get_registry(self.hass)
        devices = async_entries_for_config_entry(entity_registry,
                                                 self.config_entry.entry_id)
        stats = {
            e.unique_id: e.capabilities
            for e in devices if e.entity_id.startswith('climate.')
        }

        if user_input is not None:
            _LOGGER.debug(f"user_input: {user_input}")
            _LOGGER.debug(f"original config: {self.config}")

            # Remove any devices where hvac_modes have been unset.
            remove_devices = [
                unique_id for unique_id in stats.keys()
                if unique_id == user_input["device"]
                if len(user_input["hvac_modes"]) == 0
            ]
            for unique_id in remove_devices:
                if unique_id in self.config:
                    self.config.pop(unique_id)

            if len(user_input["hvac_modes"]) != 0:
                if not errors:
                    # Add the new device config.
                    self.config[
                        user_input["device"]] = user_input["hvac_modes"]

            _LOGGER.debug(f"updated config: {self.config}")

            if not errors:
                # If user selected the 'more' tickbox, show this form again
                # so they can configure additional devices.
                if user_input.get('more', False):
                    return await self.async_step_init()

                # Value of data will be set on the options property of the config_entry instance.
                return self.async_create_entry(
                    title="", data={CONF_HVAC_MODES: self.config})

        options_schema = vol.Schema({
            vol.Optional("device", default=list(stats.keys())):
            vol.In(stats.keys()),
            vol.Optional("hvac_modes", default=list(default_modes)):
            cv.multi_select(modes),
            vol.Optional("more"):
            cv.boolean
        })

        return self.async_show_form(step_id="init",
                                    data_schema=options_schema,
                                    errors=errors)
Exemplo n.º 2
0
    async def async_step_advanced(self,
                                  user_input: dict[str, Any] | None = None
                                  ) -> FlowResult:
        """Choose advanced options."""
        if (not self.show_advanced_options or user_input is not None
                or self.hk_options[CONF_HOMEKIT_MODE] != HOMEKIT_MODE_BRIDGE):
            if user_input:
                self.hk_options.update(user_input)
                if (self.show_advanced_options
                        and self.hk_options[CONF_HOMEKIT_MODE]
                        == HOMEKIT_MODE_BRIDGE):
                    self.hk_options[CONF_DEVICES] = user_input[CONF_DEVICES]

            for key in (CONF_DOMAINS, CONF_ENTITIES):
                if key in self.hk_options:
                    del self.hk_options[key]

            if CONF_INCLUDE_EXCLUDE_MODE in self.hk_options:
                del self.hk_options[CONF_INCLUDE_EXCLUDE_MODE]

            return self.async_create_entry(title="", data=self.hk_options)

        all_supported_devices = await _async_get_supported_devices(self.hass)
        # Strip out devices that no longer exist to prevent error in the UI
        devices = [
            device_id for device_id in self.hk_options.get(CONF_DEVICES, [])
            if device_id in all_supported_devices
        ]
        return self.async_show_form(
            step_id="advanced",
            data_schema=vol.Schema({
                vol.Optional(CONF_DEVICES, default=devices):
                cv.multi_select(all_supported_devices)
            }),
        )
Exemplo n.º 3
0
    async def async_step_events(self, user_input=None):
        """Manage event options."""
        if user_input is not None:
            if ADD_NEW_EVENT not in user_input:
                self.options[CONF_SUBSCRIBE_EVENTS] = user_input.get(
                    CONF_SUBSCRIBE_EVENTS, [])
                return self.async_create_entry(title="", data=self.options)

            selected = user_input.get(CONF_SUBSCRIBE_EVENTS, [])
            self.events.add(user_input[ADD_NEW_EVENT])
            selected.append(user_input[ADD_NEW_EVENT])
        else:
            self.events = set(
                self.config_entry.options.get(CONF_SUBSCRIBE_EVENTS) or [])
            selected = self._default(CONF_SUBSCRIBE_EVENTS)

        return self.async_show_form(
            step_id="events",
            data_schema=vol.Schema({
                vol.Optional(CONF_SUBSCRIBE_EVENTS, default=selected):
                cv.multi_select(self.events),
                vol.Optional(ADD_NEW_EVENT):
                str,
            }),
        )
Exemplo n.º 4
0
    async def async_step_init(self,
                              user_input: dict[str, Any] | None = None
                              ) -> FlowResult:
        """Manage the Kraken options."""
        if user_input is not None:
            return self.async_create_entry(title="", data=user_input)

        api = KrakenAPI(krakenex.API(), retry=0, crl_sleep=0)
        tradable_asset_pairs = await self.hass.async_add_executor_job(
            get_tradable_asset_pairs, api)
        tradable_asset_pairs_for_multi_select = {
            v: v
            for v in tradable_asset_pairs.keys()
        }
        options = {
            vol.Optional(
                CONF_SCAN_INTERVAL,
                default=self.config_entry.options.get(
                    CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
                ),
            ): int,
            vol.Optional(
                CONF_TRACKED_ASSET_PAIRS,
                default=self.config_entry.options.get(CONF_TRACKED_ASSET_PAIRS, []),
            ): cv.multi_select(tradable_asset_pairs_for_multi_select),
        }

        return self.async_show_form(step_id="init",
                                    data_schema=vol.Schema(options))
Exemplo n.º 5
0
    async def async_step_repositories(
        self,
        user_input: dict[str, Any] | None = None,
    ) -> FlowResult:
        """Handle repositories step."""

        # mypy is not aware that we can't get here without having this set already
        assert self._login is not None

        if not user_input:
            repositories = await get_repositories(self.hass, self._login.access_token)
            return self.async_show_form(
                step_id="repositories",
                data_schema=vol.Schema(
                    {
                        vol.Required(CONF_REPOSITORIES): cv.multi_select(
                            {k: k for k in repositories}
                        ),
                    }
                ),
            )

        return self.async_create_entry(
            title="",
            data={CONF_ACCESS_TOKEN: self._login.access_token},
            options={CONF_REPOSITORIES: user_input[CONF_REPOSITORIES]},
        )
Exemplo n.º 6
0
    async def async_step_forecasts_monitored(self, user_input=None):
        """Handle the forecasts monitored step."""
        monitored = {
            "temp_max": "Max. Temperature",
            "temp_min": "Min. Temperature",
            "extended_text": "Extended Text",
            "icon_descriptor": "Icon Descriptor",
            "mdi_icon": "MDI Icon",
            "short_text": "Short Text",
            "uv_category": "UV Category",
            "uv_max_index": "UV Max Index",
            "uv_start_time": "UV Protection Start Time",
            "uv_end_time": "UV Protection End Time",
            "uv_forecast": "UV Forecast Summary",
            "rain_amount_min": "Rain Amount Min.",
            "rain_amount_max": "Rain Amount Max.",
            "rain_amount_range": "Rain Amount Range",
            "rain_chance": "Rain Chance",
            "fire_danger": "Fire Danger",
            "now_now_label": "Now Now Label",
            "now_temp_now": "Now Temp Now",
            "now_later_label": "Now Later Label",
            "now_temp_later": "Now Temp Later",
            "astronomical_sunrise_time": "Sunrise Time",
            "astronomical_sunset_time": "Sunset Time",
        }

        data_schema = vol.Schema({
            vol.Required(
                CONF_FORECASTS_BASENAME,
                default=self.collector.locations_data["data"]["name"],
            ):
            str,
            vol.Required(CONF_FORECASTS_MONITORED):
            cv.multi_select(monitored),
            vol.Required(CONF_FORECASTS_DAYS):
            vol.All(vol.Coerce(int), vol.Range(0, 7)),
        })

        errors = {}
        if user_input is not None:
            try:
                self.data.update(user_input)

                if self.data[CONF_WARNINGS_CREATE]:
                    return await self.async_step_warnings_basename()
                return self.async_create_entry(
                    title=self.collector.locations_data["data"]["name"],
                    data=self.data)

            except CannotConnect:
                errors["base"] = "cannot_connect"
            except Exception:
                _LOGGER.exception("Unexpected exception")
                errors["base"] = "unknown"

        # If there is no user input or there were errors, show the form again, including any errors that were found with the input.
        return self.async_show_form(step_id="forecasts_monitored",
                                    data_schema=data_schema,
                                    errors=errors)
Exemplo n.º 7
0
    async def async_step_options_2(self, user_input=None):
        """Manage the options 2."""
        if user_input is not None:
            self.options.update(user_input)
            return await self._update_options()

        return self.async_show_form(
            step_id="options_2",
            data_schema=vol.Schema({
                vol.Optional(
                    CONF_STRING,
                    default=self.config_entry.options.get(
                        CONF_STRING,
                        "Default",
                    ),
                ):
                str,
                vol.Optional(
                    CONF_SELECT,
                    default=self.config_entry.options.get(
                        CONF_SELECT, "default"),
                ):
                vol.In(["default", "other"]),
                vol.Optional(
                    CONF_MULTISELECT,
                    default=self.config_entry.options.get(
                        CONF_MULTISELECT, ["default"]),
                ):
                cv.multi_select({
                    "default": "Default",
                    "other": "Other"
                }),
            }),
        )
    async def async_step_select_instruments(self, user_input=None):
        if user_input is not None:
            self._init_info[CONF_RESOURCES] = user_input[CONF_RESOURCES]
            del self._init_info["CONF_VEHICLES"]

            if self._init_info[CONF_NAME] is None:
                self._init_info[CONF_NAME] = self._init_info[CONF_VEHICLE]

            await self.async_set_unique_id(self._init_info[CONF_VEHICLE])
            self._abort_if_unique_id_configured()

            return self.async_create_entry(title=self._init_info[CONF_NAME],
                                           data=self._init_info)

        instruments = self._init_info["CONF_VEHICLES"][
            self._init_info[CONF_VEHICLE]]
        instruments_dict = {
            instrument.attr: instrument.name
            for instrument in instruments
        }
        return self.async_show_form(
            step_id="select_instruments",
            errors=self._errors,
            data_schema=vol.Schema({
                vol.Optional(CONF_RESOURCES,
                             default=list(instruments_dict.keys())):
                cv.multi_select(instruments_dict)
            }),
        )
Exemplo n.º 9
0
    async def async_step_user(self, user_input=None):
        if user_input:
            return self.async_create_entry(title='', data=user_input)

        host = self.entry.options['host']
        token = self.entry.options['token']
        ble = self.entry.options.get('ble', True)
        stats = self.entry.options.get('stats', False)
        debug = self.entry.options.get('debug', [])
        buzzer = self.entry.options.get('buzzer', False)
        parent = self.entry.options.get('parent')
        zha = self.entry.options.get('zha', False)

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema({
                vol.Required('host', default=host):
                str,
                vol.Required('token', default=token):
                str,
                vol.Required('ble', default=ble):
                bool,
                vol.Required('stats', default=stats):
                bool,
                vol.Optional('debug', default=debug):
                cv.multi_select(OPT_DEBUG),
                vol.Optional('buzzer', default=buzzer):
                bool,
                vol.Optional('parent', default=parent):
                vol.In(OPT_PARENT),
                vol.Required('zha', default=zha):
                vol.In(OPT_MODE),
            }),
        )
Exemplo n.º 10
0
    async def async_step_simple_options(self, user_input=None):
        """For users without advanced settings enabled."""
        if user_input is not None:
            self.options.update(user_input)
            return await self._update_options()

        clients_to_block = {}

        for client in self.controller.api.clients.values():
            clients_to_block[
                client.
                mac] = f"{client.name or client.hostname} ({client.mac})"

        return self.async_show_form(
            step_id="simple_options",
            data_schema=vol.Schema({
                vol.Optional(
                    CONF_TRACK_CLIENTS,
                    default=self.controller.option_track_clients,
                ):
                bool,
                vol.Optional(
                    CONF_TRACK_DEVICES,
                    default=self.controller.option_track_devices,
                ):
                bool,
                vol.Optional(CONF_BLOCK_CLIENT,
                             default=self.options[CONF_BLOCK_CLIENT]):
                cv.multi_select(clients_to_block),
            }),
        )
Exemplo n.º 11
0
    async def async_step_client_control(self, user_input=None):
        """Manage configuration of network access controlled clients."""
        errors = {}

        if user_input is not None:
            self.options.update(user_input)
            return await self.async_step_statistics_sensors()

        clients_to_block = {}

        for client in self.controller.api.clients.values():
            clients_to_block[
                client.
                mac] = f"{client.name or client.hostname} ({client.mac})"

        return self.async_show_form(
            step_id="client_control",
            data_schema=vol.Schema({
                vol.Optional(CONF_BLOCK_CLIENT,
                             default=self.options[CONF_BLOCK_CLIENT]):
                cv.multi_select(clients_to_block),
                vol.Optional(
                    CONF_POE_CLIENTS,
                    default=self.options.get(CONF_POE_CLIENTS, DEFAULT_POE_CLIENTS),
                ):
                bool,
                vol.Optional(
                    CONF_DPI_RESTRICTIONS,
                    default=self.options.get(CONF_DPI_RESTRICTIONS, DEFAULT_DPI_RESTRICTIONS),
                ):
                bool,
            }),
            errors=errors,
        )
Exemplo n.º 12
0
    async def async_step_systems(self, user_input=None):
        """Configure selected systems."""
        if user_input is not None:
            self.user_data[CONF_SYSTEMS] = {
                key: {}
                for key in user_input[CONF_SYSTEMS]
            }

            return self.async_create_entry(title="", data=self.user_data)

        systems = await self.uplink.get_systems()
        systems_dict = {
            str(x["systemId"]): f"{x['name']} ({x['productName']})"
            for x in systems
        }
        systems_sel = list(systems_dict.keys())

        return self.async_show_form(
            step_id="systems",
            description_placeholders={},
            data_schema=vol.Schema({
                vol.Required(CONF_SYSTEMS, default=systems_sel):
                cv.multi_select(systems_dict)
            }),
        )
Exemplo n.º 13
0
    async def async_step_init(self,
                              user_input: dict[str, Any] | None = None
                              ) -> FlowResult:
        """Manage the options."""
        errors = {}
        if user_input is not None:
            options_input = {CONF_SOURCES: user_input[CONF_SOURCES]}
            return self.async_create_entry(title="", data=options_input)
        # Get sources
        sources_list = await async_get_sources(self.host, self.key)
        if not sources_list:
            errors["base"] = "cannot_retrieve"

        sources = [
            s for s in self.options.get(CONF_SOURCES, []) if s in sources_list
        ]
        if not sources:
            sources = sources_list

        options_schema = vol.Schema({
            vol.Optional(
                CONF_SOURCES,
                description={"suggested_value": sources},
            ):
            cv.multi_select({source: source
                             for source in sources_list}),
        })

        return self.async_show_form(step_id="init",
                                    data_schema=options_schema,
                                    errors=errors)
    async def async_step_init(self, user_input=None):
        """Handle options flow."""
        if user_input is not None:
            return self.async_create_entry(title="", data=user_input)

        from pydigitalstrom import constants

        # build scene list for mutli select
        scenes = {}
        for scene_id, scene_name in constants.SCENE_NAMES.items():
            scenes[scene_name] = scene_name
        scenes = sorted(scenes)

        # build options based on multi select
        options = {
            vol.Optional(
                OPTION_GENERIC_SCENES,
                default=self.config_entry.options.get(
                    OPTION_GENERIC_SCENES, OPTION_GENERIC_SCENES_DEFAULT),
            ):
            config_validation.multi_select(scenes),
        }

        return self.async_show_form(step_id="init",
                                    data_schema=vol.Schema(options))
Exemplo n.º 15
0
    async def async_step_remove_devices(
            self,
            user_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """Handle the device removal step."""
        errors: Dict[str, str] = {}

        assert self.hass is not None

        devices: List[DeviceEntry] = await self.hass.async_create_task(
            _get_devices(cast(HomeAssistant, self.hass), self.config_entry))
        device_schema = vol.Schema({
            vol.Optional(CONF_DEVICES, default=[]):
            cv.multi_select({d.id: d.name
                             for d in devices}),
        })

        if user_input is not None:
            ids = [id for id in user_input[CONF_DEVICES]]
            await self.hass.async_create_task(
                _remove_devices(cast(HomeAssistant, self.hass), ids))
            return await self.async_step_override_lights()

        if len(errors) == 0:
            form_errors = None
        else:
            form_errors = errors

        return self.async_show_form(
            step_id=STEP_REMOVE_DEVICES,
            data_schema=device_schema,
            errors=form_errors,
        )
Exemplo n.º 16
0
    async def async_step_xiaoai(
            self,
            user_input=None,
            error=None):  # 本地发现不了设备,需要手动输入model,输入后再修改mapping,params
        errors = {}
        if user_input is not None:
            self._input2 = {**self._input2, **user_input}
            self._model = user_input[CONF_MODEL]
            # Line 240-270
            self._info = await guess_mp_from_model(self.hass, self._model)
            hint = ""
            if self._info and self._info.get('mapping') != "{}":
                hint += f"\n根据 model (**{self._model}**),已经自动发现配置参数。\n如无特殊需要,无需修改下列内容。\n"
                devtype_default = self._info.get('device_type')

                mp = self._info.get('mapping')
                prm = self._info.get('params')
                mapping_default = mp
                params_default = prm
            else:
                hint += f"很抱歉,未能自动发现配置参数。但这不代表您的设备不受支持。\n您可以[手工编写配置](https://github.com/ha0y/xiaomi_miot_raw/#文件配置法),或者将型号 **{self._model}** 报告给作者。"
                devtype_default = []
                mapping_default = '{"switch":{"switch_status":{"siid":2,"piid":1}}}'
                params_default = '{"switch":{"switch_status":{"power_on":true,"power_off":false}}}'

            if not self._non_interactive:
                return self.async_show_form(
                    step_id="devinfo",
                    data_schema=vol.Schema({
                        vol.Required('devtype', default=devtype_default):
                        cv.multi_select(SUPPORTED_DOMAINS),
                        vol.Required(CONF_MAPPING, default=mapping_default):
                        str,
                        vol.Required(CONF_CONTROL_PARAMS,
                                     default=params_default):
                        str,
                        vol.Optional('cloud_read', default=True):
                        bool,
                        vol.Optional('cloud_write', default=True):
                        bool,
                    }),
                    description_placeholders={"device_info": hint},
                    errors=errors,
                )
            else:
                return await self.async_step_devinfo({
                    'devtype': devtype_default,
                    CONF_MAPPING: mapping_default,
                    CONF_CONTROL_PARAMS: params_default,
                    'cloud_read': True,
                    'cloud_write': True,
                })

        return self.async_show_form(step_id='xiaoai',
                                    data_schema=vol.Schema({
                                        vol.Required(CONF_MODEL,
                                                     default=self._model):
                                        str,
                                    }),
                                    errors={'base': 'no_connect_warning'})
Exemplo n.º 17
0
    async def async_step_remove_devices(self,
                                        user_input: Optional[Dict[str,
                                                                  Any]] = None
                                        ) -> FlowResult:
        """Handle the device removal step."""
        errors: Dict[str, str] = {}

        assert self.hass is not None

        devices = _get_devices(self.hass, self.config_entry)
        device_map = {d.id: d.name for d in devices}
        device_schema = vol.Schema({
            vol.Optional(CONF_DEVICES, default=[]):
            cv.multi_select(device_map),
        })

        if user_input is not None:
            ids = [id for id in user_input[CONF_DEVICES]]
            _remove_devices(self.hass, ids)
            return await self.async_step_override_lights()

        if len(errors) == 0:
            form_errors = None
        else:
            form_errors = errors

        return self.async_show_form(
            step_id=STEP_REMOVE_DEVICES,
            data_schema=device_schema,
            errors=form_errors,
        )
Exemplo n.º 18
0
    async def async_step_select_devices(self, user_input=None):
        errors = {}
        if user_input is not None:
            for device in user_input['devices']:
                self.hass.async_add_job(
                    self.hass.config_entries.flow.async_init(
                        DOMAIN,
                        context={"source": "batch_add"},
                        data={'did': device}))
            return self.async_create_entry(title="", data=None)

        devlist = {}
        for device in self.hass.data[DOMAIN]['micloud_devices']:
            if device['did'] not in devlist:
                dt = get_conn_type(device)
                dt = "WiFi" if dt == 0 else "ZigBee" if dt == 1 else "BLE" if dt == 2 \
                                        else "BLE Mesh" if dt == 3 else "Unknown"
                name = f"{device['name']} ({dt}{', '+device['localip'] if (dt == '''WiFi''') else ''})"
                devlist[device['did']] = name
        return self.async_show_form(
            step_id='select_devices',
            data_schema=vol.Schema({
                vol.Required('devices', default=[]):
                cv.multi_select(devlist),
            }),
            errors=errors,
        )
Exemplo n.º 19
0
    async def async_step_public_weather_areas(self, user_input=None):
        """Manage configuration of Netatmo public weather areas."""
        errors = {}

        if user_input is not None:
            new_client = user_input.pop(CONF_NEW_AREA, None)
            areas = user_input.pop(CONF_WEATHER_AREAS, None)
            user_input[CONF_WEATHER_AREAS] = {
                area: self.options[CONF_WEATHER_AREAS][area]
                for area in areas
            }
            self.options.update(user_input)
            if new_client:
                return await self.async_step_public_weather(
                    user_input={CONF_NEW_AREA: new_client})

            return self._create_options_entry()

        weather_areas = list(self.options[CONF_WEATHER_AREAS])

        data_schema = vol.Schema({
            vol.Optional(
                CONF_WEATHER_AREAS,
                default=weather_areas,
            ):
            cv.multi_select(weather_areas),
            vol.Optional(CONF_NEW_AREA):
            str,
        })
        return self.async_show_form(
            step_id="public_weather_areas",
            data_schema=data_schema,
            errors=errors,
        )
Exemplo n.º 20
0
    async def async_step_init(self, user_input=None):
        """Handle options flow."""
        conf = self.config_entry
        if conf.source == config_entries.SOURCE_IMPORT:
            return self.async_show_form(step_id="init", data_schema={})
        errors = {}
        if user_input is not None:
            validate_options(user_input, errors)
            if not errors:
                return self.async_create_entry(title="", data=user_input)

        all_lights = [
            light for light in self.hass.states.async_entity_ids("light")
            if _supported_features(self.hass, light)
        ]
        to_replace = {CONF_LIGHTS: cv.multi_select(sorted(all_lights))}

        options_schema = {}
        for name, default, validation in VALIDATION_TUPLES:
            key = vol.Optional(name, default=conf.options.get(name, default))
            value = to_replace.get(name, validation)
            options_schema[key] = value

        return self.async_show_form(step_id="init",
                                    data_schema=vol.Schema(options_schema),
                                    errors=errors)
Exemplo n.º 21
0
    async def async_step_robots(self, user_input=None):
        """Handle the robots selection step."""

        errors = {}
        if user_input is not None:
            try:
                if len(user_input[CONF_DEVICEID]) < 1:
                    errors["base"] = "select_robots"
                else:
                    self.data[CONF_DEVICEID] = user_input
                    return self.async_create_entry(
                        title=self.data[CONF_USERNAME], data=self.data)
            except Exception:
                _LOGGER.exception("Unexpected exception")
                errors["base"] = "unknown"

        # If there is no user input or there were errors, show the form again, including any errors that were found with the input.
        robot_listDict = {e["name"]: e["nick"] for e in self.robot_list}
        options_schema = vol.Schema({
            vol.Required(CONF_DEVICEID, default=list(robot_listDict.keys())):
            cv.multi_select(robot_listDict)
        })

        return self.async_show_form(step_id="robots",
                                    data_schema=options_schema,
                                    errors=errors)
Exemplo n.º 22
0
    async def async_step_user(self, user_input=None):
        """Handle the initial step."""
        errors = {}
        if user_input is not None:
            port = await self._async_available_port()
            name = self._async_available_name()
            title = f"{name}:{port}"
            self.homekit_data = user_input.copy()
            self.homekit_data[CONF_NAME] = name
            self.homekit_data[CONF_PORT] = port
            self.homekit_data[CONF_FILTER] = {
                CONF_INCLUDE_DOMAINS: user_input[CONF_INCLUDE_DOMAINS],
                CONF_INCLUDE_ENTITIES: [],
                CONF_EXCLUDE_DOMAINS: [],
                CONF_EXCLUDE_ENTITIES: [],
            }
            del self.homekit_data[CONF_INCLUDE_DOMAINS]
            self.entry_title = title
            return await self.async_step_pairing()

        default_domains = [] if self._async_current_entries(
        ) else DEFAULT_DOMAINS
        setup_schema = vol.Schema({
            vol.Optional(CONF_AUTO_START, default=DEFAULT_AUTO_START):
            bool,
            vol.Required(CONF_INCLUDE_DOMAINS, default=default_domains):
            cv.multi_select(SUPPORTED_DOMAINS),
        })

        return self.async_show_form(step_id="user",
                                    data_schema=setup_schema,
                                    errors=errors)
Exemplo n.º 23
0
    async def async_step_include(self, user_input=None):
        """Choose entities to include from the domain on the bridge."""
        domains = self.hk_options[CONF_DOMAINS]
        if user_input is not None:
            entities = cv.ensure_list(user_input[CONF_ENTITIES])
            entity_filter = _async_build_entites_filter(domains, entities)
            self.included_cameras = _async_cameras_from_entities(entities)
            self.hk_options[CONF_FILTER] = entity_filter
            if self.included_cameras:
                return await self.async_step_cameras()
            return await self.async_step_advanced()

        entity_filter = self.hk_options.get(CONF_FILTER, {})
        entities = entity_filter.get(CONF_INCLUDE_ENTITIES, [])

        all_supported_entities = _async_get_matching_entities(
            self.hass, domains)
        if not entities:
            entities = entity_filter.get(CONF_EXCLUDE_ENTITIES, [])
        # Strip out entities that no longer exist to prevent error in the UI
        default_value = [
            entity_id for entity_id in entities
            if entity_id in all_supported_entities
        ]

        return self.async_show_form(
            step_id="include",
            description_placeholders={
                "domains": await _async_domain_names(self.hass, domains)
            },
            data_schema=vol.Schema({
                vol.Optional(CONF_ENTITIES, default=default_value):
                cv.multi_select(all_supported_entities)
            }),
        )
Exemplo n.º 24
0
    async def async_step_select_devices(self, user_input=None):
        errors = {}
        if user_input is not None:
            for device in user_input['devices']:
                self.hass.async_add_job(self.hass.config_entries.flow.async_init(
                    DOMAIN, context={"source": "batch_add"}, data={'did': device}
                ))
            return self.async_abort(reason="success")

        devlist = {}
        while not self.hass.data[DOMAIN]['micloud_devices']:
            await asyncio.sleep(1)
        for device in self.hass.data[DOMAIN]['micloud_devices']:
            if device['did'] not in devlist:
                dt = get_conn_type(device)
                dt = "WiFi" if dt == 0 else "ZigBee" if dt == 1 else "BLE" if dt == 2 \
                                        else "BLE Mesh" if dt == 3 else "InfraRed" if dt == 4 else "Unknown"
                name = f"{device['name']} ({dt}{', '+device['localip'] if (dt == '''WiFi''') else ''})"
                devlist[device['did']] = name
        return self.async_show_form(
            step_id='select_devices',
            data_schema=vol.Schema({
                vol.Required('devices', default=[]): cv.multi_select(devlist),
            }),
            description_placeholders={"dev_count": str(len(devlist))},
            errors=errors,
        )
Exemplo n.º 25
0
    async def async_step_init(
        self,
        user_input: dict[str, Any] | None = None,
    ) -> FlowResult:
        """Handle options flow."""
        if not user_input:
            configured_repositories: list[str] = self.config_entry.options[
                CONF_REPOSITORIES
            ]
            repositories = await get_repositories(
                self.hass, self.config_entry.data[CONF_ACCESS_TOKEN]
            )

            # In case the user has removed a starred repository that is already tracked
            for repository in configured_repositories:
                if repository not in repositories:
                    repositories.append(repository)

            return self.async_show_form(
                step_id="init",
                data_schema=vol.Schema(
                    {
                        vol.Required(
                            CONF_REPOSITORIES,
                            default=configured_repositories,
                        ): cv.multi_select({k: k for k in repositories}),
                    }
                ),
            )

        return self.async_create_entry(title="", data=user_input)
Exemplo n.º 26
0
    async def async_step_cameras(self, user_input=None):
        """Choose camera config."""
        if user_input is not None:
            entity_config = self.hk_options[CONF_ENTITY_CONFIG]
            for entity_id in self.included_cameras:
                if entity_id in user_input[CONF_CAMERA_COPY]:
                    entity_config.setdefault(
                        entity_id, {})[CONF_VIDEO_CODEC] = VIDEO_CODEC_COPY
                elif (entity_id in entity_config
                      and CONF_VIDEO_CODEC in entity_config[entity_id]):
                    del entity_config[entity_id][CONF_VIDEO_CODEC]
            return await self.async_step_advanced()

        cameras_with_copy = []
        entity_config = self.hk_options.setdefault(CONF_ENTITY_CONFIG, {})
        for entity in self.included_cameras:
            hk_entity_config = entity_config.get(entity, {})
            if hk_entity_config.get(CONF_VIDEO_CODEC) == VIDEO_CODEC_COPY:
                cameras_with_copy.append(entity)

        data_schema = vol.Schema({
            vol.Optional(
                CONF_CAMERA_COPY,
                default=cameras_with_copy,
            ):
            cv.multi_select(self.included_cameras),
        })
        return self.async_show_form(step_id="cameras", data_schema=data_schema)
Exemplo n.º 27
0
    async def async_step_include_domains(
            self,
            user_input: ConfigType | None = None
    ) -> data_entry_flow.FlowResult:
        yaml_config = await async_integration_yaml_config(self.hass, DOMAIN)
        if DOMAIN in yaml_config and not is_config_filter_empty(
                yaml_config[DOMAIN]):
            return await self.async_step_include_domains_yaml()

        if user_input is not None:
            self._options.update(user_input)
            return await self.async_step_include_exclude()

        entity_filter = self._options.get(const.CONF_FILTER, {})
        domains = entity_filter.get(CONF_INCLUDE_DOMAINS, [])
        include_entities = entity_filter.get(CONF_INCLUDE_ENTITIES)
        if include_entities:
            domains.extend(_domains_set_from_entities(include_entities))
        name_to_type_map = await _async_name_to_type_map(self.hass)

        return self.async_show_form(
            step_id='include_domains',
            data_schema=vol.Schema({
                vol.Required(CONF_DOMAINS, default=sorted(set(domains))):
                cv.multi_select(name_to_type_map),
            }),
        )
Exemplo n.º 28
0
    async def async_step_cloud(self, user_input=None, error=None):
        if user_input:
            if not user_input['servers']:
                return await self.async_step_cloud(error='no_servers')

            session = async_create_clientsession(self.hass)
            cloud = MiCloud(session)
            if await cloud.login(user_input['username'],
                                 user_input['password']):
                user_input.update(cloud.auth)
                return self.async_create_entry(title=user_input['username'],
                                               data=user_input)

            else:
                return await self.async_step_cloud(error='cant_login')

        return self.async_show_form(
            step_id='cloud',
            data_schema=vol.Schema({
                vol.Required('username'): str,
                vol.Required('password'): str,
                vol.Required('servers', default=['cn']):
                    cv.multi_select(SERVERS)
            }),
            errors={'base': error} if error else None
        )
Exemplo n.º 29
0
    async def async_step_init(self, user_input=None):
        """Handle options flow."""
        if self.config_entry.source == SOURCE_IMPORT:
            return await self.async_step_yaml(user_input)

        if user_input is not None:
            self.hk_options.update(user_input)
            return await self.async_step_include_exclude()

        self.hk_options = dict(self.config_entry.options)
        entity_filter = self.hk_options.get(CONF_FILTER, {})
        homekit_mode = self.hk_options.get(CONF_HOMEKIT_MODE, DEFAULT_HOMEKIT_MODE)
        domains = entity_filter.get(CONF_INCLUDE_DOMAINS, [])
        include_entities = entity_filter.get(CONF_INCLUDE_ENTITIES)
        if include_entities:
            domains.extend(_domains_set_from_entities(include_entities))
        name_to_type_map = await _async_name_to_type_map(self.hass)

        return self.async_show_form(
            step_id="init",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_HOMEKIT_MODE, default=homekit_mode): vol.In(
                        HOMEKIT_MODES
                    ),
                    vol.Required(
                        CONF_DOMAINS,
                        default=domains,
                    ): cv.multi_select(name_to_type_map),
                }
            ),
        )
Exemplo n.º 30
0
    async def async_step_init(self, user_input=None):
        """Manage options."""
        if user_input is not None:
            if not is_ip_address(user_input.get(CONF_HOST)):
                return self.async_abort(reason="connection_error")
            self._host = user_input.get(CONF_HOST)
            if len(user_input.get(CONF_PASSWORD, "")) >= 1:
                self._password = user_input.get(CONF_PASSWORD)
            return self.async_create_entry(
                title='',
                data={
                    CONF_HOST: self._host,
                    CONF_PASSWORD: self._password,
                    CONF_MODEL: self._model
                },
            )
        self._host = self.config_entry.options[CONF_HOST]
        self._password = self.config_entry.options[CONF_PASSWORD]
        self._model = self.config_entry.options.get(CONF_MODEL, '')
        debug = self.config_entry.options.get(CONF_DEBUG, [])

        return self.async_show_form(
            step_id="init",
            data_schema=vol.Schema({
                vol.Required(CONF_HOST, default=self._host):
                str,
                vol.Optional(CONF_PASSWORD, default=self._password):
                str,
                vol.Optional(CONF_MODEL):
                vol.In(OPT_DEVICE_NAME),
                vol.Optional(CONF_DEBUG, default=debug):
                cv.multi_select(OPT_DEBUG),
            }),
        )