Automation - publish mqtt depending on sensor value in one automation

Hi.

As I see there is no real “switch-case statement” in automation available.
I want to publish the payload of a mqtt msg depending on the current range of a sensor.
E.g.
If sensor value is between 1 and 5 publish payload A
If sensor value is between 6 and 8 publish payload B
If sensor value is between 9 and 10 publish payload C to topic

It’s an easy thing to this with multiple automations via conditions. But is it possible to put this to a single automation? Would be more “well-arranged”.

Thanks in advance.

action:
  - choose:
      - conditions:
          - condition: numeric_state
            entity_id: sensor.some_sensor
            above: 0
          - condition: numeric_state
            entity_id: sensor.some_sensor
            below: 6
        sequence: 
          - service: mqtt.publish
            data:
              topic: mytopic/blah
              payload: A
      - conditions:
          - condition: numeric_state
            entity_id: sensor.some_sensor
            above: 5
          - condition: numeric_state
            entity_id: sensor.some_sensor
            below: 9
        sequence: 
          - service: mqtt.publish
            data:
              topic: mytopic/blah
              payload: B
      - conditions:
          - condition: numeric_state
            entity_id: sensor.some_sensor
            above: 8
          - condition: numeric_state
            entity_id: sensor.some_sensor
            below: 11
        sequence: 
          - service: mqtt.publish
            data:
              topic: mytopic/blah
              payload: C
    default: []

Something like that

But when you get in to Jinja, it can also just be done like this:

action:
  - service: mqtt.publish
    data:
      topic: mytopic/blah
      payload: >-
        {% set p = "A" %}
        {% set s = states('sensor.mysensor')|float(0) %}
        {% if s >= 6 and s <= 8 %}
          {% set p = "B" %}
        {% elif s >= 9 and s <= 10 %}
          {% set p = "C" %}
        {% endif %}
        {{ p }}

Shorter version with out-of-range guards:

      payload: >-
        {% set m = {0: "-", 5: "A", 8: "B", 10: "C"} %}
        {{ m.get(m.keys()|select(">=",states('sensor.your_entity')|int(0))|list|first,"-") }}
1 Like