Example #1
0
 def __init__(
     self,
     opp,
     device_id,
     friendly_name,
     state_template,
     icon_template,
     entity_picture_template,
     availability_template,
     on_action,
     off_action,
     unique_id,
 ):
     """Initialize the Template switch."""
     super().__init__(
         availability_template=availability_template,
         icon_template=icon_template,
         entity_picture_template=entity_picture_template,
     )
     self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id, opp=opp)
     self._name = friendly_name
     self._template = state_template
     domain = __name__.split(".")[-2]
     self._on_script = Script(opp, on_action, friendly_name, domain)
     self._off_script = Script(opp, off_action, friendly_name, domain)
     self._state = False
     self._unique_id = unique_id
Example #2
0
    def __init__(self, opp, object_id, cfg, raw_config, blueprint_inputs):
        """Initialize the script."""
        self.object_id = object_id
        self.icon = cfg.get(CONF_ICON)
        self.description = cfg[CONF_DESCRIPTION]
        self.fields = cfg[CONF_FIELDS]

        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self.script = Script(
            opp,
            cfg[CONF_SEQUENCE],
            cfg.get(CONF_ALIAS, object_id),
            DOMAIN,
            running_description="script sequence",
            change_listener=self.async_change_listener,
            script_mode=cfg[CONF_MODE],
            max_runs=cfg[CONF_MAX],
            max_exceeded=cfg[CONF_MAX_EXCEEDED],
            logger=logging.getLogger(f"{__name__}.{object_id}"),
            variables=cfg.get(CONF_VARIABLES),
        )
        self._changed = asyncio.Event()
        self._raw_config = raw_config
        self._trace_config = cfg[CONF_TRACE]
        self._blueprint_inputs = blueprint_inputs
Example #3
0
async def async_setup_entry(opp, entry, async_add_entities):
    """Set up the Samsung TV from a config entry."""
    bridge = opp.data[DOMAIN][entry.entry_id]

    host = entry.data[CONF_HOST]
    on_script = None
    data = opp.data[DOMAIN]
    if turn_on_action := data.get(host, {}).get(CONF_ON_ACTION):
        on_script = Script(
            opp, turn_on_action, entry.data.get(CONF_NAME, DEFAULT_NAME), DOMAIN
        )
Example #4
0
 def __init__(
     self,
     opp,
     name,
     value_template,
     availability_template,
     command_lock,
     command_unlock,
     optimistic,
     unique_id,
 ):
     """Initialize the lock."""
     super().__init__(availability_template=availability_template)
     self._state = None
     self._name = name
     self._state_template = value_template
     domain = __name__.split(".")[-2]
     self._command_lock = Script(opp, command_lock, name, domain)
     self._command_unlock = Script(opp, command_unlock, name, domain)
     self._optimistic = optimistic
     self._unique_id = unique_id
Example #5
0
    def __init__(
        self,
        opp,
        device_id,
        name,
        state_template,
        disarm_action,
        arm_away_action,
        arm_home_action,
        arm_night_action,
        code_arm_required,
        unique_id,
    ):
        """Initialize the panel."""
        super().__init__()
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT,
                                                  device_id,
                                                  opp=opp)
        self._name = name
        self._template = state_template
        self._disarm_script = None
        self._code_arm_required = code_arm_required
        domain = __name__.split(".")[-2]
        if disarm_action is not None:
            self._disarm_script = Script(opp, disarm_action, name, domain)
        self._arm_away_script = None
        if arm_away_action is not None:
            self._arm_away_script = Script(opp, arm_away_action, name, domain)
        self._arm_home_script = None
        if arm_home_action is not None:
            self._arm_home_script = Script(opp, arm_home_action, name, domain)
        self._arm_night_script = None
        if arm_night_action is not None:
            self._arm_night_script = Script(opp, arm_night_action, name,
                                            domain)

        self._state = None
        self._unique_id = unique_id
