Digital Adapter

The last component that we have to implement to complete our first simple Digital Twin definition through the WLDT library is a Digital Adapter in charge of:

  • Receiving events from the DT’s Core related to the variation of properties, events, available actions and relationships
  • Expose received information to the external world according to its implementation and the supported protocol
  • Handle incoming digital actions and forward them to the Core in order to be validated and processed by the Shadowing Function

The basic library class that we are going to extend is called DigitalAdapter and we create a new class named DemoDigitalAdapter. The DigitalAdapter class takes as Generic Type the type of Configuration used to configure its behaviours. In this simplified example we are defining a Digital Adapter without any Configuration.

A Digital Adapter has access to the current DT’s State through callbacks or directly, in a synchronous way, using the two protected methods getDigitalTwinStateDescription() and getDigitalTwinStateValues(): through them it is possible to navigate everything that currently composes the state of our Digital Twin. They always return the complete local copy of the state (never filtered), refreshed on every state update (see Digital Twin State).

Changed in 0.9.0: the callback onStateUpdate(...) and the protected field digitalTwinState have been removed.

Callbacks

The Digital Adapter class has a set of callback methods to allow the adapter to be updated about the variations and changes on the twin. Available callbacks can be summarized as follows:

  • Digital Adapter Start/Stop:
    • onAdapterStart(): Feedback when the Digital Adapter correctly starts
    • onAdapterStop(): Feedback when the Digital Adapter has been stopped
  • Digital Twin Life Cycle Notifications:
    • onDigitalTwinCreate(): The DT has been created
    • onDigitalTwinStart(): The DT started. It is called before the adapter is executed (before onAdapterStart()), so do not use it to initialize adapter resources
    • onDigitalTwinSync(DigitalTwinStateDescription description, DigitalTwinStateValues values): The DT is synchronized with its physical counterpart. The current description and values of the state are passed as parameters to allow the Digital Adapter to know the current state and consequently implement its behaviour
    • onDigitalTwinUnSync(DigitalTwinStateDescription description, DigitalTwinStateValues values): The DT is not synchronized anymore with its physical counterpart. The last known description and values are passed as parameters. While the DT is not synchronized the adapter does not follow the state: it is unsubscribed from the state topics and its local copy is dropped. At the next synchronization the copy is initialized again and the subscription is renewed
    • onDigitalTwinStop(): The DT is stopped
    • onDigitalTwinDestroy(): The DT has been destroyed and the application stopped
  • Digital Twin State Variation:
    • onStateDescriptionUpdate(DigitalTwinStateDescription description, List<DigitalTwinStateChange> descriptionChanges): Called every time the description (structure) of the DT’s State changes
    • onStateValuesUpdate(DigitalTwinStateValues values, List<DigitalTwinStateChange> relevantChanges): Called when the values of the DT’s State change
  • Event Notification:
    • onEventNotificationReceived(DigitalTwinStateEventNotification<?> notification): Called when a notification of an observed DT State Event is received. For example in the DT State we can have the declaration of the overheating-event-key event, while the effective occurrence of the event is received through this dedicated callback

The life cycle follows this order: CREATED and STARTED are notified before the Physical and Digital Adapters are executed, then the adapters bind (BOUND) and the shadowing synchronizes the DT (SYNCHRONIZED).

Methods to Control the Observation

  • DT’s State:
    • observeDigitalTwinState(): Enables the observation of all the Digital Twin State variations. It is called automatically when the DT is synchronized, unless the adapter already enabled the observation
    • observeDigitalTwinState(DigitalTwinStateFilter filter) and observeDigitalTwinState(DigitalTwinStateFilter filter, DigitalTwinStateChangeFilter changeFilter): Enable the observation applying a content filter and optionally a trigger filter on the values updates
    • clearStateFilter(): Removes the filters, the adapter receives again every values update, complete
    • unObserveDigitalTwinState(): Cancels the observation of the Digital Twin State variations
  • Events notifications (the payload of an event is not part of the state updates):
    • observeAllDigitalTwinEventsNotifications(DigitalTwinStateDescription description): Enables the observation of the notifications of all the events declared in the description
    • unObserveAllDigitalTwinEventsNotifications(DigitalTwinStateDescription description): Cancels the observation of the notifications of all the events declared in the description
    • observeDigitalTwinEventsNotifications(List<String> eventsList): Enables the observation of the notifications associated to a specific list of Digital Twin State events
    • unObserveDigitalTwinEventsNotifications(List<String> eventsList): Cancels the observation of a target list of events
    • observeDigitalTwinEventNotification(String eventKey): Enables the observation of the notifications associated to a single Digital Twin State event
    • unObserveDigitalTwinEventNotification(String eventKey): Cancels the observation of a single target event

