MQTT Sensor: get last value at startup

I’m using a “virtual” mqtt sensor, to manually publish my water consumption.

This is the configuration

- platform: mqtt
  name: "Water reading"
  state_topic: "utilities/water/reading"
  value_template: "{{ value_json.liters }}"
  unit_of_measurement: "l"
  payload_available: "true"
  payload_not_available: "false"

And I’m trying to publish with

{"liters": 2, "retain": true} to the topic utilities/water/reading

When I send a value, it displays at the frontend

- type: entities
    title: Acqua
    entities:
      - sensor.water_reading

But at restart of HomeAssistant, I get “unknown” until next publishing…

Is it possible fetch last value and display e.g. that “2 l” at the start If I reboot Home assistant?

Thank you

Are you publishing the payload using something like this?

  action:
  - service: mqtt.publish
    data:
      topic: utilities/water/reading
      payload: '{"liters": 2, "retain": true}'
      retain: true <-------------- This is important

That means the payload was not published as a retained message. The MQTT Broker was not instructed to store a copy of the payload. When Home Assistant restarts and subscribes to utilities/water/reading the Broker has no stored value to give to Home Assistant.

For the moment, I used native function of HomeAssistant, like in picture:

Probably I made error, I see you place retain “out” of the payload…

Is it possible publish the retain inside home assistant?

Yes, you can create a script using the information I posted above or you can use Developer tools > Services.

Screenshot from 2021-01-16 13-56-52


NOTE

Why do you include “retain”: true in the payload?

'{"liters": 2, "retain": true}'

The MQTT Broker doesn’t inspect the contents of the payload so that information is not used by the broker.

1 Like

Thank you very much. I was testing and I was wrong, at same time. Thank you for your effort :wink:

1 Like