Dynamic MQTT state_topic

Hi,
I manually configured MQTT sensors within the mqtt-section e.g. this way:

sensor:
  - platform: mqtt
    name: ist_reading
    state_topic: ist/5678/reading

Unfortunately the number within the topic is changing from time to time AND this number is used in many mqtt-sensors.
So I added a number helper this way:

input_number:
  topic_number:
    initial: 5678
    step: 1
    mode: box

sensor:
  - platform: mqtt
    name: ist_reading
    state_topic: ist/{{states(input_number.topic_number)|int}}/reading

But then, after reloading HA-config, the sensor gets unknown.

What is wrong?
It would be no problem for me that I have to reload the config after an topic_number-change.
Is there any other way to modify the topic number within my configuration (e.g. with env-variable) without copy&replacing the number within the config.

Bye, Alex

state_topic doesn’t support a template.

MQTT supports single and multi-level wildcards so you can use a single-level wildcard like this:

state_topic: ist/+/reading

The + character matches any value. If you don’t want any value but only one specific value, that you change occasionally via an Input Number, then I don’t believe that’s possible.

Reference

Thank you Taras! Your wildcard-workaround works perfectly for me.

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.