Add scan interval to Command Line (#93752)
* Add scan interval * Handle previous not complete * Fix faulty text * Add tests * lingering * Cool down * Fix tests
This commit is contained in:
parent
aa636a2805
commit
038b0e6d23
10 changed files with 463 additions and 41 deletions
|
@ -1,10 +1,10 @@
|
|||
"""Allows to configure custom shell commands to turn a value for a sensor."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
|
@ -20,6 +20,7 @@ from homeassistant.const import (
|
|||
CONF_COMMAND,
|
||||
CONF_DEVICE_CLASS,
|
||||
CONF_NAME,
|
||||
CONF_SCAN_INTERVAL,
|
||||
CONF_UNIQUE_ID,
|
||||
CONF_UNIT_OF_MEASUREMENT,
|
||||
CONF_VALUE_TEMPLATE,
|
||||
|
@ -28,15 +29,14 @@ from homeassistant.core import HomeAssistant
|
|||
from homeassistant.exceptions import TemplateError
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
|
||||
from homeassistant.helpers.template import Template
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
|
||||
from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN
|
||||
from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN, LOGGER
|
||||
from .utils import check_output_or_log
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_JSON_ATTRIBUTES = "json_attributes"
|
||||
|
||||
DEFAULT_NAME = "Command Sensor"
|
||||
|
@ -88,6 +88,7 @@ async def async_setup_platform(
|
|||
if value_template is not None:
|
||||
value_template.hass = hass
|
||||
json_attributes: list[str] | None = sensor_config.get(CONF_JSON_ATTRIBUTES)
|
||||
scan_interval: timedelta = sensor_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
|
||||
data = CommandSensorData(hass, command, command_timeout)
|
||||
|
||||
async_add_entities(
|
||||
|
@ -99,15 +100,17 @@ async def async_setup_platform(
|
|||
value_template,
|
||||
json_attributes,
|
||||
unique_id,
|
||||
scan_interval,
|
||||
)
|
||||
],
|
||||
True,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class CommandSensor(SensorEntity):
|
||||
"""Representation of a sensor that is using shell commands."""
|
||||
|
||||
_attr_should_poll = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
data: CommandSensorData,
|
||||
|
@ -116,6 +119,7 @@ class CommandSensor(SensorEntity):
|
|||
value_template: Template | None,
|
||||
json_attributes: list[str] | None,
|
||||
unique_id: str | None,
|
||||
scan_interval: timedelta,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
self._attr_name = name
|
||||
|
@ -126,8 +130,39 @@ class CommandSensor(SensorEntity):
|
|||
self._value_template = value_template
|
||||
self._attr_native_unit_of_measurement = unit_of_measurement
|
||||
self._attr_unique_id = unique_id
|
||||
self._scan_interval = scan_interval
|
||||
self._process_updates: asyncio.Lock | None = None
|
||||
|
||||
async def async_update(self) -> None:
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Call when entity about to be added to hass."""
|
||||
await super().async_added_to_hass()
|
||||
await self._update_entity_state(None)
|
||||
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,
|
||||
),
|
||||
)
|
||||
|
||||
async def _update_entity_state(self, now) -> None:
|
||||
"""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 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:
|
||||
"""Get the latest data and updates the state."""
|
||||
await self.hass.async_add_executor_job(self.data.update)
|
||||
value = self.data.value
|
||||
|
@ -144,11 +179,11 @@ class CommandSensor(SensorEntity):
|
|||
if k in json_dict
|
||||
}
|
||||
else:
|
||||
_LOGGER.warning("JSON result was not a dictionary")
|
||||
LOGGER.warning("JSON result was not a dictionary")
|
||||
except ValueError:
|
||||
_LOGGER.warning("Unable to parse output as JSON: %s", value)
|
||||
LOGGER.warning("Unable to parse output as JSON: %s", value)
|
||||
else:
|
||||
_LOGGER.warning("Empty reply found when expecting JSON data")
|
||||
LOGGER.warning("Empty reply found when expecting JSON data")
|
||||
if self._value_template is None:
|
||||
self._attr_native_value = None
|
||||
return
|
||||
|
@ -163,6 +198,8 @@ class CommandSensor(SensorEntity):
|
|||
else:
|
||||
self._attr_native_value = value
|
||||
|
||||
self.async_write_ha_state()
|
||||
|
||||
|
||||
class CommandSensorData:
|
||||
"""The class for handling the data retrieval."""
|
||||
|
@ -191,7 +228,7 @@ class CommandSensorData:
|
|||
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)
|
||||
LOGGER.exception("Error rendering command template: %s", ex)
|
||||
return
|
||||
else:
|
||||
rendered_args = None
|
||||
|
@ -203,5 +240,5 @@ class CommandSensorData:
|
|||
# Template used. Construct the string used in the shell
|
||||
command = f"{prog} {rendered_args}"
|
||||
|
||||
_LOGGER.debug("Running command: %s", command)
|
||||
LOGGER.debug("Running command: %s", command)
|
||||
self.value = check_output_or_log(command, self.timeout)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue