How to process zigbee2mqtt inputs

I have been working on a lot of SmartHome related flows and have run into a bit of a challenge. While I have a lot more going on, I can describe the problem involving 3 Zigbee devices:

  1. Ikea Switch
  2. Ikea Smart Bulb
  3. Ikea Motion Sensor

Most of my logic is simple:

  • If the motion detector senses motion turn on the bulb.
  • If the on side of the button is pushed turn on the bulb.
  • If the off side of the button is pushed turn off the bulb.

There is however an additional set of logic that involves a bunch of loops and filters:

  • Show a NR dashboard switch that turns the bulb on or off
  • Connect to a hubitat that has a virtual lightbulb device. This virtual device in turn can be turned on or off via hubitat dashboard or via Alexa which the hubitat is connected too
  • Connecting using the smart Nora nodes to Google Home
  • Connecting via mqtt to zigbee2mqtt which is the place of actual zigbee control of the bulb. It too has a dashboard that can turn the bulb on or off.
  • This key part of this logic is that when the state is changed in any one place, the desired change goes from source to NR to mqtt broker to Z2M to the bulb and it also goes from source to all the other places that show the state (dashboard, hubitat, alexa, google home) and puts them into a synchronized state.

This in general is working very well (except....)
When I change the state on the bulb, Z2M is sending 2 messages via mqtt to NR. The first shows the old state, while the seconds shows the new state. I have no need for the old state so I built some logic that takes inputs from Z2M and compares this to the last measurement/value which is stored in an NR env variable and if they match, discards it. If it is new, then it passes it to the rest of my flows.

Without this filter, I would experience circumstances where the light will flicker from rapidly being cycled as the feedback sends the old and new on/off states. The filter above fixed this problem entirely.

Then I found that by adding this as a general filter it broke other things. Here is my sequence of events that shows it broken:

  1. Turn on the light with the switch (on command)
  2. Do some work
  3. Turn off the light with the switch (off command)
  4. Turn on the light via motion detection
  5. Do some work
  6. Attempt and fail to turn off the light using the switch (off command). This fails because my filter says last input from the switch is off so discard the duplicate.

Does anyone have enough experience with Z2M and NR to explain an viable general solution? The best I have come up with is to modify my filter logic to catagorize the device/measurement as either filterable or normal passthrough. This is doable, but ends up requiring maintenance every time a new type of device is added to my environment.