Synchronize the on/off state of 2 entities

I’ve seen this too but I don’t know how to fix it yet. The problem is basically:

  • devices A and B are linked
  • turn A on and off quickly → sends B and on and an off command
  • B gets turned on - tells A to turn on
  • A is already turned off, so when it gets told to turn on it does - it also tells B to turn on
  • meanwhile, B is processing the command to turn off
  • hilarity ensues

The way we used to deal with this in the old days is that an event would come in with a timestamp that says when it was initiated. This is a little different from time_fired (which we do have), since an event that is triggered by another event would inherit the initiated time from the previous event. If a device already processed a later event it would ignore older ones. This means that the state object needs to store the initiated time, which is different from the last_updated and last_changed that we already have. To apply that to our example:

  • devices A and B are linked
  • turn A on and off quickly → sends B an On@t0 and Off@t1
  • B gets the On@t0 and turns itself on - sends A an On@t0
  • A is already turned off by this point with time of t1 (which > t0), so when it gets told to turn on with t0, it ignores it
  • meanwhile, B is processing the Off@t1, turns itself off - sends A and Off@t1
  • A sees t1 = t1 and either ignores it or checks if the states match to be safe, sees that they do, and then ignores it

Without that initiating timestamp in the states though, it’s much harder.

Extra credit: turn A on and B off at the same time.

2 Likes