2019-04-03 15:40:03 +00:00
|
|
|
"""Support for custom shell commands to turn a switch on/off."""
|
2021-12-28 20:56:38 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
import asyncio
|
|
|
|
from datetime import timedelta
|
2022-02-12 14:19:37 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2016-09-02 14:09:09 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2017-08-08 20:36:59 +00:00
|
|
|
from homeassistant.components.switch import (
|
2023-05-29 06:00:50 +00:00
|
|
|
DOMAIN as SWITCH_DOMAIN,
|
2019-07-31 19:25:30 +00:00
|
|
|
ENTITY_ID_FORMAT,
|
2019-12-08 16:55:57 +00:00
|
|
|
PLATFORM_SCHEMA,
|
2020-04-26 16:50:37 +00:00
|
|
|
SwitchEntity,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2016-09-02 14:09:09 +00:00
|
|
|
from homeassistant.const import (
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_COMMAND_OFF,
|
|
|
|
CONF_COMMAND_ON,
|
|
|
|
CONF_COMMAND_STATE,
|
2019-12-08 16:55:57 +00:00
|
|
|
CONF_FRIENDLY_NAME,
|
2023-05-08 08:19:37 +00:00
|
|
|
CONF_ICON,
|
2021-12-03 18:06:32 +00:00
|
|
|
CONF_ICON_TEMPLATE,
|
2023-05-08 08:19:37 +00:00
|
|
|
CONF_NAME,
|
2023-06-03 03:35:11 +00:00
|
|
|
CONF_SCAN_INTERVAL,
|
2019-12-08 16:55:57 +00:00
|
|
|
CONF_SWITCHES,
|
2022-01-03 10:44:47 +00:00
|
|
|
CONF_UNIQUE_ID,
|
2019-12-08 16:55:57 +00:00
|
|
|
CONF_VALUE_TEMPLATE,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2019-12-08 16:55:57 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
2023-06-03 03:35:11 +00:00
|
|
|
from homeassistant.helpers.event import async_track_time_interval
|
2023-05-29 06:00:50 +00:00
|
|
|
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
|
2022-02-12 14:19:37 +00:00
|
|
|
from homeassistant.helpers.template import Template
|
2023-05-08 08:19:37 +00:00
|
|
|
from homeassistant.helpers.template_entity import ManualTriggerEntity
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
2023-06-12 19:50:23 +00:00
|
|
|
from homeassistant.util import dt as dt_util, slugify
|
2015-09-15 05:56:08 +00:00
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN, LOGGER
|
2023-03-27 19:19:09 +00:00
|
|
|
from .utils import call_shell_with_timeout, check_output_or_log
|
2020-08-05 03:00:02 +00:00
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
SCAN_INTERVAL = timedelta(seconds=30)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
SWITCH_SCHEMA = vol.Schema(
|
|
|
|
{
|
|
|
|
vol.Optional(CONF_COMMAND_OFF, default="true"): cv.string,
|
|
|
|
vol.Optional(CONF_COMMAND_ON, default="true"): cv.string,
|
|
|
|
vol.Optional(CONF_COMMAND_STATE): cv.string,
|
|
|
|
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
|
|
|
|
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
2021-12-03 18:06:32 +00:00
|
|
|
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
|
2020-08-05 03:00:02 +00:00
|
|
|
vol.Optional(CONF_COMMAND_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
|
2022-01-03 10:44:47 +00:00
|
|
|
vol.Optional(CONF_UNIQUE_ID): cv.string,
|
2019-07-31 19:25:30 +00:00
|
|
|
}
|
|
|
|
)
|
2016-09-02 14:09:09 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
|
|
|
|
)
|
2016-09-02 14:09:09 +00:00
|
|
|
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
async def async_setup_platform(
|
2021-12-28 20:56:38 +00:00
|
|
|
hass: HomeAssistant,
|
|
|
|
config: ConfigType,
|
2023-03-27 19:19:09 +00:00
|
|
|
async_add_entities: AddEntitiesCallback,
|
2021-12-28 20:56:38 +00:00
|
|
|
discovery_info: DiscoveryInfoType | None = None,
|
|
|
|
) -> None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Find and return switches controlled by shell commands."""
|
2020-08-26 00:52:36 +00:00
|
|
|
|
2023-05-29 06:00:50 +00:00
|
|
|
if discovery_info:
|
|
|
|
entities: dict[str, Any] = {slugify(discovery_info[CONF_NAME]): discovery_info}
|
|
|
|
else:
|
|
|
|
async_create_issue(
|
|
|
|
hass,
|
|
|
|
DOMAIN,
|
|
|
|
"deprecated_yaml_switch",
|
2023-06-29 09:59:36 +00:00
|
|
|
breaks_in_ha_version="2023.12.0",
|
2023-05-29 06:00:50 +00:00
|
|
|
is_fixable=False,
|
|
|
|
severity=IssueSeverity.WARNING,
|
|
|
|
translation_key="deprecated_platform_yaml",
|
|
|
|
translation_placeholders={"platform": SWITCH_DOMAIN},
|
|
|
|
)
|
|
|
|
entities = config.get(CONF_SWITCHES, {})
|
2020-08-26 00:52:36 +00:00
|
|
|
|
2016-09-02 14:09:09 +00:00
|
|
|
switches = []
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-05-29 06:00:50 +00:00
|
|
|
for object_id, device_config in entities.items():
|
|
|
|
if name := device_config.get(
|
|
|
|
CONF_FRIENDLY_NAME
|
|
|
|
): # Backward compatibility. Can be removed after deprecation
|
|
|
|
device_config[CONF_NAME] = name
|
|
|
|
|
|
|
|
if icon := device_config.get(
|
|
|
|
CONF_ICON_TEMPLATE
|
|
|
|
): # Backward compatibility. Can be removed after deprecation
|
|
|
|
device_config[CONF_ICON] = icon
|
|
|
|
|
2023-05-08 08:19:37 +00:00
|
|
|
trigger_entity_config = {
|
|
|
|
CONF_UNIQUE_ID: device_config.get(CONF_UNIQUE_ID),
|
2023-05-29 06:00:50 +00:00
|
|
|
CONF_NAME: Template(device_config.get(CONF_NAME, object_id), hass),
|
|
|
|
CONF_ICON: device_config.get(CONF_ICON),
|
2023-05-08 08:19:37 +00:00
|
|
|
}
|
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
value_template: Template | None = device_config.get(CONF_VALUE_TEMPLATE)
|
2016-09-28 04:29:55 +00:00
|
|
|
|
|
|
|
if value_template is not None:
|
|
|
|
value_template.hass = hass
|
|
|
|
|
2016-09-02 14:09:09 +00:00
|
|
|
switches.append(
|
2015-06-02 13:40:02 +00:00
|
|
|
CommandSwitch(
|
2023-05-08 08:19:37 +00:00
|
|
|
trigger_entity_config,
|
Use entity_id for backend, friendly name for frontend (#4343)
* Use entity_id for backend, friendly name for frontend
Closes https://github.com/home-assistant/home-assistant/issues/3434
Command line switches had the option to set a `friendly_name` reportedly
for use in the front end. However, if set, it was also being used as the
`entity_id`.
This did not seem like obvious behavior to me. This PR changes the
behavior so the entity_id is the object_id, which must already be
unique, and is an obvious place to have a very predictable slug (even if
long or unsightly), and the friendly name (if set) is used for the
display.
Example:
```yaml
switch:
platform: command_line
switches:
rf_kitchen_light_one:
command_on: switch_command on kitchen
command_off: switch_command off kitchen
command_state: query_command kitchen
value_template: '{{ value == "online" }}'
friendly_name: "Beautiful bright kitchen light!"
```
If you were using in an automation or from dev tools, would use:
`switch.rf_kitchen_light_one`, but your front end would still show `Beautiful
bright kitchen light!`
* Add new arg to test_assumed_state_should_be_true_if_command_state_is_false
* Import ENTITY_ID _FORMAT from existing, rename device_name to object_id
* Rename `device_name` to `object_id`
* Test that `entity_id` and `name` are set as expected
2016-11-13 06:46:23 +00:00
|
|
|
object_id,
|
2020-08-05 03:00:02 +00:00
|
|
|
device_config[CONF_COMMAND_ON],
|
|
|
|
device_config[CONF_COMMAND_OFF],
|
2016-09-02 14:09:09 +00:00
|
|
|
device_config.get(CONF_COMMAND_STATE),
|
2019-07-31 19:25:30 +00:00
|
|
|
value_template,
|
2020-08-05 03:00:02 +00:00
|
|
|
device_config[CONF_COMMAND_TIMEOUT],
|
2023-06-03 03:35:11 +00:00
|
|
|
device_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL),
|
2016-09-02 14:09:09 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
if not switches:
|
2023-06-03 03:35:11 +00:00
|
|
|
LOGGER.error("No switches added")
|
2021-12-28 20:56:38 +00:00
|
|
|
return
|
2016-09-02 14:09:09 +00:00
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
async_add_entities(switches)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
|
|
|
|
2023-05-08 08:19:37 +00:00
|
|
|
class CommandSwitch(ManualTriggerEntity, SwitchEntity):
|
2016-03-08 12:35:39 +00:00
|
|
|
"""Representation a switch that can be toggled using shell commands."""
|
2015-12-22 00:49:39 +00:00
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
_attr_should_poll = False
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2023-05-08 08:19:37 +00:00
|
|
|
config: ConfigType,
|
2022-02-12 14:19:37 +00:00
|
|
|
object_id: str,
|
|
|
|
command_on: str,
|
|
|
|
command_off: str,
|
|
|
|
command_state: str | None,
|
|
|
|
value_template: Template | None,
|
|
|
|
timeout: int,
|
2023-06-03 03:35:11 +00:00
|
|
|
scan_interval: timedelta,
|
2022-02-12 14:19:37 +00:00
|
|
|
) -> None:
|
2016-03-08 12:35:39 +00:00
|
|
|
"""Initialize the switch."""
|
2023-05-08 08:19:37 +00:00
|
|
|
super().__init__(self.hass, config)
|
Use entity_id for backend, friendly name for frontend (#4343)
* Use entity_id for backend, friendly name for frontend
Closes https://github.com/home-assistant/home-assistant/issues/3434
Command line switches had the option to set a `friendly_name` reportedly
for use in the front end. However, if set, it was also being used as the
`entity_id`.
This did not seem like obvious behavior to me. This PR changes the
behavior so the entity_id is the object_id, which must already be
unique, and is an obvious place to have a very predictable slug (even if
long or unsightly), and the friendly name (if set) is used for the
display.
Example:
```yaml
switch:
platform: command_line
switches:
rf_kitchen_light_one:
command_on: switch_command on kitchen
command_off: switch_command off kitchen
command_state: query_command kitchen
value_template: '{{ value == "online" }}'
friendly_name: "Beautiful bright kitchen light!"
```
If you were using in an automation or from dev tools, would use:
`switch.rf_kitchen_light_one`, but your front end would still show `Beautiful
bright kitchen light!`
* Add new arg to test_assumed_state_should_be_true_if_command_state_is_false
* Import ENTITY_ID _FORMAT from existing, rename device_name to object_id
* Rename `device_name` to `object_id`
* Test that `entity_id` and `name` are set as expected
2016-11-13 06:46:23 +00:00
|
|
|
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_is_on = False
|
2015-06-02 13:40:02 +00:00
|
|
|
self._command_on = command_on
|
|
|
|
self._command_off = command_off
|
2015-12-22 00:49:39 +00:00
|
|
|
self._command_state = command_state
|
|
|
|
self._value_template = value_template
|
2020-08-05 03:00:02 +00:00
|
|
|
self._timeout = timeout
|
2023-06-03 03:35:11 +00:00
|
|
|
self._scan_interval = scan_interval
|
|
|
|
self._process_updates: asyncio.Lock | None = None
|
|
|
|
|
|
|
|
async def async_added_to_hass(self) -> None:
|
|
|
|
"""Call when entity about to be added to hass."""
|
|
|
|
await super().async_added_to_hass()
|
|
|
|
if self._command_state:
|
|
|
|
self.async_on_remove(
|
|
|
|
async_track_time_interval(
|
|
|
|
self.hass,
|
|
|
|
self._update_entity_state,
|
|
|
|
self._scan_interval,
|
|
|
|
name=f"Command Line Cover - {self.name}",
|
|
|
|
cancel_on_shutdown=True,
|
|
|
|
),
|
|
|
|
)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
async def _switch(self, command: str) -> bool:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Execute the actual commands."""
|
2023-06-03 03:35:11 +00:00
|
|
|
LOGGER.info("Running command: %s", command)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
success = (
|
|
|
|
await self.hass.async_add_executor_job(
|
|
|
|
call_shell_with_timeout, command, self._timeout
|
|
|
|
)
|
|
|
|
== 0
|
|
|
|
)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
|
|
|
if not success:
|
2023-06-03 03:35:11 +00:00
|
|
|
LOGGER.error("Command failed: %s", command)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
|
|
|
return success
|
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def _query_state_value(self, command: str) -> str | None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Execute state command for return value."""
|
2023-06-03 03:35:11 +00:00
|
|
|
LOGGER.info("Running state value command: %s", command)
|
2020-08-05 03:00:02 +00:00
|
|
|
return check_output_or_log(command, self._timeout)
|
2015-12-22 00:49:39 +00:00
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def _query_state_code(self, command: str) -> bool:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Execute state command for return code."""
|
2023-06-03 03:35:11 +00:00
|
|
|
LOGGER.info("Running state code command: %s", command)
|
2020-08-06 10:36:59 +00:00
|
|
|
return (
|
|
|
|
call_shell_with_timeout(command, self._timeout, log_return_code=False) == 0
|
|
|
|
)
|
2015-12-28 03:49:55 +00:00
|
|
|
|
2015-06-02 13:40:02 +00:00
|
|
|
@property
|
2022-02-12 14:19:37 +00:00
|
|
|
def assumed_state(self) -> bool:
|
2016-03-15 12:32:33 +00:00
|
|
|
"""Return true if we do optimistic updates."""
|
2017-01-27 05:41:30 +00:00
|
|
|
return self._command_state is None
|
2016-03-15 12:32:33 +00:00
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def _query_state(self) -> str | int | None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Query for state."""
|
2022-02-12 14:19:37 +00:00
|
|
|
if self._command_state:
|
|
|
|
if self._value_template:
|
|
|
|
return self._query_state_value(self._command_state)
|
|
|
|
return self._query_state_code(self._command_state)
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
return None
|
2015-12-28 03:49:55 +00:00
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
async def _update_entity_state(self, now) -> None:
|
|
|
|
"""Update the state of the entity."""
|
|
|
|
if self._process_updates is None:
|
|
|
|
self._process_updates = asyncio.Lock()
|
|
|
|
if self._process_updates.locked():
|
|
|
|
LOGGER.warning(
|
|
|
|
"Updating Command Line Switch %s took longer than the scheduled update interval %s",
|
|
|
|
self.name,
|
|
|
|
self._scan_interval,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
async with self._process_updates:
|
|
|
|
await self._async_update()
|
|
|
|
|
|
|
|
async def _async_update(self) -> None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Update device state."""
|
2015-12-28 03:49:55 +00:00
|
|
|
if self._command_state:
|
2023-03-27 19:19:09 +00:00
|
|
|
payload = str(await self.hass.async_add_executor_job(self._query_state))
|
2023-05-08 08:19:37 +00:00
|
|
|
value = None
|
2015-12-28 03:49:55 +00:00
|
|
|
if self._value_template:
|
2023-05-08 08:19:37 +00:00
|
|
|
value = self._value_template.async_render_with_possible_json_value(
|
2023-03-27 19:19:09 +00:00
|
|
|
payload, None
|
|
|
|
)
|
|
|
|
self._attr_is_on = None
|
2023-05-08 08:19:37 +00:00
|
|
|
if payload or value:
|
|
|
|
self._attr_is_on = (value or payload).lower() == "true"
|
|
|
|
self._process_manual_data(payload)
|
2023-06-16 07:08:51 +00:00
|
|
|
self.async_write_ha_state()
|
2015-12-22 00:49:39 +00:00
|
|
|
|
2023-06-12 19:50:23 +00:00
|
|
|
async def async_update(self) -> None:
|
|
|
|
"""Update the entity.
|
|
|
|
|
|
|
|
Only used by the generic entity update service.
|
|
|
|
"""
|
|
|
|
await self._update_entity_state(dt_util.now())
|
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
async def async_turn_on(self, **kwargs: Any) -> None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Turn the device on."""
|
2023-03-27 19:19:09 +00:00
|
|
|
if await self._switch(self._command_on) and not self._command_state:
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_is_on = True
|
2023-03-27 19:19:09 +00:00
|
|
|
self.async_schedule_update_ha_state()
|
2023-06-03 03:35:11 +00:00
|
|
|
await self._update_entity_state(None)
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-03-27 19:19:09 +00:00
|
|
|
async def async_turn_off(self, **kwargs: Any) -> None:
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Turn the device off."""
|
2023-03-27 19:19:09 +00:00
|
|
|
if await self._switch(self._command_off) and not self._command_state:
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_is_on = False
|
2023-03-27 19:19:09 +00:00
|
|
|
self.async_schedule_update_ha_state()
|
2023-06-03 03:35:11 +00:00
|
|
|
await self._update_entity_state(None)
|