2019-04-03 15:40:03 +00:00
|
|
|
"""Support for custom shell commands to turn a switch on/off."""
|
2024-03-08 13:51:32 +00:00
|
|
|
|
2021-12-28 20:56:38 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-06-03 03:35:11 +00:00
|
|
|
import asyncio
|
2024-01-02 19:04:28 +00:00
|
|
|
from datetime import datetime, timedelta
|
2023-11-04 15:17:31 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, cast
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-11-04 15:17:31 +00:00
|
|
|
from homeassistant.components.switch import ENTITY_ID_FORMAT, SwitchEntity
|
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,
|
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_VALUE_TEMPLATE,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
|
|
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
2023-06-03 03:35:11 +00:00
|
|
|
from homeassistant.helpers.event import async_track_time_interval
|
2022-02-12 14:19:37 +00:00
|
|
|
from homeassistant.helpers.template import Template
|
2024-04-02 19:47:04 +00:00
|
|
|
from homeassistant.helpers.trigger_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
|
|
|
|
2024-04-02 19:47:04 +00:00
|
|
|
from .const import CONF_COMMAND_TIMEOUT, LOGGER, TRIGGER_ENTITY_OPTIONS
|
2024-03-02 04:15:10 +00:00
|
|
|
from .utils import async_call_shell_with_timeout, async_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
|
|
|
|
|
|
|
|
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
|
|
|
|
2024-04-02 19:47:04 +00:00
|
|
|
switches = []
|
2023-11-04 15:17:31 +00:00
|
|
|
discovery_info = cast(DiscoveryInfoType, discovery_info)
|
2024-04-02 19:47:04 +00:00
|
|
|
entities: dict[str, dict[str, Any]] = {
|
|
|
|
slugify(discovery_info[CONF_NAME]): discovery_info
|
|
|
|
}
|
2020-08-26 00:52:36 +00:00
|
|
|
|
2024-04-02 19:47:04 +00:00
|
|
|
for object_id, switch_config in entities.items():
|
|
|
|
if value_template := switch_config.get(CONF_VALUE_TEMPLATE):
|
|
|
|
value_template.hass = hass
|
2015-06-02 13:40:02 +00:00
|
|
|
|
2023-05-08 08:19:37 +00:00
|
|
|
trigger_entity_config = {
|
2024-04-02 19:47:04 +00:00
|
|
|
CONF_NAME: Template(switch_config.get(CONF_NAME, object_id), hass),
|
|
|
|
**{k: v for k, v in switch_config.items() if k in TRIGGER_ENTITY_OPTIONS},
|
2023-05-08 08:19:37 +00:00
|
|
|
}
|
|
|
|
|
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,
|
2024-04-02 19:47:04 +00:00
|
|
|
switch_config[CONF_COMMAND_ON],
|
|
|
|
switch_config[CONF_COMMAND_OFF],
|
|
|
|
switch_config.get(CONF_COMMAND_STATE),
|
2019-07-31 19:25:30 +00:00
|
|
|
value_template,
|
2024-04-02 19:47:04 +00:00
|
|
|
switch_config[CONF_COMMAND_TIMEOUT],
|
|
|
|
switch_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL),
|
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
|
|
|
|
2024-03-02 04:15:10 +00:00
|
|
|
success = await async_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
|
|
|
|
|
2024-03-02 04:15:10 +00:00
|
|
|
async def _async_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)
|
2024-03-02 04:15:10 +00:00
|
|
|
return await async_check_output_or_log(command, self._timeout)
|
2015-12-22 00:49:39 +00:00
|
|
|
|
2024-03-02 04:15:10 +00:00
|
|
|
async def _async_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 (
|
2024-03-02 04:15:10 +00:00
|
|
|
await async_call_shell_with_timeout(
|
|
|
|
command, self._timeout, log_return_code=False
|
|
|
|
)
|
|
|
|
== 0
|
2020-08-06 10:36:59 +00:00
|
|
|
)
|
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
|
|
|
|
2024-03-02 04:15:10 +00:00
|
|
|
async def _async_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:
|
2024-03-02 04:15:10 +00:00
|
|
|
return await self._async_query_state_value(self._command_state)
|
|
|
|
return await self._async_query_state_code(self._command_state)
|
2022-02-12 14:19:37 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
return None
|
2015-12-28 03:49:55 +00:00
|
|
|
|
2024-01-02 19:04:28 +00:00
|
|
|
async def _update_entity_state(self, now: datetime | None = None) -> None:
|
2023-06-03 03:35:11 +00:00
|
|
|
"""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:
|
2024-03-02 04:15:10 +00:00
|
|
|
payload = str(await self._async_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
|
2024-04-28 16:36:01 +00:00
|
|
|
self.async_write_ha_state()
|
2024-01-02 19:04:28 +00:00
|
|
|
await self._update_entity_state()
|
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
|
2024-04-28 16:36:01 +00:00
|
|
|
self.async_write_ha_state()
|
2024-01-02 19:04:28 +00:00
|
|
|
await self._update_entity_state()
|