I am trying to find a way to log/measure stats from my Hassio MQTT integration.
Does anyone know if I can set up a sensor to detect/count MQTT messages arriving for a given topic?
Ignoring the payload, just counting messages.
Cheers
P
I am trying to find a way to log/measure stats from my Hassio MQTT integration.
Does anyone know if I can set up a sensor to detect/count MQTT messages arriving for a given topic?
Ignoring the payload, just counting messages.
Cheers
P
The overall stats are available in $SYS topic, but not individual topics.
You might have a look at the github code for MQTT Explorer. Maybe some ideas there:
I quickly tried something, and this might work;
- platform: mqtt
name: counter
state_topic: "counter/test"
value_template: >
{% if is_state('sensor.counter', 'unknown') %}
1
{% else %}
{{ states('sensor.counter') | int + 1 }}
{% endif %}
But the value (as expected) resets every restartâŠ
I owe you beer friendâŠ
I stumbled upon this thread and just wanted to add a âshort versionâ of this template, because the else branch of this template can handle an unknown state just fine:
- platform: mqtt
name: counter
state_topic: "counter/test"
value_template: "{{ states('sensor.counter') | int + 1 }}"
Everything that isnât a valid number will be cast to â0â (zero) by the int
filter. The first time this sensor is triggered, the unknown state becomes 0 after the int
and after +1
the result is 1 for the first message, just as in the original template.
This gets reset to 0 every time Home Assistant restarts. Any way to keep it persistent?
Put it in an input_number on HA shutdown, and restore from the input_number on HA restart.
I suppose an automation to increment an input_number every time the MQTT sensor is incremented is called for.
I just had a hours-long research and figured out a wonky roundabout way of doing it without a counter to avoid using a prosthetic input_number, but found the familiar glaring flaw in HA: no ability to persist data after HA restarts besides marginal integrations like Input Number/Boolean/etc. and Utility Meter. Otherwise the solution above would work great.