Mqtt text sensor state change to toggle relay

Hi Folks,

What I am doing may not be possible but if anyone has any ideas, please let me know. I suspect a lambda will be involved which I am still getting my head round.

I have a device with a relay and I want the relay to change state when the state of an mqtt text sensor changes.

The text sensor can either be on or off and I want the relay to change when the state changes but not necessarily tied directly to what the state is. Just when it changes.

e.g the text sensor is off and the relay is on. Text sensor changes to on so the relay changes to off. also if the sensor and the relay are both on and the text sensor changes to off, the relay turns off.

I am trying to replace a home assistant automation that takes a change of state from one switch (shelly attached to a wall switch) to toggle the state of another (lamp with a sonoff basic/esphome) and do it all with MQTT regardless of whether home assistant is running. The issue is that within home assistant there are light groups and automations that control the sonoff basic directly so the wall switch and lamp states can get out of sync.

The physical wall switch becomes like half of a 2 way switch so it can be physically up or down with the light on and changing its position changes the current state of the light.

I hope this makes sense.

So far I have the shelly sending the state via MQTT and the esphome device with an mqtt text sensor (id: shelly) that accurately reflects the shelly state.


Just to add, I did try adding:

        - switch.toggle: relay

to the text sensor but the shelly sends it’s current state every 30 seconds so that just resulted in the relay turning on and off every 30 seconds. Its the change of state I need to try and detect somehow