On vlaue range > but with lambda

Hi folks,

I am looking for advice how to approach my case more effectively. Basicaly, I want to dynamically change the above / below option of on_value_range trigger in HA GUI.

I have pH probe (ADC component) measuring the water. My goal is to automate the pH lowering aka dosing acid solution to water.
I can do it with on_value_range, but I realize, I can not use number component as mapped value for “above / below” option.
So, I tried the lambda function. It works, but the nice thing on value_on_range is, that it is triggered when crossing the threshold. Lambda function is evaluated on any value change. So, If I have the some actions in progress, it start the action in parallel, aka dosing the solution again. But in water, it takes some time to dissolve the acid. I can solve this with bigger update interval, but that doesn’t seems to be the right solution.

  - platform: template
    name: "pH"
    id: ph
    unit_of_measurement: 'pH'
    accuracy_decimals: 1
    update_interval: 10s
    lambda: 'return (id(ph_v).state);'
    filters:
      # Measured voltage -> Actual pH (buffer solution)
      - calibrate_linear:
          - 1.868 -> 7.0
          - 0.680 -> 4.0

# of course, only one trigger is used when the code is uploaded
# on_value_range works well, but I can not set the range in HA GUI 
    on_value_range:
      - below: 6.0
        then:
          - switch.turn_off: ph_dosing
      - above: 6.0
        then:
          - switch.turn_on: ph_dosing
# this works, but on_value is triggered on any value change
     on_value:
       then:
         if:
           condition:
             lambda: |-
               return id(ph).state > id(phTr).state;
           then:
             - switch.turn_on: ph_dosing
             - delay: 0.2s
             - switch.turn_off: ph_dosing
             - delay: 10s
             - switch.turn_on: Pump
             - delay: 15s
             - switch.turn_off: Pump
             - delay: 300s
           else:
             - switch.turn_off: ph_dosing

Is there a way, how to emulate the threshold crossing in lambda. Or is there better approach?

Perhaps you use a Template Number to control the threshold in HA.

Then create a Template Binary Sensor that is basically this bit.

 lambda: |-
               return id(ph).state > id(phTr).state;

Then trigger your actions via the on_press action or similar.

It may be helpful to add delay_on or off the the binary sensor too.

Not sure if this is the best solution but it’s an option…

That works. Thank you.

1 Like