Skip to content

Conversation

dmamelin
Copy link
Contributor

@dmamelin dmamelin commented Oct 9, 2025

StateVal Helpers

  • New StateVal helpers wrap Home Assistant’s forgiving converters, so input_number.brightness.as_int(default=0) or sensor.timestamp.as_datetime() just work - no more manual int(...)/float(...) juggling or wrapping those casts in try/except.
  • Added availability checks: .is_unknown(), .is_unavailable(), and .has_value() replace ad-hoc comparisons with unavailable/unknown.

Example (for illustration only):

@state_trigger("float(sensor.some_number)>10") #got error on unavailable/unknown
def old_style():
    try:
        sensor_value = int(sensor.another_sensor)
    except Exception:
        sensor_value = 0
    if sensor_value > 10 or binary_sensor.motion == "on":
        try:
            temperature = float(sensor.temperature)
            if temperature > 20:
                if climate.ac not in ["unavailable", "unknown"]: #check device online
                    climate.ac.set_temperature(temperature=sensor_value+10)
        except Exception:
            pass

@state_trigger("sensor.some_number.as_float(default=0)>10") # no error on unavailable/unknown
def new_style():
    sensor_value = sensor.another_sensor.as_int(default=0)
    
    if sensor_value > 10 or binary_sensor.motion.as_bool(False):
        temperature = sensor.temperature.as_float(-100)
        if temperature > 20 and climate.ac.has_value():
            climate.ac.set_temperature(temperature=sensor_value+10)

@craigbarratt
Copy link
Member

This is awesome! Thanks for the PR.

@craigbarratt craigbarratt merged commit 29a9891 into custom-components:master Oct 9, 2025
6 checks passed
@dmamelin
Copy link
Contributor Author

dmamelin commented Oct 9, 2025

Found a regression affecting state_active and as_*; working on a fix.

@dmamelin dmamelin deleted the feature/stateval-conversion-helpers branch October 11, 2025 17:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants