This project describes one way (out of many) to build a custom counter using only things that are available in HA. No code is needed, only configuration. I have chosen to use it to count number of cups of coffee I drink every day, but you can use it for basically anything. To read an even more detailed description of this project, you can find an in-depth post at Github.
The idea is to create a counter that easily can be incremented over the internet. I use three things; an input_number, automations, and the webhook api.
First I set up an input_number:
input_number:
coffee_counter:
name: Coffee counter
initial: 0
min: 0
max: 25
step: 1
mode: box
unit_of_measurement: cups
Then, I add an automation listening to a webhook.
- alias: Increment coffee counter
trigger:
platform: webhook
webhook_id: coffee
action:
service: input_number.set_value
data_template:
entity_id: input_number.coffee_counter
value: "{{ 1 + (states.input_number.coffee_counter.state | int) }}"
For the sake of clarity I used a short webhook id named coffee, but in a real setup it should be replaced (mainly for security reasons).
Now we have set up our homeassistant to trigger each time we do a POST request with Content-Type: application/json to our endpoint at http://example-ha.duckdns.org:8123/api/webhook/coffee.
The third step is to set up an automation that resets the counter every day at midnight.
- alias: Reset coffee counter
trigger:
platform: time
at: '00:00:00'
action:
service: input_number.set_value
data_template:
entity_id: input_number.coffee_counter
value: 0
Finally I add a history graph card to show the data in the UI.
- type: history-graph
entities:
- input_number.coffee_counter
title: Coffees
hours_to_show: 120
The HA part is now done, the system is ready to accept incoming requests. I am currently using HTTP Shortcuts to generate an icon on my home screen, which I then just tap to trigger the webhook automation. In the app, I specify url, add header Content-Type: application/json, and specify the request body as an empty object {}.
The result is a really easy to use shortcut which produces a chart showing the amount of coffee you drink every day.