Refactor Command Line sensor to use ManualTriggerEntity (#93999)

* Refactor sensor to use ManualTriggerEntity

* Add device and state class
This commit is contained in:
G Johansson 2023-06-04 21:00:53 +02:00 committed by GitHub
parent 1fe4c4fa59
commit b5b9a06c2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,6 +5,7 @@ import asyncio
from collections.abc import Mapping from collections.abc import Mapping
from datetime import timedelta from datetime import timedelta
import json import json
from typing import Any, cast
import voluptuous as vol import voluptuous as vol
@ -15,6 +16,7 @@ from homeassistant.components.sensor import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
STATE_CLASSES_SCHEMA, STATE_CLASSES_SCHEMA,
SensorEntity, SensorEntity,
SensorStateClass,
) )
from homeassistant.const import ( from homeassistant.const import (
CONF_COMMAND, CONF_COMMAND,
@ -32,6 +34,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.template import Template from homeassistant.helpers.template import Template
from homeassistant.helpers.template_entity import ManualTriggerEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN, LOGGER from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT, DOMAIN, LOGGER
@ -89,24 +92,31 @@ async def async_setup_platform(
value_template.hass = hass value_template.hass = hass
json_attributes: list[str] | None = sensor_config.get(CONF_JSON_ATTRIBUTES) json_attributes: list[str] | None = sensor_config.get(CONF_JSON_ATTRIBUTES)
scan_interval: timedelta = sensor_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) scan_interval: timedelta = sensor_config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
state_class: SensorStateClass | None = sensor_config.get(CONF_STATE_CLASS)
data = CommandSensorData(hass, command, command_timeout) data = CommandSensorData(hass, command, command_timeout)
trigger_entity_config = {
CONF_UNIQUE_ID: unique_id,
CONF_NAME: Template(name, hass),
CONF_DEVICE_CLASS: sensor_config.get(CONF_DEVICE_CLASS),
}
async_add_entities( async_add_entities(
[ [
CommandSensor( CommandSensor(
data, data,
name, trigger_entity_config,
unit, unit,
state_class,
value_template, value_template,
json_attributes, json_attributes,
unique_id,
scan_interval, scan_interval,
) )
] ]
) )
class CommandSensor(SensorEntity): class CommandSensor(ManualTriggerEntity, SensorEntity):
"""Representation of a sensor that is using shell commands.""" """Representation of a sensor that is using shell commands."""
_attr_should_poll = False _attr_should_poll = False
@ -114,25 +124,30 @@ class CommandSensor(SensorEntity):
def __init__( def __init__(
self, self,
data: CommandSensorData, data: CommandSensorData,
name: str, config: ConfigType,
unit_of_measurement: str | None, unit_of_measurement: str | None,
state_class: SensorStateClass | None,
value_template: Template | None, value_template: Template | None,
json_attributes: list[str] | None, json_attributes: list[str] | None,
unique_id: str | None,
scan_interval: timedelta, scan_interval: timedelta,
) -> None: ) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
self._attr_name = name super().__init__(self.hass, config)
self.data = data self.data = data
self._attr_extra_state_attributes = {} self._attr_extra_state_attributes = {}
self._json_attributes = json_attributes self._json_attributes = json_attributes
self._attr_native_value = None self._attr_native_value = None
self._value_template = value_template self._value_template = value_template
self._attr_native_unit_of_measurement = unit_of_measurement self._attr_native_unit_of_measurement = unit_of_measurement
self._attr_unique_id = unique_id self._attr_state_class = state_class
self._scan_interval = scan_interval self._scan_interval = scan_interval
self._process_updates: asyncio.Lock | None = None self._process_updates: asyncio.Lock | None = None
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return extra state attributes."""
return cast(dict, self._attr_extra_state_attributes)
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Call when entity about to be added to hass.""" """Call when entity about to be added to hass."""
await super().async_added_to_hass() await super().async_added_to_hass()
@ -186,6 +201,7 @@ class CommandSensor(SensorEntity):
LOGGER.warning("Empty reply found when expecting JSON data") LOGGER.warning("Empty reply found when expecting JSON data")
if self._value_template is None: if self._value_template is None:
self._attr_native_value = None self._attr_native_value = None
self._process_manual_data(value)
return return
if self._value_template is not None: if self._value_template is not None:
@ -197,7 +213,7 @@ class CommandSensor(SensorEntity):
) )
else: else:
self._attr_native_value = value self._attr_native_value = value
self._process_manual_data(value)
self.async_write_ha_state() self.async_write_ha_state()