Digital Twin State

Since version 0.9.0 the Digital Twin State does not travel anymore as a single, complete object inside the twin. This page describes how the state is structured, how it is read and written, how its variations are propagated on the internal Event Bus and how each component keeps its own up to date copy.

Description and Values

The Digital Twin State is made of two distinct parts, that travel and are read separately (the complete state is internal to the DigitalTwinStateManager and is never exposed):

  • The description (DigitalTwinStateDescription): the structure of the state, i.e., which properties, actions, events and relationships are defined and how (key or name, type, content type, access flags), without any value.
  • The values (DigitalTwinStateValues): the current value of each property, the instances of each relationship, and the instant of the last invocation of each action and of the last notification of each event. The values always carry the id of the description they belong to.

Main read methods of DigitalTwinStateDescription:

  • getId(): The unique id of the description
  • getProperties(), getActions(), getEvents(), getRelationships(): The (unmodifiable) lists of PropertyDescription (key, type, content type, readable, writable, exposed), ActionDescription (key, type, content type, exposed), EventDescription (key, type, content type) and RelationshipDescription (name, type)
  • getEvaluationInstant(): The evaluation instant of the state it comes from
  • isEmpty() and isSameStructureAs(DigitalTwinStateDescription other): two descriptions are equal if they have the same structure, regardless of id and evaluation instant

Main read methods of DigitalTwinStateValues (an immutable snapshot):

  • getDescriptionId(): The id of the description these values are associated to
  • getPropertyValues() / getPropertyValue(String key): The property values by key
  • getRelationshipInstances(): The instances of each relationship by relationship name (a relationship without instances has an empty list)
  • getLastActionInvocations() / getLastEventNotifications(): The instant of the last invocation of each action and of the last notification of each event (only the ones that happened)
  • getEvaluationInstant() and isEmpty()
  • filter(DigitalTwinStateFilter filter): A copy of the values limited to the accepted resources

Description id

DigitalTwinStateDescription.getId() has the format <creationTimestamp>_<numSeq>: the epoch milliseconds of the creation of the DigitalTwinStateManager followed by a sequence number that starts from 0 (the initial, empty description) and grows every time the structure of the state really changes. A transaction that changes several resources produces one new description.

Reading the state

// In the Shadowing Function (DigitalTwinModel)
DigitalTwinStateDescription description = this.digitalTwinStateManager.getDigitalTwinStateDescription();
DigitalTwinStateValues values = this.digitalTwinStateManager.getDigitalTwinStateValues();
// In a Digital Adapter (complete local copy, never filtered)
DigitalTwinStateDescription description = getDigitalTwinStateDescription();
DigitalTwinStateValues values = getDigitalTwinStateValues();

Examples of access to the information:

// Is a property defined in the state?
boolean hasTemperature = description.getProperties().stream()
        .anyMatch(property -> property.getKey().equals("temperature-property-key"));

// Current value of a property
Object temperature = values.getPropertyValue("temperature-property-key");

// Last time an action has been executed / an event has been notified (null if it never happened)
Instant lastInvocation = values.getLastActionInvocations().get("set-temperature-action-key");
Instant lastNotification = values.getLastEventNotifications().get("overheating-event-key");

Writing the State

All the edits are performed by the Shadowing Function on the DigitalTwinStateManager through a transaction:

  • startStateTransaction() opens the transaction
  • the edit methods collect the changes
  • commitStateTransaction() applies all of them together and publishes the resulting state events on the Event Bus
  • rollbackTransaction() discards the collected changes (and the pending event notifications)

Calling an edit method without an open transaction throws a WldtDigitalTwinStateException. The list of the edit methods is reported in the Shadowing Function page.

Two methods update the last triggered information, that is part of the state values, and must be called inside a transaction:

  • notifyDigitalTwinStateEvent(DigitalTwinStateEventNotification<?> notification): Notifies the occurrence of a Digital Twin State Event (its key must be defined in the state). The instant of the notification becomes a value of the state and the notification is published at commit time, after the description and values events. A rolled back transaction publishes nothing. Called outside a transaction it throws WldtDigitalTwinStateEventNotificationException.
  • notifyActionExecuted(String actionKey) / notifyActionExecuted(String actionKey, Instant executionInstant): Records that an action has been executed (by default now). The invocation of a Digital Action does not update it automatically.