Example #6
0
async def handle_execute_script(opp: OpenPeerPower,
                                connection: ActiveConnection,
                                msg: dict[str, Any]) -> None:
    """Handle execute script command."""
    # Circular dep
    # pylint: disable=import-outside-toplevel
    from openpeerpower.helpers.script import Script

    context = connection.context(msg)
    script_obj = Script(opp, msg["sequence"], f"{const.DOMAIN} script",
                        const.DOMAIN)
    await script_obj.async_run(msg.get("variables"), context=context)
    connection.send_message(
        messages.result_message(msg["id"], {"context": context}))
Example #7
0
 def __init__(
     self,
     opp,
     name,
     host,
     mac_address,
     off_action,
     broadcast_address,
     broadcast_port,
 ):
     """Initialize the WOL switch."""
     self._opp = opp
     self._name = name
     self._host = host
     self._mac_address = mac_address
     self._broadcast_address = broadcast_address
     self._broadcast_port = broadcast_port
     domain = __name__.split(".")[-2]
     self._off_script = Script(opp, off_action, name,
                               domain) if off_action else None
     self._state = False
     self._assumed_state = host is None
     self._unique_id = dr.format_mac(mac_address)
Example #8
0
def setup_platform(opp, config, add_entities, discovery_info=None):
    """Set up the LG TV platform."""

    host = config.get(CONF_HOST)
    access_token = config.get(CONF_ACCESS_TOKEN)
    name = config.get(CONF_NAME)
    on_action = config.get(CONF_ON_ACTION)

    client = LgNetCastClient(host, access_token)
    domain = __name__.split(".")[-2]
    on_action_script = Script(opp, on_action, name,
                              domain) if on_action else None

    add_entities([LgTVDevice(client, name, on_action_script)], True)
Example #9
0
async def async_setup_platform(opp, config, async_add_entities, discovery_info=None):
    """Set up the LG webOS Smart TV platform."""

    if discovery_info is None:
        return

    host = discovery_info[CONF_HOST]
    name = discovery_info[CONF_NAME]
    customize = discovery_info[CONF_CUSTOMIZE]
    turn_on_action = discovery_info.get(CONF_ON_ACTION)

    client = opp.data[DOMAIN][host]["client"]
    on_script = Script(opp, turn_on_action, name, DOMAIN) if turn_on_action else None

    entity = LgWebOSMediaPlayerEntity(client, name, customize, on_script)

    async_add_entities([entity], update_before_add=False)
Example #10
0
async def async_setup_entry(opp, config_entry):
    """Set up Panasonic Viera from a config entry."""
    panasonic_viera_data = opp.data.setdefault(DOMAIN, {})

    config = config_entry.data

    host = config[CONF_HOST]
    port = config[CONF_PORT]

    on_action = config[CONF_ON_ACTION]
    if on_action is not None:
        on_action = Script(opp, on_action, config[CONF_NAME], DOMAIN)

    params = {}
    if CONF_APP_ID in config and CONF_ENCRYPTION_KEY in config:
        params["app_id"] = config[CONF_APP_ID]
        params["encryption_key"] = config[CONF_ENCRYPTION_KEY]

    remote = Remote(opp, host, port, on_action, **params)
    await remote.async_create_remote_control(during_setup=True)

    panasonic_viera_data[config_entry.entry_id] = {ATTR_REMOTE: remote}

    # Add device_info to older config entries
    if ATTR_DEVICE_INFO not in config or config[ATTR_DEVICE_INFO] is None:
        device_info = await remote.async_get_device_info()
        unique_id = config_entry.unique_id
        if device_info is None:
            _LOGGER.error(
                "Couldn't gather device info; Please restart Open Peer Power with your TV turned on and connected to your network"
            )
        else:
            unique_id = device_info[ATTR_UDN]
        opp.config_entries.async_update_entry(
            config_entry,
            unique_id=unique_id,
            data={
                **config, ATTR_DEVICE_INFO: device_info
            },
        )

    opp.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    return True
