MQTT sensors don't change state

Hi. I have an ESP8266 with temperature probes. I’m sending temperature, wifi, and connection status (binary sensor) over MQTT. It all works fine except for two things:

  1. When the ESP is disconnected, all values, badges, etc are just frozen as the last value
  2. Binary sensor doesn’t change to ‘offline’

How should one go about having the state of all sensor being updated over MQTT. Is it somehow through birth/will messages?

Here’s my ESP Yaml (addresses and credentials are removed):

mqtt:
  broker: x
  discovery: true
  username: x
  password: x
  port: 1883
  topic_prefix: test/unit_1
  birth_message:
    topic: test/unit_1
    payload: online
  will_message:
    topic: test/unit_1
    payload: offline

Example of MQTT sensor from my config.yaml

sensor:
#Unit-1: TEMPERATURE
  - platform: mqtt
    name: "mqtt_temp_unit_1"
    state_topic: "test/unit_1/sensor/unit_1/state"
    unit_of_measurement: "°C"
    payload_available: "online"
    payload_not_available: "offline"

Your HA sensor config is missing an availability_topic (which should match the topic used in birth_message and will_message):

availability_topic : 'test/unit_1'

I think that if you’re using ESPHome’s HA integration (and not a separate MQTT sensor) it will handle availability automatically.

1 Like

Thanks, I’ll try it later today.

I have both sensors registered in the ESPhome integration as well. But they are physically located away from the Pi (different buildings) so my solution is to use MQTT. My understanding is that the integration only detects online/offline if they’re on the same network as the Pi. Perhaps I am mistaken?

If they are in a different location(/network) it likely won’t work with the ESPHome integration, AFAIK that will only work locally.

That worked brilliantly. Thanks a lot. Why exactly does your solution work though? Which message carries the info for the availability topic, and how does it force HA to switch status?

You’re publishing the “birth” and “will” messages to the availability topic. The “birth” message is sent by ESPHome once it connects to the MQTT broker, which will set the topic to the value “online”. This tells HA the device is online.

When the MQTT broker notices that the connection to your ESPHome device is gone, the broker will publish the “will” message (“offline”) to the availability topic, which tells HA the device is offline.

1 Like

Thanks.

I added retain, otherwise it kept triggering one of my low temp automations.

For anyone else with the same problems:

  birth_message:
    topic: X
    payload: online
    retain: TRUE
  will_message:
    topic: X
    payload: offline
    retain: TRUE
1 Like