this.digitalTwinStateManager.startStateTransaction();
this.digitalTwinStateManager.notifyActionExecuted("set-temperature-action-key");
this.digitalTwinStateManager.notifyDigitalTwinStateEvent(
        new DigitalTwinStateEventNotification<>("overheating-event-key", "critical", System.currentTimeMillis()));
this.digitalTwinStateManager.commitStateTransaction();

State Events on the Event Bus

Every committed transaction publishes up to two state events (plus the notifications of the events notified in the transaction), always in this order. The complete state never travels on the bus: only what changed.

EventTopicPublished whenBodyMetadata
Description updatedt.state.description.update (WldtEventTypes.DT_STATE_DESCRIPTION_UPDATE_MESSAGE_EVENT_TYPE)The structure of the state really changed (compared structurally with the previous description)The complete new DigitalTwinStateDescriptionDT_STATE_DESCRIPTION_UPDATE_METADATA_PREVIOUS_DESCRIPTION: the previous description. DT_STATE_DESCRIPTION_UPDATE_METADATA_CHANGE_LIST: the changes that alter the structure
Values updatedt.state.values.update (WldtEventTypes.DT_STATE_VALUES_UPDATE_MESSAGE_EVENT_TYPE)The transaction contains at least one change of the valuesA DigitalTwinStateValues delta with only the values that changedDT_STATE_VALUES_UPDATE_METADATA_PREVIOUS_VALUES: the previous values of the same resources. DT_STATE_VALUES_UPDATE_METADATA_CHANGE_LIST: the changes that alter the values
Event notificationdt.state.event.notification.<eventKey>At commit time, for each notifyDigitalTwinStateEvent of the transactionThe DigitalTwinStateEventNotification

The topics are also available through the static methods DigitalTwinStateManager.getStateDescriptionUpdateWldtEventMessageType(), getStateValuesUpdateWldtEventMessageType() and getEventNotificationWldtEventMessageType(eventKey). The old topic dt.state.update, that carried the complete state, does not exist anymore.

Content of the values delta

  • A property added or whose value changed: its new value. A property whose value is unchanged is not in the body
  • A relationship added, or whose instances changed: the complete list of the instances of that relationship
  • A relationship instance added or removed: the complete, updated list of the instances of that relationship
  • The last invocation of an action or last notification of an event triggered in the transaction
  • Nothing for a removed property, relationship, action or event: the removal is not a values update, it travels only in the description event and every local copy drops the value when it applies the new description

Which changes alter what

Each variation is described by a DigitalTwinStateChange: an operation (OPERATION_ADD, OPERATION_UPDATE, OPERATION_UPDATE_VALUE, OPERATION_REMOVE), a resource type (PROPERTY, PROPERTY_VALUE, ACTION, EVENT, RELATIONSHIP, RELATIONSHIP_INSTANCE) and the resource.

ChangeDescription updateValues update
PROPERTY, RELATIONSHIP with OPERATION_ADD / OPERATION_UPDATEyesyes (the value / the instances)
PROPERTY, RELATIONSHIP, ACTION, EVENT with OPERATION_REMOVEyesno (no values callback is invoked)
ACTION, EVENT with OPERATION_ADD / OPERATION_UPDATEyesno (they carry no value)
OPERATION_UPDATE_VALUE (property value, last invocation of an action, last notification of an event)noyes
RELATIONSHIP_INSTANCE with OPERATION_ADD / OPERATION_REMOVEnoyes (the complete list of the instances)

The methods isDescriptionChange() and isValueChange() of DigitalTwinStateChange (and the static helpers descriptionChanges(list) / valueChanges(list)) implement this classification.

Rules to keep in mind:

  • A change is published in the description event only if the structure really changed: for example updateProperty(...) with an identical structure produces a values update but no description update.
  • A transaction that changes only the structure (for example it enables an action) does not publish a values update.
  • The values update is published also when the delta is empty but the change list is not (for example a property updated with the same value).
  • The description update is always published before the values update of the same transaction. Delivery to the subscribers is asynchronous and the two topics are independent: a subscriber can receive the values before their description.

Keeping a Local Copy of the State

