core/homeassistant/components/command_line/switch.py

171 lines
5.0 KiB
Python
Raw Normal View History

"""Support for custom shell commands to turn a switch on/off."""
import logging
import subprocess
import voluptuous as vol
from homeassistant.components.switch import (
2019-07-31 19:25:30 +00:00
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchDevice,
2019-07-31 19:25:30 +00:00
)
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
CONF_COMMAND_OFF,
CONF_COMMAND_ON,
CONF_COMMAND_STATE,
CONF_FRIENDLY_NAME,
CONF_SWITCHES,
CONF_VALUE_TEMPLATE,
2019-07-31 19:25:30 +00:00
)
import homeassistant.helpers.config_validation as cv
2015-09-15 05:56:08 +00:00
_LOGGER = logging.getLogger(__name__)
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,
}
)
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
2016-02-23 20:06:50 +00:00
"""Find and return switches controlled by shell commands."""
devices = config.get(CONF_SWITCHES, {})
switches = []
for object_id, device_config in devices.items():
value_template = device_config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
switches.append(
CommandSwitch(
2015-12-22 00:49:39 +00:00
hass,
object_id,
device_config.get(CONF_FRIENDLY_NAME, object_id),
device_config.get(CONF_COMMAND_ON),
device_config.get(CONF_COMMAND_OFF),
device_config.get(CONF_COMMAND_STATE),
2019-07-31 19:25:30 +00:00
value_template,
)
)
if not switches:
_LOGGER.error("No switches added")
return False
add_entities(switches)
2015-06-13 21:56:20 +00:00
class CommandSwitch(SwitchDevice):
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
2019-07-31 19:25:30 +00:00
def __init__(
self,
hass,
object_id,
friendly_name,
command_on,
command_off,
command_state,
value_template,
):
2016-03-08 12:35:39 +00:00
"""Initialize the switch."""
2015-12-22 00:49:39 +00:00
self._hass = hass
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
self._name = friendly_name
2015-06-13 21:56:20 +00:00
self._state = False
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
@staticmethod
def _switch(command):
2016-02-23 20:06:50 +00:00
"""Execute the actual commands."""
_LOGGER.info("Running command: %s", command)
success = subprocess.call(command, shell=True) == 0 # nosec # shell by design
if not success:
_LOGGER.error("Command failed: %s", command)
return success
2015-12-22 00:49:39 +00:00
@staticmethod
2015-12-28 03:49:55 +00:00
def _query_state_value(command):
2016-02-23 20:06:50 +00:00
"""Execute state command for return value."""
_LOGGER.info("Running state command: %s", command)
2015-12-22 00:49:39 +00:00
try:
return_value = subprocess.check_output(
command, shell=True # nosec # shell by design
)
2019-07-31 19:25:30 +00:00
return return_value.strip().decode("utf-8")
2015-12-22 00:49:39 +00:00
except subprocess.CalledProcessError:
_LOGGER.error("Command failed: %s", command)
2015-12-22 00:49:39 +00:00
2015-12-28 03:49:55 +00:00
@staticmethod
def _query_state_code(command):
2016-02-23 20:06:50 +00:00
"""Execute state command for return code."""
_LOGGER.info("Running state command: %s", command)
return subprocess.call(command, shell=True) == 0 # nosec # shell by design
2015-12-28 03:49:55 +00:00
@property
def should_poll(self):
2016-02-23 20:06:50 +00:00
"""Only poll if we have state command."""
2015-12-28 03:49:55 +00:00
return self._command_state is not None
@property
def name(self):
2016-03-08 12:35:39 +00:00
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
2016-03-08 12:35:39 +00:00
"""Return true if device is on."""
2015-06-13 21:56:20 +00:00
return self._state
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._command_state is None
2015-12-28 03:49:55 +00:00
def _query_state(self):
2016-02-23 20:06:50 +00:00
"""Query for state."""
2015-12-28 03:49:55 +00:00
if not self._command_state:
_LOGGER.error("No state command specified")
2015-12-28 03:49:55 +00:00
return
if self._value_template:
return CommandSwitch._query_state_value(self._command_state)
return CommandSwitch._query_state_code(self._command_state)
2015-12-22 00:49:39 +00:00
def update(self):
2016-02-23 20:06:50 +00:00
"""Update device state."""
2015-12-28 03:49:55 +00:00
if self._command_state:
payload = str(self._query_state())
if self._value_template:
2019-07-31 19:25:30 +00:00
payload = self._value_template.render_with_possible_json_value(payload)
self._state = payload.lower() == "true"
2015-12-22 00:49:39 +00:00
def turn_on(self, **kwargs):
2016-02-23 20:06:50 +00:00
"""Turn the device on."""
2019-07-31 19:25:30 +00:00
if CommandSwitch._switch(self._command_on) and not self._command_state:
2015-12-31 23:39:40 +00:00
self._state = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
2016-02-23 20:06:50 +00:00
"""Turn the device off."""
2019-07-31 19:25:30 +00:00
if CommandSwitch._switch(self._command_off) and not self._command_state:
2015-12-31 23:39:40 +00:00
self._state = False
self.schedule_update_ha_state()