Can somebody explain why my switch is sending the opposite state?

I seriously have no idea what’s going on here! I want to have a MQTT message when a switch is flipped, so I use this as the trigger:

- entity_id: switch.zwavebryter_lyd_5
  platform: state

Then I feed the code into a payload template:

- alias: Brytere - Endringsvarsel
  action:
    data_template:
      payload_template: "Node: {{trigger.from_state.attributes.node_id}},{{trigger.from_state.state}},Lydsone: {{trigger.from_state.attributes.friendly_name.split(' ')[2]}},{{trigger.from_state}}"
      topic: eg/ZWaveBryter
    service: mqtt.publish
  condition: []
  id: '1524678991642'

Theoretically it should give me the result on or off, depending on if that switch (which is node 4, something the first part of the payload gives me) is on or off. And it does the opposite! I have a statestream for ZWave that gives the correct result. Check this out:

eg/switch/zwavebryter_lyd_5/state u"off"
eg/ZWaveBryter u"Node: 4,on,Lydsone: 5"
12:56:30 Node: 4,on,Lydsone: 5

The first line is the state stream, and it correctly shows that I have turned off the switch. But then the second part comes, which is the code, and it says the switch is on!

I have spent two hours of my workday (I am self-employed, so it only means that I have to work late today) on this. Still as confused. And to add insult to injury, if I replace {{trigger.from_state.state}} with {{states.switch.zwavebryter_lyd_5.state}} it shows the correct value! So for some reason it seems the code shows previous value.

Can somebody please tell me what’s going on there before it drives me nuts?

trigger.from_state shows the state before the state change.
So if the state changes from off to on, the switch is on and the from_state is off.
You need to_state.

1 Like

Aha! That explains it! :joy: Now I feel really dumb having spent so long not understanding it!

1 Like

That was cool! Now I can show what it went from and to, not for any particular reason, it just looks good. :smile: