Combining multiple sensor values into one with most recent wins strategy

Hi All,

I’m looking to see what the best (or just easiest!) way to take merge the values of 2 sensors into one.
Fibaro wall plugs have 2 power reports that appear in HA as two separate sensors.
I’d like to combine them in a way that both reports are updating the one power value - with the most recent report always being the more accurate.

Does that make sense, and is it feasible?

thanks for your time!

Eamonn

@halfbaked

You should be able to use a template sensor with this as the template.

{{ ((float(states.sensor.home_energy_monitor_20.state) + 
     float(states.sensor.home_energy_monitor_2_37.state))) | round(2)
}}

The min/max component with give you a potential desired result as well.

1 Like

Thanks Mike, I appreciate the input. I’m a newbie here with HA, so could be wrong but is that trying to give me the average of the two? What I’m looking for is the same effect as how presence with multiple platforms (for example: nmap + owntracks) where the most recent update is the determinant.

Sorry misnderstood. This is possible but might take a little work.

Maybe start a template sensor like this for both.

  plw_sensor_last_update:
    value_template: "{% if states.sensor.power_line_watts %}{{(as_timestamp(now())-as_timestamp(states.sensor.power_line_watts.last_updated)) | int }}{% else %}??{% endif %}"
    unit_of_measurement: 'sec'
    entity_id:
      - sensor.time
      - sensor.power_line_watts

Then automations to hide a group with the entity that is the oldest.

That’s what I was looking for. Thanks a lot!

1 Like

Tackling this recently I have another approach using input_number (formerly input_slider).

You don’t want the input_number to appear in the UI (with its input box) - you’ll want to add an extra template sensor for that - but the slider has the really neat property of discarding values outside its min and max parameters. So you can filter out dirty sensor data.

The automation is trivial and just updates the input_number if any of the child sensors report.

input_number:
  mostrecent_power:
    step: 0.1
    min: 0
    max: 2000
    mode: box
    unit_of_measurement: "W"

automation:
  - alias: "Latest Power"
    trigger:
      - platform: state
        entity_id:
          - sensor.mostrecent_1_power
          - sensor.mostrecent_2_power
    action:
      - service: input_number.set_value
        data_template:
          entity_id: input_number.mostrecent_power
          value: '{{ trigger.to_state.state }}'

The proper fix for this within HA is for the min_max sensor to support a .last attribute of course…