Example #11
0
class WolSwitch(SwitchEntity):
    """Representation of a wake on lan switch."""
    def __init__(
        self,
        opp,
        name,
        host,
        mac_address,
        off_action,
        broadcast_address,
        broadcast_port,
    ):
        """Initialize the WOL switch."""
        self._opp = opp
        self._name = name
        self._host = host
        self._mac_address = mac_address
        self._broadcast_address = broadcast_address
        self._broadcast_port = broadcast_port
        domain = __name__.split(".")[-2]
        self._off_script = Script(opp, off_action, name,
                                  domain) if off_action else None
        self._state = False
        self._assumed_state = host is None
        self._unique_id = dr.format_mac(mac_address)

    @property
    def is_on(self):
        """Return true if switch is on."""
        return self._state

    @property
    def name(self):
        """Return the name of the switch."""
        return self._name

    @property
    def assumed_state(self):
        """Return true if no host is provided."""
        return self._assumed_state

    @property
    def should_poll(self):
        """Return false if assumed state is true."""
        return not self._assumed_state

    @property
    def unique_id(self):
        """Return the unique id of this switch."""
        return self._unique_id

    def turn_on(self, **kwargs):
        """Turn the device on."""
        service_kwargs = {}
        if self._broadcast_address is not None:
            service_kwargs["ip_address"] = self._broadcast_address
        if self._broadcast_port is not None:
            service_kwargs["port"] = self._broadcast_port

        _LOGGER.info(
            "Send magic packet to mac %s (broadcast: %s, port: %s)",
            self._mac_address,
            self._broadcast_address,
            self._broadcast_port,
        )

        wakeonlan.send_magic_packet(self._mac_address, **service_kwargs)

        if self._assumed_state:
            self._state = True
            self.async_write_op_state()

    def turn_off(self, **kwargs):
        """Turn the device off if an off action is present."""
        if self._off_script is not None:
            self._off_script.run(context=self._context)

        if self._assumed_state:
            self._state = False
            self.async_write_op_state()

    def update(self):
        """Check if device is on and update the state. Only called if assumed state is false."""
        if platform.system().lower() == "windows":
            ping_cmd = [
                "ping",
                "-n",
                "1",
                "-w",
                str(DEFAULT_PING_TIMEOUT * 1000),
                str(self._host),
            ]
        else:
            ping_cmd = [
                "ping",
                "-c",
                "1",
                "-W",
                str(DEFAULT_PING_TIMEOUT),
                str(self._host),
            ]

        status = sp.call(ping_cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
        self._state = not bool(status)
Example #12
0
    def __init__(
        self,
        opp,
        device_id,
        friendly_name,
        state_template,
        icon_template,
        entity_picture_template,
        availability_template,
        on_action,
        off_action,
        level_action,
        level_template,
        temperature_action,
        temperature_template,
        color_action,
        color_template,
        white_value_action,
        white_value_template,
        effect_action,
        effect_list_template,
        effect_template,
        max_mireds_template,
        min_mireds_template,
        supports_transition_template,
        unique_id,
    ):
        """Initialize the light."""
        super().__init__(
            availability_template=availability_template,
            icon_template=icon_template,
            entity_picture_template=entity_picture_template,
        )
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id, opp=opp)
        self._name = friendly_name
        self._template = state_template
        domain = __name__.split(".")[-2]
        self._on_script = Script(opp, on_action, friendly_name, domain)
        self._off_script = Script(opp, off_action, friendly_name, domain)
        self._level_script = None
        if level_action is not None:
            self._level_script = Script(opp, level_action, friendly_name, domain)
        self._level_template = level_template
        self._temperature_script = None
        if temperature_action is not None:
            self._temperature_script = Script(
                opp, temperature_action, friendly_name, domain
            )
        self._temperature_template = temperature_template
        self._color_script = None
        if color_action is not None:
            self._color_script = Script(opp, color_action, friendly_name, domain)
        self._color_template = color_template
        self._white_value_script = None
        if white_value_action is not None:
            self._white_value_script = Script(
                opp, white_value_action, friendly_name, domain
            )
        self._white_value_template = white_value_template
        self._effect_script = None
        if effect_action is not None:
            self._effect_script = Script(opp, effect_action, friendly_name, domain)
        self._effect_list_template = effect_list_template
        self._effect_template = effect_template
        self._max_mireds_template = max_mireds_template
        self._min_mireds_template = min_mireds_template
        self._supports_transition_template = supports_transition_template

        self._state = False
        self._brightness = None
        self._temperature = None
        self._color = None
        self._white_value = None
        self._effect = None
        self._effect_list = None
        self._max_mireds = None
        self._min_mireds = None
        self._supports_transition = False
        self._unique_id = unique_id
