Lambda with addressable_set

I’m trying to make my esphome implementation a bit cleaner and easier to maintain. As part of that, I’m trying to lean on lambdas to selectively set the color in an addressible_set action.

What I have right now (below) works but is hard to maintain and takes up a bunch of room

- if:
    condition:
      text_sensor.state:
        id: sensor_front_lock
        state: 'locked'
    then:
      - light.addressable_set:
          id: door_alert
          range_from: ${front_lock}
          range_to: ${front_lock}
          red: 0
          green: 1
          blue: 0
    else:
      - light.addressable_set:
          id: door_alert
          range_from: ${front_lock}
          range_to: ${front_lock}
          red: 1
          green: 0
          blue: 0

I’ve tried to set this down to a single addressable_set call with the following, but the light doesn’t light up

- light.addressable_set:
    id: door_alert
    range_from: ${front_lock}
    range_to: ${front_lock}
    red: !lambda |-
      return (id(sensor_front_lock).state == "locked") ? 0 : 1;
    green: !lambda |-
      return (id(sensor_front_lock).state == "locked") ? 1 : 0;
    blue: 0

I have tried this with both 1 and 1.0 being returned. I’ve tried this by expanding it to a full if/else instead of the ternary but no amount of lambdas I write seem to make this work. What am I missing?

Bonus question:
I’ve got to do similar logic for a total of 4 locks and then 4 binary sensors. Is there a way to write a function that takes in some parameters so I can just write all the color logic once and pass in the from/to and it’s state?

If you use lambdas, for the red, green and blue values you need to return a value in the range 0-255 instead of 0-1 (yes, this is not what the documentation says, I’m working on fixing it for v1.20).

As for your bonus question, using the includes option any C++ file with custom functions can be included: ESPHome Core Configuration — ESPHome

Thanks for the clarification. I had seen the .h information but was hopeful there was a different way since it doesn’t seem like there’s an easy way to manage .h files in the ESPHome web frontend.