Creating an MQTT sensor with States (as strings) build from received numbers


I am new here and with Home Assistant. I successfully integrated my own MQTT lights into HA. Now I struggle to bring my push buttons also into HA.
My buttons provide events (short click, long click, double click) by publishing a number on a specific topic (0 => short click…). I made a yaml configuration (see below) that gives me that number. Works. But I want to have the meaningful string instead of the pure number (e.g. “short click”). How?

I am confused by several posting using some old/obsolete(?) syntax and the official docu does not provide any examples for that?!

Did I miss any important information you need to point me into the right direction?

- name: "TestSensor"
  unique_id: "TestSensor"
  state_topic: "myTopic/button123/event"
  value_template: "{{ value_json }}"


You could just index an array if they’re sequential numbers you receive:

value_template: >-
  {% set values = ['opt0', 'opt1', 'opt2'] %}
  {{ values[value_json] }}

It’s probably also a good idea to store the number in an attribute, as you’ll probably want it in the future.

1 Like