2019-04-03 15:40:03 +00:00
|
|
|
"""Allows to configure custom shell commands to turn a value for a sensor."""
|
2018-07-29 06:37:34 +00:00
|
|
|
import collections
|
|
|
|
from datetime import timedelta
|
|
|
|
import json
|
2015-09-13 09:38:06 +00:00
|
|
|
import logging
|
2017-08-10 16:52:52 +00:00
|
|
|
import shlex
|
2018-07-29 06:37:34 +00:00
|
|
|
import subprocess
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2016-09-02 14:09:09 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
|
|
|
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
|
|
|
from homeassistant.const import (
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_COMMAND,
|
|
|
|
CONF_NAME,
|
|
|
|
CONF_UNIT_OF_MEASUREMENT,
|
|
|
|
CONF_VALUE_TEMPLATE,
|
|
|
|
STATE_UNKNOWN,
|
|
|
|
)
|
2018-07-29 06:37:34 +00:00
|
|
|
from homeassistant.exceptions import TemplateError
|
|
|
|
from homeassistant.helpers import template
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
2015-09-13 09:38:06 +00:00
|
|
|
from homeassistant.helpers.entity import Entity
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_COMMAND_TIMEOUT = "command_timeout"
|
|
|
|
CONF_JSON_ATTRIBUTES = "json_attributes"
|
2018-07-29 06:37:34 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
DEFAULT_NAME = "Command Sensor"
|
2018-07-29 06:37:34 +00:00
|
|
|
DEFAULT_TIMEOUT = 15
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2017-01-05 23:16:12 +00:00
|
|
|
SCAN_INTERVAL = timedelta(seconds=60)
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_COMMAND): cv.string,
|
|
|
|
vol.Optional(CONF_COMMAND_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
|
|
|
|
vol.Optional(CONF_JSON_ATTRIBUTES): cv.ensure_list_csv,
|
|
|
|
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
|
|
|
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
|
|
|
|
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
}
|
|
|
|
)
|
2016-09-02 14:09:09 +00:00
|
|
|
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2018-08-24 14:37:30 +00:00
|
|
|
def setup_platform(hass, config, add_entities, discovery_info=None):
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Set up the Command Sensor."""
|
2016-09-02 14:09:09 +00:00
|
|
|
name = config.get(CONF_NAME)
|
|
|
|
command = config.get(CONF_COMMAND)
|
|
|
|
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
|
|
|
|
value_template = config.get(CONF_VALUE_TEMPLATE)
|
2018-07-17 20:58:30 +00:00
|
|
|
command_timeout = config.get(CONF_COMMAND_TIMEOUT)
|
2016-09-28 04:29:55 +00:00
|
|
|
if value_template is not None:
|
|
|
|
value_template.hass = hass
|
2018-07-29 06:37:34 +00:00
|
|
|
json_attributes = config.get(CONF_JSON_ATTRIBUTES)
|
2018-07-17 20:58:30 +00:00
|
|
|
data = CommandSensorData(hass, command, command_timeout)
|
2016-09-02 14:09:09 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
add_entities(
|
|
|
|
[CommandSensor(hass, data, name, unit, value_template, json_attributes)], True
|
|
|
|
)
|
2015-09-13 09:38:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CommandSensor(Entity):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Representation of a sensor that is using shell commands."""
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def __init__(
|
|
|
|
self, hass, data, name, unit_of_measurement, value_template, json_attributes
|
|
|
|
):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the sensor."""
|
2015-12-14 17:29:27 +00:00
|
|
|
self._hass = hass
|
2015-09-13 09:38:06 +00:00
|
|
|
self.data = data
|
2018-07-29 06:37:34 +00:00
|
|
|
self._attributes = None
|
|
|
|
self._json_attributes = json_attributes
|
2015-09-13 09:38:06 +00:00
|
|
|
self._name = name
|
2017-08-08 20:36:59 +00:00
|
|
|
self._state = None
|
2015-09-13 09:38:06 +00:00
|
|
|
self._unit_of_measurement = unit_of_measurement
|
2015-12-14 17:29:27 +00:00
|
|
|
self._value_template = value_template
|
2015-09-13 09:38:06 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the name of the sensor."""
|
2015-09-13 09:38:06 +00:00
|
|
|
return self._name
|
|
|
|
|
|
|
|
@property
|
|
|
|
def unit_of_measurement(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the unit the value is expressed in."""
|
2015-09-13 09:38:06 +00:00
|
|
|
return self._unit_of_measurement
|
|
|
|
|
|
|
|
@property
|
|
|
|
def state(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Return the state of the device."""
|
2015-09-13 09:38:06 +00:00
|
|
|
return self._state
|
|
|
|
|
2018-07-29 06:37:34 +00:00
|
|
|
@property
|
|
|
|
def device_state_attributes(self):
|
|
|
|
"""Return the state attributes."""
|
|
|
|
return self._attributes
|
|
|
|
|
2015-09-13 09:38:06 +00:00
|
|
|
def update(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Get the latest data and updates the state."""
|
2015-09-13 09:38:06 +00:00
|
|
|
self.data.update()
|
|
|
|
value = self.data.value
|
|
|
|
|
2018-07-29 06:37:34 +00:00
|
|
|
if self._json_attributes:
|
|
|
|
self._attributes = {}
|
|
|
|
if value:
|
|
|
|
try:
|
|
|
|
json_dict = json.loads(value)
|
|
|
|
if isinstance(json_dict, collections.Mapping):
|
2019-07-31 19:25:30 +00:00
|
|
|
self._attributes = {
|
|
|
|
k: json_dict[k]
|
|
|
|
for k in self._json_attributes
|
|
|
|
if k in json_dict
|
|
|
|
}
|
2018-07-29 06:37:34 +00:00
|
|
|
else:
|
|
|
|
_LOGGER.warning("JSON result was not a dictionary")
|
|
|
|
except ValueError:
|
2019-07-31 19:25:30 +00:00
|
|
|
_LOGGER.warning("Unable to parse output as JSON: %s", value)
|
2018-07-29 06:37:34 +00:00
|
|
|
else:
|
|
|
|
_LOGGER.warning("Empty reply found when expecting JSON data")
|
|
|
|
|
2016-10-29 02:03:40 +00:00
|
|
|
if value is None:
|
|
|
|
value = STATE_UNKNOWN
|
|
|
|
elif self._value_template is not None:
|
2016-09-28 04:29:55 +00:00
|
|
|
self._state = self._value_template.render_with_possible_json_value(
|
2019-07-31 19:25:30 +00:00
|
|
|
value, STATE_UNKNOWN
|
|
|
|
)
|
2015-12-14 17:49:54 +00:00
|
|
|
else:
|
|
|
|
self._state = value
|
2015-09-13 09:38:06 +00:00
|
|
|
|
|
|
|
|
2018-07-20 08:45:20 +00:00
|
|
|
class CommandSensorData:
|
2016-03-08 15:46:34 +00:00
|
|
|
"""The class for handling the data retrieval."""
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2018-07-17 20:58:30 +00:00
|
|
|
def __init__(self, hass, command, command_timeout):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the data object."""
|
2015-09-13 09:38:06 +00:00
|
|
|
self.value = None
|
2017-08-10 16:52:52 +00:00
|
|
|
self.hass = hass
|
|
|
|
self.command = command
|
2018-07-17 20:58:30 +00:00
|
|
|
self.timeout = command_timeout
|
2015-09-13 09:38:06 +00:00
|
|
|
|
|
|
|
def update(self):
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Get the latest data with a shell command."""
|
2017-08-10 16:52:52 +00:00
|
|
|
command = self.command
|
|
|
|
cache = {}
|
|
|
|
|
|
|
|
if command in cache:
|
|
|
|
prog, args, args_compiled = cache[command]
|
2019-07-31 19:25:30 +00:00
|
|
|
elif " " not in command:
|
2017-08-10 16:52:52 +00:00
|
|
|
prog = command
|
|
|
|
args = None
|
|
|
|
args_compiled = None
|
|
|
|
cache[command] = (prog, args, args_compiled)
|
|
|
|
else:
|
2019-07-31 19:25:30 +00:00
|
|
|
prog, args = command.split(" ", 1)
|
2017-08-10 16:52:52 +00:00
|
|
|
args_compiled = template.Template(args, self.hass)
|
|
|
|
cache[command] = (prog, args, args_compiled)
|
|
|
|
|
|
|
|
if args_compiled:
|
|
|
|
try:
|
|
|
|
args_to_render = {"arguments": args}
|
|
|
|
rendered_args = args_compiled.render(args_to_render)
|
|
|
|
except TemplateError as ex:
|
|
|
|
_LOGGER.exception("Error rendering command template: %s", ex)
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
rendered_args = None
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2017-08-10 16:52:52 +00:00
|
|
|
if rendered_args == args:
|
|
|
|
# No template used. default behavior
|
|
|
|
shell = True
|
|
|
|
else:
|
|
|
|
# Template used. Construct the string used in the shell
|
2019-07-31 19:25:30 +00:00
|
|
|
command = str(" ".join([prog] + shlex.split(rendered_args)))
|
2017-08-10 16:52:52 +00:00
|
|
|
shell = True
|
2015-09-13 09:38:06 +00:00
|
|
|
try:
|
2019-04-15 17:56:32 +00:00
|
|
|
_LOGGER.debug("Running command: %s", command)
|
2017-05-02 16:18:47 +00:00
|
|
|
return_value = subprocess.check_output(
|
2019-07-31 19:25:30 +00:00
|
|
|
command, shell=shell, timeout=self.timeout
|
|
|
|
)
|
|
|
|
self.value = return_value.strip().decode("utf-8")
|
2015-09-14 08:44:07 +00:00
|
|
|
except subprocess.CalledProcessError:
|
2017-08-10 16:52:52 +00:00
|
|
|
_LOGGER.error("Command failed: %s", command)
|
2016-07-30 17:36:56 +00:00
|
|
|
except subprocess.TimeoutExpired:
|
2017-08-10 16:52:52 +00:00
|
|
|
_LOGGER.error("Timeout for command: %s", command)
|