How to prevent extreme values (maximums and minimums) of sensors that do calculations of a binary sensor outputs?

Hello, I’ve been wrecking my brain for the past couple of weeks with some of my sensors and would appreciate any help.

In short
I work for a small company and I need to calculate the amount (count), tempo (sec/piece) and trend/projections for SKUs of our product getting processed.

The only physical sensor I’m working with is a laser sensor that detects when a piece goes by (binary sensor, with OFF and ON states).

Detailed
This sensor is set up in HA as binary_sensor.teksturat_input and outputs ON whenever a piece is detected, otherwise it’s in OFF state.

I’m trying to create additional functional sensors/entities in HA that would do various calculations.

The main and most basic data I get is the amount of pieces processed (simple count of the binary sensor ON states).

Then I calculate how many pieces are done per minute (count how many ON states in the past 60 seconds).

sensor:
  - platform: history_stats
    name: Teksturat count 1min
    unique_id: teksturat_count_1min
    entity_id: binary_sensor.teksturat_input
    state: "on"
    type: count
    start: "{{ now() - timedelta(seconds=60) }}"
    end: "{{ now() }}"

After that I calculate the average tempo (seconds per piece) for the work station (60 divided by the value of the previous sensor that counts for 60 seconds).

template:
  - sensor:
      - name: "Average seconds per piece (1min)"
        unique_id: teksturat_1min_average_time/piece
        unit_of_measurement: "seconds"
        state: >-
          {% set count = states('sensor.teksturat_count_1min') | int %}
          {% if count > 0 %}
            {{ (60 / count) | round(1) }}
          {% else %}
            0
          {% endif %}

I’ve made some additional sensors/entities that do further calculations (projected until end of day, percent done (according to plan)…

The problem
There are intermittent breaks during the day when the conveyor stops running for some time. That’s as planned and these breaks are unavoidable at this stage but it means I get bad data. Because the counts are being done for the moving minute, there are unneeded minimums and maximums that skew data and graphs (see bellow).

Graph bellow (encircled is good data, arrows show unwanted peaks and valleys). As you can see, work breaks completely skew value calculations. Values at the starts or ends go to either the maximum or minimum limit. I want to avoid these (specifically the maximums, peaks).

For the love of me, I cannot find a good solution. I’ve been in a rut and would appreciate some fresh outside perspective. Maybe I’ve been going at it completely wrong.

I’ve tried using the filter integration but it’s not working completely as I want it to. When the binary stays in OFF state (which means the conveyor is paused/stopped) the Average seconds per piece (1min) goes to 0, but the filter the result gets stuck some value and doesn’t drop to 0.

This is the filter sensor:

sensor:
  - platform: filter
    name: "Filtered tempo 1 min (outlier + tsma) r2,5"
    unique_id: filtered_tempo_1_min_(outlier+tsma)_r2,5
    entity_id: sensor.average_seconds_per_piece_1min
    filters:
      - filter: outlier
        window_size: 15 # Last 15 states
        radius: 2.5 # Remove extreme deviations
      - filter: time_simple_moving_average
        window_size: "00:01:00" # 1-minute rolling window
        type: last
        precision: 1

And this is the graph of all three sensors that are connected through calculations:

As you can see filtered_tempo_1_min_(outlier+tsma)_r2,5 staying on the last value instead of dropping to zero, like sensor.average_seconds_per_piece_1min does.

Potential theoretical solution that evades me
I’ve been thinking of trying to add some sensors/helpers/entities, that would check if the laser sensor has been active for the past minute. Lets say if actual count of pieces done per minute is above the planned count of pieces per minute which is multiplied by two (to give ourselves an arbitrary maximum limit)… only if said logic returns true, do the tempo calculation. This would prevent doing the calculations in realtime but do them for the already passed minute. Kind of a forced 1 minute lag. If the check is OK for the passed minute, then do calculations, if it’s not, then stay at zero. But unsure if this logic makes sense or if it’s even possible to do in HA?

I’m obviously open to other better solutions.

Can you show the history of the binary_sensor.teksturat_input during the problematic timeframe

Do you need the graph or the values themselves (though values would be just timestamps for the ON and OFF states)? The history chart of the sensor is included in the last image I posted above (above the time line chart).

If you need a closer look for better resolution here is the same date as above but only from 07:50 to 08:20:

And an even closer look (8:10 to 8:25):

It’s hard to tell the ON and OFF states because of so many data points. But the main thing is visible. Whenever there is a longer OFF state, it influences the Average seconds per piece (1min) outputting maximums (peaks on the graph).