Trigger template sensor

I have 4 sensors that are populated with an hour timestamp (eg 2023-01-25T00:00:00+00:00) every time they fetch some data relating to energy usage at that time. This is done via a restful api call.

So, at the point where all this data has been collected, these 4 sensors will have matching timestamps.

When all 4 have changed to a matching timestamp, I would like to collate all the info in a single triggered template sensor.

I have used such triggered template sensors before where I am just checking for a single sensor state change. However, I need this new template to trigger only when all 4 of these match each other (ie the last of these 4 is updated with a matching timestamp).

I cannot be certain which of the 4 will be updated last so I guess my logic needs to be:

  1. A timestamp has changed in one of the 4 sensors
  2. All 4 now match

Can that be coded in yaml?

Basic info regarding the names of theses restful sensors and how they are populated is below which may help in formulating the code:

  sensor:
    - name: "test elec cons time"
      value_template: "{{ value_json.data.0.0 | int | timestamp_local }}"
  sensor:
    - name: "test elec cost time"
      value_template: "{{ value_json.data.0.0 | int | timestamp_local }}"
  sensor:
    - name: "test gas cons time"
      value_template: "{{ value_json.data.0.0 | int | timestamp_local }}"
  sensor:
    - name: "test gas cost time"
      value_template: "{{ value_json.data.0.0 | int | timestamp_local }}"

Template triggers update whenever one of the sensors inside the template changes. So that takes care of requirement 1. Then just match the sensor states in the template. E.g.

trigger:
  - platform: template
    value_template: >
      {{ states('sensor.test_elec _cons_time') == states('sensor.test_elec _cost_time') and 
         states('sensor.test_elec _cost_time') == states('sensor.test_gas _cons_time') and 
         states('sensor.test_gas _cons_time') == states('sensor.test_gas _cost_time') }}

Copy-paste the following template into the Template Editor and confirm it reports true when all four sensors have the same state value. If it meets your requirements, use it in a Template Trigger.

  {{ [ states('sensor.test_elect_cons_time'),
       states('sensor.test_elect_cost_time'),
       states('sensor.test_gas_cons_time'),
       states('sensor.test_gas_cost_time') ]
    | unique | list | count == 1 }}

Thanks for both the answers. I did eventually use the unique method. Cheers

1 Like