Implementing the Digital Adapter

The resulting code, after adding the required methods (still empty) and the basic constructor with the id String parameter, is the following:

import it.wldt.adapter.digital.DigitalAdapter;
import it.wldt.core.state.*;

import java.util.List;

public class DemoDigitalAdapter extends DigitalAdapter<Void> {

    public DemoDigitalAdapter(String id) {
        super(id);
    }

    /**
     * Callback to notify the adapter on its correct startup
     */
    @Override
    public void onAdapterStart() {}

    /**
     * Callback to notify the adapter that has been stopped
     */
    @Override
    public void onAdapterStop() {}

    /**
     * Notification that the description (structure) of the DT State changed
     *
     * @param description the complete new description
     * @param descriptionChanges the changes that altered the structure
     */
    @Override
    protected void onStateDescriptionUpdate(DigitalTwinStateDescription description,
                                            List<DigitalTwinStateChange> descriptionChanges) {}

    /**
     * Notification that the values of the DT State changed
     *
     * @param values the complete current values
     * @param relevantChanges the changes that altered the values
     */
    @Override
    protected void onStateValuesUpdate(DigitalTwinStateValues values,
                                       List<DigitalTwinStateChange> relevantChanges) {}

    /**
     * DT Life Cycle notification that the DT is correctly on Sync
     */
    @Override
    public void onDigitalTwinSync(DigitalTwinStateDescription digitalTwinStateDescription,
                                  DigitalTwinStateValues digitalTwinStateValues) {}

    /**
     * DT Life Cycle notification that the DT is currently Not Sync
     */
    @Override
    public void onDigitalTwinUnSync(DigitalTwinStateDescription digitalTwinStateDescription,
                                    DigitalTwinStateValues digitalTwinStateValues) {}

    /**
     * DT Life Cycle notification that the DT has been created
     */
    @Override
    public void onDigitalTwinCreate() {}

    /**
     * DT Life Cycle Notification that the DT has correctly Started
     */
    @Override
    public void onDigitalTwinStart() {}

    /**
     * DT Life Cycle Notification that the DT has been stopped
     */
    @Override
    public void onDigitalTwinStop() {}

    /**
     * DT Life Cycle Notification that the DT has destroyed
     */
    @Override
    public void onDigitalTwinDestroy() {}

    /**
     * Callback method to receive a new computed Event Notification (associated to event declared in the DT State)
     *
     * @param digitalTwinStateEventNotification The generated Notification associated to a DT Event
     */
    @Override
    protected void onEventNotificationReceived(DigitalTwinStateEventNotification<?> digitalTwinStateEventNotification) {}
}

onStateDescriptionUpdate(...) and onStateValuesUpdate(...) are abstract: a Digital Adapter must implement both (even with an empty body).

Observing the Digital Twin State

By default, a Digital Adapter observes all the variations of the DT’s State in terms of Properties, Relationships, Actions and Events. The state travels on the Event Bus as two separate events: the adapter applies each of them to its local, complete copy of the state and then calls one of the two callbacks, with the list of the changes (DigitalTwinStateChange: operation, resource type and resource).

CallbackCalled whenWhat it receivesFiltered
onStateDescriptionUpdateA property, action, event or relationship is added, updated or removed and the structure really changesThe complete DigitalTwinStateDescription and the changes that altered the structureNever
onStateValuesUpdateA value changes: a property value, the instances of a relationship, the last invocation of an action or last notification of an eventThe complete DigitalTwinStateValues of the local copy (limited to the accepted resources if a content filter is set) and the changes that altered the valuesYes: called only if at least one change passes the content filter and matches the trigger filter (if set)

The adapter receives the complete values at every call, even if the event carries only the changed ones: the delta is merged with its local copy, that is always updated even when the callback is filtered out.

The removal of a property, relationship, action or event is delivered only through onStateDescriptionUpdate: no values callback is invoked for it.

Threading: the state callbacks run on the Event Bus thread of the adapter, one at a time and in order, while holding the monitor of the local copy of the state. A callback that takes long, or that keeps a lock needed by other threads, blocks the arrival of the following state events (and the access to getDigitalTwinStateValues()). An exception thrown by a callback is logged, counted in the monitoring metrics (da_state_update_processing_exec_error_count) and does not stop the following callbacks.

A simple implementation of the two callbacks is the following:

