Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

ClientEvent related updates and tests

Rich Turner10b8a9500bfa
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
index 8070e1537..40d11ef88 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
@@ -118,9 +118,9 @@ public class SimulatorProtocol extends AbstractProtocol {
protected static final String VERSION = "1.0";
- static final protected Map<AttributeRef, Instance> instances = new HashMap<>();
- static final protected Map<AttributeRef, AttributeRef> attributeInstanceMap = new HashMap<>();
- static final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();
+ final protected Map<AttributeRef, Instance> instances = new HashMap<>();
+ final protected Map<AttributeRef, AttributeRef> attributeInstanceMap = new HashMap<>();
+ final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();
protected static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Arrays.asList(
new MetaItemDescriptorImpl("PROTOCOL_SIMULATOR_MODE",
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 30d3964c9..834ebe396 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -297,8 +297,11 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Need to record time here otherwise an infinite loop generated inside one of the processors means the timestamp
// is not updated so tests can't then detect the problem.
lastProcessedEventTimestamp = System.currentTimeMillis();
+ int processorCount = 0;
processorLoop:
for (Consumer<AssetState> processor : processors) {
+ processorCount++;
+
try {
LOG.finest("==> Processor " + processor + " accepts: " + assetState);
processor.accept(assetState);
@@ -322,9 +325,16 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.ERROR) {
if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.COMPLETED)
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
- clientEventService.publishEvent(new AttributeEvent(
- assetState.getId(), assetState.getAttributeName(), assetState.getValue(), timerService.getCurrentTimeMillis()
- ));
+
+ // Only notify clients of events that reach the end of the chain
+ if (processorCount == processors.size()) {
+ clientEventService.publishEvent(new AttributeEvent(
+ assetState.getId(),
+ assetState.getAttributeName(),
+ assetState.getValue(),
+ timerService.getCurrentTimeMillis()
+ ));
+ }
}
LOG.fine("<<< Processing complete: " + assetState);
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 18d83194e..ff8f6649d 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -100,7 +100,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
clientEventService = container.getService(ClientEventService.class);
clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {
- if (!subscription.isEventType(AssetTreeModifiedEvent.class))
+ if (!subscription.isEventType(AssetTreeModifiedEvent.class) && !subscription.isEventType(LocationEvent.class))
return false;
return identityService.getIdentityProvider().canSubscribeWith(
auth,
@@ -1177,12 +1177,16 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Did the location change?
Point oldLocation = persistenceEvent.getPreviousState("location");
Point newLocation = persistenceEvent.getCurrentState("location");
- if ((oldLocation == null && newLocation != null) || oldLocation != newLocation || (oldLocation != null && oldLocation.equalsExact(newLocation, 0))) {
- clientEventService.publishEvent(
- new LocationEvent(asset.getId(), asset.getCoordinates(), timerService.getCurrentTimeMillis())
- );
- }
+ if (!(oldLocation == null && newLocation == null)) {
+ if (oldLocation == null || newLocation == null || !oldLocation.equalsExact(newLocation, 0)) {
+ clientEventService.publishEvent(
+ new LocationEvent(asset.getId(),
+ asset.getCoordinates(),
+ timerService.getCurrentTimeMillis())
+ );
+ }
+ }
break;
case DELETE:
clientEventService.publishEvent(
diff --git a/manager/src/main/java/org/openremote/manager/asset/ServerAsset.java b/manager/src/main/java/org/openremote/manager/asset/ServerAsset.java
index 8b8f772cd..3913a81a7 100644
--- a/manager/src/main/java/org/openremote/manager/asset/ServerAsset.java
+++ b/manager/src/main/java/org/openremote/manager/asset/ServerAsset.java
@@ -174,7 +174,7 @@ public class ServerAsset extends Asset {
public static void setCoordinates(Asset asset, Point location) {
if (location == null) {
- asset.setCoordinates();
+ asset.setCoordinates((double[]) null);
} else {
asset.setCoordinates(
location.getCoordinate().getOrdinate(Coordinate.X),
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index 9aff029a0..b9ddb1556 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -237,6 +237,10 @@ public class ClientEventService implements ContainerService {
return exchange.getIn().getHeader(WebsocketConstants.SESSION_KEY, String.class);
}
+ public EventSubscriptions getEventSubscriptions() {
+ return eventSubscriptions;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
index 051e13ada..d452e526d 100644
--- a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
+++ b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
@@ -45,10 +45,7 @@ public class EventSubscriptions {
class SessionSubscriptions extends HashSet<SessionSubscription> {
public void removeExpired() {
removeIf(sessionSubscription -> {
- boolean expired =
- sessionSubscription.timestamp
- + (EventSubscription.RENEWAL_PERIOD_SECONDS * 1000)
- < timerService.getCurrentTimeMillis();
+ boolean expired = sessionSubscription.isExpired();
if (expired) {
LOG.fine("Removing expired; " + sessionSubscription.subscription);
}
@@ -79,6 +76,14 @@ public class EventSubscriptions {
public boolean matches(SharedEvent event) {
return subscription.getEventType().equals(event.getEventType());
}
+
+ /**
+ * Subscriptions with internal consumer never expire
+ */
+ public boolean isExpired() {
+ return subscription.getInternalConsumer() == null
+ && timestamp + (EventSubscription.RENEWAL_PERIOD_SECONDS * 1000) < timerService.getCurrentTimeMillis();
+ }
}
public EventSubscriptions(TimerService timerService, ManagerExecutorService executorService) {
@@ -145,11 +150,15 @@ public class EventSubscriptions {
if (sessionSubscription.subscription.getFilter() == null
|| sessionSubscription.subscription.getFilter().apply(event)) {
LOG.fine("Creating message for subscribed session '" + sessionKey + "': " + event);
- Message msg = new DefaultMessage();
- msg.setBody(event); // Don't copy the event, use same reference
- msg.setHeaders(new HashMap<>(exchange.getIn().getHeaders())); // Copy headers
- msg.setHeader(WebsocketConstants.SESSION_KEY, sessionKey);
- messageList.add(msg);
+ if (sessionSubscription.subscription.getInternalConsumer() == null) {
+ Message msg = new DefaultMessage();
+ msg.setBody(event); // Don't copy the event, use same reference
+ msg.setHeaders(new HashMap<>(exchange.getIn().getHeaders())); // Copy headers
+ msg.setHeader(WebsocketConstants.SESSION_KEY, sessionKey);
+ messageList.add(msg);
+ } else {
+ sessionSubscription.subscription.getInternalConsumer().accept(event);
+ }
}
}
}
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index 18b26a0a6..712f138dc 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -24,11 +24,11 @@ import org.openremote.agent.protocol.simulator.SimulatorProtocol;
import org.openremote.container.Container;
import org.openremote.manager.asset.ServerAsset;
import org.openremote.manager.setup.AbstractManagerSetup;
-import org.openremote.model.security.Tenant;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetState;
import org.openremote.model.asset.UserAsset;
import org.openremote.model.attribute.*;
+import org.openremote.model.security.Tenant;
import org.openremote.model.simulator.element.ColorSimulatorElement;
import org.openremote.model.simulator.element.NumberSimulatorElement;
import org.openremote.model.simulator.element.SwitchSimulatorElement;
@@ -69,6 +69,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
public String agentId;
public final String agentProtocolConfigName = "simulator123";
public String thingId;
+ public final String thingLightToggleAttributeName = "light1Toggle";
public String smartHomeId;
public String apartment1Id;
public String apartment1ServiceAgentId;
@@ -162,7 +163,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
ServerAsset thing = new ServerAsset("Demo Thing", THING, agent);
thing.setLocation(agent.getLocation());
thing.setAttributes(
- new AssetAttribute("light1Toggle", BOOLEAN, Values.create(true))
+ new AssetAttribute(thingLightToggleAttributeName, BOOLEAN, Values.create(true))
.setMeta(new Meta(
new MetaItem(
LABEL,
diff --git a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java
index 9ade995c2..87e3aafa8 100644
--- a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java
+++ b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java
@@ -21,6 +21,8 @@ package org.openremote.model.event.shared;
import org.openremote.model.event.Event;
+import java.util.function.Consumer;
+
/**
* A client can subscribe to {@link SharedEvent}s on the server, providing the
* type of event it wants to receive as well as filter criteria to restrict the
@@ -36,6 +38,10 @@ public class EventSubscription<E extends SharedEvent> {
protected String eventType;
protected EventFilter<E> filter;
+ /**
+ * Optional only set when an internal subscription is made
+ */
+ protected Consumer<E> internalConsumer;
protected EventSubscription() {
}
@@ -57,6 +63,12 @@ public class EventSubscription<E extends SharedEvent> {
this.filter = filter;
}
+ public EventSubscription(Class<E> eventClass, EventFilter<E> filter, Consumer<E> internalConsumer) {
+ this.eventType = Event.getEventType(eventClass);
+ this.filter = filter;
+ this.internalConsumer = internalConsumer;
+ }
+
public String getEventType() {
return eventType;
}
@@ -77,6 +89,10 @@ public class EventSubscription<E extends SharedEvent> {
return Event.getEventType(eventClass).equals(getEventType());
}
+ public Consumer<E> getInternalConsumer() {
+ return internalConsumer;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index ae568cfd3..1841c3565 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.openremote.model.asset.AssetTreeModifiedEvent;
+import org.openremote.model.asset.LocationEvent;
import org.openremote.model.asset.ReadAssetAttributesEvent;
import org.openremote.model.asset.agent.AgentStatusEvent;
import org.openremote.model.attribute.AttributeEvent;
@@ -44,7 +45,8 @@ import org.openremote.model.syslog.SyslogEvent;
@JsonSubTypes.Type(value = SimulatorState.class, name = "simulator-state"),
@JsonSubTypes.Type(value = RequestSimulatorState.class, name = "request-simulator-state"),
@JsonSubTypes.Type(value = AgentStatusEvent.class, name = "agent-status"),
- @JsonSubTypes.Type(value = RulesetStatusEvent.class, name = "rules-engine-status")
+ @JsonSubTypes.Type(value = RulesetStatusEvent.class, name = "rules-engine-status"),
+ @JsonSubTypes.Type(value = LocationEvent.class, name = "location")
})
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
new file mode 100644
index 000000000..dab30536f
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
@@ -0,0 +1,242 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.test.event
+
+import com.vividsolutions.jts.geom.Coordinate
+import com.vividsolutions.jts.geom.GeometryFactory
+import org.openremote.agent.protocol.simulator.SimulatorProtocol
+import org.openremote.manager.agent.AgentService
+import org.openremote.manager.asset.AssetProcessingService
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.setup.SetupService
+import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.asset.AssetMeta
+import org.openremote.model.asset.LocationEvent
+import org.openremote.model.asset.agent.AgentStatusEvent
+import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.attribute.MetaItem
+import org.openremote.model.event.shared.EventSubscription
+import org.openremote.model.event.shared.SharedEvent
+import org.openremote.model.value.Values
+import org.openremote.test.ClientEventService
+import org.openremote.test.GwtClientTrait
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import static org.openremote.container.util.MapAccess.getBoolean
+import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.manager.event.ClientEventService.WEBSOCKET_EVENTS
+import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
+import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
+import static org.openremote.model.Constants.*
+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo
+
+/**
+ * This tests client event subscription and publishing.
+ */
+// TODO: Add publishing tests
+class ClientEventTest extends Specification implements ManagerContainerTrait, GwtClientTrait {
+
+ def "Event subscription"() {
+
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
+
+ when: "the container is started"
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def agentService = container.getService(AgentService.class)
+ def internalClientEventService = container.getService(org.openremote.manager.event.ClientEventService.class)
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def simulatorProtocol = container.getService(SimulatorProtocol.class)
+
+ then: "the system should settle down"
+ conditions.eventually {
+ assert noEventProcessedIn(assetProcessingService, 500)
+ assert simulatorProtocol.elements.size() == 10
+ }
+
+ when: "a client websocket connection and attached event bus and service"
+ def accessToken = {
+ authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
+ ).token
+ }
+ List<SharedEvent> collectedSharedEvents = []
+ def eventBus = createEventBus(collectedSharedEvents)
+ def clientEventService = new ClientEventService(eventBus, container.JSON)
+ def websocketSession = connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, MASTER_REALM, accessToken.call())
+
+ and: "a subscription is made to the agent status event"
+ clientEventService.subscribe(AgentStatusEvent.class)
+
+ and: "an existing protocol configuration is disabled"
+ def agent = assetStorageService.find(managerDemoSetup.agentId, true)
+ agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().addMeta(
+ new MetaItem(AssetMeta.DISABLED)
+ )
+ agent = assetStorageService.merge(agent)
+
+ then: "the agent status change event should have been received"
+ conditions.eventually {
+ assert collectedSharedEvents.size() == 3
+ assert collectedSharedEvents[0] instanceof AgentStatusEvent
+ assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId
+ assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName
+ assert (collectedSharedEvents[0] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISCONNECTED
+ assert collectedSharedEvents[1] instanceof AgentStatusEvent
+ assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId
+ assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName
+ assert (collectedSharedEvents[1] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
+ assert collectedSharedEvents[2] instanceof AgentStatusEvent
+ assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId
+ assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName
+ assert (collectedSharedEvents[2] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISABLED
+ }
+
+ when: "the subscription is removed"
+ clientEventService.unsubscribe(AgentStatusEvent.class)
+ collectedSharedEvents.clear()
+
+ and: "the existing protocol configuration is re-enabled"
+ agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().getMeta().removeIf(
+ isMetaNameEqualTo(AssetMeta.DISABLED)
+ );
+ agent = assetStorageService.merge(agent)
+
+ then: "the protocol should be CONNECTED but no new events should have been received"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(
+ new AttributeRef(managerDemoSetup.agentId, managerDemoSetup.agentProtocolConfigName)
+ ) == ConnectionStatus.CONNECTED
+ assert collectedSharedEvents.isEmpty()
+ }
+
+ when: "a subscription is made to the location event"
+ clientEventService.subscribe(LocationEvent.class)
+
+ and: "an assets location is changed"
+ def asset = assetStorageService.find(managerDemoSetup.thingId, true)
+ asset.setLocation(new GeometryFactory().createPoint(new Coordinate(120.1d, 50.43d)))
+ asset = assetStorageService.merge(asset)
+
+ then: "the location event should have been received"
+ conditions.eventually {
+ assert collectedSharedEvents.size() == 1
+ assert collectedSharedEvents[0] instanceof LocationEvent
+ assert (collectedSharedEvents[0] as LocationEvent).assetId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[0] as LocationEvent).coordinates[0] == 120.1d
+ assert (collectedSharedEvents[0] as LocationEvent).coordinates[1] == 50.43d
+ }
+
+ when: "the assets location is set to null"
+ asset.setLocation(null)
+ asset = assetStorageService.merge(asset)
+
+ then: "the location event should have been received with null coordinates"
+ conditions.eventually {
+ assert collectedSharedEvents.size() == 2
+ assert collectedSharedEvents[1] instanceof LocationEvent
+ assert (collectedSharedEvents[1] as LocationEvent).assetId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[1] as LocationEvent).coordinates == null
+ }
+
+ when: "the location is changed"
+ asset.setLocation(new GeometryFactory().createPoint(new Coordinate(-10.11d, -50.233d)))
+ asset = assetStorageService.merge(asset)
+
+ then: "the location event should have been received"
+ conditions.eventually {
+ assert collectedSharedEvents.size() == 3
+ assert collectedSharedEvents[2] instanceof LocationEvent
+ assert (collectedSharedEvents[2] as LocationEvent).assetId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[2] as LocationEvent).coordinates[0] == -10.11d
+ assert (collectedSharedEvents[2] as LocationEvent).coordinates[1] == -50.233d
+ }
+
+ when: "the location is set with the same value"
+ asset.setLocation(new GeometryFactory().createPoint(new Coordinate(-10.11d, -50.233d)))
+ asset = assetStorageService.merge(asset)
+
+ then: "no location event should have been received"
+ Thread.sleep(300)
+ assert collectedSharedEvents.size() == 3
+
+ when: "the subscription is removed"
+ clientEventService.unsubscribe(LocationEvent.class)
+ collectedSharedEvents.clear()
+
+ and: "a new attribute event subscription is added"
+ clientEventService.subscribe(AttributeEvent.class, new AttributeEvent.EntityIdFilter(managerDemoSetup.thingId))
+
+ and: "an internal attribute event subscription is made"
+ List<AttributeEvent> internalReceivedEvents = []
+ internalClientEventService.getEventSubscriptions().update(
+ ClientEventTest.class.getName(),
+ new EventSubscription<>(
+ AttributeEvent.class,
+ new AttributeEvent.EntityIdFilter(managerDemoSetup.thingId),
+ {attributeEvent ->
+ internalReceivedEvents.add(attributeEvent as AttributeEvent)
+ }
+ ))
+
+ and: "the subscribed asset is modified"
+ def currentValue = asset.getAttribute(managerDemoSetup.thingLightToggleAttributeName).get().getValueAsBoolean().orElse(false)
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(
+ managerDemoSetup.thingId,
+ managerDemoSetup.thingLightToggleAttributeName,
+ Values.create(!currentValue)))
+
+ // TODO: Only 1 attribute event should reach the subscribers below
+ then: "an attribute event should have been received by the internal subscriber"
+ conditions.eventually {
+ assert internalReceivedEvents.size() == 1
+ assert internalReceivedEvents[0].entityId == managerDemoSetup.thingId
+ assert internalReceivedEvents[0].attributeName == managerDemoSetup.thingLightToggleAttributeName
+ assert internalReceivedEvents[0].value.isPresent()
+ assert internalReceivedEvents[0].value.flatMap({v -> Values.getBoolean(v)}).get() == !currentValue
+ }
+
+ and: "an attribute event should have been received by the external subscriber"
+ conditions.eventually {
+ assert collectedSharedEvents.size() == 1
+ assert collectedSharedEvents[0] instanceof AttributeEvent
+ assert (collectedSharedEvents[0] as AttributeEvent).entityId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[0] as AttributeEvent).attributeName == managerDemoSetup.thingLightToggleAttributeName
+ assert (collectedSharedEvents[0] as AttributeEvent).attributeState.currentValue.flatMap({v -> Values.getBoolean(v)}).get() == !currentValue
+ }
+
+ cleanup: "the client should be stopped"
+ if (clientEventService != null) clientEventService.close()
+
+ and: "the server should be stopped"
+ stopContainer(container)
+ }
+}
\ No newline at end of file
diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
index 8dbd1f159..3c7dca715 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -23,33 +23,23 @@ import org.openremote.agent.protocol.AbstractProtocol
import org.openremote.agent.protocol.Protocol
import org.openremote.agent.protocol.filter.RegexFilter
import org.openremote.agent.protocol.filter.SubStringFilter
-import org.openremote.model.asset.agent.AgentStatusEvent
-import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.asset.ServerAsset
-import org.openremote.model.Constants
import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
+import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.model.asset.agent.ProtocolConfiguration
import org.openremote.model.attribute.*
-import org.openremote.model.event.shared.SharedEvent
import org.openremote.model.value.Values
-import org.openremote.test.ClientEventService
import org.openremote.test.GwtClientTrait
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.container.util.MapAccess.getString
-import static org.openremote.manager.event.ClientEventService.WEBSOCKET_EVENTS
-import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
-import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM
-import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
/**
* This tests the basic protocol interface and abstract protocol implementation.
@@ -106,7 +96,8 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
@Override
protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
protocolMethodCalls.add("UNLINK_PROTOCOL")
- protocolLinkedConfigurations.removeAll { it.getReferenceOrThrow().equals(protocolConfiguration.getReferenceOrThrow()) }
+ protocolLinkedConfigurations.removeAll { (it.getReferenceOrThrow() == protocolConfiguration.getReferenceOrThrow())
+ }
}
@Override
@@ -128,7 +119,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(true)))
} else if (attributeName.startsWith("tempTarget")) {
// Set target temps to 25.5
- updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(25.5)))
+ updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(25.5d)))
}
}
}
@@ -137,14 +128,14 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
protocolMethodCalls.add("UNLINK_ATTRIBUTE")
(protocolLinkedAttributes[protocolConfiguration.getName().orElse("")])
- .removeAll { it.getReferenceOrThrow().equals(attribute.getReferenceOrThrow()) }
+ .removeAll { (it.getReferenceOrThrow() == attribute.getReferenceOrThrow())}
}
@Override
protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {
protocolMethodCalls.add("ATTRIBUTE_WRITE")
if (!(protocolLinkedAttributes[protocolConfiguration.getName().orElse("")])
- .any {it.getReferenceOrThrow().equals(event.attributeRef)}) {
+ .any {(it.getReferenceOrThrow() == event.attributeRef)}) {
throw new IllegalStateException("Attribute is not linked")
}
protocolWriteAttributeEvents.add(event)
@@ -173,25 +164,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
def agentService = container.getService(AgentService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
- when: "a client websocket connection and attached event bus and service"
- def accessToken = {
- authenticate(
- container,
- MASTER_REALM,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
- ).token
- }
- List<SharedEvent> collectedSharedEvents = []
- def eventBus = createEventBus(collectedSharedEvents)
- def clientEventService = new ClientEventService(eventBus, container.JSON)
- def websocketSession = connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, MASTER_REALM, accessToken.call())
-
- and: "a subscription is made to the agent status event"
- clientEventService.subscribe(AgentStatusEvent.class)
-
- and: "a mock agent that uses the mock protocol is created with several protocol configurations"
+ when: "a mock agent that uses the mock protocol is created with several protocol configurations"
def mockAgent = new ServerAsset()
mockAgent.setName("Mock Agent")
mockAgent.setType(AssetType.AGENT)
@@ -211,16 +184,16 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
new MetaItem(AssetMeta.DISABLED, Values.create(true))
)
)
- mockAgent.setRealmId(Constants.MASTER_REALM)
+ mockAgent.setRealmId(MASTER_REALM)
mockAgent = assetStorageService.merge(mockAgent)
then: "the protocol configurations should be linked and their deployment status should be available in the agent service"
conditions.eventually {
assert protocolLinkedConfigurations.size() == 4
- def config1 = protocolLinkedConfigurations.find { it.getName().orElse("").equals("mockConfig1") }
- def config2 = protocolLinkedConfigurations.find { it.getName().orElse("").equals("mockConfig2") }
- def config3 = protocolLinkedConfigurations.find { it.getName().orElse("").equals("mockConfig3") }
- def config4 = protocolLinkedConfigurations.find { it.getName().orElse("").equals("mockConfig4") }
+ def config1 = protocolLinkedConfigurations.find { (it.getName().orElse("") == "mockConfig1")}
+ def config2 = protocolLinkedConfigurations.find { (it.getName().orElse("") == "mockConfig2")}
+ def config3 = protocolLinkedConfigurations.find { (it.getName().orElse("") == "mockConfig3")}
+ def config4 = protocolLinkedConfigurations.find { (it.getName().orElse("") == "mockConfig4")}
assert config1 != null
assert config2 != null
assert config3 != null
@@ -229,32 +202,6 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
assert agentService.getProtocolConnectionStatus(config2.getReferenceOrThrow()) == ConnectionStatus.ERROR
assert agentService.getProtocolConnectionStatus(config3.getReferenceOrThrow()) == ConnectionStatus.ERROR
assert agentService.getProtocolConnectionStatus(config4.getReferenceOrThrow()) == ConnectionStatus.DISABLED
- assert !collectedSharedEvents.isEmpty()
- assert collectedSharedEvents[0] instanceof AgentStatusEvent
- assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig1"
- assert (collectedSharedEvents[0] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
- assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig1"
- assert (collectedSharedEvents[1] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTED
- assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig2"
- assert (collectedSharedEvents[2] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
- assert (collectedSharedEvents[3] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[3] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig2"
- assert (collectedSharedEvents[3] as AgentStatusEvent).connectionStatus == ConnectionStatus.ERROR
- assert (collectedSharedEvents[4] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[4] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig3"
- assert (collectedSharedEvents[4] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
- assert (collectedSharedEvents[5] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[5] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig3"
- assert (collectedSharedEvents[5] as AgentStatusEvent).connectionStatus == ConnectionStatus.ERROR
- assert (collectedSharedEvents[6] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[6] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig4"
- assert (collectedSharedEvents[6] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
- assert (collectedSharedEvents[7] as AgentStatusEvent).protocolConfiguration.entityId == mockAgent.id
- assert (collectedSharedEvents[7] as AgentStatusEvent).protocolConfiguration.attributeName == "mockConfig4"
- assert (collectedSharedEvents[7] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISABLED
}
when: "a mock thing asset is created that links to the mock protocol configurations"
@@ -558,10 +505,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
assert !mockThing.getAttribute("filterRegexSubstring").get().getValueAsNumber().isPresent()
}
- cleanup: "the client should be stopped"
- if (clientEventService != null) clientEventService.close()
-
- and: "the server should be stopped"
+ cleanup: "the server should be stopped"
stopContainer(container)
}
}
\ No newline at end of file