MQTT send switch state in action automation

Hi,

I’m trying to get MQTT to send a message through an automation action where the payload of the message is the state of a switch. I’ve tried this using the following code but get the error "Invalid service data for mqtt.publish: extra keys not allowed @ data[‘value_template’]. Got “{{ states(‘switch.radio_2_kitchen’) }}”

  • alias: “Birth Message”
    trigger:
    • platform: mqtt
      topic: “home/pis/kitchenr2”
      payload: ‘birth’
      action:
      service: mqtt.publish
      data:
      topic: “home/pis/kitchenr2”
      value_template: “{{ states(‘switch.radio_2_kitchen’) }}”

You might need to replace data: with template_data:

hi thanks for looking at this.

Made this change but it generates the error: [template_data] is an invalid option for [automation].

Try it like this …

   action:
     - service: mqtt.publish
       data_template:
         topic: "cmnd/MQTTSign/SPEED"
         payload_template: '{{states.input_number.mqttsignspeed.state | int}}'

Same error; this is my config

 - alias: "Birth Message"
   trigger:
     - platform: mqtt
       topic: "home/pis/kitchenr2"
       payload: 'birth'
   action:
      - service: mqtt.publish
        data_template::
          topic: "home/pis/kitchenr2"
          payload_template: '{{ states.switch.radio_2_kitchen.state }}'

btw - if you want all state changes published on all entities, there is statestream

1 Like

Try changing payload_template: ‘{{ states.switch.radio_2_kitchen.state }}’
to
payload_template: ‘{{ states.switch.radio_2_kitchen.state + " " }}’

And remove the double “::” from data_template

Thanks everyone, tried with the updated config:

 - alias: "Birth Message"
   trigger:
     - platform: mqtt
       topic: "home/pis/kitchenr2"
       payload: 'birth'
   action:
      - service: mqtt.publish
        data_template:
          topic: "home/pis/kitchenr2"
          payload_template: '{{ states.switch.radio_2_kitchen.state  " " }}'

it’s giving the error:
2017-10-23 17:00:39 ERROR (MainThread) [homeassistant.config] Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token ‘end of print statement’, got ‘string’) for dictionary value @ data[‘action’][0][‘data_template’][‘payload_template’]. Got None.

Post edit;
Tried it without the double quotes in the payload_template and it worked.

To make it work with the " " you needed to include the +, but glad you got it to work :slight_smile:

saved my bacon (mqtt statestream)