Hi guys,
I was looking for a simple way to implement a counter sensor, which I could increment based on an event, and reset every day. My use case is my motion sensor at home, when it senses motion, it saves the motion event picture to my Plex library and now I wanted to have a counter so I could so how many motion events got triggered (so later on I can build automations on it, since everybody leaves for work between certain hours, it would be ok to have that many motion events during the timeframe etc). This counter should get reset at midnight every day. I couldn’t find any direct solution, without using any other components (like the statistics one), so I created my own, and I wanted to share this with the community, as I’m sure other will be able to use this as well.
What this does:
Basically it registers 2 services in your HA instance, counter.increment
and counter.reset
.
Calling the first one, increments the counter.simple
entity by 1.
Calling the second one, obviously resets the counter.simple
entity.
Currently it’s not configurable at all, and if you want to change the entity name, you’ll have to modify the code itself, I might add this later on.
The code:
def setup(hass, config):
"""Setup the sensor platform."""
hass.states.set('counter.simple', 0)
def handle_increment(call):
state = hass.states.get('counter.simple')
new_state = int(state.state) + 1
hass.states.set('counter.simple', new_state)
def handle_reset(call):
hass.states.set('counter.simple', 0)
hass.services.register('counter', 'increment', handle_increment)
hass.services.register('counter', 'reset', handle_reset)
return True
Place this inside the counter.py
file inside your custom_components directory, enable it by adding counter:
to your config, and you’re done.
as you can see, this is really simplistic, and probably error prone
But now, I can let my Rpi with my motion camera fire a custom event in my HA, and act on that to trigger the increment service.