Skip to content

armgit / core

Public Imported from GitHub
0

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

Added attribute state change consumer and router and skeleton RulesService

Rich Turner7e6da59d2a5c
diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.java
index 2cae8fde0..6ce4e86fd 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java
@@ -27,10 +27,12 @@ import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.manager.server.agent.AgentService;
import org.openremote.manager.server.asset.AssetService;
+import org.openremote.manager.server.attribute.AttributeStateRouterService;
import org.openremote.manager.server.asset.datapoint.DatapointService;
import org.openremote.manager.server.event.EventService;
import org.openremote.manager.server.i18n.I18NService;
import org.openremote.manager.server.map.MapService;
+import org.openremote.manager.server.rules.RulesService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.setup.SetupService;
import org.openremote.manager.server.web.ManagerWebService;
@@ -54,7 +56,9 @@ public class Main {
new EventService(),
new AssetService(),
new DatapointService(),
- new AgentService()
+ new AgentService(),
+ new RulesService(),
+ new AttributeStateRouterService()
));
ServiceLoader.load(Protocol.class).forEach(this::add);
addAll(Arrays.asList(
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index 8e8d19181..67935e5bd 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -94,26 +94,6 @@ public class AgentService extends RouteBuilder implements ContainerService {
deployThing(asset, persistenceEvent.getCause());
}
});
-
- // Update thing asset when attribute change value messages are published on the sensor topic
- from(SENSOR_TOPIC)
- .filter(body().isInstanceOf(AttributeState.class))
- .process(exchange -> {
- AttributeState attributeState =
- exchange.getIn().getBody(AttributeState.class);
- // Note that this is a _direct_ update of the attribute value in the database, it will
- // not trigger a persistence event - we don't want to redeploy a thing just because an
- // attribute value changed!
- boolean success = assetService.updateThingAttributeValue(attributeState);
- // TODO If success then... notify asset listener clients? If not, then handle error?
- if (success) {
- LOG.fine("Asset database update successful: " + attributeState);
- datapointService.storeAssetDatapoint(attributeState);
- } else {
- throw new RuntimeException("Asset database update failed for: " + attributeState);
- }
-
- });
}
protected void deployAgent(Asset agent, PersistenceEvent.Cause cause) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
index 66c289e1f..5fd5c59c0 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
@@ -29,13 +29,14 @@ import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.web.WebService;
import org.openremote.manager.server.agent.AgentAttributes;
-import org.openremote.manager.server.agent.ThingAttributes;
+import org.openremote.manager.server.attribute.AttributeStateChange;
+import org.openremote.manager.server.attribute.AttributeStateConsumerResult;
+import org.openremote.manager.server.attribute.AttributeStateChangeConsumer;
import org.openremote.manager.server.event.EventService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.asset.SubscribeAssetModified;
import org.openremote.manager.shared.asset.UnsubscribeAssetModified;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeState;
import org.openremote.model.Function;
import org.openremote.model.asset.*;
import org.postgresql.util.PGobject;
@@ -55,7 +56,7 @@ import static org.openremote.manager.server.event.EventPredicates.isEventType;
import static org.openremote.model.asset.AssetType.AGENT;
import static org.openremote.model.asset.AssetType.THING;
-public class AssetService extends RouteBuilder implements ContainerService {
+public class AssetService extends RouteBuilder implements ContainerService, AttributeStateChangeConsumer {
private static final Logger LOG = Logger.getLogger(AssetService.class.getName());
@@ -362,36 +363,24 @@ public class AssetService extends RouteBuilder implements ContainerService {
});
}
- public boolean updateThingAttributeValue(AttributeState attributeState) {
+ @Override
+ public AttributeStateConsumerResult consumeAttributeStateChange(AttributeStateChange attributeStateChange) {
// TODO: More fine-grained return to distinguish failures ("wrong value type" is not the same as "not found")
- AttributeRef attributeRef = attributeState.getAttributeRef();
- ServerAsset thing = find(attributeRef.getEntityId());
- if (thing == null) {
- LOG.fine("Ignoring attribute update for unknown asset: " + attributeState);
- return false;
- }
+ ServerAsset thing = (ServerAsset)attributeStateChange.getAttributeParent();
+
+ // TODO: Not sure why asset service is handling things as they're children of agent so should be handled by agent service
if (thing.getWellKnownType() != THING) {
- LOG.fine("Ignoring attribute update '" + attributeState + "' for non-thing asset: " + thing);
- return false;
- }
- ThingAttributes thingAttributes = new ThingAttributes(thing);
- ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(
- agentLinkResolver, attributeRef.getAttributeName()
- );
- if (thingAttribute == null) {
- LOG.fine("Ignoring attribute update '" + attributeState + "' for unknown/unlinked attribute: " + thing);
- return false;
+ LOG.fine("Ignoring attribute update '" + attributeStateChange + "' for non-thing asset: " + thing);
+ return AttributeStateConsumerResult.UNEXPECTED_ASSET_TYPE;
}
- if (thingAttribute.getType().getJsonType() != attributeState.getValue().getType()) {
- LOG.fine("Ignoring attribute update '" + attributeState + "', wrong value type '" + attributeState.getValue().getType() + "': " + thing);
- return false;
- }
- LOG.fine("Applying '" + attributeState + "' on: " + thing);
- thingAttribute.setValue(attributeState.getValue());
+ ThingAttribute thingAttribute = (ThingAttribute)attributeStateChange.getAttribute();
+ LOG.fine("Applying '" + attributeStateChange + "' on: " + thing);
+ thingAttribute.setValue(attributeStateChange.getNewValue());
- return updateAttributeValue(thing.getId(), thingAttribute.getName(), thingAttribute.getValue_TODO_BUG_IN_JAVASCRIPT());
+ boolean success = updateAttributeValue(thing.getId(), thingAttribute.getName(), thingAttribute.getValue_TODO_BUG_IN_JAVASCRIPT());
+ return success ? AttributeStateConsumerResult.OK : AttributeStateConsumerResult.UNKOWN_ERROR;
}
protected ServerAsset loadAsset(EntityManager em, String assetId) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
index 86496cee4..e0dcdcb54 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
@@ -3,7 +3,10 @@ package org.openremote.manager.server.asset.datapoint;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.model.AttributeState;
+import org.openremote.manager.server.asset.ServerAsset;
+import org.openremote.manager.server.attribute.AttributeStateChange;
+import org.openremote.manager.server.attribute.AttributeStateConsumerResult;
+import org.openremote.manager.server.attribute.AttributeStateChangeConsumer;
import org.openremote.model.datapoint.AssetDatapoint;
import java.util.logging.Logger;
@@ -11,7 +14,7 @@ import java.util.logging.Logger;
/**
* Store and retrieve datapoints.
*/
-public class DatapointService implements ContainerService {
+public class DatapointService implements ContainerService, AttributeStateChangeConsumer {
private static final Logger LOG = Logger.getLogger(DatapointService.class.getName());
@@ -30,10 +33,11 @@ public class DatapointService implements ContainerService {
public void stop(Container container) throws Exception {
}
- public void storeAssetDatapoint(AttributeState attributeState) {
- AssetDatapoint assetDatapoint = new AssetDatapoint(attributeState);
+ @Override
+ public AttributeStateConsumerResult consumeAttributeStateChange(AttributeStateChange attributeStateChange) {
+ ServerAsset asset = (ServerAsset)attributeStateChange.getAttributeParent();
+ AssetDatapoint assetDatapoint = new AssetDatapoint(asset.getId(), attributeStateChange.getAttribute().getName(), attributeStateChange.getNewValue());
// TODO
-
+ return AttributeStateConsumerResult.OK;
}
-
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java
new file mode 100644
index 000000000..9d685206d
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java
@@ -0,0 +1,97 @@
+/*
+ * 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.manager.server.attribute;
+
+import elemental.json.JsonValue;
+import org.openremote.model.Attribute;
+
+public class AttributeStateChange {
+ protected Object attributeParent;
+ protected Attribute attribute;
+ protected JsonValue oldValue;
+ protected JsonValue newValue;
+ protected boolean rewind;
+ protected boolean handled;
+ protected boolean error;
+
+ public AttributeStateChange(Object attributeParent, Attribute attribute, JsonValue oldValue, JsonValue newValue) {
+ this.attributeParent = attributeParent;
+ this.attribute = attribute;
+ this.oldValue = oldValue;
+ this.newValue = newValue;
+ }
+
+ void setRewind() {
+ rewind = true;
+ JsonValue oldValue = this.oldValue;
+ this.oldValue = newValue;
+ this.newValue = oldValue;
+ }
+
+ public Object getAttributeParent() {
+ return attributeParent;
+ }
+
+ public JsonValue getOldValue() {
+ return oldValue;
+ }
+
+ public JsonValue getNewValue() {
+ return newValue;
+ }
+
+ public boolean isRewind() {
+ return rewind;
+ }
+
+ public Attribute getAttribute() {
+ return attribute;
+ }
+
+ public boolean isHandled() {
+ return handled;
+ }
+
+ public boolean isError() {
+ return error;
+ }
+
+ /**
+ * Update the value of the
+ * @param newValue
+ */
+ public void updateNewValue(JsonValue newValue) {
+ if (attribute.getType().getJsonType() != newValue.getType()) {
+ error = true;
+ throw new RuntimeException("Update Attribute state change value failed as new value type '" + newValue.getType() + "' doesn't match attribute type '" + attribute.getType().getJsonType() + "'");
+ }
+
+ this.newValue = newValue;
+ }
+
+ /**
+ * Marks the state change as consumed so the state change won't be passed to any
+ * more consumers in the chain
+ * @param handled
+ */
+ public void setHandled(boolean handled) {
+ this.handled = handled;
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChangeConsumer.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChangeConsumer.java
new file mode 100644
index 000000000..f07568f7d
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChangeConsumer.java
@@ -0,0 +1,29 @@
+/*
+ * 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.manager.server.attribute;
+
+/**
+ * An attribute state change consumer can consume state change messages and even possibly modify the
+ * state change message (mark it as handled to prevent further processing by other consumers or change
+ * the value of the state change)
+ */
+public interface AttributeStateChangeConsumer {
+ AttributeStateConsumerResult consumeAttributeStateChange(AttributeStateChange attributeStateChange);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateConsumerResult.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateConsumerResult.java
new file mode 100644
index 000000000..f520d881c
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateConsumerResult.java
@@ -0,0 +1,28 @@
+/*
+ * 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.manager.server.attribute;
+
+// TODO: create more granular results and react to them accordingly
+public enum AttributeStateConsumerResult {
+ OK, // Consumer is happy for attribute state to continue through the system
+ UNEXPECTED_ASSET_TYPE, // The asset type referred to by the state change was not expected by the consumer
+ INVALID_VALUE, // The attribute value provided is not valid
+ UNKOWN_ERROR, // An unknown error has occurred
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java
new file mode 100644
index 000000000..c786f2d89
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java
@@ -0,0 +1,134 @@
+/*
+ * 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.manager.server.attribute;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.openremote.container.Container;
+import org.openremote.container.ContainerService;
+import org.openremote.container.message.MessageBrokerSetupService;
+import org.openremote.manager.server.agent.ThingAttributes;
+import org.openremote.manager.server.asset.AssetService;
+import org.openremote.manager.server.asset.ServerAsset;
+import org.openremote.manager.server.asset.datapoint.DatapointService;
+import org.openremote.manager.server.rules.RulesService;
+import org.openremote.model.AttributeState;
+import org.openremote.model.asset.ThingAttribute;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+
+import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;
+
+/**
+ * This class is responsible for configuring the routing of attribute state messages.
+ *
+ * Long term maybe AttributeStateChangeConsumers should be camel components and then use camel routes for processing chain
+ */
+public class AttributeStateRouterService extends RouteBuilder implements ContainerService {
+ private static final Logger LOG = Logger.getLogger(AttributeStateRouterService.class.getName());
+ protected RulesService rulesService;
+ protected AssetService assetService;
+ protected DatapointService datapointService;
+ protected List<AttributeStateChangeConsumer> consumers = new ArrayList<>();
+
+ @Override
+ public void init(Container container) throws Exception {
+ rulesService = container.getService(RulesService.class);
+ assetService = container.getService(AssetService.class);
+ datapointService = container.getService(DatapointService.class);
+ consumers.add(rulesService);
+ consumers.add(assetService);
+ consumers.add(datapointService);
+
+ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void configure() throws Exception {
+
+ // Protocols send Attribute State messages on the Sensor Topic so convert it to an AttributeStateChange
+ // object and pass it through to the required consumers sequentially with each returning a state consumer result
+ from(SENSOR_TOPIC)
+ .filter(body().isInstanceOf(AttributeState.class))
+ .process(exchange -> {
+ AttributeState attributeState =
+ exchange.getIn().getBody(AttributeState.class);
+
+ // From sensor topic means this is a thing asset so we can get the thing
+ ServerAsset thing = assetService.find(attributeState.getAttributeRef().getEntityId());
+
+ // Get the attribute
+ ThingAttributes thingAttributes = new ThingAttributes(thing);
+ ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(
+ assetService.getAgentLinkResolver(), attributeState.getAttributeRef().getAttributeName()
+ );
+
+ if (thingAttribute == null) {
+ LOG.fine("Ignoring attribute state change '" + attributeState + "' for unknown/unlinked attribute: " + thing);
+ return;
+ }
+
+ // Validate the value type against the attribute type
+ if (thingAttribute.getType().getJsonType() != attributeState.getValue().getType()) {
+ LOG.fine("Ignoring attribute state change '" + attributeState + "', wrong value type '" + attributeState.getValue().getType() + "': " + thing);
+ return;
+ }
+
+ AttributeStateChange stateChange = new AttributeStateChange(
+ thing,
+ thingAttribute,
+ thingAttribute.getValue_TODO_BUG_IN_JAVASCRIPT(),
+ attributeState.getValue());
+
+ for (int i=0; i<consumers.size(); i++) {
+ AttributeStateConsumerResult result = consumers.get(i).consumeAttributeStateChange(stateChange);
+ if(result == null) {
+ // Assume ok if no result returned
+ result = AttributeStateConsumerResult.OK;
+ }
+ switch (result) {
+ case OK:
+ // Check handled status of change
+ if (stateChange.isHandled()) {
+ // Don't pass this change to any more consumers
+ LOG.finest("Attribute state change consumer returned abort result so not passing state change onto any more consumers");
+ return;
+ }
+ break;
+ default:
+ // TODO: maybe rewind the state change and run through processed consumers in reverse order?
+ LOG.info("Attribute state change consumer returned ERROR result so abandoning further processing of state change");
+ throw new RuntimeException("Attribute state change consumer return ERROR result");
+ }
+ }
+ });
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java
new file mode 100644
index 000000000..010ad0819
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java
@@ -0,0 +1,137 @@
+package org.openremote.manager.server.rules;
+
+import org.kie.api.definition.rule.Rule;
+import org.kie.api.event.rule.BeforeMatchFiredEvent;
+import org.kie.api.event.rule.DefaultAgendaEventListener;
+import org.kie.api.runtime.rule.Match;
+import org.openremote.agent.sensor.Sensor;
+import org.openremote.agent.sensor.SensorState;
+
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * This class logs Drools rule execution. It is intended to assist the user in debugging Drools behavior.
+ */
+public class RuleExecutionLogger extends DefaultAgendaEventListener {
+
+ private static final Logger LOG = Logger.getLogger(RuleExecutionLogger.class.getName());
+
+ public static Logger getLOG() {
+ return LOG;
+ }
+
+ @Override
+ public void beforeMatchFired(BeforeMatchFiredEvent event) {
+ final Rule rule = event.getMatch().getRule();
+ String ruleName = rule.getName();
+
+ String rulePackage = rule.getPackageName();
+ ruleName = "\"" + ruleName + "\" // (package " + rulePackage + ")";
+
+ Match matchEvent = event.getMatch();
+ List<String> declarationIDs = matchEvent.getDeclarationIds();
+ List<Object> antecedents = matchEvent.getObjects();
+
+ String declarationLog = "";
+ for (String declarationID : declarationIDs) {
+ Object declarationValue = matchEvent.getDeclarationValue(declarationID);
+ String declarationValueString = this.declarationValueToString(declarationValue);
+ if (declarationValue instanceof Sensor || declarationValue instanceof SensorState) {
+ declarationLog = String.format("%s\t\tDeclaration: \"%s\"\n\t\tValue:\n\t\t\t%s\n", declarationLog, declarationID, declarationValueString);
+ } else {
+ declarationLog = String.format("%s\t\tDeclaration: \"%s: %s\"\n", declarationLog, declarationID, declarationValueString);
+ }
+ }
+
+ String objectLog = "";
+ for (Object antecedent : antecedents) {
+ String theClass = antecedent.getClass().getSimpleName();
+ String theValue = this.antecedentValueToString(antecedent);
+ objectLog = String.format("%s\t\tClass: \"%s\"\n\t\tFields: \n\t\t\t%s\n", objectLog, theClass, theValue);
+ }
+
+ if (ruleName.startsWith("\"--")) {
+ LOG.finest(String.format("rule %s\n" +
+ "\tDeclarations \n%s" +
+ "\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));
+ return;
+ }
+
+ if (ruleName.startsWith("\"-")) {
+ LOG.fine(String.format("rule %s\n" +
+ "\tDeclarations \n%s" +
+ "\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));
+ return;
+ }
+
+ LOG.info(String.format("rule %s\n" +
+ "\tDeclarations \n%s" +
+ "\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));
+ }
+
+ /**
+ * This method converts a declarationValue into a string.
+ * The need for this method would be obviated if all our facts descended from
+ * a Fact class with a method to return the most salient value of a fact.
+ *
+ * @param antecedent - An object referenced by a drools LHS
+ */
+ private String antecedentValueToString(Object antecedent) {
+ String theValue = null;
+ if (antecedent != null) {
+ theValue = antecedent.toString();
+ }
+
+ if (antecedent instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
+ {
+ Sensor theSensor = (Sensor) antecedent;
+ String sensorName = theSensor.getSensorDefinition().getName();
+ theValue = String.format("Sensor: %s\n", sensorName);
+
+ theValue = String.format("%s\t\tSensor Properties\n", theValue);
+ Map<String, String> sensorValues = theSensor.getSensorDefinition().getProperties();
+
+ for (Map.Entry<String, String> entry : sensorValues.entrySet()) {
+ String entryName = entry.getKey();
+ String entryValue = entry.getValue();
+ theValue = String.format("%sName: \t\"%s\"\n\t\t\tValue: \t\"%s\"", theValue, entryName, entryValue);
+ }
+ }
+ if (antecedent instanceof SensorState) {
+ SensorState theSensorState = (SensorState) antecedent;
+ String sensorName = theSensorState.getSensorName();
+ String stateValue = theSensorState.getValue().toString(); //assumes all values can directly cast to String
+ theValue = String.format("Sensor name: \t\"%s\"\n\t\t\tState value: \t\"%s\"", sensorName, stateValue);
+ }
+
+ return theValue;
+ }
+
+ /**
+ * This method converts a declarationValue into a string.
+ * The need for this method would be obviated if all our facts descended from
+ * a Fact class with a method to return the unique identifier as a string.
+ *
+ * @param declarationValue - The object associated with a drools LHS declaration
+ */
+ private String declarationValueToString(Object declarationValue) {
+ String convertedDeclarationValue = null;
+ if (declarationValue != null) {
+ convertedDeclarationValue = declarationValue.toString();
+ }
+
+ if (declarationValue instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
+ {
+ convertedDeclarationValue = ((Sensor) declarationValue).getSensorDefinition().getName();
+ }
+ if (declarationValue instanceof SensorState) {
+ String sensorName = ((SensorState) declarationValue).getSensorName();
+ String sensorValue = ((SensorState) declarationValue).getValue().toString();
+ convertedDeclarationValue = String.format("Sensor Name: \"%s\"\n\t\t\tSensor Value: \"%s\"", sensorName, sensorValue);
+ }
+
+ return convertedDeclarationValue;
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java
new file mode 100644
index 000000000..d3c7bec8e
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java
@@ -0,0 +1,34 @@
+package org.openremote.manager.server.rules;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+public class RulePersistence {
+
+ private static final Logger LOG = Logger.getLogger(RulePersistence.class.getName());
+
+ // TODO: This should be persistent on disk
+ final protected Map<String, String> data = new HashMap<>();
+
+ public void writeData(String key, Object value) {
+ LOG.fine("Writing '" + key + "': " + value);
+ data.put(key, value != null ? value.toString() : null);
+ }
+
+ public String readData(String key) {
+ LOG.fine("Reading '" + key + "'");
+ return data.get(key);
+ }
+
+ public String readData(String key, String defaultValue) {
+ LOG.fine("Reading '" + key + "', default: " + defaultValue);
+ return data.containsKey(key) ? data.get(key) : defaultValue;
+ }
+
+ public void deleteData(String key) {
+ LOG.fine("Deleting '" + key + "'");
+ data.remove(key);
+ }
+
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.java
new file mode 100644
index 000000000..29498b8f4
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.java
@@ -0,0 +1,104 @@
+package org.openremote.manager.server.rules;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class RuleUtil {
+
+ /**
+ * @param o A timestamp string as 'HH:mm:ss' or 'HH:mm'.
+ * @return Epoch time or 0 if there is a problem parsing the timestamp string.
+ */
+ public long parseTimestamp(Object o) {
+ String timestamp = o.toString();
+ SimpleDateFormat sdf;
+ if (timestamp.length() == 8) {
+ sdf = new SimpleDateFormat("HH:mm:ss");
+ } else if (timestamp.length() == 5) {
+ sdf = new SimpleDateFormat("HH:mm");
+ } else {
+ return (0L);
+ }
+ try {
+ return (sdf.parse(timestamp).getTime());
+ } catch (ParseException e) {
+ return (0L);
+ }
+ }
+
+ /**
+ * @param timestamp Epoch time
+ * @return The timestamp formatted as 'HH:mm' or <code>null</code> if the timestamp is <= 0.
+ */
+ public String formatTimestamp(long timestamp) {
+ if (timestamp <= 0)
+ return null;
+ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
+ return (sdf.format(new Date(timestamp)));
+ }
+
+ /**
+ * @param timestamp Epoch time
+ * @return The timestamp formatted as 'HH:mm:ss' or <code>null</code> if the timestamp is <= 0.
+ */
+ public String formatTimestampWithSeconds(long timestamp) {
+ if (timestamp <= 0)
+ return null;
+ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
+ return (sdf.format(new Date(timestamp)));
+ }
+
+ /**
+ * @param o A timestamp string as 'HH:mm' or '-'.
+ * @param minutes The minutes to increment/decrement from timestamp.
+ * @return Timestamp string as 'HH:mm', modified with the given minutes or the current time + 60 minutes if
+ * the given timestamp was '-' or the given timestamp couldn't be parsed.
+ */
+ public String shiftTime(Object o, int minutes) {
+ String timestamp = o.toString();
+ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
+ Date date = null;
+ if (timestamp != null && timestamp.length() >= 1 && timestamp.substring(0, 1).equals("-")) {
+ date = new Date();
+ date.setTime(date.getTime() + 60 * 60000);
+ } else {
+ try {
+ date = sdf.parse(timestamp);
+ date.setTime(date.getTime() + minutes * 60000);
+ } catch (ParseException ex) {
+ date = new Date();
+ date.setTime(date.getTime() + 60 * 60000);
+ }
+ }
+ return (sdf.format(date));
+ }
+
+ /**
+ * @param o A string representation of a double value.
+ * @return The parsed value or 0.0 if the string couldn't be parsed.
+ */
+ public Double parseDouble(Object o) {
+ String s = o.toString();
+ try {
+ if (s.length() >= 1) {
+ return (Double.parseDouble(s.substring(0, s.length() - 1)));
+ } else {
+ return (0.0);
+ }
+ } catch (NumberFormatException e) {
+ return (0.0);
+ }
+ }
+
+ /**
+ * @param o A string representation of a double value.
+ * @param shift Increments or decrements the parsed value.
+ * @param suffix A string appended to the result.
+ */
+ public String shiftDouble(Object o, double shift, String suffix) {
+ Double d = parseDouble(o);
+ d = d + shift;
+ return (String.format("%.1f", d) + suffix);
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java
new file mode 100644
index 000000000..821b48ae8
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java
@@ -0,0 +1,12 @@
+package org.openremote.manager.server.rules;
+
+import org.kie.api.KieServices;
+import org.kie.api.io.Resource;
+
+import java.util.stream.Stream;
+
+public interface RulesProvider {
+
+ Stream<Resource> getResources(KieServices kieServices);
+
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
new file mode 100644
index 000000000..e6be48e6a
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -0,0 +1,48 @@
+/*
+ * 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.manager.server.rules;
+
+import org.openremote.container.Container;
+import org.openremote.container.ContainerService;
+import org.openremote.manager.server.attribute.AttributeStateChange;
+import org.openremote.manager.server.attribute.AttributeStateConsumerResult;
+import org.openremote.manager.server.attribute.AttributeStateChangeConsumer;
+
+public class RulesService implements ContainerService, AttributeStateChangeConsumer {
+ @Override
+ public void init(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+
+ }
+
+ @Override
+ public AttributeStateConsumerResult consumeAttributeStateChange(AttributeStateChange attributeStateChange) {
+ return null;
+ }
+}
diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index 5821a54e7..70be2a68f 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -6,6 +6,8 @@ import org.openremote.container.ContainerService
import org.openremote.container.message.MessageBrokerService
import org.openremote.container.message.MessageBrokerSetupService
import org.openremote.container.persistence.PersistenceService
+import org.openremote.manager.server.attribute.AttributeStateRouterService
+import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.agent.AgentService
import org.openremote.manager.server.asset.AssetService
@@ -29,6 +31,8 @@ trait ManagerContainerTrait extends ContainerTrait {
new AssetService(),
new DatapointService(),
new AgentService(),
+ new RulesService(),
+ new AttributeStateRouterService(),
*Lists.newArrayList(ServiceLoader.load(Protocol.class)),
new MapService(),
new MessageBrokerService(),
diff --git a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
index cd81586fe..16090d7af 100644
--- a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
+++ b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
@@ -22,8 +22,20 @@ public class AssetDatapoint extends Datapoint {
super(attributeRef, value);
}
- public AssetDatapoint(String entityId, String attributeName, long timestamp, JsonValue value) {
- super(entityId, attributeName, timestamp, value);
+ public AssetDatapoint(String entityId, String attributeName, JsonValue value) {
+ super(entityId, attributeName, value);
+ }
+
+ public AssetDatapoint(AttributeState attributeState, long timestamp) {
+ super(attributeState, timestamp);
+ }
+
+ public AssetDatapoint(AttributeRef attributeRef, JsonValue value, long timestamp) {
+ super(attributeRef, value, timestamp);
+ }
+
+ public AssetDatapoint(String entityId, String attributeName, JsonValue value, long timestamp) {
+ super(entityId, attributeName, value, timestamp);
}
}
diff --git a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
index 3bbd959a0..0d619b7f6 100644
--- a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
+++ b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.datapoint;
+import elemental.json.Json;
import elemental.json.JsonValue;
import org.openremote.model.AttributeRef;
import org.openremote.model.AttributeState;
@@ -62,11 +63,23 @@ public abstract class Datapoint implements Serializable {
this(attributeState.getAttributeRef(), attributeState.getValue());
}
+ public Datapoint(AttributeState attributeState, long timestamp) {
+ this(attributeState.getAttributeRef(), attributeState.getValue(), timestamp);
+ }
+
public Datapoint(AttributeRef attributeRef, JsonValue value) {
- this(attributeRef.getEntityId(), attributeRef.getAttributeName(), System.currentTimeMillis(), value);
+ this(attributeRef.getEntityId(), attributeRef.getAttributeName(), value);
+ }
+
+ public Datapoint(AttributeRef attributeRef, JsonValue value, long timestamp) {
+ this(attributeRef.getEntityId(), attributeRef.getAttributeName(), value, timestamp);
+ }
+
+ public Datapoint(String entityId, String attributeName, JsonValue value) {
+ this(entityId, attributeName, value, System.currentTimeMillis());
}
- public Datapoint(String entityId, String attributeName, long timestamp, JsonValue value) {
+ public Datapoint(String entityId, String attributeName, JsonValue value, long timestamp) {
this.entityId = entityId;
this.attributeName = attributeName;
this.timestamp = timestamp;