Prevent HA from sending last known state (MQTT)

I have a Sonoff programmed (own code) to interact with HA. The Sonoff is connected to a wall switch.

There is only one thing I cannot seem to solve. Whenever I toggle the wall switch the Sonoff will turn off. Upon powering the Sonoff up again, HA will send the last known state to the Sonoff.

How do I prevent this? Upon reconnecting the state for the switch in HA should always be “ON”. The Sonoff already sends a “ON” command upon powering up, but the “OFF” command send by HA gets prioritized. I probably could solve it in my code by ignoring the first message received from the broker, but that’s not the way I would like to do it.

This is my MQTT configuration.

mqtt:
broker: 127.0.0.1
port: 1883
client_id: home-assistant
username: pi
password: mqtt
keepalive: 60
protocol: 3.1.1

switch:

  • platform: mqtt
    name: “Woonkamer”
    state_topic: “woonkamer/lamp1”
    command_topic: “woonkamer/lamp1/set”
    payload_on: “1”
    payload_off: “0”
    optimistic: false
    qos: 1
    retain: false

Are you sure it is HA sending the message, rather than a retained message sent directly from the broker? I don’t think HA sends a message unless from a manual update of the gui or an automation.

You mean it reports its state with topic woonkamer/lamp1 or it actually sends a command with a topic woonkamer/lamp1/set ?