Manage Thing Shadows with the thingShadow class
masterThe thingShadow class wraps a device instance to provide high-level API access to AWS IoT Thing Shadows.
Lifecycle and Operations:
- Register: You must call
register(thingName, [options], [callback])before performing operations. This subscribes the client to the necessary shadow topics.options.ignoreDeltas: Iftrue, ignores thedeltasub-topic.options.persistentSubscribe: Iffalse, the client unsubscribes from operation sub-topics when not performing an operation (improves traffic but slows down operations).options.discardStale: Iffalse, allows receiving messages with old version numbers.options.enableVersioning: Iftrue, sends version numbers with updates to prevent overwriting concurrent changes.
- Perform Operations: Use
update(),get(), ordelete(). These return aclientToken(string or number) used to track the operation via'status'or'timeout'events. - Unregister: Call
unregister(thingName)to stop receiving events and unsubscribe from shadow topics.
Core Events:
'status': Emitted whenupdate|get|deletecompletes. Returns(thingName, stat, clientToken, stateObject).statis either'accepted'or'rejected'.'delta': Emitted when a delta is received for a registered shadow. Returns(thingName, stateObject).'foreignStateChange': Emitted when a different client performs anupdateordeleteon the shadow. Returns(thingName, operation, stateObject).'timeout': Emitted when an operation times out. Returns(thingName, clientToken).'message': Emitted for non-shadow MQTT messages. Returns(topic, message).
const shadow = awsIot.thingShadow(device, { operationTimeout: 10000 });
shadow.register('myThing', { ignoreDeltas: false }, (err) => {
if (!err) {
const token = shadow.update('myThing', { state: { temperature: 25 } });
console.log('Update operation token:', token);
}
});
shadow.on('status', (thingName, stat, clientToken, stateObject) => {
console.log(`Operation ${clientToken} for ${thingName} was ${stat}`);
});