Finding the mean of the absolute value of a sensor

I’m trying to detect power loss on a solar system with no direct integration .
My solar system w/battery will silently switch to battery, and I’m trying to detect when this happens.
My approach is a Tuya Wifi power clamp which is attached to the grid power of my inverter.
I can tell if I’m consuming power, or sending power to the provider, but I cannot tell when the flow stops.
I’ve tried with the following:

sensor:
  - platform: statistics
    name: "Average Grid Consumption over 5 minutes"
    entity_id: sensor.active_power_1
    state_characteristic: mean
    max_age:
      minutes: 5
    sampling_size: 50
    precision: 2

My problem is as the sun goes down, the sensor “bounces” between positive and negative as the sun fades, but the sensor is summing the net values, not the absolute value.

BTW, I have not tried to include my tuya power meter with the energy dashboard…

Thanks in advance,
tan

I assume there’s some reason you can’t just check for zero?

You could create a template sensor that has the absolute value of this sensor.active_power_1 and then create the statistics sensor on top of that. Something like:

template:
  - sensor:
    - name: Absolute value of active power
      state: >-
        {{ states('sensor.active_power_1') | abs }}

I am not completely clear on what you are trying to establish, but this template sensor will give you the absolute value of your active power sensor:

template:
  - sensor:
      - name: "Absolute Grid Consumption"
        unit_of_measurement: "W"
        state: "{{ states('sensor.active_power_1') | float(0) | abs }}"

You could then use this sensor in your statistics sensor?

Ah, that seems so obvious now :slight_smile:

I’ve seen some negative values that I couldn’t explain, so I renamed, and ended up with:

sensor:
  - platform: template
    sensors:
      abs_active_power_1:
        friendly_name: ABS Active Power 1
        value_template: >-
          {{ states('sensor.active_power_1') | float(0) | abs }}
        
  - platform: statistics
    name: "Average Grid Consumption over 5 minutes"
    entity_id: sensor.abs_active_power_1
    state_characteristic: mean
    max_age:
      minutes: 10
    sampling_size: 50
    precision: 2

I’ll report back after a few days, but thank you both!