Brightness in MQTT template scheme

Hi,

Help me. Why brightness is not work in this code:

  command_on_template: >
    {% if brightness is defined %}
      {{ "BRI" + brightness }}
    {% else %}
      {% if effect is defined %}
        {{ "EFF" + effect }}
      {% else %}
        {% if state is defined %}
          {{ "P_ON" }}
        {% endif %}
      {% endif %}
    {% endif %}

Effect and power on works correctly.

The plus operator (+) is normally used to add numbers (arithmetic addition). However, if all items are strings then the plus operator will combine them (string concatenation). If one of the items is a string ("BRI") and the other is a number (45) then the plus operator will fail.

The tilde operator (~) is used to combine strings (string concatenation). If one of the items is not a string but a number, it will convert the number to a string.

Try this:

  command_on_template: >
    {% if brightness is defined %}
      {{ "BRI" ~ brightness }}
    {% else %}
      {% if effect is defined %}
        {{ "EFF" ~ effect }}
      {% else %}
        {% if state is defined %}
          {{ "P_ON" }}
        {% endif %}
      {% endif %}
    {% endif %}

Tnx! It’s work!

1 Like

Glad to hear it works now.

For the benefit of other user, please mark my post with the Solution tag. It will help other people, who may have a similar question, find the answer.