Template for a tricky sensor

I have a watering system (hydrawise) which outputs the number of minutes it has to run to the end of its current cycle. Eg if I have a 4 minute watering plan it outputs five state change records with a state of 4, 3, 2, 1, 0. I want to show a badge of how long the last cycle was. The sensor itself always shows the most recent value - zero ! How can I capture the first value of the latest sequence and keep it. The trick will be to save the state where the previous state was zero and the current state is not zero.
How do I do that?

Might be easier to do it with an automation and an input_number. Whenever the existing sensor changes state from: 0, then save the new value to the input_number.

@pnbruckner Doesn’t that get lost in a restart of HA?
This sensor only triggers in the middle of the night so kind of hard to test too !

If I look at the event record using SQL I can see the record I want. It has the new and old state. Just how to select it and save it in another sensor. I’ve been looking at things like trigger_from_state but not getting any sense out of that.

The current aspiration looks something like this:


- platform: template
  sensors:
    lawn_watered:
      value_template: "{% if states('sensor.lawn_watering_time') != '0' 
         and states('sensor.lawn_watering_time.old_state') == '0' %} 
         {{ states('sensor.lawn_watering_time') }} 
         {% else %} {{ states('sensor.lawn_watered') }} {% endif %}"

I found a solution that meets my need. No idea if it is the best way. Feedback appreciated.

- platform: sql
  queries:
    - name: lawn_time
      query: "select max(state) as lawn_water,substr(datetime(created,'localtime'),1,16) as date_time FROM states where entity_id = 'sensor.lawn_watering_time' group by substr(datetime(created,'localtime'),1,12) order by created desc limit 1"
      column: 'lawn_water'
      unit_of_measurement: mins

No. See doc.

It would be quite easy to test. Just use the Developer Tools → STATES page to force the sensor to change states, which will trigger the automation just like when the sensor changes on its own.

Although your solution works, it does require querying the database repeatedly on a periodic basis, so is an unnecessary load, and it doesn’t update immediately when the sensor first changes from zero. But maybe in the grand scheme of things it doesn’t matter. It is definitely an overall simpler solution, so that’s always good!