Skip to content

armgit / core

Public Imported from GitHub
0

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

Initial implementation of trigger protocol (not tested)

Rich Turner443492e9d6a2
diff --git a/agent/build.gradle b/agent/build.gradle
index 35ce03d8f..6117257ac 100644
--- a/agent/build.gradle
+++ b/agent/build.gradle
@@ -9,6 +9,7 @@ dependencies {
compile "org.drools:drools-decisiontables:$droolsVersion"
compile "com.luckycatlabs:SunriseSunsetCalculator:$sunriseSunsetCalculatorVersion"
+ compile "org.quartz-scheduler:quartz:$quartzVersion"
testCompile "junit:junit:$junitVersion"
testCompile "org.spockframework:spock-core:$spockVersion"
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java
new file mode 100644
index 000000000..4473e4581
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java
@@ -0,0 +1,109 @@
+/*
+ * 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.agent3.protocol.trigger;
+
+import elemental.json.JsonValue;
+import org.openremote.agent3.protocol.AbstractProtocol;
+import org.openremote.container.Container;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
+import org.openremote.model.AttributeState;
+
+public abstract class AbstractTriggerHandler {
+
+ protected static TriggerProtocol protocol;
+
+ protected abstract String getName();
+
+ protected abstract boolean isValidValue(JsonValue triggerValue);
+
+ protected abstract void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled);
+
+ protected abstract void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled);
+
+ protected abstract void unregisterTrigger(AttributeRef triggerRef);
+
+ /**
+ * The {@link AbstractTriggerHandler} implementation should override this method
+ * to handle the request based on the propertyName and the {@link AttributeEvent}.
+ *
+ * The propertyName should relate to a request to read that property from the trigger
+ * handler and the trigger handler is responsible for pushing updates to the attribute
+ * by calling {@link #updateAttributeValue(AttributeState)}
+ *
+ */
+ protected abstract void registerAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName);
+
+ protected abstract void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName);
+
+ protected abstract void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef);
+
+ /**
+ * A {@link AbstractProtocol#sendToActuator(AttributeEvent)} has occurred on the protocol.
+ *
+ * The {@link AbstractTriggerHandler} implementation should override this method
+ * to handle the request based on the propertyName and the {@link AttributeEvent}.
+ *
+ * {@link TriggerProtocol#TRIGGER_PROPERTY_ENABLED} writes are handled here and are
+ * applicable for all trigger types (implementations can override but should still
+ * call this super method).
+ *
+ * If the handler wishes to alter the trigger's value as a result of the request
+ * (e.g. request was to adjust the time of a TimeTrigger) then the handler
+ * should call {@link #updateTriggerValue(AttributeState)} with the new desired value.
+ */
+ protected abstract void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event);
+
+ /**
+ * Called by the protocol init
+ */
+ protected void init(Container container) throws Exception {}
+
+ /**
+ * Called by the protocol start
+ */
+ protected void start(Container container) throws Exception {}
+
+ /**
+ * Called by the protocol stop
+ */
+ protected void stop(Container container) throws Exception {}
+
+ /**
+ * Allows trigger handlers to update a trigger's value
+ */
+ protected void updateTriggerValue(AttributeState triggerRefAndValue) {
+ protocol.updateTriggerValue(triggerRefAndValue);
+ }
+
+ /**
+ * Allows trigger handlers to update the value of linked attributes
+ */
+ protected void updateAttributeValue(AttributeState attributeState) {
+ protocol.updateAttribute(attributeState);
+ }
+
+ /**
+ * Allows trigger handlers to request execution of the trigger action
+ */
+ protected void executeTrigger(AttributeRef triggerRef) {
+ protocol.doTriggerAction(triggerRef);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java
new file mode 100644
index 000000000..fc810025d
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java
@@ -0,0 +1,180 @@
+/*
+ * 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.agent3.protocol.trigger;
+
+import elemental.json.Json;
+import elemental.json.JsonValue;
+import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.AttributeState;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.util.JsonUtil;
+
+import java.util.Optional;
+import java.util.function.Function;
+
+import static org.openremote.agent3.protocol.trigger.TriggerProtocol.*;
+import static org.openremote.agent3.protocol.trigger.TriggerType.toJsonValue;
+import static org.openremote.model.AttributeType.STRING;
+import static org.openremote.model.MetaItem.isMetaNameEqualTo;
+import static org.openremote.model.MetaItem.replaceMetaByName;
+import static org.openremote.model.asset.agent.ProtocolConfiguration.getProtocolName;
+
+/**
+ * Utility functions for working with trigger attributes for the {@link TriggerProtocol}
+ */
+final public class TriggerConfiguration {
+
+ private TriggerConfiguration() {
+ }
+
+ public static Function<AssetAttribute, AssetAttribute> initTriggerConfiguration() {
+ return attribute -> {
+ attribute.setType(STRING);
+ attribute.setValue(Json.create(TriggerProtocol.PROTOCOL_NAME));
+ return attribute;
+ };
+ }
+
+ public static boolean isTriggerConfiguration(AssetAttribute attribute) {
+ return getProtocolName(attribute)
+ .map(TriggerProtocol.PROTOCOL_NAME::equals)
+ .orElse(false);
+ }
+
+ public static boolean isValidTriggerConfiguration(AssetAttribute attribute) {
+ return isTriggerConfiguration(attribute)
+ && isTriggerActionValid(attribute)
+ && isTriggerTypeAndValueValid(attribute);
+ }
+
+ public static boolean hasTriggerType(AssetAttribute attribute) {
+ return attribute != null && attribute
+ .getMetaStream()
+ .anyMatch(isMetaNameEqualTo(META_TRIGGER_TYPE));
+ }
+
+ public static boolean isTriggerTypeValid(AssetAttribute attribute) {
+ return getTriggerType(attribute).isPresent();
+ }
+
+ public static Optional<TriggerType> getTriggerType(AssetAttribute attribute) {
+ return attribute == null ? Optional.empty() : attribute
+ .getMetaItem(META_TRIGGER_TYPE)
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .flatMap(TriggerType::fromString);
+ }
+
+ public static void setTriggerType(AssetAttribute attribute, TriggerType triggerType) {
+ if (attribute == null)
+ return;
+
+ replaceMetaByName(attribute.getMeta(), META_TRIGGER_TYPE, toJsonValue(triggerType));
+ }
+
+ public static Optional<AbstractTriggerHandler> getTriggerTypeHandler(AssetAttribute attribute) {
+ return getTriggerType(attribute)
+ .map(TriggerType::getHandler);
+ }
+
+ public static boolean hasTriggerValue(AssetAttribute attribute) {
+ return attribute != null && attribute.hasMetaItem(META_TRIGGER_VALUE);
+ }
+
+ public static boolean isTriggerTypeAndValueValid(AssetAttribute attribute) {
+ Optional<JsonValue> triggerValue = getTriggerValue(attribute);
+ Optional<AbstractTriggerHandler> handler = getTriggerTypeHandler(attribute);
+ return triggerValue.isPresent() && handler
+ .map(h ->
+ isTriggerValueValid(h,
+ triggerValue.get()
+ )
+ )
+ .orElse(false);
+ }
+
+ public static boolean isTriggerValueValid(AbstractTriggerHandler handler, JsonValue value) {
+ return handler != null && value != null && handler.isValidValue(value);
+ }
+
+ public static Optional<JsonValue> getTriggerValue(AssetAttribute attribute) {
+ return attribute == null ? Optional.empty() : attribute
+ .getMetaItem(META_TRIGGER_VALUE)
+ .flatMap(AbstractValueHolder::getValue);
+ }
+
+ public static void setTriggerValue(AssetAttribute attribute, JsonValue value) {
+ if (attribute == null)
+ return;
+
+ replaceMetaByName(attribute.getMeta(), META_TRIGGER_VALUE, value);
+ }
+
+ public static boolean hasTriggerAction(AssetAttribute attribute) {
+ return attribute != null && attribute.hasMetaItem(META_TRIGGER_ACTION);
+ }
+
+ public static boolean isTriggerActionValid(AssetAttribute attribute) {
+ return attribute != null && attribute.getMetaItem(META_TRIGGER_ACTION)
+ .flatMap(AbstractValueHolder::getValue)
+ .map(AttributeState::isAttributeState)
+ .orElse(false);
+ }
+
+ public static Optional<AttributeState> getTriggerAction(AssetAttribute attribute) {
+ return attribute == null ? Optional.empty() : attribute
+ .getMetaItem(META_TRIGGER_ACTION)
+ .flatMap(AbstractValueHolder::getValueAsJsonObject)
+ .flatMap(AttributeState::fromJsonValue);
+ }
+
+ public static void setTriggerAction(AssetAttribute attribute, AttributeState action) {
+ if (attribute == null)
+ return;
+
+ replaceMetaByName(attribute.getMeta(), META_TRIGGER_ACTION, AttributeState.toJsonValue(action));
+ }
+
+ public static void removeTrigger(AssetAttribute attribute) {
+ if (attribute == null)
+ return;
+
+ attribute
+ .getMeta()
+ .removeIf(
+ isMetaNameEqualTo(META_TRIGGER_TYPE)
+ .or(isMetaNameEqualTo(META_TRIGGER_VALUE))
+ .or(isMetaNameEqualTo(META_TRIGGER_ACTION))
+ );
+ }
+
+ public static boolean hasTriggerProperty(AssetAttribute attribute) {
+ return attribute != null && attribute
+ .getMetaItem(META_TRIGGER_PROPERTY)
+ .flatMap(AbstractValueHolder::getValue)
+ .map(JsonUtil::isOfTypeString)
+ .orElse(false);
+ }
+
+ public static Optional<String> getTriggerProperty(AssetAttribute attribute) {
+ return attribute == null ? Optional.empty() : attribute
+ .getMetaItem(META_TRIGGER_PROPERTY)
+ .flatMap(AbstractValueHolder::getValueAsString);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerHandlerProducer.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerHandlerProducer.java
new file mode 100644
index 000000000..a87bfc585
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerHandlerProducer.java
@@ -0,0 +1,24 @@
+/*
+ * 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.agent3.protocol.trigger;
+
+public interface TriggerHandlerProducer {
+ AbstractTriggerHandler getHandler();
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java
new file mode 100644
index 000000000..5135209e2
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java
@@ -0,0 +1,338 @@
+/*
+ * 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.agent3.protocol.trigger;
+
+import elemental.json.Json;
+import elemental.json.JsonValue;
+import org.openremote.agent3.protocol.AbstractProtocol;
+import org.openremote.container.Container;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
+import org.openremote.model.AttributeState;
+import org.openremote.model.asset.AssetAttribute;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.logging.Logger;
+
+import static org.openremote.agent3.protocol.trigger.TriggerConfiguration.*;
+import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.asset.AssetMeta.ENABLED;
+import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
+import static org.openremote.model.util.JsonUtil.asBoolean;
+
+/**
+ * This protocol can be used to trigger {@link AttributeEvent} using a trigger type:
+ *
+ * A trigger is defined by creating a {@link TriggerConfiguration} attribute on an
+ * agent. A trigger consists of:
+ *
+ * Trigger Type {@link TriggerType}
+ * Trigger Value ({@link TriggerType#TIME} = CRON EXPRESSION, {@link TriggerType#ATTRIBUTE} = {@link org.openremote.model.AttributeRef})
+ * Trigger Action {@link org.openremote.model.AttributeState} that should be sent when triggered
+ *
+ * {@link AssetAttribute}s can link to time triggers to read/write the trigger time and/or enable/disable
+ * the trigger.
+ *
+ * The {@link #META_TRIGGER_PROPERTY} meta should be used on linked attributes to indicate what property
+ * of the trigger the attribute should read/write. The content of the meta should be a string that is
+ * specific to the trigger type handler. The only globally recognised value is {@link #TRIGGER_PROPERTY_ENABLED}
+ * which reads/writes the trigger's {@link org.openremote.model.asset.AssetMeta#ENABLED} meta item.
+ *
+ */
+public class TriggerProtocol extends AbstractProtocol {
+
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":trigger";
+ public static final String META_TRIGGER_VALUE = ASSET_META_NAMESPACE + ":triggerValue";
+ public static final String META_TRIGGER_TYPE = ASSET_META_NAMESPACE + ":triggerType";
+ public static final String META_TRIGGER_ACTION = ASSET_META_NAMESPACE + ":triggerAction";
+ public static final String META_TRIGGER_PROPERTY = ASSET_META_NAMESPACE + ":triggerProperty";
+ public static final String TRIGGER_PROPERTY_ENABLED = "ENABLED";
+ private static final Logger LOG = Logger.getLogger(TriggerProtocol.class.getName());
+ protected final Map<AttributeRef, AssetAttribute> protocolConfigMap = new HashMap<>();
+ protected final Map<AttributeRef, AbstractTriggerHandler> attributeTriggerHandlerMap = new HashMap<>();
+
+ @Override
+ public String getProtocolName() {
+ return PROTOCOL_NAME;
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+ super.start(container);
+
+ for (TriggerType triggerType : TriggerType.values()) {
+ AbstractTriggerHandler handler = triggerType.getHandler();
+ LOG.info("Starting trigger handler: " + handler.getName());
+ handler.start(container);
+ }
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ for (TriggerType triggerType : TriggerType.values()) {
+ AbstractTriggerHandler handler = triggerType.getHandler();
+ LOG.info("Stopping trigger handler: " + handler.getName());
+ handler.stop(container);
+ }
+
+ super.stop(container);
+ }
+
+ @Override
+ public void init(Container container) throws Exception {
+ super.init(container);
+
+ // TODO: Wire up AssetStorageService so we can push trigger configuration updates
+ //container.getService(AssetStorageService.class);
+ // Push static protocol reference so trigger handlers can call doTriggerAction
+ AbstractTriggerHandler.protocol = this;
+
+ for (TriggerType triggerType : TriggerType.values()) {
+ AbstractTriggerHandler handler = triggerType.getHandler();
+ LOG.info("Initialising trigger handler: " + handler.getName());
+ handler.init(container);
+ }
+ }
+
+ @Override
+ protected void sendToActuator(AttributeEvent event) {
+ LOG.fine("Request to send to actuator");
+
+ // Send to actuator means that the trigger wants to be updated
+ // if the attributes' META_TRIGGER_PROPERTY value is TRIGGER_PROPERTY_ENABLED
+ // then handle the request here, otherwise delegate to the trigger handler
+ AssetAttribute attribute = getLinkedAttribute(event.getAttributeRef());
+ AttributeRef triggerRef = getAgentLink(attribute)
+ .orElseThrow(() -> new IllegalStateException("Trigger configuration link cannot be found on attribute: " + event.getAttributeRef()));
+
+ TriggerConfiguration.getTriggerProperty(attribute)
+ .ifPresent(propertyName -> {
+ if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
+ // Check that event contains a boolean
+ asBoolean(event.getValue())
+ .ifPresent(enabled ->
+ // We update the trigger configuration and wait for it to come back through the processing
+ // chain as an update to the protocol configuration in the agent service
+ updateTriggerMeta(new AttributeState(triggerRef, Json.create(enabled)), ENABLED.getUrn())
+ );
+ } else {
+ synchronized (attributeTriggerHandlerMap) {
+ AbstractTriggerHandler handler = attributeTriggerHandlerMap.get(event.getAttributeRef());
+ if (handler != null) {
+ LOG.info("Passing attribute write request to trigger handler '" +handler.getName() + "'");
+ handler.processAttributeWrite(event.getAttributeRef(), triggerRef, propertyName, event);
+ }
+ }
+ }
+ });
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ @Override
+ protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+
+ // The protocol configuration is actually a Trigger Configuration
+ // TODO: Initialise triggers even if they don't have linked attributes
+ AssetAttribute initialisedProtocolConfiguration;
+
+ synchronized (protocolConfigMap) {
+ initialisedProtocolConfiguration = protocolConfigMap.computeIfAbsent(protocolConfiguration.getReferenceOrThrow(), protocolConfigRef ->
+ {
+ // Verify that this is a valid Trigger Configuration
+ if (!isValidTriggerConfiguration(protocolConfiguration)) {
+ LOG.warning("Trigger Configuration is not valid so it will be ignored: " + protocolConfigRef);
+ return null;
+ }
+
+ // Register the trigger with its handler
+ TriggerType type = getTriggerType(protocolConfiguration).get();
+ AbstractTriggerHandler handler = getTriggerTypeHandler(protocolConfiguration).get();
+ JsonValue value = getTriggerValue(protocolConfiguration).get();
+ handler.registerTrigger(protocolConfigRef, value, protocolConfiguration.isEnabled());
+
+ return protocolConfiguration;
+ });
+ }
+
+ // Do nothing if protocol configuration is not valid
+ if (initialisedProtocolConfiguration == null) {
+ LOG.warning("The Trigger Configuration linked to by the attribute is invalid so cannot use it");
+ return;
+ }
+
+ // Wire up the attribute
+ TriggerConfiguration.getTriggerTypeHandler(protocolConfiguration)
+ .ifPresent(handler -> registerAttributeWithTriggerHandler(attribute, protocolConfiguration, handler));
+ }
+
+ @Override
+ protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ // Check if this attribute is already linked to a handler and that it is the same
+ AbstractTriggerHandler oldHandler;
+ AbstractTriggerHandler newHandler;
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+
+ synchronized (attributeTriggerHandlerMap) {
+ oldHandler = attributeTriggerHandlerMap.get(attributeRef);
+ }
+
+ newHandler = getTriggerTypeHandler(protocolConfiguration).orElse(null);
+
+ if (oldHandler == null && newHandler == null) {
+ LOG.finer("Both old and new handlers are null so nothing to do here");
+ return;
+ }
+
+ if (newHandler == oldHandler) {
+ updateAttributeWithTriggerHandler(attribute, protocolConfiguration, oldHandler);
+ return;
+ }
+
+ if (oldHandler != null) {
+ unRegisterAttributeWithTriggerHandler(attributeRef, protocolConfiguration.getReferenceOrThrow(), oldHandler);
+ }
+
+ if (newHandler != null) {
+ registerAttributeWithTriggerHandler(attribute, protocolConfiguration, newHandler);
+ }
+ }
+
+ @Override
+ protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ AbstractTriggerHandler oldHandler;
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+
+ synchronized (attributeTriggerHandlerMap) {
+ oldHandler = attributeTriggerHandlerMap.get(attributeRef);
+
+ if (oldHandler != null) {
+ unRegisterAttributeWithTriggerHandler(attributeRef, protocolConfiguration.getReferenceOrThrow(), oldHandler);
+ }
+ }
+ }
+
+ protected void registerAttributeWithTriggerHandler(AssetAttribute attribute, AssetAttribute triggerConfiguration, AbstractTriggerHandler handler) {
+ LOG.fine("Request to register attribute with trigger handler");
+
+ TriggerConfiguration.getTriggerProperty(attribute)
+ .ifPresent(propertyName -> {
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+
+ if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
+ AttributeState state = new AttributeState(attributeRef, Json.create(triggerConfiguration.isEnabled()));
+ // Push current value of enabled status into the attribute
+ LOG.info("Updating attribute value with trigger enabled status: " + state);
+ onSensorUpdate(state);
+ } else {
+ LOG.info("Registering attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
+ synchronized (attributeTriggerHandlerMap) {
+ attributeTriggerHandlerMap.put(attribute.getReferenceOrThrow(), handler);
+ }
+ handler.registerAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);
+ }
+ });
+ }
+
+ protected void updateAttributeWithTriggerHandler(AssetAttribute attribute, AssetAttribute triggerConfiguration, AbstractTriggerHandler handler) {
+ LOG.fine("Request to update attribute with trigger handler");
+
+ TriggerConfiguration.getTriggerProperty(attribute)
+ .ifPresent(propertyName -> {
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+
+ if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
+ // META_TRIGGER_PROPERTY has changed must not have been using TRIGGER_ENABLED value before
+ unRegisterAttributeWithTriggerHandler(attributeRef, triggerConfiguration.getReferenceOrThrow(), handler);
+
+ LOG.info("Registering attribute for trigger enabled status: " + attributeRef);
+
+ // Push current value of enabled status into the attribute
+ onSensorUpdate(new AttributeState(attributeRef, Json.create(triggerConfiguration.isEnabled())));
+ } else {
+ LOG.info("Updating attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
+ handler.updateAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);
+ }
+ });
+ }
+
+ protected void unRegisterAttributeWithTriggerHandler(AttributeRef attributeRef, AttributeRef triggerRef, AbstractTriggerHandler handler) {
+ LOG.fine("Request to unregister attribute with trigger handler");
+
+ // Check if attribute is linked to a trigger handler
+ synchronized (attributeTriggerHandlerMap) {
+ if (attributeTriggerHandlerMap.remove(attributeRef) != null) {
+ LOG.info("Un-registering attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
+ handler.unregisterAttribute(attributeRef, triggerRef);
+ }
+ }
+ }
+
+ /**
+ * Updates the value of an attribute linked to a trigger handler
+ */
+ void updateAttribute(AttributeState state) {
+ onSensorUpdate(state);
+ }
+
+ /**
+ * Sends the trigger's attribute state into the processing chain
+ */
+ void doTriggerAction(AttributeRef triggerRef) {
+ LOG.info("Trigger handler requested trigger action to be executed");
+
+ synchronized (protocolConfigMap) {
+ Optional.ofNullable(protocolConfigMap.get(triggerRef))
+ .ifPresent(triggerConfiguration ->
+ getTriggerAction(triggerConfiguration)
+ .ifPresent(this::sendAttributeEvent)
+ );
+ }
+ }
+
+ /**
+ * Update the trigger's {@link #META_TRIGGER_VALUE}
+ */
+ void updateTriggerValue(AttributeState state) {
+ updateTriggerMeta(state, META_TRIGGER_VALUE);
+ }
+
+ /**
+ * Updates the trigger configuration on the owning agent
+ */
+ // TODO: Implement trigger meta update
+ protected void updateTriggerMeta(AttributeState state, String metaName) {
+ LOG.info("Updating trigger meta '" + metaName + "': " + state.getAttributeRef());
+
+ synchronized (protocolConfigMap) {
+ Optional.ofNullable(protocolConfigMap.get(state.getAttributeRef()))
+ .ifPresent(triggerConfiguration ->
+ LOG.info("Updating trigger configuration")
+ // Set the trigger Configuration meta and update the agent
+ //replaceMetaByName(triggerConfiguration, metaName, state.getValue());
+ //Asset agent = assetStorageService.get(triggerConfiguration.getAssetId(), true);
+ //agent.replaceAttribute(triggerConfiguration);
+ //assetStorageService.merge(agent);
+ );
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java
new file mode 100644
index 000000000..e7942a022
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java
@@ -0,0 +1,78 @@
+/*
+ * 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.agent3.protocol.trigger;
+
+import elemental.json.Json;
+import elemental.json.JsonValue;
+import org.openremote.agent3.protocol.trigger.attribute.AttributeTriggerHandler;
+import org.openremote.agent3.protocol.trigger.time.TimeTriggerHandler;
+
+import java.util.Objects;
+import java.util.Optional;
+
+import static org.openremote.model.util.JsonUtil.asString;
+
+public enum TriggerType implements TriggerHandlerProducer {
+ /**
+ * For cron based triggers
+ */
+ TIME(new TimeTriggerHandler()),
+
+ /**
+ * For {@link org.openremote.model.AttributeEvent} triggers
+ */
+ ATTRIBUTE(new AttributeTriggerHandler());
+
+ private AbstractTriggerHandler handler;
+
+ // Prevents cloning of values each time fromString is called
+ private static final TriggerType[] copyOfValues = values();
+
+ TriggerType(AbstractTriggerHandler handler) {
+ this.handler = handler;
+ }
+
+ public AbstractTriggerHandler getHandler() {
+ return handler;
+ }
+
+ public static Optional<TriggerType> fromString(String value) {
+ for (TriggerType type : copyOfValues) {
+ if (type.name().equalsIgnoreCase(value))
+ return Optional.of(type);
+ }
+ return Optional.empty();
+ }
+
+ public static String toString(TriggerType triggerType) {
+ Objects.requireNonNull(triggerType);
+ return triggerType.toString();
+ }
+
+ public static TriggerType fromJsonValue(JsonValue value) {
+ return asString(value)
+ .flatMap(TriggerType::fromString)
+ .orElse(null);
+ }
+
+ public static JsonValue toJsonValue(TriggerType triggerType) {
+ return Json.create(toString(triggerType));
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java
new file mode 100644
index 000000000..b565cd49a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java
@@ -0,0 +1,74 @@
+/*
+ * 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.agent3.protocol.trigger.attribute;
+
+import elemental.json.JsonValue;
+import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
+
+public class AttributeTriggerHandler extends AbstractTriggerHandler {
+ public static final String ATTRIBUTE_TRIGGER_HANDLER_NAME = "Attribute Event Trigger Handler";
+
+ @Override
+ protected String getName() {
+ return ATTRIBUTE_TRIGGER_HANDLER_NAME;
+ }
+
+ @Override
+ protected boolean isValidValue(JsonValue triggerValue) {
+ return false;
+ }
+
+ @Override
+ protected void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {
+
+ }
+
+ @Override
+ protected void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {
+
+ }
+
+ @Override
+ protected void unregisterTrigger(AttributeRef triggerRef) {
+
+ }
+
+ @Override
+ protected void registerAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
+
+ }
+
+ @Override
+ protected void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
+
+ }
+
+ @Override
+ protected void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef) {
+
+ }
+
+ @Override
+ protected void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event) {
+ // This trigger handler doesn't support updates for now
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronExpressionParser.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronExpressionParser.java
new file mode 100644
index 000000000..354981059
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronExpressionParser.java
@@ -0,0 +1,195 @@
+/*
+ * 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.agent3.protocol.trigger.time;
+
+import org.quartz.CronExpression;
+
+import java.util.EnumSet;
+import java.util.Locale;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Basic cron expression parser (unfortunately the quartz cron expression class
+ * uses all protected methods and class is final).
+ *
+ */
+public class CronExpressionParser {
+
+ enum DaysOfWeek {
+ SUN,
+ MON,
+ TUE,
+ WED,
+ THU,
+ FRI,
+ SAT;
+
+ private static DaysOfWeek[] values = DaysOfWeek.values();
+ static final EnumSet<DaysOfWeek> ALL_OPTS = EnumSet.allOf(DaysOfWeek.class);
+
+ public static EnumSet<DaysOfWeek> fromString(String str) {
+ String[] arr = str.split(",");
+ EnumSet<DaysOfWeek> set = EnumSet.noneOf(DaysOfWeek.class);
+
+ for (String e : arr) {
+ DaysOfWeek daysOfWeek = null;
+
+ try {
+ int i = Integer.parseInt(e);
+ daysOfWeek = values[i-1];
+ } catch (NumberFormatException ex) {
+ try {
+ daysOfWeek = DaysOfWeek.valueOf(e.trim().toUpperCase(Locale.ROOT));
+ } catch(Exception ex2) {
+ LOG.log(Level.INFO, "Cannot convert cron value for days of week to a day", ex2);
+ }
+ }
+ if (daysOfWeek != null && !set.contains(daysOfWeek)) {
+ set.add(daysOfWeek);
+ }
+ }
+ return set;
+ }
+ }
+
+ enum Months {
+ JAN,
+ FEB,
+ MAR,
+ APR,
+ MAY,
+ JUN,
+ JUL,
+ AUG,
+ SEP,
+ OCT,
+ NOV,
+ DEC;
+
+ private static Months[] values = Months.values();
+ static final EnumSet<Months> ALL_OPTS = EnumSet.allOf(Months.class);
+
+ public static EnumSet<Months> fromString(String str) {
+ String[] arr = str.split(",");
+ EnumSet<Months> set = EnumSet.noneOf(Months.class);
+
+ for (String e : arr) {
+ Months months = null;
+
+ try {
+ int i = Integer.parseInt(e);
+ months = values[i-1];
+ } catch (NumberFormatException ex) {
+ try {
+ months = Months.valueOf(e.trim().toUpperCase(Locale.ROOT));
+ } catch(Exception ex2) {
+ LOG.log(Level.INFO, "Cannot convert cron value for days of week to a day", ex2);
+ }
+ }
+ if (months != null && !set.contains(months)) {
+ set.add(months);
+ }
+ }
+ return set;
+ }
+ }
+
+ private static final Logger LOG = Logger.getLogger(CronExpressionParser.class.getName());
+
+ protected final String originalCronExpression;
+ protected static final int SECONDS = 0;
+ protected static final int MINUTES = 1;
+ protected static final int HOURS = 2;
+ protected static final int DAY_OF_MONTH = 0;
+ protected static final int MONTH = 1;
+ protected static final int DAY_OF_WEEK = 2;
+ protected static final int YEAR = 3;
+ protected int[] timeValues = new int[3];
+ protected String[] otherValues = new String[4];
+ protected boolean compatible = true;
+ protected boolean valid;
+
+ protected CronExpressionParser(String cronExpression) {
+ valid = CronExpression.isValidExpression(cronExpression);
+ originalCronExpression = cronExpression;
+ String[] fields = cronExpression.split("\\s+");
+
+ if (fields.length < 6 || fields.length > 7) {
+ LOG.info("Cron expression doesn't contain the required 6 or 7 space separated values");
+ compatible = false;
+ } else {
+ for (int i=0; i<3; i++) {
+ Integer value = parseNumberExpression(fields[i]);
+ if (value == null) {
+ compatible = false;
+ } else {
+ timeValues[i] = value;
+ }
+ }
+
+ // Initialise empty year value
+ otherValues[6] = "";
+
+ System.arraycopy(fields, 3, otherValues, 0, fields.length - 3);
+ }
+ }
+
+ protected boolean isCompatible() {
+ return compatible;
+ }
+
+ public boolean isValid() {
+ return valid;
+ }
+
+ protected String buildCronExpression() {
+ if (!isCompatible()) {
+ return originalCronExpression;
+ } else {
+ return timeValues[0] + " " + timeValues[1] + " " + timeValues[2] + " " + String.join(" ", otherValues).trim();
+ }
+ }
+
+ protected void setTime(int hours, int minutes, int seconds) {
+ hours = Math.max(0, hours % 24);
+ minutes = Math.max(0, minutes % 60);
+ seconds = Math.max(0, seconds % 60);
+ compatible = true;
+
+ timeValues[HOURS] = hours;
+ timeValues[MINUTES] = minutes;
+ timeValues[SECONDS] = seconds;
+ }
+
+ protected String getFormattedTime() {
+ return String.format("%02d:%02d:%02d", timeValues[HOURS], timeValues[MINUTES], timeValues[SECONDS]);
+ }
+
+ protected static Integer parseNumberExpression(String field) {
+ try {
+ return Integer.parseInt(field);
+ } catch(NumberFormatException e) {
+ LOG.info("Field is not a simple integer expression: " + field);
+ return null;
+ }
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronScheduler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronScheduler.java
new file mode 100644
index 000000000..da112fe18
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/CronScheduler.java
@@ -0,0 +1,143 @@
+/*
+ * 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.agent3.protocol.trigger.time;
+
+import org.quartz.*;
+import org.quartz.impl.StdSchedulerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+class CronScheduler {
+
+ static class CronJob implements Job {
+ @Override
+ public void execute(JobExecutionContext context) throws JobExecutionException {
+ Runnable executeAction = (Runnable)context.getMergedJobDataMap().get("ACTION");
+
+ if (executeAction != null) {
+ LOG.info("Cron trigger fired: " + context.getTrigger().getKey().getName());
+ executeAction.run();
+ }
+ }
+ }
+
+
+ private static final Logger LOG = Logger.getLogger(CronScheduler.class.getName());
+ protected static final int ALARM_UPDATE_DELAY_MS = 10000;
+ protected final List<String> jobIds = new ArrayList<>();
+ protected final org.quartz.Scheduler scheduler;
+
+ CronScheduler() {
+ org.quartz.Scheduler tempScheduler;
+
+ // Set properties for cronScheduler factory
+ Properties schedulerProperties = new Properties();
+ schedulerProperties.setProperty("org.quartz.threadPool.threadCount", "1");
+ // Use default thread pool for now
+ //schedulerProperties.setProperty("org.quartz.threadPool.class", null);
+
+ try {
+ // Initialise Quartz CronScheduler
+ SchedulerFactory factory = new StdSchedulerFactory(schedulerProperties);
+ tempScheduler = factory.getScheduler();
+ } catch (SchedulerException e) {
+ tempScheduler = null;
+ LOG.log(Level.WARNING, "Failed to create quartz cronScheduler", e);
+ }
+
+ scheduler = tempScheduler;
+ }
+
+ protected boolean isValid() {
+ return scheduler != null;
+ }
+
+ protected void shutdown() {
+ if (scheduler != null) {
+ try {
+ scheduler.shutdown(false);
+ } catch (SchedulerException e) {
+ LOG.log(Level.FINE, "Exception has occurred during force shutdown of quartz cronScheduler", e);
+ }
+ }
+ }
+
+ protected void addOrReplaceJob(String id, CronExpression expression, Runnable executeHandler) {
+ if (jobIds.contains(id)) {
+ removeJob(id);
+ }
+
+ CronTrigger cronTrigger = createCronTrigger(id, expression, executeHandler);
+
+ try {
+ scheduler.scheduleJob(cronTrigger);
+
+ if (!scheduler.isStarted()) {
+ LOG.info("Starting the cron cronScheduler");
+ scheduler.start();
+ }
+
+ jobIds.add(id);
+ } catch (SchedulerException e) {
+ LOG.log(Level.WARNING, "Unable to start cron job: " + id, e);
+ }
+ }
+
+ protected void removeJob(String id) {
+ try {
+ scheduler.unscheduleJob(TriggerKey.triggerKey(id));
+ } catch (SchedulerException e) {
+ LOG.log(Level.FINE, "Exception thrown whilst trying to unschedule cron job: " + id, e);
+ } finally {
+ jobIds.remove(id);
+ }
+ }
+
+ protected static CronTrigger createCronTrigger(String id, CronExpression cronExpression, Runnable executeHandler) {
+ if (cronExpression == null) {
+ LOG.info("Cron expression is null so cannot create trigger: " + id);
+ return null;
+ }
+
+ // Create the cron schedule
+ CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cronExpression);
+
+ // Create the job data (just the execute handler
+ JobDataMap jobData = new JobDataMap();
+ jobData.put("ACTION", executeHandler);
+
+ // Create the execution job
+ JobDetail cronJob = JobBuilder.newJob(CronJob.class)
+ .withIdentity("cronJob1", id)
+ .setJobData(jobData)
+ .build();
+
+ // Create the cron trigger for this alarm
+ return TriggerBuilder.newTrigger()
+ .withIdentity(TriggerKey.triggerKey(id))
+ .withSchedule(cronSchedule)
+ .forJob(cronJob)
+ .build();
+ }
+}
\ No newline at end of file
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java
new file mode 100644
index 000000000..aaf9a99e9
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java
@@ -0,0 +1,220 @@
+/*
+ * 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.agent3.protocol.trigger.time;
+
+import elemental.json.Json;
+import elemental.json.JsonValue;
+import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
+import org.openremote.model.AttributeState;
+import org.openremote.model.util.TextUtil;
+import org.quartz.CronExpression;
+
+import javax.ws.rs.NotSupportedException;
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.logging.Logger;
+
+import static java.util.logging.Level.FINER;
+import static org.openremote.agent3.protocol.trigger.time.CronExpressionParser.parseNumberExpression;
+import static org.openremote.model.util.JsonUtil.asString;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+public class TimeTriggerHandler extends AbstractTriggerHandler {
+ private static final Logger LOG = Logger.getLogger(TimeTriggerHandler.class.getName());
+ public static final String TIME_TRIGGER_HANDLER_NAME = "Time Trigger Handler";
+ protected final Map<AttributeRef, CronExpressionParser> cronExpressionMap = new HashMap<>();
+ protected CronScheduler cronScheduler;
+
+ @Override
+ protected String getName() {
+ return TIME_TRIGGER_HANDLER_NAME;
+ }
+
+ @Override
+ protected boolean isValidValue(JsonValue triggerValue) {
+ return isValidCronExpression(asString(triggerValue).orElse(null));
+ }
+
+ @Override
+ protected void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {
+ Optional<String> expression = asString(value).flatMap(TextUtil::asNonNullAndNonEmpty);
+ CronExpressionParser cronExpressionParser = null;
+
+ if (expression.isPresent()) {
+ cronExpressionParser = new CronExpressionParser(expression.get());
+ } else {
+ LOG.warning("Time trigger value is not a cron expression string");
+ }
+
+ synchronized (cronExpressionMap) {
+ cronExpressionMap.put(triggerRef, cronExpressionParser);
+ }
+
+ if (isEnabled && cronExpressionParser != null && cronExpressionParser.isValid()) {
+ @SuppressWarnings("ConstantConditions")
+ CronExpression cronExpression = createCronExpression(cronExpressionParser.buildCronExpression());
+ if (cronExpression != null) {
+ getCronScheduler().addOrReplaceJob(getTriggerId(triggerRef), cronExpression, () -> {
+ // This is executed when the job triggers
+ executeTrigger(triggerRef);
+ });
+ }
+ }
+ }
+
+ @Override
+ protected void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {
+ unregisterTrigger(triggerRef);
+ registerTrigger(triggerRef, value, isEnabled);
+ }
+
+ @Override
+ protected void unregisterTrigger(AttributeRef triggerRef) {
+ getCronScheduler().removeJob(getTriggerId(triggerRef));
+ }
+
+ @Override
+ protected void registerAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
+ TimeTriggerProperty property = TimeTriggerProperty.fromString(propertyName);
+ if (property == null) {
+ LOG.warning("Property name is not valid for time trigger handler: " + propertyName);
+ return;
+ }
+
+ CronExpressionParser parser = getCronExpressionParser(triggerRef);
+ if (parser == null) {
+ LOG.info("Attribute is linked to an invalid trigger so it will be ignored");
+ return;
+ }
+
+ switch (property) {
+ case CRON_EXPRESSION:
+ // Pass the entire cron expression through to the attribute
+ updateAttributeValue(new AttributeState(attributeRef, Json.create(parser.buildCronExpression())));
+ break;
+ case TIME:
+ // Pass the 24h formatted time
+ updateAttributeValue(new AttributeState(attributeRef, Json.create(parser.getFormattedTime())));
+ break;
+ }
+ }
+
+ @Override
+ protected void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
+ registerAttribute(attributeRef, triggerRef, propertyName);
+ }
+
+ @Override
+ protected void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef) {
+
+ }
+
+ @Override
+ protected void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event) {
+ TimeTriggerProperty triggerProperty = TimeTriggerProperty.fromString(propertyName);
+ if (triggerProperty == null) {
+ LOG.warning("Attribute is using an invalid trigger property name '" + propertyName + "': " + attributeRef);
+ return;
+ }
+
+ // Don't remove or alter any running trigger just push update back through the system
+ // and wait for add, remove or update trigger call
+ Optional<String> writeValue = asString(event.getValue()).flatMap(TextUtil::asNonNullAndNonEmpty);
+
+ if (!writeValue.isPresent()) {
+ LOG.warning("Send to actuator value for time trigger must be a non empty string");
+ return;
+ }
+
+ String value = writeValue.get().trim();
+
+ switch (triggerProperty) {
+ case CRON_EXPRESSION:
+ // Allow writing invalid cron expressions; mean that the trigger will stop working
+ // but that is handled gracefully
+ updateTriggerValue(new AttributeState(triggerRef, Json.create(value)));
+ break;
+ case TIME:
+ CronExpressionParser parser = getCronExpressionParser(triggerRef);
+ if (parser == null) {
+ LOG.info("Ignoring trigger update because current cron expression is invalid");
+ return;
+ }
+
+ String[] writeTimeValues = value.split(":");
+ Integer hours;
+ Integer minutes;
+ Integer seconds;
+
+ if (writeTimeValues.length != 3
+ || (hours = parseNumberExpression(writeTimeValues[0])) == null
+ || (minutes = parseNumberExpression(writeTimeValues[1])) == null
+ || (seconds = parseNumberExpression(writeTimeValues[2])) == null) {
+ LOG.info("Expected value to be in format HH:MM:SS, actual: " + writeValue);
+ return;
+ }
+
+ parser.setTime(hours, minutes, seconds);
+ updateTriggerValue(new AttributeState(triggerRef, Json.create(parser.buildCronExpression())));
+ break;
+ default:
+ throw new NotSupportedException("Unsupported trigger property");
+ }
+
+ }
+
+ protected CronScheduler getCronScheduler() {
+ if (cronScheduler == null) {
+ LOG.fine("Create cron scheduler");
+ cronScheduler = new CronScheduler();
+ }
+
+ return cronScheduler;
+ }
+
+ protected CronExpressionParser getCronExpressionParser(AttributeRef triggerRef) {
+ synchronized (cronExpressionMap) {
+ return cronExpressionMap.get(triggerRef);
+ }
+ }
+
+ public static CronExpression createCronExpression(String expression) {
+ CronExpression cronExpression = null;
+ try {
+ cronExpression = new CronExpression(expression);
+ } catch (ParseException e) {
+ LOG.log(FINER, "Failed to create cron expression from string: " + expression, e);
+ }
+
+ return cronExpression;
+ }
+
+ public static boolean isValidCronExpression(String expression) {
+ return !isNullOrEmpty(expression) && createCronExpression(expression) != null;
+ }
+
+ protected static String getTriggerId(AttributeRef triggerRef) {
+ return triggerRef.getEntityId() + ":" + triggerRef.getAttributeName();
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerProperty.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerProperty.java
new file mode 100644
index 000000000..38fe4b439
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerProperty.java
@@ -0,0 +1,51 @@
+/*
+ * 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.agent3.protocol.trigger.time;
+
+import java.util.Locale;
+
+public enum TimeTriggerProperty {
+
+ /**
+ * Links the entire cron expression to an attribute for read/write
+ */
+ CRON_EXPRESSION,
+
+ /**
+ * Links the time of the cron expression to an attribute for read/write
+ * (read works for simple hour, min and second cron expressions
+ * e.g. 0 35 15 ? * *) once a write is performed to a non simple cron
+ * expression then it becomes simple.
+ *
+ * 24h time format
+ */
+ TIME;
+
+// /**
+// * Links the Day of week of the cron expression to an attribute for
+// * read/write (only works for single day of week cron expressions)
+// */
+// //TODO: Could pull multiple days as a JsonArray
+// DAY_OF_WEEK
+
+ public static TimeTriggerProperty fromString(String value) {
+ return value == null ? null : valueOf(value.toUpperCase(Locale.ROOT));
+ }
+}
diff --git a/gradle.properties b/gradle.properties
index 6b59617ce..3588ef4cc 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -30,3 +30,4 @@ tyrusVersion = 1.10
ahcVersion = 1.9.39
sunriseSunsetCalculatorVersion = 1.2
droolsVersion = 6.5.0.Final
+quartzVersion= 2.2.3
\ No newline at end of file