2019-04-03 15:40:03 +00:00
|
|
|
"""Allows to configure custom shell commands to turn a value for a sensor."""
|
2021-12-28 20:56:38 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2020-04-12 16:00:57 +00:00
|
|
|
from collections.abc import Mapping
|
2018-07-29 06:37:34 +00:00
|
|
|
from datetime import timedelta
|
|
|
|
import json
|
2015-09-13 09:38:06 +00:00
|
|
|
import logging
|
|
|
|
|
2016-09-02 14:09:09 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2021-03-22 11:37:16 +00:00
|
|
|
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
|
2016-09-02 14:09:09 +00:00
|
|
|
from homeassistant.const import (
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_COMMAND,
|
|
|
|
CONF_NAME,
|
2022-01-03 10:44:47 +00:00
|
|
|
CONF_UNIQUE_ID,
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_UNIT_OF_MEASUREMENT,
|
|
|
|
CONF_VALUE_TEMPLATE,
|
|
|
|
STATE_UNKNOWN,
|
|
|
|
)
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2018-07-29 06:37:34 +00:00
|
|
|
from homeassistant.exceptions import TemplateError
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
2020-08-26 00:52:36 +00:00
|
|
|
from homeassistant.helpers.reload import setup_reload_service
|
2022-02-12 14:19:37 +00:00
|
|
|
from homeassistant.helpers.template import Template
|
2021-12-28 20:56:38 +00:00
|
|
|
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2020-08-05 03:00:02 +00:00
|
|
|
from . import check_output_or_log
|
2020-08-26 00:52:36 +00:00
|
|
|
from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN, PLATFORMS
|
2020-08-05 03:00:02 +00:00
|
|
|
|
2015-09-13 09:38:06 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
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"
|
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,
|
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
|
|
|
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2021-12-28 20:56:38 +00:00
|
|
|
def setup_platform(
|
|
|
|
hass: HomeAssistant,
|
|
|
|
config: ConfigType,
|
|
|
|
add_entities: AddEntitiesCallback,
|
|
|
|
discovery_info: DiscoveryInfoType | None = None,
|
|
|
|
) -> None:
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Set up the Command Sensor."""
|
2020-08-26 00:52:36 +00:00
|
|
|
|
|
|
|
setup_reload_service(hass, DOMAIN, PLATFORMS)
|
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
name: str = config[CONF_NAME]
|
|
|
|
command: str = config[CONF_COMMAND]
|
|
|
|
unit: str | None = config.get(CONF_UNIT_OF_MEASUREMENT)
|
|
|
|
value_template: Template | None = config.get(CONF_VALUE_TEMPLATE)
|
|
|
|
command_timeout: int = config[CONF_COMMAND_TIMEOUT]
|
|
|
|
unique_id: str | None = config.get(CONF_UNIQUE_ID)
|
2016-09-28 04:29:55 +00:00
|
|
|
if value_template is not None:
|
|
|
|
value_template.hass = hass
|
2022-02-12 14:19:37 +00:00
|
|
|
json_attributes: list[str] | None = 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(
|
2022-02-12 14:19:37 +00:00
|
|
|
[CommandSensor(data, name, unit, value_template, json_attributes, unique_id)],
|
2022-01-03 10:44:47 +00:00
|
|
|
True,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2015-09-13 09:38:06 +00:00
|
|
|
|
|
|
|
|
2021-03-22 11:37:16 +00:00
|
|
|
class CommandSensor(SensorEntity):
|
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__(
|
2022-01-03 10:44:47 +00:00
|
|
|
self,
|
2022-02-12 14:19:37 +00:00
|
|
|
data: CommandSensorData,
|
|
|
|
name: str,
|
|
|
|
unit_of_measurement: str | None,
|
|
|
|
value_template: Template | None,
|
|
|
|
json_attributes: list[str] | None,
|
|
|
|
unique_id: str | None,
|
|
|
|
) -> None:
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the sensor."""
|
2015-09-13 09:38:06 +00:00
|
|
|
self.data = data
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_extra_state_attributes = {}
|
2018-07-29 06:37:34 +00:00
|
|
|
self._json_attributes = json_attributes
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_name = name
|
|
|
|
self._attr_native_value = None
|
|
|
|
self._attr_native_unit_of_measurement = unit_of_measurement
|
2015-12-14 17:29:27 +00:00
|
|
|
self._value_template = value_template
|
2022-01-03 10:44:47 +00:00
|
|
|
self._attr_unique_id = unique_id
|
2015-09-13 09:38:06 +00:00
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def update(self) -> None:
|
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:
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_extra_state_attributes = {}
|
2018-07-29 06:37:34 +00:00
|
|
|
if value:
|
|
|
|
try:
|
|
|
|
json_dict = json.loads(value)
|
2020-04-12 16:00:57 +00:00
|
|
|
if isinstance(json_dict, Mapping):
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_extra_state_attributes = {
|
2019-07-31 19:25:30 +00:00
|
|
|
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:
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_native_value = (
|
|
|
|
self._value_template.render_with_possible_json_value(
|
|
|
|
value, STATE_UNKNOWN
|
|
|
|
)
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2015-12-14 17:49:54 +00:00
|
|
|
else:
|
2022-02-12 14:19:37 +00:00
|
|
|
self._attr_native_value = 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
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None:
|
2016-03-08 15:46:34 +00:00
|
|
|
"""Initialize the data object."""
|
2022-02-12 14:19:37 +00:00
|
|
|
self.value: str | None = 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
|
|
|
|
2022-02-12 14:19:37 +00:00
|
|
|
def update(self) -> None:
|
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
|
|
|
|
|
2021-03-01 16:27:04 +00:00
|
|
|
if " " not in command:
|
2017-08-10 16:52:52 +00:00
|
|
|
prog = command
|
|
|
|
args = None
|
|
|
|
args_compiled = None
|
|
|
|
else:
|
2019-07-31 19:25:30 +00:00
|
|
|
prog, args = command.split(" ", 1)
|
2022-02-12 14:19:37 +00:00
|
|
|
args_compiled = Template(args, self.hass)
|
2017-08-10 16:52:52 +00:00
|
|
|
|
|
|
|
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
|
2020-01-20 16:44:55 +00:00
|
|
|
pass
|
2017-08-10 16:52:52 +00:00
|
|
|
else:
|
|
|
|
# Template used. Construct the string used in the shell
|
2020-06-10 16:31:59 +00:00
|
|
|
command = f"{prog} {rendered_args}"
|
2020-08-05 03:00:02 +00:00
|
|
|
|
|
|
|
_LOGGER.debug("Running command: %s", command)
|
|
|
|
self.value = check_output_or_log(command, self.timeout)
|