Sensor-based rain gauge not counting triggers

I was going through the long rain gauge thread and followed a link to this project page. From here, I printed the enclosure and added the Aqara door sensor, calibrated the device, and added code to HA and waited for rain. I can see state changes in HA (under MQTT using Z2M) as the sensor opens and closes. The problem I’m having is that the code doesn’t seem to be counting the changes so accumulation is never reported. I’ve been looking at this for weeks and can’t figure out what I’m missing (but it’s clearly something simple).

**sensor.yaml**
sensor:
  - platform: history_stats
    name: "aqara_rainsensor_flips_on"
    entity_id: binary_sensor.rain_gauge_contact
    state: "on"
    type: count
    start: "{{ now() - timedelta(hours=24)}}"
    end: "{{ now() }}"
    state_class: measurement
    unique_id: aqara_rainsensor_flips_on_count

  - platform: history_stats
    name: "aqara_rainsensor_flips_off"
    entity_id: binary_sensor.rain_gauge_contact
    state: "off"
    type: count
    start: "{{ now() - timedelta(hours=24)}}"
    end: "{{ now() }}"
    state_class: measurement
    unique_id: aqara_rainsensor_flips_off_count

**templates.yaml** 
- sensor:
    - name: Rainfall [day]
      state_class: measurement
      unique_id: rainfall_day
      unit_of_measurement: mm
      icon: mdi:weather-pouring
      state: >-
        {% set count = (states('sensor.aqara_rainsensor_flips_on') | int(0)) + (states('sensor.aqara_rainsensor_flips_off') | int(0)) %}
        {% set mm = count * 0.52615 %}
        {% if count >= 0 %}
          {{ mm|round(1, 'floor') }}
        {% endif %}

In MQTT I see an entity titled ‘sensor.rain_gauge_trigger_count’ but unsure where this is coming from and the value is always 0.

Anyone see what I’m missing? I know it’s staring me in the face but just cn’t figure it out. Thanks!

I actually don’t see why you wouldn’t be getting a non-zero value if your door sensor is actually changing states. Depending on how much you’ve changed this code you may want to restart HA, clear your browser cache, and verify (using developer tools-> states) that there aren’t duplicate entities ending in _2 on your system.

But i would recommend against the setup you’re attempting to get working anyway. The history_stats ‘count’ function will count matching states, but what you need instead is to count state transitions. Let’s say the door sensor has not tripped at all in the last 24 hours. The history stats counter will return 1 because the sensor matched one state. Even though the bucket never tipped a single time. In other words your sensor will never report less than 0.53mm of rainfall.

Here is a setup that does what you want. You’ll get a total rainfall sensor (total all time) and then using the statistics platform you can calculate the previous 24 hours rainfall.

template:
  - trigger:
      - platform: state
        entity_id: binary_sensor.rain_gauge_contact
        from: 
          - "on"
          - "off"
        to:
          - "on"
          - "off"
    sensor:
      - name: Rainfall [total]
        unit_of_measurement: mm
        device_class: precipitation
        state_class: total_increasing
        state: "{{ this.state | float(0) + 0.52615 }}"
sensor:
  - platform: statistics
    name: Rainfall [24h]
    entity_id: sensor.rainfall_total
    state_characteristic: change
    max_age:
      hours: 24
1 Like

History stats relies on sensor history. Do you keep at least 24hrs of history?

It’s the purge_keep_days option of the recorder.

For debugging purposes, can you add a history stats sensor on another binary sensor to see if that works?

Also try to replace the start with start: '{{ now().replace(hour=0, minute=0, second=0) }}' as in my rain gauge post

1 Like

We’ve been under drought conditions since I first posted but had a torrent of rain today (and I’ve been too busy and/or lazy to manually move the sensor). Seems like the recommended changes worked as expected, greatly appreciate the code and knowledge.

I’m unclear why the previous dry days are now showing 11.58mm of rain. Could this be stale data that’s displayed in the place of a zero reading? Would the purge_keep_days, as suggested by @parrel, be needed somewhere in the code?


That’s a good amount of rain!
It’s probably the apex chart that causes this, because there is no data before. Try another bar chart to compare.

