Moved from domoticz - don't know how to toggle button using arduino & mqtt

Hi,
Excuse me if I posted on wrong topic.
I’m new but I’ve googled for an hour and could’nt find reliable answer.

How to toggle a button using mqtt and arduino (esp8266)?

In domoticz i’d send “command” : “toggle” to domoticz/in topic.
I need to “toggle” the wall switch and perform action and don’t want to check if it’s on or off on esp8266 side (cause it’s not reliable).
In domoticz it was just ‘toggle’.

AFAIK there’s no toggle command in HA right?

You can also take a look at ESPHome.

You need an MQTT switch or similar in Home Assistant to react on the MQTT topic. However, I don’t understand what you want to do exactly.

There surely is.

OK, the answer is: there is no “toggle” command in mqtt.
Please leave the answer for other guys moving from Domoticz that are coding by their own.

The key to success is to use “retain” function in HA that allows you to set the last status.
When you have the last status you just create new global bool to control the toggle behaviuor. Something like this:

button press:
if ( debouncer.fell() ) {
if (isOn==false) publikuj(“ON”); else publikuj(“OFF”);
isOn = !isOn;
}

and you set the bool value in callback services like for example:

void obsluga(String cmnd)
{
Serial.println("Komenda: " + cmnd);

if (cmnd=="ON") { digitalWrite(RELAY_PIN,LOW); isOn=true; Serial.println("zalaczam" +RELAY_PIN); publikuj("ON");}
if (cmnd=="OFF") { digitalWrite(RELAY_PIN,HIGH); isOn=false; Serial.println("wylaczam" +RELAY_PIN); publikuj("OFF"); }

}
void callback(char* topic, byte* payload, unsigned int length) {

char receivedChar[length];
Serial.print("Message arrived: ");

for (int i=0;i<length;i++) {
receivedChar[i] = (char)payload[i];

}
Serial.println(receivedChar);
obsluga(receivedChar);

}

I just want to help you, things are different in the Home Assistant ecosystem and ESPHome is by far the easiest solution to integrate ESP devices into Home Assistant, as it was made especially for this purpose.

What retain function? MQTT can have payloads with a retained flag, but what is the retain function of HA?

1 Like

You’re right, it’s a flag - not a function.
Thanks!