Split esphome state property decorators (#124332)
This commit is contained in:
parent
ebc49d938a
commit
41b129e990
6 changed files with 49 additions and 36 deletions
|
@ -118,20 +118,35 @@ def esphome_state_property[_R, _EntityT: EsphomeEntity[Any, Any]](
|
|||
) -> Callable[[_EntityT], _R | None]:
|
||||
"""Wrap a state property of an esphome entity.
|
||||
|
||||
This checks if the state object in the entity is set, and
|
||||
prevents writing NAN values to the Home Assistant state machine.
|
||||
This checks if the state object in the entity is set
|
||||
and returns None if it is not set.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
def _wrapper(self: _EntityT) -> _R | None:
|
||||
return func(self) if self._has_state else None
|
||||
|
||||
return _wrapper
|
||||
|
||||
|
||||
def esphome_float_state_property[_EntityT: EsphomeEntity[Any, Any]](
|
||||
func: Callable[[_EntityT], float | None],
|
||||
) -> Callable[[_EntityT], float | None]:
|
||||
"""Wrap a state property of an esphome entity that returns a float.
|
||||
|
||||
This checks if the state object in the entity is set, and returns
|
||||
None if its not set. If also prevents writing NAN values to the
|
||||
Home Assistant state machine.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
def _wrapper(self: _EntityT) -> float | None:
|
||||
if not self._has_state:
|
||||
return None
|
||||
val = func(self)
|
||||
if isinstance(val, float) and not math.isfinite(val):
|
||||
# Home Assistant doesn't use NaN or inf values in state machine
|
||||
# (not JSON serializable)
|
||||
return None
|
||||
return val
|
||||
# Home Assistant doesn't use NaN or inf values in state machine
|
||||
# (not JSON serializable)
|
||||
return None if val is None or not math.isfinite(val) else val
|
||||
|
||||
return _wrapper
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue