Accessing string payload from MQTT in a service

Hey, I’m trying to configure automation to basically switch my light depending on the mqtt payload. I would lik eto do something like this:

automation:
trigger:
platform: mqtt
topic: ggamble22/feeds/bedroom-light
action:
service_template: >
{% if mqtt.payload | string() == ‘ON’ %} “I get an error here for mqtt is undefined”
light.turn_on
{% else %}
light.turn_off
{% endif %}
entity_id: light.Bedroom

The issue is that I’m not sure what is the variable name to access the payload properly. I know I could make two separate automation services and that works fine based off the example in the docs but that seems unnecessarily cumbersome. Any help would be appreciated. Thanks.

Try this: {% if trigger.payload | string == 'ON' %}

Beware that HASS states are case sensitive, so if your payload is actually ‘on’ or ‘On’, this condition will not be met. Also, I’m not sure that | string is necessary, but on the other hand it shouldn’t hurt.

1 Like

@fanaticDavid that worked fine. Thanks. The case sensitivity is the reason I am keeping everything capitalized. Well, that and it was the default when getting started with adafruit’s mqtt server.

1 Like

Hi,
Do you have any idea what might be wrong with this automation?

 - alias: "Turn On/Off zw_bedroomsunlamp_switch"
   initial_state: 'on'
   trigger:
     - platform: mqtt
       topic: homeassistant/switch/zw_bedroomsunlamp_switch/command
   action:
     - service_template: >-
         {% if is_state('trigger.payload', 'on') %}
           switch.turn_on
         {% else %} 
           switch.turn_off
         {% endif %} 
           entity_id: switch.zw_bedroomsunlamp_switch

I get an error when rendering the service call…

Template rendered invalid service: switch.turn_off
 
  entity_id: switch.zw_bedroomsunlamp_switch

I’ve tried service_template: > and >-
Any help much appreciated as I’ve been looking at this for the last few days :stuck_out_tongue:
BTW I’m on HASSIO 0.68.1

MQTT Lens shows the correct topic and payload…
image

Any chance this works?

- alias: "Turn On/Off zw_bedroomsunlamp_switch"
  initial_state: 'on'
  trigger:
    - platform: mqtt
      topic: homeassistant/switch/zw_bedroomsunlamp_switch/command
  action:
    - service_template: >
        {% if trigger.payload == 'on' %}
          switch.turn_on
        {% else %} 
          switch.turn_off
        {% endif %} 
      entity_id: switch.zw_bedroomsunlamp_switch

Hi David,

I figured it out, both ways work but the entity:id must line up with the s of service_template :P, thanks for showing me the light :smiley:

No problem, glad you got it sorted. YAML is very picky about indentation :wink:

1 Like