Average a sensor value only while another binary sensor is on

I am trying to calculate the average current a pump draws while it it is running. Currently I have the following entities already set up:

  • sensor.sp_measured_current: Current meaurement from ESPHome
  • binary_sensor.sump_pump_running: From code bellow
  • sensor.sump_pump_running_24h_count: From code bellow
  • sensor.sump_pump_running_24h_time: From code bellow

I would like to add sensor.sump_pump_running_24h_average that is the average over the last 24 hours of sensor.sp_measured_current while binary_sensor.sump_pump_running is on.
I have looked into the statistics and average sensors but they are averaging the entire 24 hours.

binary_sensor:
  - platfrom: template
    sensors:
      sump_pump_running:
        friendly_name: "Main Sump Pump Running"
        value_template: '{{states("sensor.sp_measured_current") | float > 2}}'

sensor:
  - platfrom: history_stats
    name: sump_ump_running_24h_count
    entity_id: binary_sensor.sump_pump_running
    state: "on"
    type: count
    end: "{{ now() }}"
    duration:
      hours: 24
  - platfrom: history_stats
    name: sump_ump_running_24h_time
    entity_id: binary_sensor.sump_pump_running
    state: "on"
    type: time
    end: "{{ now() }}"
    duration:
      hours: 24
1 Like