Rotary Encoder - Synchronise State with HA

A while ago, I came upon this guide to creating a pseudo-dimmer switch: Analogue style rotary dimmer switch - Sonoff + ESPEasy + MQTT

I’ve managed to get this set up, and it works for the most part. However, the problem is that if I change the brightness of a bulb using some other means (HA app, Hue app, etc), the dimmer is now out of sync. So if I turn the dimmer to the maximum, then reduce the brightness using an app, I can’t turn the brightness up again using the dimmer. Instead, I have to knock it down a bit, then back up. (Admittedly, it’s not so much a problem for me since I understand what’s happening… more the other people in my house!)

I’m thinking there are two possible solutions, but am yet to try them out and probably need a bit of guidance.

  1. Is it possible to use relative values in the code for the dimmer? So, instead of saying set the value to 10, it should be add 10 to whatever value it’s already at.

Or

  1. If the brightness is changed in an app, is it possible to sync this back to the value of the encoder somehow? This seems less likely to be possible to me.

Any ideas welcome!