TREND binary sensor : improvments and/or bug fix


I’m using the trend platform to better be notified of the ZoneMinder motion detection. I created a template sensor, sum of all the cameras event count, and a trend sensor based on this value :

  - platform: template
        friendly_name : 'Mouvements ZM'
        unit_of_measurement: 'Events'
        value_template: "{{ ((states.sensor.cam1_events.state | int) + (states.sensor.cam2_events.state | int) + (states.sensor.cam3_events.state | int) + (states.sensor.cam4_events.state | int) + (states.sensor.cam5_events.state | int)) }}"

Then the trend binary sensor, based on this :

  - platform: trend
        # On if 5 events per minute
        entity_id: sensor.alarms
        sample_duration: 600
        min_gradient: 0.08
        device_class: moving
        max_samples: 10

This way, I only get notification when there are several alerts in one minute, which means real activity in the house. I’m not bothered when someone drops something in the mailbox, nor when the dog walks around (yes I have a lazy dog, he doesn’t move that much !)
But on some occasion, mostly when luminosity varies a lot (cloud + wind), there are lots of alerts, like one every 2s for a few minutes. This I wouldn’t be notified of.

It would be nice to add a “max_gradient” parameter, so that the binary sensor only turns on when the gradient is between the min_gradient and the max_gradient values. (defaults to “none” won’t break the current behavior)

Of course, I could use a template binary sensor, compound of 2 trend sensors, but all in the same sensor makes things easier to understand and support.

Second point, the ZoneMinder sensor only gets updated when the number of alerts changes. Say I have 10 motions in 1mn, then nothing for 2 hours, the trend sensor will still remain ON, and the gradient stays to the latest value.
When setting a “sample_duration”, I expect the sample to be deleted after this time, even if no other sample appeared. Right now, it simply doesn’t get updated until the next sample.
I wouldn’t call it a bug as the documentation states that “Each time the state changes, a new sample is stored”, but the logical behavior is that the trend is updated after the “sample_duration” expired because otherwise, the information in the sensor isn’t accurate. It’s not a problem when you use it as a trigger (=change of status), it becomes one when it’s a condition (=current status which can be incorrect).