Example #13
0
 def __init__(self, opp, object_id, name, icon, sequence):
     """Initialize the script."""
     self.object_id = object_id
     self.icon = icon
     self.entity_id = ENTITY_ID_FORMAT.format(object_id)
     self.script = Script(opp, sequence, name, self.async_update_op_state)
Example #14
0
class ScriptEntity(ToggleEntity):
    """Representation of a script entity."""

    icon = None

    def __init__(self, opp, object_id, name, icon, sequence):
        """Initialize the script."""
        self.object_id = object_id
        self.icon = icon
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self.script = Script(opp, sequence, name, self.async_update_op_state)

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def name(self):
        """Return the name of the entity."""
        return self.script.name

    @property
    def state_attributes(self):
        """Return the state attributes."""
        attrs = {}
        attrs[ATTR_LAST_TRIGGERED] = self.script.last_triggered
        if self.script.can_cancel:
            attrs[ATTR_CAN_CANCEL] = self.script.can_cancel
        if self.script.last_action:
            attrs[ATTR_LAST_ACTION] = self.script.last_action
        return attrs

    @property
    def is_on(self):
        """Return true if script is on."""
        return self.script.is_running

    async def async_turn_on(self, **kwargs):
        """Turn the script on."""
        context = kwargs.get("context")
        self.async_set_context(context)
        self.opp.bus.async_fire(
            EVENT_SCRIPT_STARTED,
            {
                ATTR_NAME: self.script.name,
                ATTR_ENTITY_ID: self.entity_id
            },
            context=context,
        )
        try:
            await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
        except Exception as err:
            self.script.async_log_exception(
                _LOGGER, f"Error executing script {self.entity_id}", err)
            raise err

    async def async_turn_off(self, **kwargs):
        """Turn script off."""
        self.script.async_stop()

    async def async_will_remove_from_opp(self):
        """Stop script and remove service when it will be removed from Open Peer Power."""
        if self.script.is_running:
            self.script.async_stop()

        # remove service
        self.opp.services.async_remove(DOMAIN, self.object_id)
Example #15
0
async def _async_process_config(
    opp: OpenPeerPower,
    config: dict[str, Any],
    component: EntityComponent,
) -> bool:
    """Process config and add automations.

    Returns if blueprints were used.
    """
    entities = []
    blueprints_used = False

    for config_key in extract_domain_configs(config, DOMAIN):
        conf: list[dict[str, Any] | blueprint.BlueprintInputs] = config[config_key]

        for list_no, config_block in enumerate(conf):
            raw_blueprint_inputs = None
            raw_config = None
            if isinstance(config_block, blueprint.BlueprintInputs):
                blueprints_used = True
                blueprint_inputs = config_block
                raw_blueprint_inputs = blueprint_inputs.config_with_inputs

                try:
                    raw_config = blueprint_inputs.async_substitute()
                    config_block = cast(
                        Dict[str, Any],
                        await async_validate_config_item(opp, raw_config),
                    )
                except vol.Invalid as err:
                    LOGGER.error(
                        "Blueprint %s generated invalid automation with inputs %s: %s",
                        blueprint_inputs.blueprint.name,
                        blueprint_inputs.inputs,
                        humanize_error(config_block, err),
                    )
                    continue
            else:
                raw_config = cast(AutomationConfig, config_block).raw_config

            automation_id = config_block.get(CONF_ID)
            name = config_block.get(CONF_ALIAS) or f"{config_key} {list_no}"

            initial_state = config_block.get(CONF_INITIAL_STATE)

            action_script = Script(
                opp,
                config_block[CONF_ACTION],
                name,
                DOMAIN,
                running_description="automation actions",
                script_mode=config_block[CONF_MODE],
                max_runs=config_block[CONF_MAX],
                max_exceeded=config_block[CONF_MAX_EXCEEDED],
                logger=LOGGER,
                # We don't pass variables here
                # Automation will already render them to use them in the condition
                # and so will pass them on to the script.
            )

            if CONF_CONDITION in config_block:
                cond_func = await _async_process_if(opp, name, config, config_block)

                if cond_func is None:
                    continue
            else:
                cond_func = None

            # Add trigger variables to variables
            variables = None
            if CONF_TRIGGER_VARIABLES in config_block:
                variables = ScriptVariables(
                    dict(config_block[CONF_TRIGGER_VARIABLES].as_dict())
                )
            if CONF_VARIABLES in config_block:
                if variables:
                    variables.variables.update(config_block[CONF_VARIABLES].as_dict())
                else:
                    variables = config_block[CONF_VARIABLES]

            entity = AutomationEntity(
                automation_id,
                name,
                config_block[CONF_TRIGGER],
                cond_func,
                action_script,
                initial_state,
                variables,
                config_block.get(CONF_TRIGGER_VARIABLES),
                raw_config,
                raw_blueprint_inputs,
                config_block[CONF_TRACE],
            )

            entities.append(entity)

    if entities:
        await component.async_add_entities(entities)

    return blueprints_used
