Files
homeassistant-core/homeassistant/components/command_line/sensor.py
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

232 lines
7.7 KiB
Python
Raw Normal View History

2019-04-03 17:40:03 +02:00
"""Allows to configure custom shell commands to turn a value for a sensor."""
from __future__ import annotations
2023-06-03 05:35:11 +02:00
import asyncio
from collections.abc import Mapping
2024-01-02 20:04:28 +01:00
from datetime import datetime, timedelta
import json
from typing import Any, cast
2015-09-13 11:38:06 +02:00
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.components.sensor.helpers import async_parse_date_datetime
from homeassistant.const import (
CONF_COMMAND,
CONF_NAME,
2023-06-03 05:35:11 +02:00
CONF_SCAN_INTERVAL,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.entity_platform import AddEntitiesCallback
2023-06-03 05:35:11 +02:00
from homeassistant.helpers.event import async_track_time_interval
2022-02-12 15:19:37 +01:00
from homeassistant.helpers.template import Template
from homeassistant.helpers.trigger_template_entity import ManualTriggerSensorEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
2023-06-12 21:50:23 +02:00
from homeassistant.util import dt as dt_util
2015-09-13 11:38:06 +02:00
from .const import CONF_COMMAND_TIMEOUT, LOGGER, TRIGGER_ENTITY_OPTIONS
from .utils import async_check_output_or_log
CONF_JSON_ATTRIBUTES = "json_attributes"
DEFAULT_NAME = "Command Sensor"
2015-09-13 11:38:06 +02:00
2017-01-06 00:16:12 +01:00
SCAN_INTERVAL = timedelta(seconds=60)
2015-09-13 11:38:06 +02:00
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
2017-05-02 18:18:47 +02:00
"""Set up the Command Sensor."""
discovery_info = cast(DiscoveryInfoType, discovery_info)
sensor_config = discovery_info
command: str = sensor_config[CONF_COMMAND]
command_timeout: int = sensor_config[CONF_COMMAND_TIMEOUT]
json_attributes: list[str] | None = sensor_config.get(CONF_JSON_ATTRIBUTES)
2023-06-03 05:35:11 +02:00
scan_interval: timedelta = sensor_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
2018-07-18 04:58:30 +08:00
data = CommandSensorData(hass, command, command_timeout)
2015-09-13 11:38:06 +02:00
if value_template := sensor_config.get(CONF_VALUE_TEMPLATE):
value_template.hass = hass
trigger_entity_config = {
CONF_NAME: Template(sensor_config[CONF_NAME], hass),
**{k: v for k, v in sensor_config.items() if k in TRIGGER_ENTITY_OPTIONS},
}
async_add_entities(
[
CommandSensor(
data,
trigger_entity_config,
value_template,
json_attributes,
2023-06-03 05:35:11 +02:00
scan_interval,
)
2023-06-03 05:35:11 +02:00
]
)
2015-09-13 11:38:06 +02:00
2023-08-18 20:19:17 +02:00
class CommandSensor(ManualTriggerSensorEntity):
2016-03-08 16:46:34 +01:00
"""Representation of a sensor that is using shell commands."""
2023-06-03 05:35:11 +02:00
_attr_should_poll = False
def __init__(
self,
2022-02-12 15:19:37 +01:00
data: CommandSensorData,
config: ConfigType,
2022-02-12 15:19:37 +01:00
value_template: Template | None,
json_attributes: list[str] | None,
2023-06-03 05:35:11 +02:00
scan_interval: timedelta,
2022-02-12 15:19:37 +01:00
) -> None:
2016-03-08 16:46:34 +01:00
"""Initialize the sensor."""
super().__init__(self.hass, config)
2015-09-13 11:38:06 +02:00
self.data = data
2024-01-02 20:04:28 +01:00
self._attr_extra_state_attributes: dict[str, Any] = {}
self._json_attributes = json_attributes
2022-02-12 15:19:37 +01:00
self._attr_native_value = None
2015-12-14 10:29:27 -07:00
self._value_template = value_template
2023-06-03 05:35:11 +02:00
self._scan_interval = scan_interval
self._process_updates: asyncio.Lock | None = None
2015-09-13 11:38:06 +02:00
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return extra state attributes."""
2024-01-02 20:04:28 +01:00
return self._attr_extra_state_attributes
2023-06-03 05:35:11 +02:00
async def async_added_to_hass(self) -> None:
"""Call when entity about to be added to hass."""
await super().async_added_to_hass()
2024-01-02 20:04:28 +01:00
await self._update_entity_state()
2023-06-03 05:35:11 +02:00
self.async_on_remove(
async_track_time_interval(
self.hass,
self._update_entity_state,
self._scan_interval,
name=f"Command Line Sensor - {self.name}",
cancel_on_shutdown=True,
),
)
2024-01-02 20:04:28 +01:00
async def _update_entity_state(self, now: datetime | None = None) -> None:
2023-06-03 05:35:11 +02:00
"""Update the state of the entity."""
if self._process_updates is None:
self._process_updates = asyncio.Lock()
2023-06-03 05:35:11 +02:00
if self._process_updates.locked():
LOGGER.warning(
"Updating Command Line Sensor %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-03-08 16:46:34 +01:00
"""Get the latest data and updates the state."""
await self.data.async_update()
2015-09-13 11:38:06 +02:00
value = self.data.value
if self._json_attributes:
2022-02-12 15:19:37 +01:00
self._attr_extra_state_attributes = {}
if value:
try:
json_dict = json.loads(value)
if isinstance(json_dict, Mapping):
2022-02-12 15:19:37 +01:00
self._attr_extra_state_attributes = {
k: json_dict[k]
for k in self._json_attributes
if k in json_dict
}
else:
2023-06-03 05:35:11 +02:00
LOGGER.warning("JSON result was not a dictionary")
except ValueError:
2023-06-03 05:35:11 +02:00
LOGGER.warning("Unable to parse output as JSON: %s", value)
else:
2023-06-03 05:35:11 +02:00
LOGGER.warning("Empty reply found when expecting JSON data")
if self._value_template is None:
self._attr_native_value = None
self._process_manual_data(value)
return
self._attr_native_value = None
if self._value_template is not None and value is not None:
value = self._value_template.async_render_with_possible_json_value(
value,
None,
)
if self.device_class not in {
SensorDeviceClass.DATE,
SensorDeviceClass.TIMESTAMP,
}:
2022-02-12 15:19:37 +01:00
self._attr_native_value = value
self._process_manual_data(value)
return
if value is not None:
self._attr_native_value = async_parse_date_datetime(
value, self.entity_id, self.device_class
)
self._process_manual_data(value)
2023-06-03 05:35:11 +02:00
self.async_write_ha_state()
2023-06-12 21:50:23 +02: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())
2015-09-13 11:38:06 +02:00
2018-07-20 11:45:20 +03:00
class CommandSensorData:
2016-03-08 16:46:34 +01:00
"""The class for handling the data retrieval."""
2015-09-13 11:38:06 +02:00
2022-02-12 15:19:37 +01:00
def __init__(self, hass: HomeAssistant, command: str, command_timeout: int) -> None:
2016-03-08 16:46:34 +01:00
"""Initialize the data object."""
2022-02-12 15:19:37 +01:00
self.value: str | None = None
self.hass = hass
self.command = command
2018-07-18 04:58:30 +08:00
self.timeout = command_timeout
2015-09-13 11:38:06 +02:00
async def async_update(self) -> None:
2016-03-08 16:46:34 +01:00
"""Get the latest data with a shell command."""
command = self.command
2015-09-13 11:38:06 +02:00
2021-03-01 08:27:04 -08:00
if " " not in command:
prog = command
args = None
args_compiled = None
else:
prog, args = command.split(" ", 1)
2022-02-12 15:19:37 +01:00
args_compiled = Template(args, self.hass)
if args_compiled:
try:
args_to_render = {"arguments": args}
rendered_args = args_compiled.async_render(args_to_render)
except TemplateError as ex:
2023-06-03 05:35:11 +02:00
LOGGER.exception("Error rendering command template: %s", ex)
return
else:
rendered_args = None
if rendered_args == args:
# No template used. default behavior
2020-01-20 18:44:55 +02:00
pass
else:
# Template used. Construct the string used in the shell
command = f"{prog} {rendered_args}"
2023-06-03 05:35:11 +02:00
LOGGER.debug("Running command: %s", command)
self.value = await async_check_output_or_log(command, self.timeout)