Publish sensor state to mqtt

I am trying to publish state of the sensor to mqtt. My sensor is defined in ESPHOME and I get sensor state values to HA. See values in the log as well as can create graph, see current state in HA.

I would like to send value to mqtt as well, so I tried to use various syntax, so far without success. This is what I tried, but in all cases I receive text (whatever is after payload: ), not value into mqtt broker.

  - mqtt.publish:
      topic: esp_pow1_From
      payload: powerV.state
  - mqtt.publish:
      topic: esp_pow1_From
      payload: powerV
  - mqtt.publish:
      topic: esp_pow1_From
      payload: powerV:state
  - mqtt.publish:
      topic: esp_pow1_From
      payload: powerV.value

From the mqtt.publish docs:

You can either use payload to hard-code a payload or use payload_template to specify a template that will be rendered to generate the payload.

This is how I publish every night my consumed energy to mqtt :

- id: '1569740295999'
  alias: Save consumed energy
  trigger:
  - at: '23:59'
    platform: time
  action:
  - data:
      payload_template: >
         {{  "%.2f" |format((states("sensor.mains_consumed_energy") | float))  }}
      topic: sensor/yesterday_energy
      retain: true
    service: mqtt.publish
  - data:
      payload_template: '{{ "%.2f"|format((states("sensor.mains_consumed_energy")  | float))  }} '
      topic: sensor/totalenergy
      retain: true
    service: mqtt.publish

Use it as an example

1 Like