How to get MQTT state_topic string from sensor entity

Hello HA Community,

I’m trying to make an automation that will take an input_select value that is a single sensor selected from a group and set the state of that sensor when a button is pressed. I have an idea on how to get all of that to work except for the fact that the input_select is built of Friendly Names and the value I need in the automation to publish the MQTT message needs to be the state_topic. For example:

This is one of my sensors, notice that the Friendly Name is different than the state_topic:

    - name: 'Sensor near Kitchen Sink'
      state_topic: '433/Kitchen_Sink_Moisture'
      device_class: moisture

When I use the Developer Tools–>Template feature of Home Assistant it looks like this.
INPUT: {{ states.binary_sensor.sensor_near_kitchen_sink.attributes }}
OUTPUT: {'device_class': 'moisture', 'friendly_name': 'Sensor near Kitchen Sink'}

The attribute list doesn’t contain the state_topic. How do I go about getting a handle on the state_topic value given the sensor name in Jinja2??

Use the Developer Tools and search for the entity. That will show all of the attributes. I don’t think I’ve ever seen an MQTT topic in the attribute list before.


This helps but how can I get to the topic from jinja2 source code? That’s ultimately what I need to resolve. Checking the spot you suggested shows the same results as the template example I shared in my original post.

I got this working yesterday! It’s awesome. The key was to tie the state_topic value to the attribute for the entity created using the json_attributes_topic and json_attributes_template, like this:

    - name: 'Sensor near Kitchen Sink'
      state_topic: '433/Kitchen_Sink_Moisture'
      device_class: moisture
      json_attributes_topic: '433/Kitchen_Sink_Moisture'
      json_attributes_template: '{"mqtt_name": "433/Kitchen_Sink_Moisture"}'

Yields this:

Then I can query the same entity for the topic, like this!

      - service: mqtt.publish
          topic_template: "{{ state_attr(states('input_select.moisture_sensor_to_reset'), 'mqtt_name') }}"
          payload: "OFF"
          retain: true

There might be a way to simplify the json_attribute_template to not be hardcoded and I’m all ears for someone to share a tighter way but this definitely works.