Shadowing Function
After the definition of the Physical Adapter it is time to start implementing the core of our DT through the definition of its Shadowing Function, in charge of:
- Handle received PAD from Physical Adapters in order to decide which properties, events, relationships or actions available on connected physical twins should be mapped and managed into the DT State
- Manage incoming notifications/callbacks associated to the variation of physical properties (e.g, temperature variation) or the generation of physical event (e.g., overheating)
- Process action requests from the digital world that should be validated and forward to the correct Physical Adapter in order to trigger the associated actions on the physical world
In the WLDT library the Shadowing Function is implemented by extending the class DigitalTwinModel.
The Shadowing Function has the responsibility to build and maintain the updated state of the Digital Twin.
The state is owned by a DigitalTwinStateManager, accessible through the variable this.digitalTwinStateManager.
As described in the Digital Twin State page, the state is made of a description (its structure) and of its values.
Reading the State
this.digitalTwinStateManager.getDigitalTwinStateDescription(): returns the currentDigitalTwinStateDescription, with the declared properties, actions, events and relationshipsthis.digitalTwinStateManager.getDigitalTwinStateValues(): returns the current (complete)DigitalTwinStateValues, with the property values, the relationship instances, the last invocation of the actions and the last notification of the events
No method of the manager returns the complete DigitalTwinState.
// Check if a property is already defined on the DT's State
boolean defined = this.digitalTwinStateManager.getDigitalTwinStateDescription()
.getProperties()
.stream()
.anyMatch(property -> property.getKey().equals("temperature-property-key"));
// Read its current value
Object currentValue = this.digitalTwinStateManager.getDigitalTwinStateValues()
.getPropertyValue("temperature-property-key");
Writing the State
All the edits are performed on the manager through a transaction:
- Start the DT State Transaction:
startStateTransaction() - Apply the DT State variations with the methods listed below
- Commit the transaction:
commitStateTransaction(). All the changes are applied together and the resulting state events are published on the Event Bus - Alternatively
rollbackTransaction()discards the collected changes (and the pending event notifications)
Calling an edit method without an open transaction throws a WldtDigitalTwinStateException.
Available edit methods of the DigitalTwinStateManager are:
- Properties:
createProperty(DigitalTwinStateProperty<?> dtStateProperty): Creates a new Property on the Digital Twin’s StateupdateProperty(DigitalTwinStateProperty<?> dtStateProperty): Replaces the whole target property (value, type and content type)updatePropertyValue(DigitalTwinStateProperty<?> dtStateProperty): Updates only the value of the target property, keeping its type and content typedeleteProperty(String propertyKey): Deletes the target property identified by the specified key
- Actions:
enableAction(DigitalTwinStateAction digitalTwinStateAction): Enables and registers the target ActionupdateAction(DigitalTwinStateAction digitalTwinStateAction): Updates an already registered ActiondisableAction(String actionKey): Disables and unregisters the target Action
- Events:
registerEvent(DigitalTwinStateEvent digitalTwinStateEvent): Registers a new Digital Twin State EventupdateRegisteredEvent(DigitalTwinStateEvent digitalTwinStateEvent): Updates the registration and signature of an existing Digital Twin State EventunRegisterEvent(String eventKey): Un-registers a Digital Twin State Event
- Relationships:
createRelationship(DigitalTwinStateRelationship<?> relationship): Creates a new RelationshipaddRelationshipInstance(DigitalTwinStateRelationshipInstance<?> instance): Adds a new Relationship instance (the relationship name is part of the instance)deleteRelationship(String name): Deletes a target Relationship identified through its namedeleteRelationshipInstance(String relationshipName, String instanceKey): Deletes the target Relationship Instance using relationship name and instance key
- Last triggered information (part of the state values):
notifyDigitalTwinStateEvent(DigitalTwinStateEventNotification<?> notification): Notifies the occurrence of a Digital Twin State Event. The event key must be defined in the state and the notification is published at commit timenotifyActionExecuted(String actionKey)/notifyActionExecuted(String actionKey, Instant executionInstant): Records that an action has been executed
Implementing the Shadowing Function
The basic library class that we are going to extend is called DigitalTwinModel. Creating a new class named DemoShadowingFunction,
implementing the required methods and the basic constructor with the id String parameter, the resulting code is the following:
import it.wldt.adapter.digital.event.DigitalActionWldtEvent;
import it.wldt.adapter.physical.PhysicalAssetDescription;
import it.wldt.adapter.physical.event.PhysicalAssetEventWldtEvent;
import it.wldt.adapter.physical.event.PhysicalAssetPropertyWldtEvent;
import it.wldt.adapter.physical.event.PhysicalAssetRelationshipInstanceCreatedWldtEvent;
import it.wldt.adapter.physical.event.PhysicalAssetRelationshipInstanceDeletedWldtEvent;
import it.wldt.augmentation.error.AugmentationFunctionError;
import it.wldt.augmentation.function.AugmentationFunction;
import it.wldt.augmentation.result.AugmentationFunctionResultList;
import it.wldt.core.model.DigitalTwinModel;
import java.util.List;
import java.util.Map;
public class DemoShadowingFunction extends DigitalTwinModel {
public DemoShadowingFunction(String id) {
super(id);
}
//// Shadowing Function Management Callbacks ////
@Override
protected void onCreate() {
}
@Override
protected void onStart() {
}
@Override
protected void onStop() {
}
//// Bound LifeCycle State Management Callbacks ////
@Override
protected void onDigitalTwinBound(Map<String, PhysicalAssetDescription> adaptersPhysicalAssetDescriptionMap) {
}
@Override
protected void onDigitalTwinUnBound(Map<String, PhysicalAssetDescription> map, String s) {
}
@Override
protected void onPhysicalAdapterBidingUpdate(String s, PhysicalAssetDescription physicalAssetDescription) {
}
//// Physical Property Variation Callback ////
@Override
protected void onPhysicalAssetPropertyVariation(PhysicalAssetPropertyWldtEvent<?> physicalAssetPropertyWldtEvent) {
}
//// Physical Event Notification Callback ////
@Override
protected void onPhysicalAssetEventNotification(PhysicalAssetEventWldtEvent<?> physicalAssetEventWldtEvent) {
}
//// Physical Relationships Notification Callbacks ////
@Override
protected void onPhysicalAssetRelationshipEstablished(PhysicalAssetRelationshipInstanceCreatedWldtEvent<?> physicalAssetRelationshipInstanceCreatedWldtEvent) {
}
@Override
protected void onPhysicalAssetRelationshipDeleted(PhysicalAssetRelationshipInstanceDeletedWldtEvent<?> physicalAssetRelationshipInstanceDeletedWldtEvent) {
}
//// Digital Action Received Callbacks ////
@Override
protected void onDigitalActionEvent(DigitalActionWldtEvent<?> digitalActionWldtEvent) {
}
//// Augmentation Functions Callbacks ////
@Override
protected void onAugmentationFunctionError(String handlerId, String functionId, AugmentationFunctionError augmentationFunctionError) {
}
@Override
protected void onAugmentationFunctionResultEvent(String augmentationFunctionHandlerId, String augmentationFunctionId, AugmentationFunctionResultList augmentationFunctionResults) {
}
@Override
protected void onAugmentationNewFunctionAvailable(String handlerId, AugmentationFunction augmentationFunction) {
}
@Override
protected void onAugmentationFunctionUnAvailable(String handlerId, AugmentationFunction augmentationFunction) {
}
@Override
protected void onAugmentationFunctionListAvailable(String handlerId, List<AugmentationFunction> augmentationFunctionList) {
}
}
The augmentation callbacks are not used in this tutorial and can be left empty: see Augmentation Functions.
The methods onCreate(), onStart() and onStop() are used to receive callbacks from the DT’s core when the Shadowing Function has been effectively created within the twin, is started or stopped
according to the evolution of its life cycle. In our initial implementation we are not implementing any of them but they can be useful to trigger specific behaviours according to the different phases.
Building the State from the Physical Asset Description
The first method that we have to implement in order to analyze received PAD and build the Digital Twin State in terms of properties, events, relationships and available actions is
the onDigitalTwinBound(Map<String, PhysicalAssetDescription> map) method. In our initial implementation we just pass through all the characteristics received from each connected
Physical Adapter mapping every physical entity into the DT’s state without any change or adaptation (of course complex behaviour can be implemented to customize the digitalization process).
Through the following method we implement the following behaviour:
- Analyze each received PAD from each connected and active Physical Adapter (in our case we will have just 1 Physical Adapter)
- Iterate over all the received Properties for each PAD and create the same Property on the Digital Twin State
- Start observing target Physical Properties in order to receive notification callback about physical variation through the method
observePhysicalAssetProperty(property); - Analyze received PAD’s Events declaration and recreate them also on the DT’s State
- Start observing target Physical Event in order to receive notification callback about physical event generation through the method
observePhysicalAssetEvent(event); - Check available Physical Actions and enable them on the DT’s State
The possibility to manually observe Physical Properties and Events has been introduced to allow the Shadowing Function to decide what to do according to the nature of the property or of the target event. For example in some cases with static properties it will not be necessary to observe any variation, and it will be enough to read the initial value to build the digital replica of that specific property.
All the changes are collected in a single transaction: the structure of the state changes once and one new description is published.
@Override
protected void onDigitalTwinBound(Map<String, PhysicalAssetDescription> adaptersPhysicalAssetDescriptionMap) {
try {
//Start the DT State Change Transaction
this.digitalTwinStateManager.startStateTransaction();
//Iterate over all the received PAD from connected Physical Adapters
adaptersPhysicalAssetDescriptionMap.values().forEach(pad -> {
//Iterate over available declared Physical Properties for the target Physical Adapter's PAD
pad.getProperties().forEach(property -> {
try {
//Create and write the property on the DT's State keeping the semantic type and the content type
this.digitalTwinStateManager.createProperty(new DigitalTwinStateProperty<>(
property.getKey(),
(Double) property.getInitialValue(),
property.getType(),
property.getContentType()));
//Start observing the variation of the physical property in order to receive notifications
//Without this call the Shadowing Function will not receive any notifications or callback about
//incoming physical property of the target type and with the target key
this.observePhysicalAssetProperty(property);
} catch (Exception e) {
e.printStackTrace();
}
});
//Iterate over available declared Physical Events for the target Physical Adapter's PAD
pad.getEvents().forEach(event -> {
try {
//Instantiate a new DT State Event with the same key, type and content type
DigitalTwinStateEvent dtStateEvent = new DigitalTwinStateEvent(event.getKey(), event.getType(), event.getContentType());
//Create and write the event on the DT's State
this.digitalTwinStateManager.registerEvent(dtStateEvent);
//Start observing the variation of the physical event in order to receive notifications
//Without this call the Shadowing Function will not receive any notifications or callback about
//incoming physical events of the target type and with the target key
this.observePhysicalAssetEvent(event);
} catch (Exception e) {
e.printStackTrace();
}
});
//Iterate over available declared Physical Actions for the target Physical Adapter's PAD
pad.getActions().forEach(action -> {
try {
//Instantiate a new DT State Action with the same key, type and content type
DigitalTwinStateAction dtStateAction = new DigitalTwinStateAction(action.getKey(), action.getType(), action.getContentType());
//Enable the action on the DT's State
this.digitalTwinStateManager.enableAction(dtStateAction);
} catch (Exception e) {
e.printStackTrace();
}
});
});
//Commit the DT State Change Transaction to apply the changes on the DT State and notify about the change
this.digitalTwinStateManager.commitStateTransaction();
//Start observation to receive all incoming Digital Action through active Digital Adapter
//Without this call the Shadowing Function will not receive any notifications or callback about
//incoming request to execute an exposed DT's Action
observeDigitalActionEvents();
//Notify the DT Core that the Bounding phase has been correctly completed and the DT has evaluated its
//internal status according to what is available and declared through the Physical Adapters
notifyShadowingSync();
} catch (Exception e) {
e.printStackTrace();
}
}
In particular the method observeDigitalActionEvents() should be called to start the observation of digital actions and
to receive all incoming Digital Action through active Digital Adapters.
Without this call the Shadowing Function will not receive any notifications or callback about
incoming request to execute an exposed DT’s Action. Of course, we have to call this method if we are mapping any digital
action in our DT.
Another fundamental method is notifyShadowingSync() used to notify the DT Core that
the Bounding phase has been correctly completed and the DT has evaluated its internal status according
to what is available and declared through the Physical Adapters.
Type and Content Type
Properties, events and actions are described by two separate fields, both in the Physical Asset Description
(PhysicalAssetProperty, PhysicalAssetEvent, PhysicalAssetAction) and in the Digital Twin State
(DigitalTwinStateProperty, DigitalTwinStateEvent, DigitalTwinStateAction):
| Field | Meaning | Example |
|---|---|---|
type | Semantic type: what the resource represents (ontology / application domain) | iot.demo.temperature |
contentType | Format used to represent the value or the payload | text/plain, application/json, java.lang.Double |
The Shadowing Function can use this information to decide how to interpret the value or the payload before mapping it on the DT’s State,
and should copy both getType() and getContentType(), as shown in the examples of this page.
By default, the content type of a Physical Property is the class name of its initial value (e.g., java.lang.Double) while for a Physical Event it
is null unless it has been explicitly declared by the Physical Adapter.
The constructors that set only the type, deprecated in 0.8.1, have been removed in 0.9.0.
In the previous example the Shadowing Function does not apply any control or check on the nature of declared
physical properties. In order to have a more granular control, it is possible to use the property key or any other field or even
the type of the instance through an instanceof check to implement different controls and behaviours.
A variation (only for the property management code) of the previous method can be the following:
//Iterate over available declared Physical Property for the target Physical Adapter's PAD
pad.getProperties().forEach(property -> {
try {
//Check property Key and validate that the value is a Double
if (property.getKey().equals("temperature-property-key")
&& property.getInitialValue() != null
&& property.getInitialValue() instanceof Double) {
//Instantiate a new DT State Property with the same key, initial value, type and content type
DigitalTwinStateProperty<Double> dtStateProperty = new DigitalTwinStateProperty<Double>(
property.getKey(),
(Double) property.getInitialValue(),
property.getType(),
property.getContentType());
//Create and write the property on the DT's State (inside the open transaction)
this.digitalTwinStateManager.createProperty(dtStateProperty);
//Start observing the variation of the physical property in order to receive notifications
this.observePhysicalAssetProperty(property);
}
} catch (Exception e) {
e.printStackTrace();
}
});
Handling Physical Variations and Digital Actions
The next methods that we have to implement in order to properly define the behaviour of our DT are:
onPhysicalAssetPropertyVariation: Method called when a new variation for a specific Physical Property has been detected by the associated Physical Adapter. The method receives as parameter aPhysicalAssetPropertyWldtEvent<?>containing all the information generated by the Physical Adapter upon the variation of the monitored physical counterpart.onPhysicalAssetEventNotification: Callback method used to be notified by a Physical Adapter about the generation of a Physical Event. It receives aPhysicalAssetEventWldtEvent<?>containing all the fields of the generated physical event.onDigitalActionEvent: This method is triggered when an Action request has been received on the Digital Interface by one of the active Digital Adapters. It receives aDigitalActionWldtEvent<?>describing the target digital action request and the associated body.
Property Variation
A simple implementation of onPhysicalAssetPropertyVariation, in charge ONLY of mapping the new Physical Property value
into the corresponding DT State property, is the following:
@Override
protected void onPhysicalAssetPropertyVariation(PhysicalAssetPropertyWldtEvent<?> physicalPropertyEventMessage) {
try {
this.digitalTwinStateManager.startStateTransaction();
//Only the value changes: updatePropertyValue() keeps the type and the contentType of the existing State Property
//(updateProperty() would replace the whole property, including its type and contentType)
this.digitalTwinStateManager.updatePropertyValue(new DigitalTwinStateProperty<>(
physicalPropertyEventMessage.getPhysicalPropertyId(),
physicalPropertyEventMessage.getBody()));
this.digitalTwinStateManager.commitStateTransaction();
} catch (WldtDigitalTwinStateException e) {
e.printStackTrace();
}
}
We directly use the data received on the PhysicalAssetPropertyWldtEvent without any additional check
or change that might be instead needed in advanced examples.
Event Notification
Following the same principle, a simplified digital mapping upon the reception of a physical event can be the following:
@Override
protected void onPhysicalAssetEventNotification(PhysicalAssetEventWldtEvent<?> physicalAssetEventWldtEvent) {
try {
//The notification of an event must be done inside a state transaction
this.digitalTwinStateManager.startStateTransaction();
this.digitalTwinStateManager.notifyDigitalTwinStateEvent(new DigitalTwinStateEventNotification<>(
physicalAssetEventWldtEvent.getPhysicalEventKey(),
physicalAssetEventWldtEvent.getBody(),
physicalAssetEventWldtEvent.getCreationTimestamp()));
this.digitalTwinStateManager.commitStateTransaction();
} catch (WldtDigitalTwinStateEventNotificationException | WldtDigitalTwinStateException e) {
e.printStackTrace();
}
}
The method notifyDigitalTwinStateEvent notifies the other DT components (e.g., Digital Adapters) about the incoming Physical Event through a
new instance of the DigitalTwinStateEventNotification class. At commit time the instant of the notification becomes the last notification
of the event in the state values and the notification is published on the Event Bus. Of course, additional controls and checks can be introduced in this
method validating and processing the incoming physical message to define complex behaviours.
Changed in
0.9.0: outside a transactionnotifyDigitalTwinStateEventthrows aWldtDigitalTwinStateEventNotificationException.
Digital Action
The last method that we are going to implement is onDigitalActionEvent, where we have to handle an incoming
Digital Action request associated to an Action declared on the DT’s State in the onDigitalTwinBound method.
In that case the Digital Action should be forwarded to the Physical Interface in order to be sent to the physical counterpart
for the effective execution.
@Override
protected void onDigitalActionEvent(DigitalActionWldtEvent<?> digitalActionWldtEvent) {
try {
this.publishPhysicalAssetActionWldtEvent(digitalActionWldtEvent.getActionKey(), digitalActionWldtEvent.getBody());
} catch (EventBusException e) {
e.printStackTrace();
}
}
The incoming Digital Action request, described through the class DigitalActionWldtEvent, is forwarded
to the Physical Adapter with the method publishPhysicalAssetActionWldtEvent, passing directly the action key and the target body.
No additional processing or validation has been introduced here, but they might be required in advanced scenarios in order to properly adapt
the incoming digital action request to what is effectively expected on the physical counterpart.
The invocation of a Digital Action does not update by itself the last invocation of the action in the state values.
When the Shadowing Function considers the action executed (for example after publishing the physical action, or when the Physical Adapter confirms it)
it records it, inside a state transaction, with notifyActionExecuted:
this.digitalTwinStateManager.startStateTransaction();
this.digitalTwinStateManager.notifyActionExecuted(digitalActionWldtEvent.getActionKey()); // or (actionKey, executionInstant)
this.digitalTwinStateManager.commitStateTransaction();