E.g.

chart_type: bar
period: day
type: statistics-graph
entities:
  - sensor.rainfall_today
stat_types:
  - state
title: Rain this week
days_to_show: 7

Seems like the stats do not get reset which is more of a problem (since I wanted to use this reading to disable irrigation). I haven’t had time to re-review code in the original thread which likely has the answer.

If you’re looking for a daily total, create a utility meter helper using your total rainfall sensor as the source. You can choose the reset cycle, which of course you’ll want daily

I believe I’m just getting dumber the more I dig into this. I created a helper to test resetting the daily value and that should occur tonight. The cumulative value is still being reported but, although we had rain today, there was not 6+ inches of rain tonight.

I’m also not seeing the trigger count updated not whereas previously (the day showing 13) it was working as expected:

I believe the code is correct and in the appropriate locations but clearly I’m missing something obvious.

It’s not clear what sensors you have and how they are configured. Can you post the yaml for whatever ones are configured in yaml, and also describe the ones that are configured in the UI?

Thanks for your continuing help and patience. The sensor is configured in Z2M and simply reporting open/close state.

Rain Gauge Door (`binary_sensor.rain_gauge_contact`)
MQTT discovery data:

* Topic: `homeassistant/binary_sensor/0x00158d000ab49c0a/contact/config`

And is showing triggers but (was?) incrementing the count:

I’m using the yaml you posted:

sensor.yaml

  - platform: statistics
    name: Rainfall [24h]
    entity_id: sensor.rainfall_total
    state_characteristic: change
    max_age:
      hours: 24

templates.yaml

  - trigger:
      - platform: state
        entity_id: binary_sensor.rain_gauge_contact
        from: 
          - "on"
          - "off"
        to:
          - "on"
          - "off"
    sensor:
      - name: Rainfall [total]
        unit_of_measurement: mm
        device_class: precipitation
        state_class: total_increasing
        state: "{{ this.state | float(0) + 0.52615 }}"

And the simple bar chart:

chart_type: bar
period: day
type: statistics-graph
entities:
  - sensor.rainfall_total
stat_types:
  - state
title: Rain this week
days_to_show: 7

That’s all I remember putting in place and don’t see anything in configuration.yaml
Thanks!

None of those sensors are called “Rain Gauge Trigger count” or have an integer for a state. You have another sensor somewhere.

The graph you showed was called “rainfall test” and I don’t see that either.

I’m not sure why you need either of those sensors but I can’t help you debug them unless you provide some information about them.

Okay, I see that “Trigger count” is a built-in entity while the open/close state of the “door” sensor is what I should be using.

The “rainfall test” was the helper I created based on your suggestion, I should have pointed that out.

There has been periodic rain today and the log is showing the sensor switching open/close as expected.

Can you show the graph for the “rainfall total” sensor over the same time period as the “rainfall test” sensor? They should both increase by the exact same amount, the only difference is one resets to zero each night.

I tried to get the graph in the approximate time frame and it’s showing steady state:

For the past 48 hours the chart shows an increase:

The helper is showing data correctly

The rainfall total sensor appears to be working correctly. How did you configure the utility meter helper? Did you make sure that the “delta values” option remained disabled?

For the helper, other than setting ‘reset cycle’ to daily I took the defaults (so only “Periodically resetting” was enabled).

I missed in your last comment that the helper is displaying correctly.

So is everything functioning now like you want it to?

The data looks good when using a helper but still unclear on how to reset the cumulative count of the rainfall_total. Will it just keep historic data of rainfall since it started tracking?

Correct, it will never reset. Think of it like your electricity meter or water meter. The magnitude of the number is irrelevant, all that matters is how much it changes over a period of time.

It is possible, if you really want, to modify the template sensor so that it will reset that number on some fixed schedule or via an automation. But I would advise against it and instead recommend you add utility_meter helpers for any cycles that you want to reset on.

1 Like

Thanks so much (again) @mekaneck for your patience and thorough explanations. I’ve had HA running for years but always learning (and re-learning) as new requirements come up and new features and functions are added.

Now on to see if the automation that disables the irrigation after X amount of rain is working :sweat_smile: