Compare commits

...
10 Commits
7 changed files with 230 additions and 186 deletions
+1
View File
@@ -46,5 +46,6 @@ STATE_ACTIVE = "active"
STATE_OFF = "off" STATE_OFF = "off"
STATE_MANUAL_ON = "manual_on" STATE_MANUAL_ON = "manual_on"
STATE_MANUAL_OFF_COOLDOWN = "manual_off_cooldown" STATE_MANUAL_OFF_COOLDOWN = "manual_off_cooldown"
STATE_FORCE_STOPPED = "force_stopped"
STATE_ERROR = "error" STATE_ERROR = "error"
STATE_DISABLED = "disabled" STATE_DISABLED = "disabled"
+53 -21
View File
@@ -28,6 +28,7 @@ from .const import (
STATE_OFF, STATE_OFF,
STATE_MANUAL_ON, STATE_MANUAL_ON,
STATE_MANUAL_OFF_COOLDOWN, STATE_MANUAL_OFF_COOLDOWN,
STATE_FORCE_STOPPED,
STATE_ERROR, STATE_ERROR,
STATE_DISABLED, STATE_DISABLED,
) )
@@ -110,6 +111,9 @@ class MotionLightCoordinator(DataUpdateCoordinator):
attrs["main_sensors"] = self.main_sensors attrs["main_sensors"] = self.main_sensors
attrs["extend_sensors"] = self.extend_sensors attrs["extend_sensors"] = self.extend_sensors
attrs["lux_sensor"] = self.lux_sensor attrs["lux_sensor"] = self.lux_sensor
attrs["force_stop_sensor"] = self.force_stop_sensor
attrs["force_stop_state"] = self.force_stop_state
attrs["force_stop_active"] = self._state == STATE_FORCE_STOPPED
attrs["active_main_sensors"] = self._get_active_main_sensors() attrs["active_main_sensors"] = self._get_active_main_sensors()
attrs["active_extend_sensors"] = self._get_active_extend_sensors() attrs["active_extend_sensors"] = self._get_active_extend_sensors()
attrs["lux_value"] = self._get_current_lux() attrs["lux_value"] = self._get_current_lux()
@@ -154,8 +158,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
def set_manual_idle_timeout(self, value: float) -> None: def set_manual_idle_timeout(self, value: float) -> None:
self.manual_idle_timeout = int(value) self.manual_idle_timeout = int(value)
self.logger.info("Manual idle timeout set to %d sec", self.manual_idle_timeout) self.logger.info("Manual idle timeout set to %d sec", self.manual_idle_timeout)
# Если таймер уже тикает, а мы изменили значение на 0, нужно его отменить
if self.manual_idle_timeout <= 0 and self._manual_idle_timer: if self.manual_idle_timeout <= 0 and self._manual_idle_timer:
self.logger.info("Manual idle timeout set to 0, cancelling active timer") self.logger.info("Manual idle timeout set to 0, cancelling active timer")
self._manual_idle_timer() self._manual_idle_timer()
@@ -175,6 +177,15 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self.logger.info("Switches: %s, Main sensors: %s, Extend sensors: %s, Lux: %s", self.logger.info("Switches: %s, Main sensors: %s, Extend sensors: %s, Lux: %s",
self.switch_entities, self.main_sensors, self.extend_sensors, self.lux_sensor) self.switch_entities, self.main_sensors, self.extend_sensors, self.lux_sensor)
# Проверяем состояние force_stop_sensor при старте
if self.force_stop_sensor:
force_stop_state_obj = self.hass.states.get(self.force_stop_sensor)
if force_stop_state_obj and force_stop_state_obj.state == self.force_stop_state:
self.logger.info("Force stop sensor is already in stop state at startup")
await self._update_state(STATE_FORCE_STOPPED)
await self._start_listening()
return
any_on = any( any_on = any(
self.hass.states.get(s) and self.hass.states.get(s).state == "on" self.hass.states.get(s) and self.hass.states.get(s).state == "on"
for s in self.switch_entities for s in self.switch_entities
@@ -294,6 +305,11 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self.logger.debug("Integration disabled, ignoring") self.logger.debug("Integration disabled, ignoring")
return return
# БЛОКИРОВЩИК: Игнорируем движение, если активна принудительная остановка
if self._state == STATE_FORCE_STOPPED:
self.logger.debug("Ignoring during force_stopped")
return
self.logger.debug("Main sensor ON by %s, current state: %s", triggered_by, self._state) self.logger.debug("Main sensor ON by %s, current state: %s", triggered_by, self._state)
if self._state == STATE_MANUAL_OFF_COOLDOWN: if self._state == STATE_MANUAL_OFF_COOLDOWN:
@@ -302,7 +318,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
if self._state == STATE_MANUAL_ON: if self._state == STATE_MANUAL_ON:
self.logger.debug("During manual_on, resetting idle timer") self.logger.debug("During manual_on, resetting idle timer")
# ИЗМЕНЕНИЕ: Сбрасываем таймер только если он включен (>0)
if self.manual_idle_timeout > 0: if self.manual_idle_timeout > 0:
self._reset_manual_idle_timer() self._reset_manual_idle_timer()
return return
@@ -394,6 +409,11 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self.logger.debug("Integration disabled, ignoring") self.logger.debug("Integration disabled, ignoring")
return return
# БЛОКИРОВЩИК: Игнорируем движение, если активна принудительная остановка
if self._state == STATE_FORCE_STOPPED:
self.logger.debug("Ignoring during force_stopped")
return
self.logger.debug("Extend sensor ON by %s, current state: %s", triggered_by, self._state) self.logger.debug("Extend sensor ON by %s, current state: %s", triggered_by, self._state)
if self._state == STATE_IDLE: if self._state == STATE_IDLE:
@@ -406,7 +426,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
if self._state == STATE_MANUAL_ON: if self._state == STATE_MANUAL_ON:
self.logger.debug("During manual_on, resetting idle timer") self.logger.debug("During manual_on, resetting idle timer")
# ИЗМЕНЕНИЕ: Сбрасываем таймер только если он включен (>0)
if self.manual_idle_timeout > 0: if self.manual_idle_timeout > 0:
self._reset_manual_idle_timer() self._reset_manual_idle_timer()
return return
@@ -439,6 +458,11 @@ class MotionLightCoordinator(DataUpdateCoordinator):
"""Handle target switch state change.""" """Handle target switch state change."""
if not self.respect_manual: if not self.respect_manual:
return return
# БЛОКИРОВЩИК: Игнорируем ручные переключения, если активна принудительная остановка
if self._state == STATE_FORCE_STOPPED:
self.logger.debug("Ignoring manual change during force_stopped")
return
new_state = event.data.get("new_state") new_state = event.data.get("new_state")
old_state = event.data.get("old_state") old_state = event.data.get("old_state")
@@ -485,9 +509,27 @@ class MotionLightCoordinator(DataUpdateCoordinator):
if not new_state: if not new_state:
return return
# Если датчик перешел в блокирующее состояние
if new_state.state == self.force_stop_state: if new_state.state == self.force_stop_state:
self.logger.info("Force stop triggered by %s", event.data.get("entity_id")) self.logger.info("Force stop triggered by %s", event.data.get("entity_id"))
self.hass.async_create_task(self._force_stop()) self.hass.async_create_task(self._enter_force_stop())
# Если датчик вышел из блокирующего состояния
else:
self.logger.info("Force stop released by %s", event.data.get("entity_id"))
self.hass.async_create_task(self._exit_force_stop())
async def _enter_force_stop(self):
"""Enter force_stopped state."""
self.logger.info("Entering force_stopped state")
self._cancel_all_timers()
if self._state in (STATE_ON, STATE_DELAYING, STATE_ACTIVE, STATE_MANUAL_ON):
await self._turn_off_switches()
await self._update_state(STATE_FORCE_STOPPED)
async def _exit_force_stop(self):
"""Exit force_stopped state to idle."""
self.logger.info("Exiting force_stopped state")
await self._update_state(STATE_IDLE)
def _is_any_main_sensor_active(self) -> bool: def _is_any_main_sensor_active(self) -> bool:
"""Check if any main sensor is currently in 'on' state.""" """Check if any main sensor is currently in 'on' state."""
@@ -658,11 +700,11 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self.hass.async_create_task(self._update_state(STATE_IDLE)) self.hass.async_create_task(self._update_state(STATE_IDLE))
async def _turn_on_switches(self) -> None: async def _turn_on_switches(self) -> None:
"""Turn on switches with our context.""" """Turn on switches/lights with our context."""
ctx = Context( ctx = Context(
id=f"motion_light_{self.entry.entry_id}_{dt_util.utcnow().timestamp()}" id=f"motion_light_{self.entry.entry_id}_{dt_util.utcnow().timestamp()}"
) )
self.logger.info("Turning ON switches: %s", self.switch_entities) self.logger.info("Turning ON entities: %s", self.switch_entities)
await self.hass.services.async_call( await self.hass.services.async_call(
"homeassistant", "homeassistant",
"turn_on", "turn_on",
@@ -671,11 +713,11 @@ class MotionLightCoordinator(DataUpdateCoordinator):
) )
async def _turn_off_switches(self) -> None: async def _turn_off_switches(self) -> None:
"""Turn off switches with our context.""" """Turn off switches/lights with our context."""
ctx = Context( ctx = Context(
id=f"motion_light_{self.entry.entry_id}_{dt_util.utcnow().timestamp()}" id=f"motion_light_{self.entry.entry_id}_{dt_util.utcnow().timestamp()}"
) )
self.logger.info("Turning OFF switches: %s", self.switch_entities) self.logger.info("Turning OFF entities: %s", self.switch_entities)
await self.hass.services.async_call( await self.hass.services.async_call(
"homeassistant", "homeassistant",
"turn_off", "turn_off",
@@ -686,7 +728,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
async def _enter_manual_on(self): async def _enter_manual_on(self):
"""Enter manual_on state.""" """Enter manual_on state."""
await self._update_state(STATE_MANUAL_ON) await self._update_state(STATE_MANUAL_ON)
# ИЗМЕНЕНИЕ: Запускаем таймер только если он не отключен (не равен 0)
if self.manual_idle_timeout > 0: if self.manual_idle_timeout > 0:
self._reset_manual_idle_timer() self._reset_manual_idle_timer()
else: else:
@@ -694,7 +735,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
def _reset_manual_idle_timer(self): def _reset_manual_idle_timer(self):
"""Reset manual idle timer.""" """Reset manual idle timer."""
# ИЗМЕНЕНИЕ: Защита от создания таймера при значении 0
if self.manual_idle_timeout <= 0: if self.manual_idle_timeout <= 0:
return return
@@ -715,8 +755,8 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self.hass.async_create_task(self._turn_off_switches_manual()) self.hass.async_create_task(self._turn_off_switches_manual())
async def _turn_off_switches_manual(self): async def _turn_off_switches_manual(self):
"""Turn off switches in manual mode.""" """Turn off switches/lights in manual mode."""
self.logger.info("Turning OFF switches (manual timeout): %s", self.switch_entities) self.logger.info("Turning OFF entities (manual timeout): %s", self.switch_entities)
await self.hass.services.async_call( await self.hass.services.async_call(
"homeassistant", "homeassistant",
"turn_off", "turn_off",
@@ -756,14 +796,6 @@ class MotionLightCoordinator(DataUpdateCoordinator):
self._lux_cooldown_timer = None self._lux_cooldown_timer = None
self.logger.info("Lux cooldown expired") self.logger.info("Lux cooldown expired")
async def _force_stop(self):
"""Force stop — turn off switches."""
self.logger.info("Force stop called")
self._cancel_all_timers()
await self._turn_off_switches()
await self._update_state(STATE_OFF)
async_call_later(self.hass, 1, self._transition_to_idle)
def _cancel_all_timers(self): def _cancel_all_timers(self):
"""Cancel all timers.""" """Cancel all timers."""
if self._motion_detect_timer: if self._motion_detect_timer:
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"domain": "motion_light", "domain": "motion_light",
"name": "Motion Light", "name": "Motion Light",
"version": "1.0.0", "version": "1.0.2",
"documentation": "https://github.com/sirmrak/motion_light", "documentation": "https://github.com/sirmrak/motion_light",
"issue_tracker": "https://github.com/sirmrak/motion_light/issues", "issue_tracker": "https://github.com/sirmrak/motion_light/issues",
"dependencies": [], "dependencies": [],
+172 -164
View File
@@ -1,165 +1,173 @@
"""Number platform for Motion Light settings.""" """Number platform for Motion Light settings."""
import logging import logging
from homeassistant.components.number import NumberEntity from homeassistant.components.number import NumberEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfTime from homeassistant.const import UnitOfTime
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.device_registry import DeviceInfo
from .const import ( from .const import (
DOMAIN, DOMAIN,
ENTITY_MOTION_FILTER, CONF_LUX_SENSOR,
ENTITY_OFF_DELAY, ENTITY_MOTION_FILTER,
ENTITY_LUX_THRESHOLD, ENTITY_OFF_DELAY,
ENTITY_LUX_COOLDOWN, ENTITY_LUX_THRESHOLD,
ENTITY_MANUAL_IDLE_TIMEOUT, ENTITY_LUX_COOLDOWN,
ENTITY_MANUAL_OFF_COOLDOWN, ENTITY_MANUAL_IDLE_TIMEOUT,
DEFAULT_MOTION_FILTER, ENTITY_MANUAL_OFF_COOLDOWN,
DEFAULT_OFF_DELAY, DEFAULT_MOTION_FILTER,
DEFAULT_LUX_THRESHOLD, DEFAULT_OFF_DELAY,
DEFAULT_LUX_COOLDOWN, DEFAULT_LUX_THRESHOLD,
DEFAULT_MANUAL_IDLE_TIMEOUT, DEFAULT_LUX_COOLDOWN,
DEFAULT_MANUAL_OFF_COOLDOWN, DEFAULT_MANUAL_IDLE_TIMEOUT,
) DEFAULT_MANUAL_OFF_COOLDOWN,
)
_LOGGER = logging.getLogger(__name__)
_LOGGER = logging.getLogger(__name__)
class PrefixLoggerAdapter(logging.LoggerAdapter):
"""Logger adapter that adds a prefix to log messages.""" class PrefixLoggerAdapter(logging.LoggerAdapter):
"""Logger adapter that adds a prefix to log messages."""
def process(self, msg, kwargs):
"""Add prefix to the log message.""" def process(self, msg, kwargs):
return f"[{self.extra.get('name', 'Unknown')}] {msg}", kwargs """Add prefix to the log message."""
return f"[{self.extra.get('name', 'Unknown')}] {msg}", kwargs
TRANSLATION_KEYS = {
ENTITY_MOTION_FILTER: "motion_light_motion_filter", TRANSLATION_KEYS = {
ENTITY_OFF_DELAY: "motion_light_off_delay", ENTITY_MOTION_FILTER: "motion_light_motion_filter",
ENTITY_LUX_THRESHOLD: "motion_light_lux_threshold", ENTITY_OFF_DELAY: "motion_light_off_delay",
ENTITY_LUX_COOLDOWN: "motion_light_lux_cooldown", ENTITY_LUX_THRESHOLD: "motion_light_lux_threshold",
ENTITY_MANUAL_IDLE_TIMEOUT: "motion_light_manual_idle_timeout", ENTITY_LUX_COOLDOWN: "motion_light_lux_cooldown",
ENTITY_MANUAL_OFF_COOLDOWN: "motion_light_manual_off_cooldown", ENTITY_MANUAL_IDLE_TIMEOUT: "motion_light_manual_idle_timeout",
} ENTITY_MANUAL_OFF_COOLDOWN: "motion_light_manual_off_cooldown",
}
ICONS = {
ENTITY_MOTION_FILTER: "mdi:timer-outline", ICONS = {
ENTITY_OFF_DELAY: "mdi:timer-sand", ENTITY_MOTION_FILTER: "mdi:timer-outline",
ENTITY_LUX_THRESHOLD: "mdi:brightness-5", ENTITY_OFF_DELAY: "mdi:timer-sand",
ENTITY_LUX_COOLDOWN: "mdi:timer-pause", ENTITY_LUX_THRESHOLD: "mdi:brightness-5",
ENTITY_MANUAL_IDLE_TIMEOUT: "mdi:timer-alert", ENTITY_LUX_COOLDOWN: "mdi:timer-pause",
ENTITY_MANUAL_OFF_COOLDOWN: "mdi:timer-off", ENTITY_MANUAL_IDLE_TIMEOUT: "mdi:timer-alert",
} ENTITY_MANUAL_OFF_COOLDOWN: "mdi:timer-off",
}
UNITS = {
ENTITY_MOTION_FILTER: UnitOfTime.SECONDS, UNITS = {
ENTITY_OFF_DELAY: UnitOfTime.SECONDS, ENTITY_MOTION_FILTER: UnitOfTime.SECONDS,
ENTITY_LUX_THRESHOLD: "lx", ENTITY_OFF_DELAY: UnitOfTime.SECONDS,
ENTITY_LUX_COOLDOWN: UnitOfTime.SECONDS, ENTITY_LUX_THRESHOLD: "lx",
ENTITY_MANUAL_IDLE_TIMEOUT: UnitOfTime.SECONDS, ENTITY_LUX_COOLDOWN: UnitOfTime.SECONDS,
ENTITY_MANUAL_OFF_COOLDOWN: UnitOfTime.SECONDS, ENTITY_MANUAL_IDLE_TIMEOUT: UnitOfTime.SECONDS,
} ENTITY_MANUAL_OFF_COOLDOWN: UnitOfTime.SECONDS,
}
async def async_setup_entry(
hass: HomeAssistant, async def async_setup_entry(
entry: ConfigEntry, hass: HomeAssistant,
async_add_entities: AddEntitiesCallback, entry: ConfigEntry,
) -> None: async_add_entities: AddEntitiesCallback,
"""Set up Motion Light number entities.""" ) -> None:
coordinator = hass.data[DOMAIN][entry.entry_id] """Set up Motion Light number entities."""
entities = [ coordinator = hass.data[DOMAIN][entry.entry_id]
MotionLightNumber(coordinator, entry, ENTITY_MOTION_FILTER, 0, 10, 1, DEFAULT_MOTION_FILTER),
MotionLightNumber(coordinator, entry, ENTITY_OFF_DELAY, 0, 600, 5, DEFAULT_OFF_DELAY), lux_sensor = entry.options.get(CONF_LUX_SENSOR) or entry.data.get(CONF_LUX_SENSOR)
MotionLightNumber(coordinator, entry, ENTITY_LUX_THRESHOLD, 1, 1000, 10, DEFAULT_LUX_THRESHOLD),
MotionLightNumber(coordinator, entry, ENTITY_LUX_COOLDOWN, 0, 300, 5, DEFAULT_LUX_COOLDOWN), entities = [
MotionLightNumber(coordinator, entry, ENTITY_MANUAL_IDLE_TIMEOUT, 0, 3600, 60, DEFAULT_MANUAL_IDLE_TIMEOUT), MotionLightNumber(coordinator, entry, ENTITY_MOTION_FILTER, 0, 10, 1, DEFAULT_MOTION_FILTER),
MotionLightNumber(coordinator, entry, ENTITY_MANUAL_OFF_COOLDOWN, 0, 300, 5, DEFAULT_MANUAL_OFF_COOLDOWN), MotionLightNumber(coordinator, entry, ENTITY_OFF_DELAY, 0, 600, 5, DEFAULT_OFF_DELAY),
] MotionLightNumber(coordinator, entry, ENTITY_MANUAL_IDLE_TIMEOUT, 0, 3600, 30, DEFAULT_MANUAL_IDLE_TIMEOUT),
async_add_entities(entities) MotionLightNumber(coordinator, entry, ENTITY_MANUAL_OFF_COOLDOWN, 0, 300, 5, DEFAULT_MANUAL_OFF_COOLDOWN),
]
class MotionLightNumber(CoordinatorEntity, NumberEntity, RestoreEntity): if lux_sensor:
"""Representation of a Motion Light setting as a number entity.""" entities.extend([
_attr_has_entity_name = True MotionLightNumber(coordinator, entry, ENTITY_LUX_THRESHOLD, 1, 1000, 10, DEFAULT_LUX_THRESHOLD),
MotionLightNumber(coordinator, entry, ENTITY_LUX_COOLDOWN, 0, 300, 5, DEFAULT_LUX_COOLDOWN),
def __init__(self, coordinator, entry, entity_id, min_val, max_val, step, default): ])
"""Initialize the number entity."""
super().__init__(coordinator) async_add_entities(entities)
self.entry = entry
class MotionLightNumber(CoordinatorEntity, NumberEntity, RestoreEntity):
self.logger = PrefixLoggerAdapter(_LOGGER, {"name": entry.title}) """Representation of a Motion Light setting as a number entity."""
_attr_has_entity_name = True
self._entity_suffix = entity_id
self._attr_unique_id = f"{entry.entry_id}_{entity_id}" def __init__(self, coordinator, entry, entity_id, min_val, max_val, step, default):
self._attr_translation_key = TRANSLATION_KEYS[entity_id] """Initialize the number entity."""
self._attr_native_min_value = min_val super().__init__(coordinator)
self._attr_native_max_value = max_val self.entry = entry
self._attr_native_step = step
self._attr_native_unit_of_measurement = UNITS[entity_id] self.logger = PrefixLoggerAdapter(_LOGGER, {"name": entry.title})
self._attr_icon = ICONS[entity_id]
self._default_value = default self._entity_suffix = entity_id
self._attr_native_value = default self._attr_unique_id = f"{entry.entry_id}_{entity_id}"
self._attr_device_info = DeviceInfo( self._attr_translation_key = TRANSLATION_KEYS[entity_id]
identifiers={(DOMAIN, entry.entry_id)}, self._attr_native_min_value = min_val
name=entry.title, self._attr_native_max_value = max_val
manufacturer="Motion Light", self._attr_native_step = step
model="Switch Control Integration", self._attr_native_unit_of_measurement = UNITS[entity_id]
) self._attr_icon = ICONS[entity_id]
self._default_value = default
@property self._attr_native_value = default
def native_value(self) -> float: self._attr_device_info = DeviceInfo(
"""Return the current value.""" identifiers={(DOMAIN, entry.entry_id)},
return self._attr_native_value name=entry.title,
manufacturer="Motion Light",
async def async_set_native_value(self, value: float) -> None: model="Switch Control Integration",
"""Update the current value.""" )
self._attr_native_value = value
self.logger.info("Setting %s to %s", self._entity_suffix, value) @property
def native_value(self) -> float:
if self._entity_suffix == ENTITY_MOTION_FILTER: """Return the current value."""
self.coordinator.set_motion_filter(value) return self._attr_native_value
elif self._entity_suffix == ENTITY_OFF_DELAY:
self.coordinator.set_off_delay(value) async def async_set_native_value(self, value: float) -> None:
elif self._entity_suffix == ENTITY_LUX_THRESHOLD: """Update the current value."""
self.coordinator.set_lux_threshold(value) self._attr_native_value = value
elif self._entity_suffix == ENTITY_LUX_COOLDOWN: self.logger.info("Setting %s to %s", self._entity_suffix, value)
self.coordinator.set_lux_cooldown(value)
elif self._entity_suffix == ENTITY_MANUAL_IDLE_TIMEOUT: if self._entity_suffix == ENTITY_MOTION_FILTER:
self.coordinator.set_manual_idle_timeout(value) self.coordinator.set_motion_filter(value)
elif self._entity_suffix == ENTITY_MANUAL_OFF_COOLDOWN: elif self._entity_suffix == ENTITY_OFF_DELAY:
self.coordinator.set_manual_off_cooldown(value) self.coordinator.set_off_delay(value)
elif self._entity_suffix == ENTITY_LUX_THRESHOLD:
self.async_write_ha_state() self.coordinator.set_lux_threshold(value)
elif self._entity_suffix == ENTITY_LUX_COOLDOWN:
async def async_added_to_hass(self) -> None: self.coordinator.set_lux_cooldown(value)
"""Handle entity which will be added.""" elif self._entity_suffix == ENTITY_MANUAL_IDLE_TIMEOUT:
await super().async_added_to_hass() self.coordinator.set_manual_idle_timeout(value)
last_state = await self.async_get_last_state() elif self._entity_suffix == ENTITY_MANUAL_OFF_COOLDOWN:
if last_state is not None: self.coordinator.set_manual_off_cooldown(value)
try:
value = float(last_state.state) self.async_write_ha_state()
self._attr_native_value = value
self.logger.info("Restored %s: %s", self._entity_suffix, value) async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
if self._entity_suffix == ENTITY_MOTION_FILTER: await super().async_added_to_hass()
self.coordinator.set_motion_filter(value) last_state = await self.async_get_last_state()
elif self._entity_suffix == ENTITY_OFF_DELAY: if last_state is not None:
self.coordinator.set_off_delay(value) try:
elif self._entity_suffix == ENTITY_LUX_THRESHOLD: value = float(last_state.state)
self.coordinator.set_lux_threshold(value) self._attr_native_value = value
elif self._entity_suffix == ENTITY_LUX_COOLDOWN: self.logger.info("Restored %s: %s", self._entity_suffix, value)
self.coordinator.set_lux_cooldown(value)
elif self._entity_suffix == ENTITY_MANUAL_IDLE_TIMEOUT: if self._entity_suffix == ENTITY_MOTION_FILTER:
self.coordinator.set_manual_idle_timeout(value) self.coordinator.set_motion_filter(value)
elif self._entity_suffix == ENTITY_MANUAL_OFF_COOLDOWN: elif self._entity_suffix == ENTITY_OFF_DELAY:
self.coordinator.set_manual_off_cooldown(value) self.coordinator.set_off_delay(value)
except (ValueError, TypeError): elif self._entity_suffix == ENTITY_LUX_THRESHOLD:
self.logger.warning("Could not restore %s, using default", self._entity_suffix) self.coordinator.set_lux_threshold(value)
self.async_write_ha_state() elif self._entity_suffix == ENTITY_LUX_COOLDOWN:
self.coordinator.set_lux_cooldown(value)
def _handle_coordinator_update(self) -> None: elif self._entity_suffix == ENTITY_MANUAL_IDLE_TIMEOUT:
"""Handle updated data from the coordinator.""" self.coordinator.set_manual_idle_timeout(value)
elif self._entity_suffix == ENTITY_MANUAL_OFF_COOLDOWN:
self.coordinator.set_manual_off_cooldown(value)
except (ValueError, TypeError):
self.logger.warning("Could not restore %s, using default", self._entity_suffix)
self.async_write_ha_state()
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self.async_write_ha_state() self.async_write_ha_state()
+1
View File
@@ -45,6 +45,7 @@ class MotionLightStatusSensor(CoordinatorEntity, SensorEntity):
"off": "mdi:lightbulb-off-outline", "off": "mdi:lightbulb-off-outline",
"manual_on": "mdi:hand-back-left", "manual_on": "mdi:hand-back-left",
"manual_off_cooldown": "mdi:timer-pause", "manual_off_cooldown": "mdi:timer-pause",
"force_stopped": "mdi:stop-circle-outline",
"error": "mdi:alert-circle", "error": "mdi:alert-circle",
"disabled": "mdi:lightbulb-off", "disabled": "mdi:lightbulb-off",
} }
@@ -55,6 +55,7 @@
"off": "Off", "off": "Off",
"manual_on": "Manual on", "manual_on": "Manual on",
"manual_off_cooldown": "Manual off cooldown", "manual_off_cooldown": "Manual off cooldown",
"force_stopped": "Force stopped",
"error": "Error", "error": "Error",
"disabled": "Disabled" "disabled": "Disabled"
} }
@@ -55,6 +55,7 @@
"off": "Выключено", "off": "Выключено",
"manual_on": "Ручное включение", "manual_on": "Ручное включение",
"manual_off_cooldown": "Пауза после ручного выкл.", "manual_off_cooldown": "Пауза после ручного выкл.",
"force_stopped": "Принудительная остановка",
"error": "Ошибка", "error": "Ошибка",
"disabled": "Отключено" "disabled": "Отключено"
} }