Action data_template help

I’m wishing to tidy up my config so if anyone can assist with turning the two automations below into one using a data_template/service_template, that would be appreciated. I see lots of variations of it in the forums but having trouble figuring out mine. I’ve got a lot more of these touch screen commands to add for entities that aren’t natively in HA as MQTT items so condensing them into one would be hugely helpful.

- alias: Lounge on via MQTT
  hide_entity: true
  trigger:
    platform: mqtt
    topic: display/kitchen/touch/lounge_light
    # Optional
    payload: 'on'
  action:
    - service: light.turn_on
      entity_id: light.lounge_light

- alias: Lounge off via MQTT
  hide_entity: true
  trigger:
    platform: mqtt
    topic: display/kitchen/touch/lounge_light
    # Optional
    payload: 'off'
  action:
    - service: light.turn_off
      entity_id: light.lounge_light

I’ve managed to figure out how to do it for the inbound messages and that is below.

## Lounge Status Updates
- alias: Lounge status via MQTT
  hide_entity: true
  trigger:
    platform: state
    entity_id: light.lounge_light
  action:
    service: mqtt.publish
    data:
      topic: "lounge_light/status"
      payload_template: "{{ states('light.lounge_light') }}"
      retain: false

Check out the Template Lock component. It performs two different actions based on the state. Perfect for combining on & off action automations.

@bradyn12 Thank you, that is good to know but I need something that is ‘looking’ at the payload of my publish command. If I send on, turn on light. If I send off, turn off light. I found the code below but don’t have the skills to tweak it for my needs.

- id: do_some_on
  alias: "Do Something"
  initial_state: 'on'
  trigger:
    platform: mqtt
    topic: "hermes/nlu/intentParsed" 
  action:    
    - service: script.turn_on
      data_template:
        entity_id: >
          {% if (trigger is defined) and ('radio in kitchen' in trigger.payload) %}
            script.radio538                      
          {% elif (trigger is defined) and ('movie time' in trigger.payload) %}
            script.turnon_movie_light             
          {%- else -%}
            script.snips_say_notok          
          {% endif %}

Try this:

trigger:
  platform: mqtt
  topic: "display/kitchen/touch/lounge_light"
action:
  entity_id: light.lounge_light
  service_template: >
    {% if trigger.payload == 'on' %}
      light.turn_on            
    {%- else -%}
      light.turn_off 
    {% endif %}
1 Like

@bradyn12 Legend Sir! Thank you. That is exactly what I was looking for and and has allowed to go crazy this evening adding switches and locks too using that methodology. :joy: