When I toggle the switch by pressing it on in the front end, it does toggle, and sets the command_topic state to ON in my mosquitto. I can see the new message arriving on the broker. But shortly after the switch toggles back, because (I think) it still reads an OFF from the state_topic.
When i set the state_topic and command_topic in the switch configuration the same, it works, but I do not think that this is the right way to go?
Could someone explain the state_topic and command_topic for me? I do not understand how these are linked.
This is correct. If HA does not receive the state topic, it assumes the switch has not received the command and so puts the switch back in the old state.
The best thing to do is have your switch publish the new state when it receives the command.
If you can’t get your switch to do this, then set the state topic to the same as the command topic. This will cause the broker to send the command topic back to HA and cause the switch to update.
Alternatively, you can set the optimistic flag in the HA switch definition, which will change the state without expecting any input from MQTT.
Also, when publishing configuration snippets, please follow the guidelines in the big blue box at the top of every topic.
So if I understand correctly MQTT works as follows:
The switch sets the command_topic, the dimmer module reads the state (at the command_topic) and confirms by setting the state_topic, and the switch is able to again verify the state_topic.
That is is how it can work. As I said before, HA can just send a command and forget about it (optimistic mode) or it can receive the same command as it sent from the broker, as a confirmation that the broker received the message.
Obviously, the most reliable way is the way you describe, as you get a positive confirmation from the device. But not all devices can do that.