Example #16
0
 def __init__(
     self,
     opp,
     device_id,
     friendly_name,
     device_class,
     state_template,
     position_template,
     tilt_template,
     icon_template,
     entity_picture_template,
     availability_template,
     open_action,
     close_action,
     stop_action,
     position_action,
     tilt_action,
     optimistic,
     tilt_optimistic,
     unique_id,
 ):
     """Initialize the Template cover."""
     super().__init__(
         availability_template=availability_template,
         icon_template=icon_template,
         entity_picture_template=entity_picture_template,
     )
     self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT,
                                               device_id,
                                               opp=opp)
     self._name = friendly_name
     self._template = state_template
     self._position_template = position_template
     self._tilt_template = tilt_template
     self._device_class = device_class
     self._open_script = None
     domain = __name__.split(".")[-2]
     if open_action is not None:
         self._open_script = Script(opp, open_action, friendly_name, domain)
     self._close_script = None
     if close_action is not None:
         self._close_script = Script(opp, close_action, friendly_name,
                                     domain)
     self._stop_script = None
     if stop_action is not None:
         self._stop_script = Script(opp, stop_action, friendly_name, domain)
     self._position_script = None
     if position_action is not None:
         self._position_script = Script(opp, position_action, friendly_name,
                                        domain)
     self._tilt_script = None
     if tilt_action is not None:
         self._tilt_script = Script(opp, tilt_action, friendly_name, domain)
     self._optimistic = optimistic or (not state_template
                                       and not position_template)
     self._tilt_optimistic = tilt_optimistic or not tilt_template
     self._position = None
     self._is_opening = False
     self._is_closing = False
     self._tilt_value = None
     self._unique_id = unique_id
