custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
874 stars 46 forks source link

state_trigger and unavailable entities #550

Open ALERTua opened 10 months ago

ALERTua commented 10 months ago
@state_trigger("float(sensor.temperature) > 10")
@state_active("sensor.temperature != 'unavailable'")
def function_1(**kwargs):
    pass

Imagine sensor.temperature goes unavailable (which is a regular thing for me). You expect function_1 not to trigger due to the state_active condition. But in reality the state_trigger condition is being crashed by an exception:

ERROR (MainThread) [custom_components.pyscript.file.my_file.function_1] Exception in <file.my_file.function_1 @state_trigger()> line 1:
    float(sensor.temperaturet) > 10
ValueError: could not convert string to float: 'unavailable'

because of pyscript.trigger:270 state_trig_expr = f"any([{', '.join(state_trig)}])" pyscript.trigger:277 state_trig_eval.parse(state_trig_expr, mode="eval")

As a workaround you can move state_active unavailability check to the state_trigger, thus lower code readability.

@state_trigger("sensor.temperature != 'unavailable' and float(sensor.temperature) > 10")
def function_1(**kwargs):
    pass

But imagine you want to turn off your server room air conditioning if the room temperature is low enough, the humidity is low enough, the server CPU temperature is low enough, drives' temperature is low enough. Each one of these entities can become unavailable and your code becomes a mess due to float conversions in state_trigger decorators. Instead of

@state_trigger(
    f"float({SERVER_ROOM_HUMIDITY}) <= 45"
    f" and float({SERVER_ROOM_TEMPERATURE}) <= 27.5"
    f" and float({SERVER_HDD_TEMP}) <= 50"
    f" and float({SERVER_TEMPERATURE}) <= 60",
)
def function_1(**kwargs):
    pass

this becomes

@state_trigger(
    f"hass.states.get(f'{SERVER_ROOM_HUMIDITY}') is not None "
    f" and {SERVER_ROOM_HUMIDITY} not in ('unavailable', 'unknown', 'null', None, 'none', 'None') "
    f" and float({SERVER_ROOM_HUMIDITY}) <= 45 "

    f" and hass.states.get(f'{SERVER_ROOM_TEMPERATURE}') is not None "
    f" and {SERVER_ROOM_TEMPERATURE} not in ('unavailable', 'unknown', 'null', None, 'none', 'None') "
    f" and float({SERVER_ROOM_TEMPERATURE}) <= 27.5"

    f" and hass.states.get(f'{SERVER_HDD_TEMP}') is not None "
    f" and {SERVER_HDD_TEMP} not in ('unavailable', 'unknown', 'null', None, 'none', 'None') "
    f" and float({SERVER_HDD_TEMP}) <= 50"

    f" and hass.states.get(f'{SERVER_TEMPERATURE}') is not None "
    f" and {SERVER_TEMPERATURE} not in ('unavailable', 'unknown', 'null', None, 'none', 'None') "
    f" and float({SERVER_TEMPERATURE}) <= 60",
)
def function_1(**kwargs):
    pass

This would be much better if state_trigger was being parsed only if the state_active condition is met.