Digital Adapters, the Storage Manager and the Augmentation Function Handlers keep a complete and never filtered local copy of the description and of the values, initialized at synchronization time (the Storage Manager when the DigitalTwin is created) and updated at every event. The delta of the values is merged with the complete values and a new description realigns the values to its id.

The class that does it, DigitalTwinStateReplica (package it.wldt.core.state), is available to custom components too. Its methods are synchronized; the caller holds synchronized (replica) around apply and read when it needs a consistent view.

MethodDescription
seed(description, values) / clear() / isSeeded()Initialize the copy at synchronization time, drop it at un-synchronization, check if it is initialized
applyDescriptionEvent(WldtEvent<?>)Applies a description event: true if applied, false for a description that is not newer than the current one or that belongs to another state. After it the waiting values events must be drained
applyValuesEvent(WldtEvent<?>)Applies a values event: true if applied, false if it is kept waiting for its description, if it is already included in the seeded values, or if it belongs to another state
applyNextPendingValues()Applies the next waiting values event and returns it, null when there is none. Call it in a loop after a description event
getDescription() / getValues()The complete local copy
getPendingValuesCount()The number of values events waiting for their description

The static methods DigitalTwinStateManager.getDescriptionChanges(event) and getValuesChanges(event) return the changes carried in the metadata of a state event.

DigitalTwinStateReplica replica = new DigitalTwinStateReplica();
replica.seed(description, values); // at synchronization time

synchronized (replica) {

    // Values event: true if it has been applied
    if (replica.applyValuesEvent(wldtEvent)) {
        DigitalTwinStateValues completeValues = replica.getValues();
        List<DigitalTwinStateChange> changes = DigitalTwinStateManager.getValuesChanges(wldtEvent);
    }

    // Description event: after it, the values events that were waiting for it must be processed
    if (replica.applyDescriptionEvent(wldtEvent)) {
        DigitalTwinStateDescription newDescription = replica.getDescription();
        List<DigitalTwinStateChange> changes = DigitalTwinStateManager.getDescriptionChanges(wldtEvent);

        WldtEvent<?> pendingEvent;
        while ((pendingEvent = replica.applyNextPendingValues()) != null) {
            DigitalTwinStateValues pendingValues = replica.getValues();
            List<DigitalTwinStateChange> pendingChanges = DigitalTwinStateManager.getValuesChanges(pendingEvent);
        }
    }
}

State Filters

Digital Adapters and Augmentation Functions can choose when they are notified of a values update and which part of the values they receive:

  • DigitalTwinStateFilter (content filter): lists by name the accepted properties, actions, events and relationships. An unset category accepts everything, an empty list accepts nothing. The event names also select the event notifications delivered.
  • DigitalTwinStateChangeFilter (trigger filter): accepts the changes with the given operation, resource type and resource name. Inside each criterion the values are alternatives (OR), the criteria are AND-ed, an empty criterion accepts everything.
// Content filter: only temperature and humidity, no action
DigitalTwinStateFilter contentFilter = DigitalTwinStateFilter.all()
        .withPropertyNames("temperature", "humidity")
        .withActionNames();

// Trigger filter: only value updates of the temperature
DigitalTwinStateChangeFilter triggerFilter = DigitalTwinStateChangeFilter.onPropertyValueUpdate("temperature");

// Trigger filter: only removed relationship instances
DigitalTwinStateChangeFilter removedInstances = DigitalTwinStateChangeFilter.builder()
        .operations(DigitalTwinStateChange.Operation.OPERATION_REMOVE)
        .resourceTypes(DigitalTwinStateChange.ResourceType.RELATIONSHIP_INSTANCE)
        .build();

Rules common to all the components:

  • Filters apply only to the values: the description is never filtered.
  • The local copy of a component is always updated, whatever the filters.
  • A trigger rule with OPERATION_REMOVE on a property, relationship, action or event never fires a values callback (the removal is delivered by the description callback).
  • The Storage Manager does not filter: it always saves the description and the complete values.

The library has four unrelated “filters”: DigitalTwinStateFilter (which values), DigitalTwinStateChangeFilter (which changes trigger a callback), WldtEventFilter (event types of an Event Bus subscription) and the Filter of the storage queries.