Example #17
0
    def __init__(
        self,
        opp,
        device_id,
        friendly_name,
        state_template,
        battery_level_template,
        fan_speed_template,
        availability_template,
        start_action,
        pause_action,
        stop_action,
        return_to_base_action,
        clean_spot_action,
        locate_action,
        set_fan_speed_action,
        fan_speed_list,
        attribute_templates,
        unique_id,
    ):
        """Initialize the vacuum."""
        super().__init__(
            attribute_templates=attribute_templates,
            availability_template=availability_template,
        )
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id, opp=opp)
        self._name = friendly_name

        self._template = state_template
        self._battery_level_template = battery_level_template
        self._fan_speed_template = fan_speed_template
        self._supported_features = SUPPORT_START

        domain = __name__.split(".")[-2]

        self._start_script = Script(opp, start_action, friendly_name, domain)

        self._pause_script = None
        if pause_action:
            self._pause_script = Script(opp, pause_action, friendly_name, domain)
            self._supported_features |= SUPPORT_PAUSE

        self._stop_script = None
        if stop_action:
            self._stop_script = Script(opp, stop_action, friendly_name, domain)
            self._supported_features |= SUPPORT_STOP

        self._return_to_base_script = None
        if return_to_base_action:
            self._return_to_base_script = Script(
                opp, return_to_base_action, friendly_name, domain
            )
            self._supported_features |= SUPPORT_RETURN_HOME

        self._clean_spot_script = None
        if clean_spot_action:
            self._clean_spot_script = Script(
                opp, clean_spot_action, friendly_name, domain
            )
            self._supported_features |= SUPPORT_CLEAN_SPOT

        self._locate_script = None
        if locate_action:
            self._locate_script = Script(opp, locate_action, friendly_name, domain)
            self._supported_features |= SUPPORT_LOCATE

        self._set_fan_speed_script = None
        if set_fan_speed_action:
            self._set_fan_speed_script = Script(
                opp, set_fan_speed_action, friendly_name, domain
            )
            self._supported_features |= SUPPORT_FAN_SPEED

        self._state = None
        self._battery_level = None
        self._fan_speed = None

        if self._template:
            self._supported_features |= SUPPORT_STATE
        if self._battery_level_template:
            self._supported_features |= SUPPORT_BATTERY

        self._unique_id = unique_id

        # List of valid fan speeds
        self._fan_speed_list = fan_speed_list
Example #18
0
    def __init__(
        self,
        opp,
        device_id,
        friendly_name,
        state_template,
        speed_template,
        percentage_template,
        preset_mode_template,
        oscillating_template,
        direction_template,
        availability_template,
        on_action,
        off_action,
        set_speed_action,
        set_percentage_action,
        set_preset_mode_action,
        set_oscillating_action,
        set_direction_action,
        speed_count,
        speed_list,
        preset_modes,
        unique_id,
    ):
        """Initialize the fan."""
        super().__init__(availability_template=availability_template)
        self.opp = opp
        self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT,
                                                  device_id,
                                                  opp=opp)
        self._name = friendly_name

        self._template = state_template
        self._speed_template = speed_template
        self._percentage_template = percentage_template
        self._preset_mode_template = preset_mode_template
        self._oscillating_template = oscillating_template
        self._direction_template = direction_template
        self._supported_features = 0

        domain = __name__.split(".")[-2]

        self._on_script = Script(opp, on_action, friendly_name, domain)
        self._off_script = Script(opp, off_action, friendly_name, domain)

        self._set_speed_script = None
        if set_speed_action:
            self._set_speed_script = Script(opp, set_speed_action,
                                            friendly_name, domain)

        self._set_percentage_script = None
        if set_percentage_action:
            self._set_percentage_script = Script(opp, set_percentage_action,
                                                 friendly_name, domain)

        self._set_preset_mode_script = None
        if set_preset_mode_action:
            self._set_preset_mode_script = Script(opp, set_preset_mode_action,
                                                  friendly_name, domain)

        self._set_oscillating_script = None
        if set_oscillating_action:
            self._set_oscillating_script = Script(opp, set_oscillating_action,
                                                  friendly_name, domain)

        self._set_direction_script = None
        if set_direction_action:
            self._set_direction_script = Script(opp, set_direction_action,
                                                friendly_name, domain)

        self._state = STATE_OFF
        self._speed = None
        self._percentage = None
        self._preset_mode = None
        self._oscillating = None
        self._direction = None

        if (self._speed_template or self._percentage_template
                or self._preset_mode_template):
            self._supported_features |= SUPPORT_SET_SPEED
        if self._oscillating_template:
            self._supported_features |= SUPPORT_OSCILLATE
        if self._direction_template:
            self._supported_features |= SUPPORT_DIRECTION

        self._unique_id = unique_id

        # Number of valid speeds
        self._speed_count = speed_count

        # List of valid speeds
        self._speed_list = speed_list

        # List of valid preset modes
        self._preset_modes = preset_modes