@Override
protected void onStateDescriptionUpdate(DigitalTwinStateDescription description,
                                        List<DigitalTwinStateChange> descriptionChanges) {
    // e.g., rebuild the interface exposed to the external world
    description.getProperties().forEach(p -> System.out.println("Property: " + p.getKey() + " type: " + p.getType() + " writable: " + p.isWritable()));
    description.getActions().forEach(a -> System.out.println("Action: " + a.getKey()));
    description.getEvents().forEach(e -> System.out.println("Event: " + e.getKey()));
    description.getRelationships().forEach(r -> System.out.println("Relationship: " + r.getName()));
}

@Override
protected void onStateValuesUpdate(DigitalTwinStateValues values,
                                   List<DigitalTwinStateChange> relevantChanges) {
    // e.g., publish the new values on the target protocol
    values.getPropertyValues().forEach((key, value) -> System.out.println("Property " + key + " = " + value));
    values.getLastEventNotifications().forEach((key, instant) -> System.out.println("Event " + key + " last notified at " + instant));
}

Each change can be inspected to differentiate the behaviour:

for (DigitalTwinStateChange change : relevantChanges) {
    switch (change.getOperation()) {
        case OPERATION_UPDATE_VALUE:
            System.out.println("Update value operation on " + change.getResourceType() + ": " + change.getResource());
            break;
        case OPERATION_ADD:
            System.out.println("Add operation on " + change.getResourceType() + ": " + change.getResource());
            break;
        case OPERATION_UPDATE:
            System.out.println("Update operation on " + change.getResourceType() + ": " + change.getResource());
            break;
        case OPERATION_REMOVE:
            System.out.println("Remove operation on " + change.getResourceType() + ": " + change.getResource());
            break;
    }
}

Filtering the Observed Values

The filters restrict when onStateValuesUpdate is called and which values it receives. The content filter (DigitalTwinStateFilter) lists, for each category (properties, actions, events and relationships), the names of the accepted resources: an unset category accepts everything, an empty list accepts nothing. The optional trigger filter (DigitalTwinStateChangeFilter) accepts only the changes with the given operation, resource type and/or resource name. They are set with observeDigitalTwinState(filter[, changeFilter]), typically in onDigitalTwinSync: the description of the state is available there and the filters are active from the first update. A new call replaces the previous filters, with one exception: the version with only the content filter keeps the trigger filter already set (pass null as changeFilter, or call clearStateFilter(), to remove it).

@Override
public void onDigitalTwinSync(DigitalTwinStateDescription digitalTwinStateDescription, DigitalTwinStateValues digitalTwinStateValues) {
    try {

        // Only the property "temperature-property-key" (and every action, event and relationship, since they are not filtered)
        observeDigitalTwinState(DigitalTwinStateFilter.all().withPropertyNames("temperature-property-key"));

        // Alternative: only temperature and humidity and nothing else, notified only when their value is updated
        // observeDigitalTwinState(DigitalTwinStateFilter.all()
        //         .withPropertyNames("temperature", "humidity")
        //         .withActionNames()
        //         .withEventNames()
        //         .withRelationshipNames(),
        //         DigitalTwinStateChangeFilter.onPropertyValueUpdate("temperature", "humidity"));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

The event names of the content filter also select the event notifications delivered to onEventNotificationReceived: the notifications of the events that the filter does not accept are discarded (the notifications to receive are still chosen with the observe*EventNotification(s) methods). A Digital Adapter has one content filter and one trigger rule; the description is never filtered.

Observing Event Notifications

The notifications of the events registered in the DT’s State carry a payload and are not part of the state updates: to receive them the adapter has to observe them with the methods presented above and implement the callback onEventNotificationReceived.

In onDigitalTwinSync we use the parameter digitalTwinStateDescription to find the declared events that we would like to observe:

@Override
public void onDigitalTwinSync(DigitalTwinStateDescription digitalTwinStateDescription, DigitalTwinStateValues digitalTwinStateValues) {

    try {

        //Retrieve the list of available events and observe all their notifications
        List<String> eventKeys = digitalTwinStateDescription.getEvents().stream()
                .map(DigitalTwinStateDescription.EventDescription::getKey)
                .collect(Collectors.toList());

        if (!eventKeys.isEmpty())
            observeDigitalTwinEventsNotifications(eventKeys);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected void onEventNotificationReceived(DigitalTwinStateEventNotification<?> digitalTwinStateEventNotification) {
    System.out.println("Event notification received - Event: " + digitalTwinStateEventNotification.getDigitalEventKey()
            + " body: " + digitalTwinStateEventNotification.getBody());
}

Both Physical Adapters and Digital Adapters can be defined natively with a custom configuration provided by the developer as illustrated in the dedicated Section: Configurable Physical & Digital Adapters.