Manage IoT devices with a digital twin synchronization pattern. The cloud maintains desired and reported state JSON documents. Write logic to compute the delta and generate commands to transition the device from reported to desired state.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about implementing a digital twin synchronization pattern for IoT devices. Let me create a comprehensive solution that demonstrates:
State management (desired vs reported)
Delta computation
Command generation
Device synchronization logic
Conflict resolution
Error handling and retry logic
I'll use a practical approach with TypeScript/Node.js to demonstrate this pattern clearly. Let me build:
Core types and interfaces
State manager for tracking desired and reported states
Delta computation logic
Command generator
Device synchronizer
Examples with different device types
Unit tests or validation scenarios
This is similar to AWS IoT Device Shadow or Azure IoT Hub Device Twin patterns.
IoT Digital Twin Synchronization Pattern
I'll create a comprehensive system for managing IoT devices with desired/reported state synchronization.
Core Implementation
typescript
// types.ts
export interface DeviceState {
[key: string]: any;
timestamp: number;
version: number;
}
export interface StateDocument {
desired: DeviceState;
reported: DeviceState;
metadata?: {
desiredVersion: number;
reportedVersion: number;
lastDesiredUpdate: number;
lastReportedUpdate: number;
};
}
export interface StateDelta {
path: string;
operation: 'add' | 'update' | 'delete' | 'conflict';
expectedValue: any;
currentValue: any;
priority: number;
}
export interface DeviceCommand {
id: string;
type: string;
parameters: Record<string, any>;
timestamp: number;
retryCount: number;
maxRetries: number;
timeout: number;
priority: 'high' | 'normal' | 'low';
}
export interface SyncResult {
deviceId: string;
success: boolean;
timestamp: number;
deltas: StateDelta[];
commands: DeviceCommand[];
errors: string[];
}
// twinManager.ts
export class DigitalTwinManager {
private twinStore = new Map<string, StateDocument>();
private commandQueue = new Map<string, DeviceCommand[]>();
private syncHistory = new Map<string, SyncResult[]>();
/**
* Initialize a new digital twin for a device
*/
initializeTwin(deviceId: string, initialDesired: any = {}): StateDocument {
const twin: StateDocument = {
desired: {
...initialDesired,
timestamp: Date.now(),
version: 1,
},
reported: {
timestamp: Date.now(),
version: 0,
},
metadata: {
desiredVersion: 1,
reportedVersion: 0,
lastDesiredUpdate: Date.now(),
lastReportedUpdate: 0,
},
};
this.twinStore.set(deviceId, twin);
this.commandQueue.set(deviceId, []);
this.syncHistory.set(deviceId, []);
return twin;
}
/**
* Get the current state document
*/
getState(deviceId: string): StateDocument | null {
return this.twinStore.get(deviceId) || null;
}
/**
* Update the desired state
*/
updateDesired(
deviceId: string,
desiredUpdates: Record<string, any>
): StateDocument {
let twin = this.twinStore.get(deviceId);
if (!twin) {
throw new Error(`Digital twin not found for device: ${deviceId}`);
}
const previousDesired = { ...twin.desired };
twin.desired = {
...twin.desired,
...desiredUpdates,
timestamp: Date.now(),
version: (twin.desired.version || 0) + 1,
};
if (twin.metadata) {
twin.metadata.desiredVersion = twin.desired.version;
twin.metadata.lastDesiredUpdate = Date.now();
}
this.twinStore.set(deviceId, twin);
console.log(`[${deviceId}] Desired state updated:`, {
previous: previousDesired,
current: twin.desired,
});
return twin;
}
/**
* Update the reported state from device
*/
updateReported(
deviceId: string,
reportedUpdates: Record<string, any>
): StateDocument {
let twin = this.twinStore.get(deviceId);
if (!twin) {
throw new Error(`Digital twin not found for device: ${deviceId}`);
}
const previousReported = { ...twin.reported };
twin.reported = {
...twin.reported,
...reportedUpdates,
timestamp: Date.now(),
version: (twin.reported.version || 0) + 1,
};
if (twin.metadata) {
twin.metadata.reportedVersion = twin.reported.version;
twin.metadata.lastReportedUpdate = Date.now();
}
this.twinStore.set(deviceId, twin);
console.log(`[${deviceId}] Reported state updated:`, {
previous: previousReported,
current: twin.reported,
});
return twin;
}
/**
* Compute delta between desired and reported states
*/
computeDelta(deviceId: string): StateDelta[] {
const twin = this.twinStore.get(deviceId);
if (!twin) {
throw new Error(`Digital twin not found for device: ${deviceId}`);
}
const deltas: StateDelta[] = [];
// Find properties in desired but not in reported (new properties)
for (const [key, value] of Object.entries(twin.desired)) {
if (key === 'timestamp' || key === 'version') continue;
if (!(key in twin.reported)) {
deltas.push({
path: key,
operation: 'add',
expectedValue: value,
currentValue: undefined,
priority: this.calculatePriority(key),
});
} else if (twin.reported[key] !== value) {
// Value mismatch
deltas.push({
path: key,
operation: 'update',
expectedValue: value,
currentValue: twin.reported[key],
priority: this.calculatePriority(key),
});
}
}
// Find properties in reported but not in desired (deletions)
for (const key of Object.keys(twin.reported)) {
if (key === 'timestamp' || key === 'version') continue;
if (!(key in twin.desired)) {
deltas.push({
path: key,
operation: 'delete',
expectedValue: undefined,
currentValue: twin.reported[key],
priority: this.calculatePriority(key, 'delete'),
});
}
}
// Sort by priority (high first)
deltas.sort((a, b) => b.priority - a.priority);
return deltas;
}
/**
* Generate commands to synchronize device state
*/
generateCommands(deviceId: string): DeviceCommand[] {
const deltas = this.computeDelta(deviceId);
const commands: DeviceCommand[] = [];
for (const delta of deltas) {
const command = this.deltaToCommand(deviceId, delta);
if (command) {
commands.push(command);
}
}
return commands;
}
/**
* Convert a delta to a device command
*/
private deltaToCommand(deviceId: string, delta: StateDelta): DeviceCommand | null {
const baseCommand: DeviceCommand = {
id: `cmd_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
timestamp: Date.now(),
retryCount: 0,
maxRetries: 3,
timeout: 30000,
priority: delta.priority > 7 ? 'high' : delta.priority > 3 ? 'normal' : 'low',
type: '',
parameters: {},
};
switch (delta.operation) {
case 'add':
case 'update':
return {
...baseCommand,
type: 'set_property',
parameters: {
property: delta.path,
value: delta.expectedValue,
},
};
case 'delete':
return {
...baseCommand,
type: 'delete_property',
parameters: {
property: delta.path,
},
};
case 'conflict':
// Handle conflicts - could implement custom resolution
console.warn(`Conflict detected for property: ${delta.path}`);
return null;
default:
return null;
}
}
/**
* Calculate priority based on property name and operation
*/
private calculatePriority(
property: string,
operation: string = 'update'
): number {
const criticalProperties = ['power', 'connectivity', 'security'];
const isCritical = criticalProperties.some((p) => property.includes(p));
if (isCritical) return 10;
if (operation === 'delete') return 3;
return 5;
}
/**
* Queue commands for a device
*/
queueCommands(deviceId: string, commands: DeviceCommand[]): void {
const existing = this.commandQueue.get(deviceId) || [];
existing.push(...commands);
// Sort by priority
const priorityMap = { high: 3, normal: 2, low: 1 };
existing.sort((a, b) => priorityMap[b.priority] - priorityMap[a.priority]);
this.commandQueue.set(deviceId, existing);
console.log(`[${deviceId}] Queued ${commands.length} commands`);
}
/**
* Get pending commands for a device
*/
getPendingCommands(deviceId: string, limit: number = 10): DeviceCommand[] {
const commands = this.commandQueue.get(deviceId) || [];
return commands.slice(0, limit);
}
/**
* Acknowledge command execution
*/
acknowledgeCommand(
deviceId: string,
commandId: string,
success: boolean,
error?: string
): void {
let commands = this.commandQueue.get(deviceId) || [];
if (success) {
commands = commands.filter((c) => c.id !== commandId);
console.log(`[${deviceId}] Command ${commandId} completed successfully`);
} else {
const cmd = commands.find((c) => c.id === commandId);
if (cmd && cmd.retryCount < cmd.maxRetries) {
cmd.retryCount++;
console.warn(
`[${deviceId}] Command ${commandId} failed (${cmd.retryCount}/${cmd.maxRetries}): ${error}`
);
} else {
commands = commands.filter((c) => c.id !== commandId);
console.error(
`[${deviceId}] Command ${commandId} failed permanently: ${error}`
);
}
}
this.commandQueue.set(deviceId, commands);
}
/**
* Synchronize device state
*/
sync(deviceId: string): SyncResult {
try {
const deltas = this.computeDelta(deviceId);
const commands = this.generateCommands(deviceId);
this.queueCommands(deviceId, commands);
const result: SyncResult = {
deviceId,
success: deltas.length === 0,
timestamp: Date.now(),
deltas,
commands,
errors: [],
};
// Record sync history
const history = this.syncHistory.get(deviceId) || [];
history.push(result);
this.syncHistory.set(deviceId, history.slice(-100)); // Keep last 100
return result;
} catch (error) {
return {
deviceId,
success: false,
timestamp: Date.now(),
deltas: [],
commands: [],
errors: [(error as Error).message],
};
}
}
/**
* Get synchronization history
*/
getSyncHistory(deviceId: string): SyncResult[] {
return this.syncHistory.get(deviceId) || [];
}
/**
* Get detailed device status
*/
getDeviceStatus(deviceId: string): any {
const twin = this.twinStore.get(deviceId);
if (!twin) throw new Error(`Device ${deviceId} not found`);
const deltas = this.computeDelta(deviceId);
const pendingCommands = this.commandQueue.get(deviceId) || [];
return {
deviceId,
twin,
deltaCount: deltas.length,
pendingCommandsCount: pendingCommands.length,
isSynced: deltas.length === 0,
deltas,
pendingCommands: pendingCommands.slice(0, 5),
};
}
}
Advanced Command Execution
typescript
Conflict Resolution
typescript
// conflictResolver.ts
export class ConflictResolver {
/**
* Detect conflicts between desired and reported states
*/
detectConflicts(
desired: any,
reported: any,
lastSync: number
): StateDelta[] {
const conflicts: StateDelta[] = [];
const now = Date.now();
const staleThreshold = 60000; // 1 minute
for (const [key, desiredValue] of Object.entries(desired)) {
if (key === 'timestamp' || key === 'version') continue;
if (key in reported) {
const reportedValue = reported[key];
if (desiredValue !== reportedValue) {
// Check if reported state is too old
const isStale = now - (reported.timestamp || 0) > staleThreshold;
conflicts.push({
path: key,
operation: 'conflict',
expectedValue: desiredValue,
currentValue: reportedValue,
priority: isStale ? 8 : 5,
});
}
}
}
return conflicts;
}
/**
* Resolve conflicts using strategies
*/
resolveConflict(
conflict: StateDelta,
strategy: 'desired' | 'reported' | 'manual' = 'desired'
): any {
switch (strategy) {
case 'desired':
return conflict.expectedValue;
case 'reported':
return conflict.currentValue;
case 'manual':
// Return conflict for manual resolution
return { conflict, action: 'pending_manual_review' };
default:
return conflict.expectedValue;
}
}
/**
* Implement last-write-wins strategy
*/
resolveUsingLastWrite(
conflict: StateDelta,
lastDesiredUpdate: number,
lastReportedUpdate: number
): any {
return lastDesiredUpdate > lastReportedUpdate
? conflict.expectedValue
: conflict.currentValue;
}
/**
* Implement custom property-based strategy
*/
resolveUsingPropertyRules(
conflict: StateDelta,
propertyRules: Map<string, string>
): any {
const strategy = propertyRules.get(conflict.path) || 'desired';
return this.resolveConflict(conflict, strategy as any);
}
}