Implementing delta computation and command generation
Outlined logic and Python code to recursively compute the delta between desired and reported JSON states and transform that delta into a list of device commands, following a digital twin synchronization pattern.
In a typical twin/shadow pattern you end up with two documents per thing:
{
"desired": {
"power": "on",
"temperature": 22,
"fan": { "speed": 2 }
},
"reported": {
"power": "off",
"temperature": 20,
"fan": { "speed": 1 }
}
}
The “delta” is simply the subset of the desired state that does not match what the device last reported. A simple recursive diff will give you that. Once you have a delta you can translate it into a list of “set” operations for the device to execute.
Here is one way to express that in Python‑like pseudocode:
def compute_delta(desired: dict, reported: dict) -> dict:
"""
Return a delta object containing only those keys where desired != reported.
"""
delta = {}
for key, desired_val in desired.items():
if key not in reported:
# device never reported this key
delta[key] = desired_val
else:
reported_val = reported[key]
if isinstance(desired_val, dict) and isinstance(reported_val, dict):
sub = compute_delta(desired_val, reported_val)
if sub: # only include non‑empty sub‑deltas
delta[key] = sub
elif desired_val != reported_val:
delta[key] = desired_val
return delta
def delta_to_commands(delta: dict, prefix: str = "") -> list:
"""
Flatten a delta object into a list of concrete set commands.
"""
commands = []
for key, val in delta.items():
path = f"{prefix}/{key}" if prefix else key
if isinstance(val, dict):
commands.extend(delta_to_commands(val, path))
else:
commands.append({
"op": "set",
"path": path, # e.g. "fan/speed"
"value": val # e.g. 2
})
return commands
# Example usage:
desired = {"power": "on", "temperature": 22, "fan": {"speed": 2}}
reported = {"power": "off", "temperature": 20, "fan": {"speed": 1}}
delta = compute_delta(desired, reported)
# delta == {"power": "on", "temperature": 22, "fan": {"speed": 2}}
cmds = delta_to_commands(delta)
# cmds == [
# {"op": "set", "path": "power", "value": "on"},
# {"op": "set", "path": "temperature", "value": 22},
# {"op": "set", "path": "fan/speed", "value": 2}
# ]
# send `cmds` down to the device; when it completes, it should update its reported
# document to match, which will clear the delta.
On the cloud side you run compute_delta(desired, reported) whenever the desired state changes or a new report arrives. If the returned delta is non‑empty, publish the generated commands to the device over MQTT/AMQP/etc. The device executes each set operation to transition its physical state to the target, then updates the twin/shadow’s reported document. Once reported matches desired the computed delta will be empty and no further commands are emitted.