HA power toggle off with sonoff switch

Hello everyone

Ive configured HA to working with sonoff via mqtt.
I can turn the light on or off via the HA power toggle. When i turn the power off ( via the regular wall switch ) HA dosent change the light toggle state to off. (Sonoff is powered off and not communicate with HA)

There is a way that HA will know if sonoff is powered off and change the power toggle?

Thanks!!

You could use the ping device tracker since it’s wifi

This is what the ‘Will’ feature of MQTT is for.

When your sonoff connects to the broker it can set a will. When the broker detects the sonoff has disconnected (such as when powered off), it will publish the will to clients that subscribe. If the will is the same as the “off” message, HA will show the switch as off.

how can i implement that feature?

The sonoff should have a way of configuring the will message. Or if you have downloaded new code, you can change that to include a will.

Something like the following when you connect to the MQTT broker instead of using a normal connect …

mqttClient.connect(MQTT::Connect(MQTT_CLIENT).set_keepalive(MQTTKEEPALIVE).set_auth(MQTT_USER, MQTT_PASS).set_will(PUB_PREFIX"/"MQTT_TOPIC, MQTT_WILLMSG))

Where MQTT_WILLMSG = “Sonoff Offline”