Skip to content

armgit / core

Public Imported from GitHub
0

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

Removed macro and timer protocols (where required should be implemented using rules)

Rich Turnere4246a8841af
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAction.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAction.java
deleted file mode 100644
index 8e5d768c2..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAction.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.agent.protocol.macro;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.openremote.model.attribute.AttributeState;
-
-import java.io.Serializable;
-import java.util.Objects;
-
-/**
- * A desired {@link AttributeState} and a delay in milli seconds before that state
- * is applied when the macro executes.
- */
-public class MacroAction implements Serializable {
-
- protected AttributeState attributeState;
- @JsonProperty("delay")
- protected int delayMilliseconds;
-
- public MacroAction(AttributeState attributeState) {
- Objects.requireNonNull(attributeState);
- this.attributeState = attributeState;
- }
-
- @JsonCreator
- public MacroAction(@JsonProperty("attributeState") AttributeState attributeState, @JsonProperty("delay") int delayMilliseconds) {
- this(attributeState);
- setDelayMilliseconds(delayMilliseconds);
- }
-
- public AttributeState getAttributeState() {
- return attributeState;
- }
-
- public void setAttributeState(AttributeState attributeState) {
- this.attributeState = Objects.requireNonNull(attributeState);
- }
-
- public int getDelayMilliseconds() {
- return delayMilliseconds;
- }
-
- public void setDelayMilliseconds(int delayMilliseconds) {
- this.delayMilliseconds = Math.max(0, delayMilliseconds);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "attributeState='" + attributeState + '\'' +
- ", delay='" + delayMilliseconds + '\'' +
- '}';
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAgent.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAgent.java
deleted file mode 100644
index fc3c2f27b..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroAgent.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright 2020, 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.agent.protocol.macro;
-
-import org.openremote.model.asset.agent.Agent;
-import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
-import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.ValueDescriptor;
-import org.openremote.model.value.ValueType;
-
-import javax.persistence.Entity;
-import javax.validation.constraints.Min;
-import java.util.Optional;
-
-@Entity
-public class MacroAgent extends Agent<MacroAgent, MacroProtocol, MacroAgent.MacroAgentLink> {
-
- public static final class MacroAgentLink extends AgentLink<MacroAgentLink> {
-
- @Min(0)
- protected Integer actionIndex;
-
- // For Hydrators
- protected MacroAgentLink() {}
-
- public MacroAgentLink(String id) {
- super(id);
- }
-
- public Optional<Integer> getActionIndex() {
- return Optional.ofNullable(actionIndex);
- }
-
- public MacroAgentLink setActionIndex(Integer actionIndex) {
- this.actionIndex = actionIndex;
- return this;
- }
- }
-
- public static final ValueDescriptor<MacroAction> MACRO_ACTION_VALUE = new ValueDescriptor<>("macroAction", MacroAction.class);
-
- public static final AttributeDescriptor<MacroAction[]> MACRO_ACTIONS = new AttributeDescriptor<>("macroActions", MACRO_ACTION_VALUE.asArray());
-
- public static final AttributeDescriptor<Boolean> MACRO_DISABLED = new AttributeDescriptor<>("macroDisabled", ValueType.BOOLEAN);
-
- public static final AttributeDescriptor<AttributeExecuteStatus> MACRO_STATUS = new AttributeDescriptor<>("macroStatus", ValueType.EXECUTION_STATUS);
-
- public static final AgentDescriptor<MacroAgent, MacroProtocol, MacroAgentLink> DESCRIPTOR = new AgentDescriptor<>(
- MacroAgent.class, MacroProtocol.class, MacroAgentLink.class
- );
-
- /**
- * For use by hydrators (i.e. JPA/Jackson)
- */
- protected MacroAgent() {
- }
-
- public MacroAgent(String name) {
- super(name);
- }
-
- @Override
- public MacroProtocol getProtocolInstance() {
- return new MacroProtocol(this);
- }
-
- public Optional<MacroAction[]> getMacroActions() {
- return getAttributes().getValue(MACRO_ACTIONS);
- }
-
- public MacroAgent setMacroActions(MacroAction[] actions) {
- getAttributes().getOrCreate(MACRO_ACTIONS).setValue(actions);
- return this;
- }
-
- public Optional<Boolean> isMacroDisabled() {
- return getAttributes().getValue(MACRO_DISABLED);
- }
-
- public MacroAgent setMacroDisabled(boolean macroDisabled) {
- getAttributes().getOrCreate(MACRO_DISABLED).setValue(macroDisabled);
- return this;
- }
-
- public Optional<AttributeExecuteStatus> getMacroStatus() {
- return getAttributes().getValue(MACRO_STATUS);
- }
-
- @Override
- public boolean isConfigurationAttribute(String attributeName) {
- return !attributeName.equals(MACRO_STATUS.getName()) && super.isConfigurationAttribute(attributeName);
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
deleted file mode 100644
index 6e17632f0..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * 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.agent.protocol.macro;
-
-import org.openremote.agent.protocol.AbstractProtocol;
-import org.openremote.model.Container;
-import org.openremote.model.asset.agent.ConnectionStatus;
-import org.openremote.model.attribute.*;
-import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.value.ValueType;
-import org.openremote.model.value.Values;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-
-import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-
-// TODO: Remove this protocol once attribute linking and flow integration is done
-/**
- * This protocol is responsible for executing macros.
- * <p>
- * It expects a {@link AttributeExecuteStatus} as the attribute event value on the {@link #doLinkedAttributeWrite}.
- * The protocol will then try to perform the request on the linked macro protocol instance.
- * <p>
- * {@link Attribute}s can also read/write the macro configuration's {@link MacroAction} values by using the
- * {@link MacroAgent.MacroAgentLink#getActionIndex} with the index of the {@link MacroAction} to link to.
- */
-public class MacroProtocol extends AbstractProtocol<MacroAgent, MacroAgent.MacroAgentLink> {
-
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, MacroProtocol.class);
-
- public static final String PROTOCOL_DISPLAY_NAME = "Macro";
-
- class MacroExecutionTask {
-
- List<MacroAction> actions;
- boolean repeat;
- boolean cancelled;
- ScheduledFuture<?> scheduledFuture;
- int step = -1;
-
- public MacroExecutionTask(List<MacroAction> actions, boolean repeat) {
- this.actions = actions;
- this.repeat = repeat;
- }
-
- void start() {
- updateExecuteStatus(AttributeExecuteStatus.RUNNING);
- run();
- }
-
- void cancel() {
- LOG.fine("Macro Execution cancel");
- scheduledFuture.cancel(false);
- cancelled = true;
- execution = null;
- updateExecuteStatus(AttributeExecuteStatus.CANCELLED);
- }
-
- private void run() {
- if (cancelled) {
- return;
- }
-
- boolean finished = false;
-
- try {
- if (step >= 0) {
- // Process the execution of the next action
- MacroAction action = actions.get(step);
- AttributeState actionState = action.getAttributeState();
-
- // send attribute event
- sendAttributeEvent(actionState);
- }
-
- boolean isLast = step == actions.size() - 1;
- boolean restart = isLast && repeat;
-
- if (restart) {
- step = 0;
- } else {
- step++;
- }
-
- finished = isLast && !restart;
- } finally {
- if (finished) {
- execution = null;
- // Update the command Status of this attribute
- updateExecuteStatus(AttributeExecuteStatus.COMPLETED);
- } else {
-
- // Get next execution delay
- int delayMillis = actions.get(step).getDelayMilliseconds();
-
- // Schedule the next iteration
- scheduledFuture = executorService.schedule(this::run, Math.max(delayMillis, 0), TimeUnit.MILLISECONDS);
- }
- }
- }
- }
-
- protected final List<MacroAction> actions = new ArrayList<>();
- protected MacroExecutionTask execution;
-
- public MacroProtocol(MacroAgent agent) {
- super(agent);
- }
-
- @Override
- public String getProtocolName() {
- return PROTOCOL_DISPLAY_NAME;
- }
-
- @Override
- public String getProtocolInstanceUri() {
- return "macro://" + agent.getId();
- }
-
- @Override
- protected void doStart(Container container) throws Exception {
-
- actions.addAll(Arrays.asList(agent.getMacroActions().orElseThrow(() -> {
- String msg = "Macro actions attribute missing or invalid: " + this;
- LOG.warning(msg);
- return new IllegalArgumentException(msg);
- })));
-
- setConnectionStatus(ConnectionStatus.CONNECTED);
- }
-
- @Override
- protected void doStop(Container container) throws Exception {
- if (execution != null) {
- execution.cancel();
- }
- }
-
- @Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, MacroAgent.MacroAgentLink agentLink) {
- AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
-
- // Check for executable meta item
- if (attribute.getType().getType() == AttributeExecuteStatus.class) {
- LOG.finer("Macro linked attribute is marked as executable so it will be linked to the firing of the macro");
- // Update the command Status of this attribute
- updateLinkedAttribute(
- new AttributeState(
- attributeRef,
- agent.isMacroDisabled().orElse(true)
- ? AttributeExecuteStatus.READY
- : AttributeExecuteStatus.DISABLED
- )
- );
- return;
- }
-
- // Check for action index or default to index 0
- int actionIndex = agentLink.getActionIndex().orElse(0);
-
- // Pull the macro action value out with the same type as the linked attribute
- // otherwise push a null value through to the attribute
- Object actionValue = null;
-
- if (actions.isEmpty()) {
- LOG.finer("No actions are available for the linked macro, maybe it is disabled?: " + this);
- } else {
- actionIndex = Math.min(actions.size(), Math.max(0, actionIndex));
- actionValue = actions.get(actionIndex).getAttributeState().getValue().orElse(null);
- LOG.finer("Attribute is linked to the value of macro action index: actionIndex");
- }
-
- // Push the value of this macro action into the attribute
- updateLinkedAttribute(new AttributeState(attributeRef, actionValue));
- }
-
- @Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, MacroAgent.MacroAgentLink agentLink) {
- }
-
- @Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, MacroAgent.MacroAgentLink agentLink, AttributeEvent event, Object processedValue) {
-
- if (attribute.getType().getType() == AttributeExecuteStatus.class) {
- // This is a macro execution related write operation
- AttributeExecuteStatus status = Values.getValueCoerced(event.getValue(), AttributeExecuteStatus.class)
- .orElse(null);
-
- if (status == null || !status.isWrite()) {
- LOG.info("Linked attribute write value is either null or not a valid execution status");
- return;
- }
-
- // Check if it's a cancellation request
- if (status == AttributeExecuteStatus.REQUEST_CANCEL) {
- if (execution == null) {
- return;
- }
-
- LOG.fine("Request received to cancel macro execution: " + event);
- execution.cancel();
- return;
- }
-
- if (actions.isEmpty()) {
- LOG.fine("No actions to execute");
- return;
- }
-
- executeMacro(status == AttributeExecuteStatus.REQUEST_REPEATING);
- return;
- }
-
- // Assume this is a write to a macro action value (default to index 0)
- int actionIndex = agentLink.getActionIndex().orElse(0);
-
- if (actions.isEmpty()) {
- LOG.fine("No actions are available for the linked macro, maybe it is disabled?: " + this);
- } else {
- actionIndex = Math.min(actions.size(), Math.max(0, actionIndex));
- MacroAction action = actions.get(actionIndex);
-
- if (action == null) {
- return;
- }
-
- Object newActionValue = event.getValue().orElse(null);
- action.setAttributeState(new AttributeState(action.getAttributeState().getRef(), newActionValue));
- updateAgentAttribute(new AttributeState(agent.getId(), MacroAgent.MACRO_ACTIONS.getName(), actions));
- updateLinkedAttribute(new AttributeState(event.getAttributeRef(), newActionValue));
- }
- }
-
- protected void executeMacro(boolean repeat) {
- MacroExecutionTask task = new MacroExecutionTask(actions, repeat);
- task.start();
- }
-
- protected void updateExecuteStatus(AttributeExecuteStatus executeStatus) {
- updateAgentAttribute(new AttributeState(agent.getId(), MacroAgent.MACRO_STATUS.getName(), executeStatus));
-
- // Update linked attribute of type AttributeExecuteStatus
- linkedAttributes.entrySet().stream()
- .filter(assetIdAndAttribute ->
- assetIdAndAttribute.getValue().getType().equals(ValueType.EXECUTION_STATUS))
- .forEach(assetIdAndAttribute ->
- updateLinkedAttribute(new AttributeState(assetIdAndAttribute.getKey(), executeStatus)));
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/CronExpressionParser.java b/agent/src/main/java/org/openremote/agent/protocol/timer/CronExpressionParser.java
deleted file mode 100644
index 698d22f5c..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/CronExpressionParser.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.agent.protocol.timer;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonValue;
-import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.TextUtil;
-import org.quartz.CronExpression;
-
-import java.io.Serializable;
-import java.util.EnumSet;
-import java.util.Locale;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-
-/**
- * Basic cron expression parser (unfortunately the quartz cron expression class
- * uses all protected methods and class is final).
- *
- */
-public class CronExpressionParser implements Serializable {
-
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, CronExpressionParser.class);
-
- 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;
- }
- }
-
- 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;
-
- @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
- public 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 = TextUtil.asInteger(fields[i]).orElse(null);
- if (value == null) {
- compatible = false;
- } else {
- timeValues[i] = value;
- }
- }
-
- // Initialise empty year value
- otherValues[3] = "";
-
- System.arraycopy(fields, 3, otherValues, 0, fields.length - 3);
- }
- }
-
- public boolean isCompatible() {
- return compatible;
- }
-
- public boolean isValid() {
- return valid;
- }
-
- @JsonValue
- public String buildCronExpression() {
- if (!isCompatible()) {
- return originalCronExpression;
- } else {
- return timeValues[0] + " " + timeValues[1] + " " + timeValues[2] + " " + String.join(" ", otherValues).trim();
- }
- }
-
- public 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;
- }
-
- public String getFormattedTime() {
- return String.format("%02d:%02d:%02d", timeValues[HOURS], timeValues[MINUTES], timeValues[SECONDS]);
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/CronJob.java b/agent/src/main/java/org/openremote/agent/protocol/timer/CronJob.java
deleted file mode 100644
index 5135fb85d..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/CronJob.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.agent.protocol.timer;
-
-import org.quartz.Job;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-
-/**
- * This has to be in its' own class or quartz has issues instantiating it
- */
-public class CronJob implements Job {
-
- @Override
- public void execute(JobExecutionContext context) throws JobExecutionException {
- Runnable executeAction = (Runnable)context.getMergedJobDataMap().get("ACTION");
-
- if (executeAction != null) {
- executeAction.run();
- }
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/CronScheduler.java b/agent/src/main/java/org/openremote/agent/protocol/timer/CronScheduler.java
deleted file mode 100644
index 488aa0d49..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/CronScheduler.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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.agent.protocol.timer;
-
-import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.Pair;
-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;
-
-import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-
-public class CronScheduler {
-
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, CronScheduler.class);
-
- protected static final int ALARM_UPDATE_DELAY_MS = 10000;
- protected final List<String> jobIds = new ArrayList<>();
- protected static org.quartz.Scheduler scheduler;
-
- static {
- 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;
- }
-
- public CronScheduler() {
- }
-
- 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);
- }
-
- Pair<JobDetail, CronTrigger> cronTrigger = createCronTrigger(id, expression, executeHandler);
-
- if (cronTrigger == null) {
- return;
- }
-
- try {
- LOG.fine("Scheduling job: " + id);
- scheduler.scheduleJob(cronTrigger.key, cronTrigger.value);
-
- if (!scheduler.isStarted()) {
- LOG.info("Starting the cron scheduler");
- 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 {
- LOG.fine("Un-scheduling job: " + id);
- scheduler.unscheduleJob(TriggerKey.triggerKey(id));
- scheduler.deleteJob(JobKey.jobKey("cronJob1", id));
- } catch (SchedulerException e) {
- LOG.log(Level.FINE, "Exception thrown whilst trying to un-schedule cron job: " + id, e);
- } finally {
- jobIds.remove(id);
- }
- }
-
- protected static Pair<JobDetail, 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 with 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
- CronTrigger trigger = TriggerBuilder.newTrigger()
- .withIdentity(TriggerKey.triggerKey(id))
- .withSchedule(cronSchedule)
- .forJob(cronJob)
- .build();
-
- return new Pair<>(cronJob, trigger);
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerAgent.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerAgent.java
deleted file mode 100644
index ef881dd23..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerAgent.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright 2020, 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.agent.protocol.timer;
-
-import org.openremote.model.asset.agent.Agent;
-import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.ValueDescriptor;
-import org.openremote.model.value.ValueType;
-
-import javax.persistence.Entity;
-import java.util.Optional;
-
-@Entity
-public class TimerAgent extends Agent<TimerAgent, TimerProtocol, TimerAgent.TimerAgentLink> {
-
- public static class TimerAgentLink extends AgentLink<TimerAgentLink> {
-
- protected TimerValue timerValue;
-
- // For Hydrators
- protected TimerAgentLink() {}
-
- public TimerAgentLink(String id) {
- super(id);
- }
-
- public Optional<TimerValue> getTimerValue() {
- return Optional.ofNullable(timerValue);
- }
-
- public TimerAgentLink setTimerValue(TimerValue timerValue) {
- this.timerValue = timerValue;
- return this;
- }
- }
-
- public static final ValueDescriptor<CronExpressionParser> TIMER_CRON_EXPRESSION_DESCRIPTOR = new ValueDescriptor<>("cRONExpression", CronExpressionParser.class);
-
- public static final AttributeDescriptor<AttributeState> TIMER_ACTION = new AttributeDescriptor<>("timerAction", ValueType.ATTRIBUTE_STATE);
-
- public static final AttributeDescriptor<CronExpressionParser> TIMER_CRON_EXPRESSION = new AttributeDescriptor<>("timerCRONExpression", TIMER_CRON_EXPRESSION_DESCRIPTOR);
-
- public static final AttributeDescriptor<Boolean> TIMER_ACTIVE = new AttributeDescriptor<>("timerActive", ValueType.BOOLEAN);
-
- public static final AgentDescriptor<TimerAgent, TimerProtocol, TimerAgentLink> DESCRIPTOR = new AgentDescriptor<>(
- TimerAgent.class, TimerProtocol.class, TimerAgentLink.class
- );
-
- /**
- * For use by hydrators (i.e. JPA/Jackson)
- */
- protected TimerAgent() {
- }
-
- public TimerAgent(String name) {
- super(name);
- }
-
- @Override
- public TimerProtocol getProtocolInstance() {
- return new TimerProtocol(this);
- }
-
- public Optional<AttributeState> getTimerAction() {
- return getAttributes().getValue(TIMER_ACTION);
- }
-
- public TimerAgent setTimerAction(AttributeState timerAction) {
- getAttributes().getOrCreate(TIMER_ACTION).setValue(timerAction);
- return this;
- }
-
- public Optional<CronExpressionParser> getTimerCronExpression() {
- return getAttributes().getValue(TIMER_CRON_EXPRESSION);
- }
-
- public TimerAgent setTimerCronExpression(CronExpressionParser cronExpression) {
- getAttributes().getOrCreate(TIMER_CRON_EXPRESSION).setValue(cronExpression);
- return this;
- }
-
- public Optional<Boolean> isTimerActive() {
- return getAttributes().getValue(TIMER_ACTIVE);
- }
-
- public TimerAgent setTimerActive(boolean timerActive) {
- getAttributes().getOrCreate(TIMER_ACTIVE).setValue(timerActive);
- return this;
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java
deleted file mode 100644
index f914c456f..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * 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.agent.protocol.timer;
-
-import org.openremote.agent.protocol.AbstractProtocol;
-import org.openremote.model.Container;
-import org.openremote.model.asset.agent.ConnectionStatus;
-import org.openremote.model.asset.agent.Protocol;
-import org.openremote.model.attribute.Attribute;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.TextUtil;
-import org.openremote.model.value.Values;
-import org.quartz.CronExpression;
-
-import javax.ws.rs.NotSupportedException;
-import java.text.ParseException;
-import java.util.logging.Logger;
-
-import static java.util.logging.Level.FINER;
-import static org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty;
-import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-
-/**
- * This protocol can be used to trigger an {@link AttributeEvent} using a cron based timer.
- * <p>
- * It is also possible to link {@link Attribute}s to this {@link Protocol} to allow reading information about the
- * timer instance and also to allow altering the timer instance (e.g. altering what time a daily timer triggers).
- */
-public class TimerProtocol extends AbstractProtocol<TimerAgent, TimerAgent.TimerAgentLink> {
-
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, TimerProtocol.class);
-
- public static final String PROTOCOL_DISPLAY_NAME = "Timer";
-
- protected boolean active;
- protected CronExpressionParser expressionParser;
- protected CronScheduler cronScheduler;
-
- public TimerProtocol(TimerAgent agent) {
- super(agent);
- }
-
- @Override
- public String getProtocolName() {
- return PROTOCOL_DISPLAY_NAME;
- }
-
- @Override
- public String getProtocolInstanceUri() {
- return expressionParser != null ? expressionParser.buildCronExpression() : "";
- }
-
- @Override
- protected void doStart(Container container) throws Exception {
-
- boolean isActive = agent.isTimerActive().orElse(true);
- expressionParser = agent.getTimerCronExpression().orElse(null);
-
- if (expressionParser == null || !expressionParser.isValid()) {
- LOG.warning("Timer cron expression is missing or invalid");
- throw new IllegalArgumentException("Timer cron expression is missing or invalid");
- }
-
- updateActive(isActive);
- }
-
- @Override
- protected void doStop(Container container) throws Exception {
- if (expressionParser != null) {
- expressionParser = null;
- getCronScheduler().removeJob(getTimerId(agent));
- }
- }
-
- @Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, TimerAgent.TimerAgentLink agentLink) throws RuntimeException {
- TimerValue timerValue = getOrThrowAgentLinkProperty(agentLink.getTimerValue(), "timer value");
-
- LOG.finer("Attribute is linked to timer value: " + timerValue);
- AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
- updateLinkedAttributeTimerValue(timerValue, attributeRef);
- }
-
- @Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, TimerAgent.TimerAgentLink agentLink) {
- // Nothing to do here
- }
-
- @Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, TimerAgent.TimerAgentLink agentLink, AttributeEvent event, Object processedValue) {
-
- // Should never be null as attribute would've only been linked if it has a valid timer value
- TimerValue timerValue = getOrThrowAgentLinkProperty(agentLink.getTimerValue(), "timer value");
-
- switch (timerValue) {
- case ACTIVE:
- // check event value is a boolean
- boolean active = Values.getBoolean(processedValue)
- .orElseThrow(() -> new IllegalStateException("Writing to agent active attribute requires a boolean value"));
-
- if (this.active == active) {
- return;
- } else {
- LOG.finer("Updating timer enabled status: " + active);
- updateActive(active);
- updateAgentAttribute(new AttributeState(agent.getId(), TimerAgent.TIMER_ACTIVE.getName(), active));
- updateLinkedAttributesTimerValues();
- }
- break;
- case CRON_EXPRESSION:
- this.expressionParser = Values.getValueCoerced(processedValue, CronExpressionParser.class)
- .orElseThrow(() -> new IllegalStateException("Writing to agent cron expression attribute requires a string value"));
- updateActive(agent.isTimerActive().orElse(true));
- updateAgentAttribute(new AttributeState(agent.getId(), TimerAgent.TIMER_CRON_EXPRESSION.getName(), this.expressionParser));
- updateLinkedAttributesTimerValues();
- break;
- case TIME:
- String writeValue = Values.getString(processedValue).orElse(null);
- if (TextUtil.isNullOrEmpty(writeValue)) {
- LOG.warning("Send to actuator value for time trigger must be a non empty string");
- return;
- }
-
- String[] writeTimeValues = writeValue.trim().split(":");
- Integer hours;
- Integer minutes;
- Integer seconds;
-
- if (writeTimeValues.length != 3
- || (hours = TextUtil.asInteger(writeTimeValues[0]).orElse(null)) == null
- || (minutes = TextUtil.asInteger(writeTimeValues[1]).orElse(null)) == null
- || (seconds = TextUtil.asInteger(writeTimeValues[2]).orElse(null)) == null) {
- LOG.info("Expected value to be in format HH:MM:SS, actual: " + writeValue);
- return;
- }
-
- expressionParser.setTime(hours, minutes, seconds);
- updateActive(agent.isTimerActive().orElse(true));
- updateAgentAttribute(new AttributeState(agent.getId(), TimerAgent.TIMER_CRON_EXPRESSION.getName(), this.expressionParser));
- updateLinkedAttributesTimerValues();
- break;
- default:
- throw new NotSupportedException("Unsupported timer value: " + timerValue);
- }
- }
-
- protected void updateActive(boolean active) {
-
- CronExpression cronExpression = createCronExpression(expressionParser.buildCronExpression());
- this.active = active && cronExpression != null;
-
- if (cronExpression == null) {
- LOG.warning("Timer cron expression is missing or invalid so timer will be inactive");
- }
-
- if (this.active) {
- getCronScheduler()
- .addOrReplaceJob(
- getTimerId(agent),
- cronExpression,
- this::doTriggerAction
- );
- setConnectionStatus(ConnectionStatus.CONNECTED);
- } else {
- getCronScheduler().removeJob(getTimerId(agent));
- setConnectionStatus(ConnectionStatus.STOPPED);
- }
- }
-
- protected void updateLinkedAttributesTimerValues() {
- linkedAttributes.entrySet()
- .forEach(es -> {
- TimerAgent.TimerAgentLink agentLink = getAgent().getAgentLink(es.getValue());
- if (agentLink != null && agentLink.getId().equals(agent.getId()) && agentLink.getTimerValue().isPresent()) {
- updateLinkedAttributeTimerValue(agentLink.getTimerValue().get(), es.getKey());
- }
- });
- }
-
- protected void updateLinkedAttributeTimerValue(TimerValue timerValue, AttributeRef attributeRef) {
- if (timerValue == null) {
- return;
- }
-
- // Push current value through to the linked attribute
- switch (timerValue) {
- case ACTIVE:
- updateLinkedAttribute(new AttributeState(attributeRef, active));
- break;
- case CRON_EXPRESSION:
- case TIME:
- if (expressionParser == null || !expressionParser.valid) {
- LOG.info("Attribute is linked to an invalid timer so cannot extract requested timer values");
- updateLinkedAttribute(new AttributeState(attributeRef));
- return;
- }
-
- String value = timerValue == TimerValue.CRON_EXPRESSION
- ? expressionParser.buildCronExpression()
- : expressionParser.getFormattedTime();
-
- updateLinkedAttribute(new AttributeState(attributeRef, value));
- break;
- }
- }
-
- /**
- * Sends the trigger's attribute state into the processing chain
- */
- protected void doTriggerAction() {
- agent.getTimerAction()
- .map(action -> {
- LOG.info("Executing timer action for protocol: " + this);
- sendAttributeEvent(action);
- return action;
- }).orElseGet(() -> {
- LOG.warning("Timer action is not set or is invalid so cannot execute: " + this);
- return null;
- });
- }
-
- protected CronScheduler getCronScheduler() {
- if (cronScheduler == null) {
- LOG.fine("Create cron scheduler");
- cronScheduler = new CronScheduler();
- }
-
- return cronScheduler;
- }
-
- protected static String getTimerId(TimerAgent agent) {
- return "TimerProtocol-" + agent.getId();
- }
-
- protected 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;
- }
-}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerValue.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerValue.java
deleted file mode 100644
index 58570c1fc..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerValue.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.agent.protocol.timer;
-
-// TODO: Add support for other links (e.g. DAY_OF_WEEK)
-public enum TimerValue {
-
- /**
- * Links an attribute to the enabled status of a timer for read/write
- */
- ACTIVE,
-
- /**
- * 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
- * <p>
- * 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
-}
diff --git a/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java b/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
index ead95a0e4..42176d211 100644
--- a/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
@@ -19,11 +19,6 @@
*/
package org.openremote.manager.setup;
-import org.openremote.agent.protocol.macro.MacroAction;
-import org.openremote.agent.protocol.macro.MacroAgent;
-import org.openremote.agent.protocol.timer.CronExpressionParser;
-import org.openremote.agent.protocol.timer.TimerAgent;
-import org.openremote.agent.protocol.timer.TimerValue;
import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
@@ -298,182 +293,6 @@ public class ManagerSetup implements Setup {
}
}
- public static class Scene {
-
- final String attributeName;
- final String sceneName;
- final String internalName;
- final String startTime;
- final boolean alarmEnabled;
- final double targetTemperature;
-
- public Scene(String attributeName, String sceneName, String internalName, String startTime,
- boolean alarmEnabled, double targetTemperature) {
- this.attributeName = attributeName;
- this.sceneName = sceneName;
- this.internalName = internalName;
- this.startTime = startTime;
- this.alarmEnabled = alarmEnabled;
- this.targetTemperature = targetTemperature;
- }
-
- MacroAgent createSceneAgent(BuildingAsset apartment, RoomAsset... rooms) {
- MacroAgent sceneAgent = new MacroAgent("Scene agent " + sceneName);
- sceneAgent.setId(UniqueIdentifierGenerator.generateId());
- sceneAgent.setParent(apartment);
-
- List<MacroAction> actions = new ArrayList<>();
- actions.add(new MacroAction(
- new AttributeState(new AttributeRef(apartment.getId(), "alarmEnabled"), alarmEnabled)));
-
- for (RoomAsset room : rooms) {
- if (room.hasAttribute("targetTemperature")) {
- actions.add(new MacroAction(new AttributeState(new AttributeRef(room.getId(), "targetTemperature"),
- targetTemperature)));
- }
- }
-
- actions.add(new MacroAction(
- new AttributeState(new AttributeRef(apartment.getId(), "lastExecutedScene"), internalName)));
-
- sceneAgent.setMacroActions(actions.toArray(new MacroAction[0]));
-
- return sceneAgent;
- }
-
- List<TimerAgent> createTimerAgents(String macroAgentId, BuildingAsset apartment) {
- List<TimerAgent> agents = new ArrayList<>();
-
- for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
- // "MONDAY" => "Monday"
- String dayOfWeekLabel = dayOfWeek.name().substring(0, 1)
- + dayOfWeek.name().substring(1).toLowerCase(Locale.ROOT);
- // "0 0 7 ? *" => "0 0 7 ? * MON *"
- String timePattern = startTime + " " + dayOfWeek.name().substring(0, 3).toUpperCase(Locale.ROOT) + " *";
- TimerAgent timerAgent = new TimerAgent("Timer agent " + sceneName + " " + dayOfWeek.name());
- timerAgent.setParent(apartment);
- timerAgent.setId(UniqueIdentifierGenerator.generateId());
- timerAgent.setTimerAction(new AttributeState(apartment.getId(), attributeName, "REQUEST_START"));
- timerAgent.setTimerCronExpression(new CronExpressionParser(timePattern));
- agents.add(timerAgent);
- }
- return agents;
- }
- }
-
- public static List<Agent<?, ?, ?>> createDemoApartmentScenes(AssetStorageService assetStorageService,
- BuildingAsset apartment, Scene[] scenes, RoomAsset... rooms) {
-
- List<Agent<?, ?, ?>> agents = new ArrayList<>();
-
- for (Scene scene : scenes) {
- MacroAgent sceneAgent = scene.createSceneAgent(apartment, rooms);
- agents.add(sceneAgent);
- agents.addAll(scene.createTimerAgents(sceneAgent.getId(), apartment));
- }
-
- addDemoApartmentSceneEnableDisableTimer(apartment, agents, scenes);
- linkDemoApartmentWithSceneAgent(apartment, agents, scenes);
- agents.forEach(assetStorageService::merge);
- apartment = assetStorageService.merge(apartment);
- return agents;
- }
-
- protected static void addDemoApartmentSceneEnableDisableTimer(BuildingAsset apartment, List<Agent<?, ?, ?>> agents,
- Scene[] scenes) {
-
- MacroAgent enableSceneAgent = new MacroAgent("Scene agent enable");
- MacroAgent disableSceneAgent = new MacroAgent("Scene agent disable");
- List<MacroAction> enableActions = new ArrayList<>();
- List<MacroAction> disableActions = new ArrayList<>();
-
- enableSceneAgent.setParent(apartment);
- enableSceneAgent.setId(UniqueIdentifierGenerator.generateId());
- disableSceneAgent.setParent(apartment);
- disableSceneAgent.setId(UniqueIdentifierGenerator.generateId());
-
- for (Scene scene : scenes) {
- for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
- String sceneAttributeName = scene.attributeName + "Enabled" + dayOfWeek;
- enableActions.add(new MacroAction(
- new AttributeState(new AttributeRef(apartment.getId(), sceneAttributeName), true)));
- disableActions.add(new MacroAction(
- new AttributeState(new AttributeRef(apartment.getId(), sceneAttributeName), false)));
- }
- }
- enableActions.add(
- new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), "sceneTimerEnabled"), true)));
- disableActions.add(
- new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), "sceneTimerEnabled"), false)));
- enableSceneAgent.setMacroActions(enableActions.toArray(new MacroAction[0]));
- disableSceneAgent.setMacroActions(disableActions.toArray(new MacroAction[0]));
-
- agents.add(enableSceneAgent);
- agents.add(disableSceneAgent);
- }
-
- protected static void linkDemoApartmentWithSceneAgent(Asset<?> apartment, List<Agent<?, ?, ?>> agents,
- Scene[] scenes) {
-
- MacroAgent enableSceneAgent = (MacroAgent) agents.get(agents.size() - 2);
- MacroAgent disableSceneAgent = (MacroAgent) agents.get(agents.size() - 1);
- int i = 0;
- for (Scene scene : scenes) {
- MacroAgent sceneAgent = (MacroAgent) agents.get(i);
-
- apartment.getAttributes().addOrReplace(
- new Attribute<>(scene.attributeName, EXECUTION_STATUS, AttributeExecuteStatus.READY).addMeta(
- new MetaItem<>(LABEL, scene.sceneName), new MetaItem<>(ACCESS_RESTRICTED_WRITE, true),
- new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(AGENT_LINK, new MacroAgent.MacroAgentLink(sceneAgent.getId()))),
- new Attribute<>(scene.attributeName + "AlarmEnabled", BOOLEAN).addMeta(
- new MetaItem<>(LABEL, scene.sceneName + " alarm enabled"),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true), new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(AGENT_LINK,
- new MacroAgent.MacroAgentLink(sceneAgent.getId()).setActionIndex(0))),
- new Attribute<>(scene.attributeName + "TargetTemperature", ValueType.NUMBER).addMeta(
- new MetaItem<>(LABEL, scene.sceneName + " target temperature"),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true), new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(AGENT_LINK,
- new MacroAgent.MacroAgentLink(sceneAgent.getId()).setActionIndex(1))));
- int j = 1;
- for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
- // "MONDAY" => "Monday"
- String dayOfWeekLabel = dayOfWeek.name().substring(0, 1)
- + dayOfWeek.name().substring(1).toLowerCase(Locale.ROOT);
- apartment.getAttributes().addOrReplace(
- new Attribute<>(scene.attributeName + "Time" + dayOfWeek.name(), ValueType.TEXT).addMeta(
- new MetaItem<>(LABEL, scene.sceneName + " time " + dayOfWeekLabel),
- new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true), new MetaItem<>(RULE_STATE, true),
- new MetaItem<>(AGENT_LINK,
- new TimerAgent.TimerAgentLink(agents.get(i + j).getId())
- .setTimerValue(TimerValue.TIME))),
- new Attribute<>(scene.attributeName + "Enabled" + dayOfWeek.name(), BOOLEAN).addMeta(
- new MetaItem<>(LABEL, scene.sceneName + " enabled " + dayOfWeekLabel),
- new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true),
- new MetaItem<>(AGENT_LINK, new TimerAgent.TimerAgentLink(agents.get(i + j).getId())
- .setTimerValue(TimerValue.ACTIVE))));
- j++;
- }
- i = i + 8; // 1 scene agent + 7 timer agents
- }
- apartment.getAttributes().addOrReplace(new Attribute<>("sceneTimerEnabled", BOOLEAN, true) // The scene timer is
- // enabled when the
- // timer protocol
- // starts
- .addMeta(new MetaItem<>(LABEL, "Scene timer enabled"), new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(READ_ONLY, true)),
- new Attribute<>("enableSceneTimer", EXECUTION_STATUS).addMeta(
- new MetaItem<>(LABEL, "Enable scene timer"), new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true),
- new MetaItem<>(AGENT_LINK, new MacroAgent.MacroAgentLink(enableSceneAgent.getId()))),
- new Attribute<>("disableSceneTimer", EXECUTION_STATUS).addMeta(
- new MetaItem<>(LABEL, "Disable scene timer"), new MetaItem<>(ACCESS_RESTRICTED_READ, true),
- new MetaItem<>(ACCESS_RESTRICTED_WRITE, true),
- new MetaItem<>(AGENT_LINK, new MacroAgent.MacroAgentLink(disableSceneAgent.getId()))));
- }
protected PeopleCounterAsset createDemoPeopleCounterAsset(String name, Asset<?> area, GeoJSONPoint location,
Supplier<AgentLink<?>> agentLinker) {
diff --git a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index 8c2721414..a7966b198 100644
--- a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -33,7 +33,6 @@ trait ManagerContainerTrait extends ContainerTrait {
(IDENTITY_NETWORK_WEBSERVER_PORT): "8081",
(SETUP_CREATE_ASSETS) : "true",
(SETUP_CREATE_USERS) : "true",
- (SETUP_CREATE_SCENES) : "false",
(SETUP_CREATE_RULES) : "false",
(MQTT_SERVER_LISTEN_HOST) : "127.0.0.1", // Works best for cross platform test running
(TIMER_CLOCK_TYPE) : PSEUDO.name()
@@ -53,12 +52,6 @@ trait ManagerContainerTrait extends ContainerTrait {
defaultServices(Arrays.asList(additionalServices))
}
- Container startContainerWithDemoScenesAndRules(Map<String, String> config, Iterable<ContainerService> services) {
- config << [(SETUP_CREATE_SCENES): "true"]
- config << [(SETUP_CREATE_RULES): "true"]
- startContainer(config, services)
- }
-
/**
* Use wall clock instead of pseudo clock.
*/
diff --git a/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java b/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
index 219d11c8d..a8c9fb712 100644
--- a/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
+++ b/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
@@ -67,13 +67,6 @@ public class ManagerTestSetup extends ManagerSetup {
public static GeoJSONPoint AREA_2_LOCATION = new GeoJSONPoint(5.473829, 51.438744);
public static GeoJSONPoint AREA_3_LOCATION = new GeoJSONPoint(5.487478, 51.446979);
public static final String thingLightToggleAttributeName = "light1Toggle";
- public static final Scene[] DEMO_APARTMENT_SCENES = new Scene[] {
- new Scene("morningScene", "Morning scene", "MORNING", "0 0 7 ? *", false, 21d),
- new Scene("dayScene", "Day scene", "DAY", "0 30 8 ? *", true, 15d),
- new Scene("eveningScene", "Evening scene", "EVENING", "0 30 17 ? *", false, 22d),
- new Scene("nightScene", "Night scene", "NIGHT", "0 0 22 ? *", true, 19d)
- };
- final protected boolean importDemoScenes;
public String smartOfficeId;
public String groundFloorId;
public String lobbyId;
@@ -81,7 +74,6 @@ public class ManagerTestSetup extends ManagerSetup {
public String thingId;
public String smartBuildingId;
public String apartment1Id;
- public List<String> apartment1SceneAgentIds;
public String apartment1ServiceAgentId;
public String apartment1LivingroomId = UniqueIdentifierGenerator.generateId("apartment1LivingroomId");
public String apartment1KitchenId;
@@ -106,9 +98,8 @@ public class ManagerTestSetup extends ManagerSetup {
public String electricitySupplierAssetId;
public String electricityBatteryAssetId;
- public ManagerTestSetup(Container container, boolean importDemoScenes) {
+ public ManagerTestSetup(Container container) {
super(container);
- this.importDemoScenes = importDemoScenes;
}
@Override
@@ -419,12 +410,6 @@ public class ManagerTestSetup extends ManagerSetup {
apartment1 = assetStorageService.merge(apartment1);
apartment1Id = apartment1.getId();
- if (importDemoScenes) {
- List<Agent<?,?,?>> demoApartment1SceneAgents = createDemoApartmentScenes(
- assetStorageService, apartment1, DEMO_APARTMENT_SCENES, apartment1Livingroom, apartment1Kitchen, apartment1Hallway);
- apartment1SceneAgentIds = demoApartment1SceneAgents.stream().map(Asset::getId).collect(Collectors.toList());
- }
-
BuildingAsset apartment2 = new BuildingAsset("Apartment 2");
apartment2.setParent(smartBuilding);
apartment2.getAttributes().addOrReplace(
diff --git a/test/src/main/java/org/openremote/test/setup/TestSetupTasks.java b/test/src/main/java/org/openremote/test/setup/TestSetupTasks.java
index d7c0f444b..984a1fa39 100644
--- a/test/src/main/java/org/openremote/test/setup/TestSetupTasks.java
+++ b/test/src/main/java/org/openremote/test/setup/TestSetupTasks.java
@@ -33,7 +33,6 @@ import static org.openremote.container.util.MapAccess.getBoolean;
*/
public class TestSetupTasks extends EmptySetupTasks {
- public static final String SETUP_CREATE_SCENES = "SETUP_CREATE_SCENES";
public static final String SETUP_CREATE_USERS = "SETUP_CREATE_USERS";
public static final String SETUP_CREATE_ASSETS = "SETUP_CREATE_ASSETS";
public static final String SETUP_CREATE_RULES = "SETUP_CREATE_RULES";
@@ -52,10 +51,6 @@ public class TestSetupTasks extends EmptySetupTasks {
return getBoolean(container.getConfig(), SETUP_CREATE_RULES, container.isDevMode());
}
- static boolean isImportScenes(Container container) {
- return getBoolean(container.getConfig(), SETUP_CREATE_SCENES, container.isDevMode());
- }
-
@Override
public List<Setup> createTasks(Container container) {
super.createTasks(container);
@@ -67,8 +62,8 @@ public class TestSetupTasks extends EmptySetupTasks {
addTask(new KeycloakTestSetup(container));
}
- if (isImportAssets(container) || isImportScenes(container)) {
- addTask(new ManagerTestSetup(container, isImportScenes(container)));
+ if (isImportAssets(container)) {
+ addTask(new ManagerTestSetup(container));
}
if (isImportRules(container)) {
diff --git a/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy
deleted file mode 100644
index cc3741996..000000000
--- a/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy
+++ /dev/null
@@ -1,121 +0,0 @@
-package org.openremote.test.protocol
-
-
-import org.openremote.manager.asset.AssetProcessingService
-import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.setup.SetupService
-import org.openremote.test.setup.ManagerTestSetup
-import org.openremote.model.attribute.AttributeEvent
-import org.openremote.model.attribute.AttributeExecuteStatus
-import org.openremote.test.ManagerContainerTrait
-import spock.lang.Specification
-import spock.util.concurrent.PollingConditions
-
-import java.util.concurrent.TimeUnit
-
-class MacroProtocolTest extends Specification implements ManagerContainerTrait {
- def "Check macro agent and device asset deployment"() {
-
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 15, initialDelay: 0)
-
- when: "the container starts"
- def container = startContainerWithDemoScenesAndRules(defaultConfig(), defaultServices())
- def assetStorageService = container.getService(AssetStorageService.class)
- def assetProcessingService = container.getService(AssetProcessingService.class)
- def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
-
- and: "the clock is stopped for testing purposes"
- stopPseudoClock()
-
- then: "the container should be running and attributes linked"
- conditions.eventually {
- assert noEventProcessedIn(assetProcessingService, 500)
-
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert apartment1.getAttribute("morningScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.READY
- assert apartment1.getAttribute("dayScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.READY
- assert apartment1.getAttribute("eveningScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.READY
- assert apartment1.getAttribute("nightScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.READY
- assert !apartment1.getAttribute("morningSceneAlarmEnabled").flatMap{it.value}.orElse(true)
- assert apartment1.getAttribute("morningSceneTargetTemperature", Double.class).get().getValue().orElse(0d) == 21d
- }
-
- when: "Apartment 1 home scene is executed"
- def macroExecute = new AttributeEvent(managerTestSetup.apartment1Id, "morningScene", AttributeExecuteStatus.REQUEST_START)
- assetProcessingService.sendAttributeEvent(macroExecute)
-
- then: "Apartment 1 alarm enabled, last scene and living room target temp attribute values should be updated to match the scene"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- def livingRoom = assetStorageService.find(managerTestSetup.apartment1LivingroomId, true)
- assert !apartment1.getAttribute("alarmEnabled").flatMap{it.value}.orElse(true)
- assert apartment1.getAttribute("lastExecutedScene").get().getValue().orElse("") == "MORNING"
- assert livingRoom.getAttribute("targetTemperature", Double.class).get().getValue().orElse(0d) == 21d
- }
-
- then: "Apartment 1 home scene attribute status should show as COMPLETED"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert apartment1.getAttribute("morningScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.COMPLETED
- }
-
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "Apartment 1 away scene is executed"
- macroExecute = new AttributeEvent(managerTestSetup.apartment1Id, "dayScene", AttributeExecuteStatus.REQUEST_START)
- assetProcessingService.sendAttributeEvent(macroExecute)
-
- then: "Apartment 1 alarm enabled, last scene and living room target temp attribute values should be update to match the scene"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- def livingRoom = assetStorageService.find(managerTestSetup.apartment1LivingroomId, true)
- assert apartment1.getAttribute("alarmEnabled").flatMap{it.value}.orElse(false)
- assert apartment1.getAttribute("lastExecutedScene").get().getValue().orElse("") == "DAY"
- assert livingRoom.getAttribute("targetTemperature", Double.class).get().getValue().orElse(0d) == 15d
- }
-
- then: "Apartment 1 away scene attribute status should show as COMPLETED"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert apartment1.getAttribute("dayScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.COMPLETED
- }
-
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "The target temperature of the home scene is modified via the apartment attribute"
- def updateTargetTemp = new AttributeEvent(managerTestSetup.apartment1Id, "morningSceneTargetTemperature", 10d)
- assetProcessingService.sendAttributeEvent(updateTargetTemp)
-
- then: "Apartment 1 home target temp should show new value"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert apartment1.getAttribute("morningSceneTargetTemperature", Double.class).get().getValue().orElse(0d) == 10d
- assert !apartment1.getAttribute("morningSceneAlarmEnabled").flatMap{it.value}.orElse(true)
- }
-
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "Apartment 1 home scene is executed"
- macroExecute = new AttributeEvent(managerTestSetup.apartment1Id, "morningScene", AttributeExecuteStatus.REQUEST_START)
- assetProcessingService.sendAttributeEvent(macroExecute)
-
- then: "Apartment 1 alarm enabled, last scene and living room target temp attribute values should be updated to match the scene"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- def livingRoom = assetStorageService.find(managerTestSetup.apartment1LivingroomId, true)
- assert !apartment1.getAttribute("alarmEnabled").flatMap{it.value}.orElse(true)
- assert apartment1.getAttribute("lastExecutedScene").get().getValue().orElse("") == "MORNING"
- assert livingRoom.getAttribute("targetTemperature",Double.class).get().getValue().orElse(0d) == 10d
- }
-
- then: "Apartment 1 home scene attribute status should show as COMPLETED"
- conditions.eventually {
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert apartment1.getAttribute("morningScene", AttributeExecuteStatus.class).get().getValue().orElse(null) == AttributeExecuteStatus.COMPLETED
- }
- }
-}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
deleted file mode 100644
index ee49ba08d..000000000
--- a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
+++ /dev/null
@@ -1,218 +0,0 @@
-package org.openremote.test.protocol
-
-import org.openremote.agent.protocol.macro.MacroAgent
-import org.openremote.agent.protocol.timer.CronScheduler
-import org.openremote.agent.protocol.timer.TimerAgent
-import org.openremote.agent.protocol.timer.TimerProtocol
-import org.openremote.agent.protocol.timer.TimerValue
-import org.openremote.manager.agent.AgentService
-import org.openremote.manager.asset.AssetProcessingService
-import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.setup.SetupService
-import org.openremote.test.setup.ManagerTestSetup
-import org.openremote.model.asset.Asset
-import org.openremote.model.attribute.Attribute
-import org.openremote.model.attribute.AttributeEvent
-import org.openremote.model.attribute.AttributeExecuteStatus
-import org.openremote.model.attribute.MetaItem
-import org.openremote.model.query.AssetQuery
-import org.openremote.model.query.filter.StringPredicate
-import org.openremote.model.value.MetaItemType
-import org.openremote.model.value.ValueType
-import org.openremote.test.ManagerContainerTrait
-import org.quartz.CronTrigger
-import org.quartz.JobKey
-import org.quartz.impl.matchers.GroupMatcher
-import spock.lang.Specification
-import spock.util.concurrent.PollingConditions
-
-class TimerProtocolTest extends Specification implements ManagerContainerTrait {
- def "Check timer protocol agent and device asset deployment"() {
-
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, initialDelay: 0)
-
- when: "the container starts"
- def container = startContainerWithDemoScenesAndRules(defaultConfig(), defaultServices())
- def assetStorageService = container.getService(AssetStorageService.class)
- def assetProcessingService = container.getService(AssetProcessingService.class)
- def agentService = container.getService(AgentService.class)
- def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
- List<MacroAgent> sceneAgents
- List<TimerAgent> timerAgents
- Asset apartment1
-
- then: "the container should be running and attributes linked"
- conditions.eventually {
- assert isContainerRunning()
- assert noEventProcessedIn(assetProcessingService, 500)
-
- apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)
- sceneAgents = assetStorageService.findAll(new AssetQuery().names(new StringPredicate(AssetQuery.Match.BEGIN, "Scene agent")).types(MacroAgent.class).parents(managerTestSetup.apartment1Id)).asList() as List<MacroAgent>
- timerAgents = agentService.agentMap.values().findAll {it.getName().startsWith("Timer agent") && it.parentId == managerTestSetup.apartment1Id} as List<TimerAgent>
- assert apartment1 != null
- assert apartment1.getAttribute("daySceneTimeFRIDAY").get().getValue().orElse("") == "08:30:00"
- assert sceneAgents != null
- assert sceneAgents.size() == 6
- assert timerAgents != null
- assert timerAgents.size() == 28
- }
-
- and: "the quartz scheduler is running and contains all the demo triggers with the correct cron expression"
- conditions.eventually {
- assert timerAgents.every {((TimerProtocol)agentService.getProtocolInstance(it.id)).cronScheduler != null}
- assert CronScheduler.scheduler != null
- assert CronScheduler.scheduler.isStarted()
- assert CronScheduler.scheduler.getJobKeys(GroupMatcher.anyJobGroup()).size() == timerAgents.size()
- }
-
- and: "the quartz job has the correct time"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- def timerProtocol = ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id))
- def jobDetail = timerProtocol.cronScheduler.scheduler.getJobDetail(jobKey)
- def triggers = timerProtocol.cronScheduler.scheduler.getTriggersOfJob(jobKey)
- assert jobDetail != null
- assert triggers.size() == 1
- assert triggers[0] instanceof CronTrigger
- def cronTrigger = (CronTrigger)triggers[0]
- assert cronTrigger.cronExpression == "0 30 8 ? * FRI *"
- }
-
- and: "all protocol linked attributes should be linked"
- conditions.eventually {
- assert timerAgents.every {
- ((TimerProtocol) agentService.getProtocolInstance(it.id)).linkedAttributes.size() == 2
- }
- }
-
- when: "a trigger is disabled"
- def disableScene = new AttributeEvent(managerTestSetup.apartment1Id, "daySceneEnabledFRIDAY", false)
- assetProcessingService.sendAttributeEvent(disableScene)
-
- then: "the corresponding cron job should be removed from the cron scheduler"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- def timerProtocol = ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id))
- def jobDetail = timerProtocol.cronScheduler.scheduler.getJobDetail(jobKey)
- def triggers = timerProtocol.cronScheduler.scheduler.getTriggersOfJob(jobKey)
- assert jobDetail == null
- assert triggers.isEmpty()
- }
-
- and: "all protocol linked attributes should be re-linked"
- conditions.eventually {
- assert timerAgents.every {
- ((TimerProtocol) agentService.getProtocolInstance(it.id)).linkedAttributes.size() == 2
- }
- }
-
- when: "the trigger is re-enabled"
- def enableScene = new AttributeEvent(managerTestSetup.apartment1Id, "daySceneEnabledFRIDAY", true)
- assetProcessingService.sendAttributeEvent(enableScene)
-
- then: "the quartz job should be recreated and have the correct time"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- def timerProtocol = ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id))
- def jobDetail = timerProtocol.cronScheduler.scheduler.getJobDetail(jobKey)
- def triggers = timerProtocol.cronScheduler.scheduler.getTriggersOfJob(jobKey)
- assert jobDetail != null
- assert triggers.size() == 1
- assert triggers[0] instanceof CronTrigger
- def cronTrigger = (CronTrigger)triggers[0]
- assert cronTrigger.cronExpression == "0 30 8 ? * FRI *"
- }
-
- when: "a trigger time is modified"
- def modifyTime = new AttributeEvent(managerTestSetup.apartment1Id, "daySceneTimeFRIDAY", "04:00:00")
- assetProcessingService.sendAttributeEvent(modifyTime)
-
- then: "the quartz job should have the new trigger time"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- def timerProtocol = ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id))
- def jobDetail = timerProtocol.cronScheduler.scheduler.getJobDetail(jobKey)
- def triggers = timerProtocol.cronScheduler.scheduler.getTriggersOfJob(jobKey)
- assert jobDetail != null
- assert triggers.size() == 1
- assert triggers[0] instanceof CronTrigger
- def cronTrigger = (CronTrigger)triggers[0]
- assert cronTrigger.cronExpression == "0 0 4 ? * FRI *"
- }
-
- when: "an attribute is added that links to a timers cron expression"
- apartment1.addAttributes(
- new Attribute<>("daySceneCronFRIDAY", ValueType.TEXT)
- .addOrReplaceMeta(
- new MetaItem<>(MetaItemType.AGENT_LINK, new TimerAgent.TimerAgentLink(timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}.id)
- .setTimerValue(TimerValue.CRON_EXPRESSION)
- )
- )
- )
- apartment1 = assetStorageService.merge(apartment1)
-
- then: "the attributes value should contain the timers cron expression"
- conditions.eventually {
- apartment1 = assetStorageService.find(apartment1.id, true)
- assert apartment1.getAttribute("daySceneCronFRIDAY").isPresent()
- assert apartment1.getAttribute("daySceneCronFRIDAY").get().getValue().isPresent()
- assert apartment1.getAttribute("daySceneCronFRIDAY").get().getValue().get() == "0 0 4 ? * FRI *"
- }
-
- when: "the trigger cron expression is modified"
- def modifyCron = new AttributeEvent(managerTestSetup.apartment1Id, "daySceneCronFRIDAY", "0 0 4 ? * MON,FRI *")
- assetProcessingService.sendAttributeEvent(modifyCron)
-
- then: "the quartz job should have the new cron expression"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- def timerProtocol = ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id))
- def jobDetail = timerProtocol.cronScheduler.scheduler.getJobDetail(jobKey)
- def triggers = timerProtocol.cronScheduler.scheduler.getTriggersOfJob(jobKey)
- assert jobDetail != null
- assert triggers.size() == 1
- assert triggers[0] instanceof CronTrigger
- def cronTrigger = (CronTrigger)triggers[0]
- assert cronTrigger.cronExpression == "0 0 4 ? * MON,FRI *"
- }
-
- when: "a timer action is executed"
- ((TimerProtocol)agentService.getProtocolInstance(timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}.id)).doTriggerAction()
-
- then: "the linked macro should have been executed"
- conditions.eventually {
- apartment1 = assetStorageService.find(apartment1.id, true)
- assert apartment1.getAttribute("dayScene").get().getValue().get() == AttributeExecuteStatus.COMPLETED
- assert apartment1.getAttribute("lastExecutedScene").get().getValue().get() == "DAY"
- }
-
- when: "a timer is deleted"
- assetStorageService.delete([timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}.id])
-
- then: "the corresponding cron job should be removed from the cron scheduler"
- conditions.eventually {
- def daySceneFridayTimer = timerAgents.find {it.name == "Timer agent Day scene FRIDAY"}
- assert daySceneFridayTimer != null
- def timerId = TimerProtocol.getTimerId(daySceneFridayTimer)
- def jobKey = JobKey.jobKey("cronJob1", timerId)
- assert ((TimerProtocol)agentService.getProtocolInstance(daySceneFridayTimer.id)) == null
- assert CronScheduler.scheduler.getJobDetail(jobKey) == null
- }
- }
-}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy
deleted file mode 100644
index ead1fe9e2..000000000
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy
+++ /dev/null
@@ -1,131 +0,0 @@
-package org.openremote.test.rules.residence
-
-import org.openremote.manager.asset.AssetProcessingService
-import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.rules.RulesEngine
-import org.openremote.manager.rules.RulesService
-import org.openremote.manager.rules.RulesetStorageService
-import org.openremote.manager.setup.SetupService
-import org.openremote.test.setup.ManagerTestSetup
-import org.openremote.model.asset.impl.BuildingAsset
-import org.openremote.model.asset.impl.RoomAsset
-import org.openremote.model.attribute.AttributeEvent
-import org.openremote.model.attribute.AttributeExecuteStatus
-import org.openremote.model.rules.AssetRuleset
-import org.openremote.model.rules.Ruleset
-import org.openremote.model.rules.TemporaryFact
-import org.openremote.test.ManagerContainerTrait
-import spock.lang.Specification
-import spock.util.concurrent.PollingConditions
-
-import java.time.DayOfWeek
-
-import static java.util.concurrent.TimeUnit.DAYS
-import static java.util.concurrent.TimeUnit.HOURS
-import static org.openremote.test.setup.ManagerTestSetup.DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES
-
-class ResidenceVacationModeTest extends Specification implements ManagerContainerTrait {
-
- def "Start and end vacation mode"() {
-
- given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 20, delay: 0.2)
- def expirationMillis = TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS
- TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = 500
- def container = startContainer(defaultConfig(), defaultServices())
- def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
- def rulesService = container.getService(RulesService.class)
- def assetProcessingService = container.getService(AssetProcessingService.class)
- def assetStorageService = container.getService(AssetStorageService.class)
- def rulesetStorageService = container.getService(RulesetStorageService.class)
- RulesEngine apartment1Engine
-
- and: "the clock is stopped for testing purposes"
- stopPseudoClock()
-
- and: "scenes are added to apartment1 rooms"
- def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id) as BuildingAsset
- def apartment1Livingroom = assetStorageService.find(managerTestSetup.apartment1LivingroomId) as RoomAsset
- def apartment1Kitchen = assetStorageService.find(managerTestSetup.apartment1KitchenId) as RoomAsset
- def apartment1Hallway = assetStorageService.find(managerTestSetup.apartment1HallwayId) as RoomAsset
- ManagerTestSetup.createDemoApartmentScenes(
- assetStorageService,
- apartment1,
- ManagerTestSetup.DEMO_APARTMENT_SCENES,
- apartment1Livingroom, apartment1Kitchen, apartment1Hallway)
-
- and: "some rules"
- Ruleset ruleset = new AssetRuleset(
- managerTestSetup.apartment1Id,
- "Demo Apartment - Vacation Mode",
- Ruleset.Lang.GROOVY,
- getClass().getResource("/org/openremote/test/rules/ResidenceVacationMode.groovy").text)
- rulesetStorageService.merge(ruleset)
-
- expect: "the rule engines to become available and be running"
- conditions.eventually {
- apartment1Engine = rulesService.assetEngines.get(managerTestSetup.apartment1Id)
- assert apartment1Engine != null
- assert apartment1Engine.isRunning()
- assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES
-
- // The macro should be ready
- def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert asset.getAttribute("dayScene").flatMap{it.getValueAs(AttributeExecuteStatus.class)}.orElse(null) == AttributeExecuteStatus.READY
- }
-
- when: "the vacation days are set to 5"
- double fiveDaysInFuture = getClockTimeOf(container) + (5 * 24 * 60 * 60 * 1000)
- assetProcessingService.sendAttributeEvent(new AttributeEvent(
- managerTestSetup.apartment1Id, "vacationUntil", fiveDaysInFuture
- ))
-
- then: "the DAY scene should be executed and scene timers disabled"
- conditions.eventually {
- def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert asset.getAttribute("dayScene").flatMap{it.getValueAs(AttributeExecuteStatus.class)}.orElse(null) == AttributeExecuteStatus.COMPLETED
- assert !asset.getAttribute("sceneTimerEnabled").flatMap{it.value}.orElse(false)
- DayOfWeek.values().each {
- assert !asset.getAttribute("morningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("daySceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("eveningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("nightSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- }
- }
-
- when: "time advanced to the next day"
- advancePseudoClock(24, HOURS, container)
-
- then: "vacation mode is still on"
- conditions.eventually {
- def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert asset.getAttribute("vacationUntil").flatMap{it.value}.orElse(0d) == fiveDaysInFuture
- assert !asset.getAttribute("sceneTimerEnabled").flatMap{it.value}.orElse(false)
- DayOfWeek.values().each {
- assert !asset.getAttribute("morningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("daySceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("eveningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert !asset.getAttribute("nightSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- }
- }
-
- when: "time advanced a few days"
- advancePseudoClock(5, DAYS, container)
-
- then: "vacation mode is off and scene timers are enabled"
- conditions.eventually {
- def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert !asset.getAttribute("vacationUntil").get().getValue().isPresent()
- assert asset.getAttribute("sceneTimerEnabled").flatMap{it.value}.orElse(false)
- DayOfWeek.values().each {
- assert asset.getAttribute("morningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert asset.getAttribute("daySceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert asset.getAttribute("eveningSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- assert asset.getAttribute("nightSceneEnabled" + it.name()).flatMap{it.value}.orElse(false)
- }
- }
-
- cleanup: "the static rules time variable is reset"
- TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = expirationMillis
- }
-}