100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added Macro protocol and command
Rich Turnerc1b1b23fca42
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.javanew file mode 100644index 000000000..a3df229a3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java@@ -0,0 +1,240 @@+/*+ * 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.macro;++import elemental.json.JsonValue;+import org.openremote.agent3.protocol.AbstractProtocol;+import org.openremote.container.Container;+import org.openremote.model.*;+import org.openremote.model.asset.macro.MacroAction;+import org.openremote.model.asset.macro.MacroAttribute;+import org.openremote.model.asset.macro.MacroAttributeCommand;+import org.openremote.model.asset.thing.ThingAttribute;++import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.logging.Level;+import java.util.logging.Logger;++/**+ * This protocol is responsible for executing macros.+ *+ * It expects a {@link MacroAttributeCommand} or the super type{@link AttributeCommand}+ * as the attribute event value on the sendToActuator. The protocol will then execute+ * the command and store the command status in the attribute value.+ */+public class MacroProtocol extends AbstractProtocol {+ class MacroExecutionTask {+ AttributeRef attributeRef;+ List<MacroAction> actions;+ List<MacroAttributeCommand.Execution> schedule;+ boolean repeat;+ boolean cancelled;+ ScheduledFuture scheduledFuture;+ int iteration = -1;++ public MacroExecutionTask(AttributeRef attributeRef, List<MacroAction> actions, List<MacroAttributeCommand.Execution> schedule, boolean repeat) {+ this.attributeRef = attributeRef;+ this.actions = actions;+ this.schedule = schedule;+ this.repeat = repeat;+ }++ void start() {+ synchronized (scheduleMap) {+ scheduleMap.put(attributeRef, this);+ }++ // Update the command Status of this attribute+ onSensorUpdate(new AttributeState(attributeRef, CommandStatus.ACTIVE.asJsonValue()));+ run();+ }++ void cancel() {+ LOG.fine("Macro Execution cancel");+ scheduledFuture.cancel(false);+ cancelled = true;+ synchronized (scheduleMap) {+ scheduleMap.remove(attributeRef);+ }++ // Update the command Status of this attribute+ onSensorUpdate(new AttributeState(attributeRef, CommandStatus.CANCELLED.asJsonValue()));+ }++ private void run() {+ if (cancelled) {+ return;+ }++ if (iteration >= 0) {+ // Process the execution+ MacroAttributeCommand.Execution execution = schedule.get(iteration);+ actions.forEach(action -> {+ // Look for override value in execution+ AttributeState overrideState = execution.getActionOverrides() == null ? null : execution.getActionOverrides()+ .stream()+ .filter(actionOverride -> actionOverride.getAttributeRef().equals(action.getAttributeState().getAttributeRef()))+ .findFirst()+ .orElse(null);++ AttributeState actionState = overrideState != null ? overrideState : action.getAttributeState();+ if (action.getDelay() > 0) {+ // TODO: Better handling of macro action delays - this is ok for short delays+ try {+ Thread.sleep(action.getDelay());+ } catch (InterruptedException e) {+ LOG.log(Level.WARNING, "Macro action was cancelled assume the thread is being terminated", e);+ return;+ }+ }++ // send attribute event+ sendAttributeUpdate(actionState);+ });+ }++ boolean isLast = iteration == schedule.size() - 1;+ boolean restart = isLast && repeat;++ if (restart) {+ iteration = 0;+ } else {+ iteration++;+ }++ if ((isLast && !restart)) {+ synchronized (scheduleMap) {+ scheduleMap.remove(attributeRef);+ }++ // Update the command Status of this attribute+ onSensorUpdate(new AttributeState(attributeRef, CommandStatus.COMPLETED.asJsonValue()));+ return;+ }++ // Get next execution delay+ Integer delay = schedule.get(iteration).getDelay();++ // Schedule the next iteration+ scheduledFuture = executor.schedule(this::run, delay != null && delay >= 0 ? delay : 0, TimeUnit.MILLISECONDS);+ }+ }++ private static final Logger LOG = Logger.getLogger(MacroProtocol.class.getName());+ protected final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();+ protected final Map<AttributeRef, List<MacroAction>> actionMap = new HashMap<>();+ protected final Map<AttributeRef, MacroExecutionTask> scheduleMap = new HashMap<>();++ @Override+ public void start(Container container) throws Exception {+ super.start(container);+ }++ @Override+ public String getProtocolName() {+ return MacroAttribute.PROTOCOL_NAME;+ }++ @Override+ protected void sendToActuator(AttributeEvent event) {+ AttributeRef attributeRef = event.getAttributeRef();++ // Check that incoming value is of type Attribute Command+ JsonValue value = event.getValue();+ MacroAttributeCommand macroCommand = MacroAttributeCommand.fromJsonValue(value);++ // Check if it's a cancellation request+ if (macroCommand.isCancel()) {+ LOG.fine("Request received to cancel macro execution: " + event);+ synchronized (scheduleMap) {+ MacroExecutionTask executionTask = scheduleMap.get(attributeRef);+ if (executionTask != null) {+ LOG.fine("Cancelling macro execution");+ executionTask.cancel();+ }+ }++ return;+ }++ List<MacroAction> actions;++ synchronized (actionMap) {+ actions = actionMap.get(attributeRef);+ }++ if (actions == null || actions.size() == 0) {+ LOG.fine("No macro actions found for attribute event: " + event);+ return;+ }++ // If the executing command has provided schedule information then include+ // this in the execution of the macro actions+ List<MacroAttributeCommand.Execution> schedule = macroCommand.getSchedule();++ if (schedule == null) {+ // Push in an empty execution+ schedule = Collections.singletonList(new MacroAttributeCommand.Execution(0));+ }++ executeMacro(attributeRef, actions, schedule, macroCommand.isRepeat());+ }++ @Override+ protected void onAttributeAdded(ThingAttribute attribute) {+ // Protocol configuration is actually a MacroAttribute+ MacroAttribute macroAttribute = new MacroAttribute(attribute.getProtocolConfiguration());++ // Store the macro actions for later execution requests+ AttributeRef reference = attribute.getReference();+ List<MacroAction> actions = macroAttribute.getActions();++ synchronized (actionMap) {+ actionMap.put(reference, actions);+ }+ }++ @Override+ protected void onAttributeUpdated(ThingAttribute attribute) {+ onAttributeAdded(attribute);+ }++ @Override+ protected void onAttributeRemoved(ThingAttribute attribute) {+ // Store the macro actions for later execution requests+ AttributeRef reference = attribute.getReference();++ synchronized (actionMap) {+ actionMap.remove(reference);+ }+ }++ protected void executeMacro(AttributeRef attributeRef, List<MacroAction> actions, List<MacroAttributeCommand.Execution> schedule, boolean repeat) {+ MacroExecutionTask task = new MacroExecutionTask(attributeRef, actions, schedule, repeat);+ task.start();+ }+}diff --git a/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol b/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocolindex dfff5053e..1f446e296 100644--- a/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol+++ b/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol@@ -1 +1,2 @@-org.openremote.agent3.protocol.simulator.SimulatorProtocol\ No newline at end of file+org.openremote.agent3.protocol.simulator.SimulatorProtocol+org.openremote.agent3.protocol.macro.MacroProtocol\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/AttributeStates.java b/model/src/main/java/org/openremote/model/AttributeStates.javadeleted file mode 100644index 110fc1cd3..000000000--- a/model/src/main/java/org/openremote/model/AttributeStates.java+++ /dev/null@@ -1,58 +0,0 @@-/*- * Copyright 2016, 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.model;--import java.util.LinkedList;--/**- * A sequence of <code>[{@link AttributeState}, Seconds]</code> items, each lasting for the given duration.- * <p>- * Optionally, repeat the states when the last item has expired.- */-public class AttributeStates extends LinkedList<AttributeStates.Item> {-- public class Item {- final AttributeState attributeState;- final int delayNextSeconds;-- public Item(AttributeState attributeState, int delayNextSeconds) {- this.attributeState = attributeState;- this.delayNextSeconds = delayNextSeconds;- }-- public AttributeState getAttributeState() {- return attributeState;- }-- public int getDelayNextSeconds() {- return delayNextSeconds;- }- }-- final protected boolean repeat;-- public AttributeStates(boolean repeat) {- this.repeat = repeat;- }-- public boolean isRepeat() {- return repeat;- }-}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex f66dec883..359086cce 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -136,6 +136,11 @@ public enum AssetMeta {*/ENABLED(ASSET_META_NAMESPACE + ":enabled", new Access(true, false, true), JsonType.BOOLEAN),+ /**+ * Identifies a meta item as a {@link org.openremote.model.asset.macro.MacroAction}+ */+ MACRO_ACTION(ASSET_META_NAMESPACE + ":macroAction", new Access(true, false, true), JsonType.ARRAY),+/*** Marks an attribute as being an executable command*/diff --git a/model/src/main/java/org/openremote/model/asset/macro/MacroAction.java b/model/src/main/java/org/openremote/model/asset/macro/MacroAction.javanew file mode 100644index 000000000..5a0c23336--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/macro/MacroAction.java@@ -0,0 +1,77 @@+/*+ * 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.model.asset.macro;++import elemental.json.Json;+import elemental.json.JsonObject;+import elemental.json.JsonValue;+import org.openremote.model.AttributeState;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AssetMeta;++public class MacroAction {+ protected AttributeState attributeState;+ protected int delay;++ public MacroAction(JsonObject jsonObject) {+ attributeState = new AttributeState(jsonObject.getObject("attributeState"));+ delay = new Double(jsonObject.getNumber("delay")).intValue();+ }++ public MacroAction(AttributeState attributeState, int delay) {+ this.attributeState = attributeState;+ this.delay = delay;+ }++ public AttributeState getAttributeState() {+ return attributeState;+ }++ public void setAttributeState(AttributeState attributeState) {+ this.attributeState = attributeState;+ }++ public int getDelay() {+ return delay;+ }++ public void setDelay(int delay) {+ this.delay = delay;+ }++ public JsonValue asJsonValue() {+ JsonObject jsonObect = Json.createObject();+ jsonObect.put("attributeState", attributeState != null ? attributeState.asJsonValue() : Json.create(null));+ jsonObect.put("delay", Json.create(delay));+ return jsonObect;+ }++ public MetaItem asMetaItem() {+ return new MetaItem(AssetMeta.MACRO_ACTION, asJsonValue());+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "attributeState='" + attributeState + '\'' ++ ", delay='" + delay + '\'' ++ '}';+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.java b/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.javanew file mode 100644index 000000000..a13245cfb--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.java@@ -0,0 +1,92 @@+/*+ * 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.model.asset.macro;++import elemental.json.JsonObject;+import org.openremote.model.Meta;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AbstractAssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.agent.ProtocolConfiguration;+import org.openremote.model.util.JsonUtil;++import java.util.Arrays;+import java.util.List;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;++public class MacroAttribute extends ProtocolConfiguration {+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";++ public MacroAttribute(String name) {+ super(name, PROTOCOL_NAME);+ }++ public MacroAttribute(String assetId, String name) {+ super(assetId, name, PROTOCOL_NAME);+ }++ public MacroAttribute(String assetId, String name, JsonObject jsonObject) {+ super(assetId, name, jsonObject);+ }++ public MacroAttribute(ProtocolConfiguration protocolConfiguration) {+ super(protocolConfiguration);+ }++ public List<MacroAction> getActions() {+ return Arrays.stream(getMeta().all())+ .filter(metaItem -> metaItem.getName().equals(AssetMeta.MACRO_ACTION.getName()))+ .map(metaItem -> new MacroAction(metaItem.getValueAsObject()))+ .collect(Collectors.toList());+ }++ public void setActions(List<MacroAction> actions) {+ Meta meta = getMeta() != null ? getMeta() : new Meta();+ meta = meta.removeAll(AssetMeta.MACRO_ACTION);+ Meta finalMeta = meta;+ actions.forEach(action -> finalMeta.add(action.asMetaItem()));+ }++ public void addAction(MacroAction action) {+ Meta meta = getMeta() != null ? getMeta() : new Meta();+ meta.add(action.asMetaItem());+ setMeta(meta);+ }++ public void removeAction(MacroAction action) {+ if (!hasMeta()) {+ return;+ }++ MetaItem[] metaItems = getMeta().all();+ IntStream.range(0, metaItems.length)+ .filter(i -> metaItems[i].getName().equals(AssetMeta.MACRO_ACTION.getName()))+ .filter(i -> JsonUtil.equals(metaItems[i].getValueAsObject(), action.asJsonValue()))+ .forEach(i -> getMeta().remove(i));+ }++ @Override+ public String getProtocolName() {+ return PROTOCOL_NAME;+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/macro/MacroAttributeCommand.java b/model/src/main/java/org/openremote/model/asset/macro/MacroAttributeCommand.javanew file mode 100644index 000000000..7b731a019--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/macro/MacroAttributeCommand.java@@ -0,0 +1,176 @@+/*+ * 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.model.asset.macro;++import elemental.json.*;+import org.openremote.model.AttributeState;+import org.openremote.model.AttributeCommand;++import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++public class MacroAttributeCommand extends AttributeCommand {+ public static class Execution {+ protected List<AttributeState> actionOverrides;+ protected Integer delay;++ public Execution() {+ }++ public Execution(List<AttributeState> actionOverrides, Integer delay) {+ this.actionOverrides = actionOverrides;+ this.delay = delay;+ }++ public Execution(Integer delay) {+ this.delay = delay;+ }++ public Execution(List<AttributeState> actionOverrides) {+ this.actionOverrides = actionOverrides;+ }++ public List<AttributeState> getActionOverrides() {+ return actionOverrides;+ }++ public void setActionOverrides(List<AttributeState> actionOverrides) {+ this.actionOverrides = actionOverrides;+ }++ public Integer getDelay() {+ return delay;+ }++ public void setDelay(Integer delay) {+ this.delay = delay;+ }++ public JsonValue asJsonValue() {+ JsonObject jsonObject = Json.createObject();++ if (actionOverrides != null) {+ JsonArray jsonArray = Json.createArray();++ IntStream.range(0, actionOverrides.size())+ .forEach(i -> jsonArray.set(i, actionOverrides.get(i).asJsonValue()));++ jsonObject.put("actionOverrides", jsonArray);+ } else {+ jsonObject.put("actionOverrides", Json.createNull());+ }++ jsonObject.put("delay", delay == null ? Json.createNull() : Json.create(delay));++ return jsonObject;+ }++ public static Execution fromJsonValue(JsonValue jsonValue) {+ if (!(jsonValue instanceof JsonObject)) {+ return null;+ }++ JsonObject jsonObject = (JsonObject)jsonValue;+ List<AttributeState> actionOverrides = null;+ Integer delay = null;++ if (jsonObject.hasKey("actionOverrides")) {+ JsonArray actionOverridesArray = jsonObject.hasKey("actionOverrides") && !jsonObject.get("actionOverrides").jsEquals(Json.createNull()) ? jsonObject.getArray("actionOverrides") : null;+ if (actionOverridesArray != null && actionOverridesArray.length() > 0) {+ actionOverrides = new ArrayList<>(actionOverridesArray.length());+ List<AttributeState> finalActionOverrides = actionOverrides;+ IntStream.range(0, actionOverridesArray.length())+ .forEach(i -> finalActionOverrides.add(i, new AttributeState(actionOverridesArray.get(i))));+ }+ }++ if (jsonObject.hasKey("delay")) {+ JsonValue value = jsonObject.get("delay");+ if (value != null && !(value instanceof JsonNull)) {+ delay = new Double(value.asNumber()).intValue();+ }+ }++ return new Execution(actionOverrides, delay);+ }+ }++ public MacroAttributeCommand() {+ this(false, false, (List<Execution>) null);+ }++ public MacroAttributeCommand(Execution execution) {+ this(false, execution);+ }++ public MacroAttributeCommand(boolean repeat, Execution execution) {+ this(repeat, false, Collections.singletonList(execution));+ }++ public MacroAttributeCommand(boolean repeat, boolean cancel, List<Execution> schedule) {+ super(repeat, cancel, scheduleAsJsonValue(schedule));+ }++ public List<Execution> getSchedule() {+ return scheduleFromJsonValue(getValue());+ }++ public void setSchedule(List<Execution> schedule) {+ setValue(scheduleAsJsonValue(schedule));+ }++ protected static JsonValue scheduleAsJsonValue(List<Execution> schedule) {+ if (schedule == null) {+ return Json.createNull();+ }++ JsonArray jsonArray = Json.createArray();+ IntStream.range(0, schedule.size())+ .forEach(i -> jsonArray.set(i, schedule.get(i).asJsonValue()));++ return jsonArray;+ }++ protected static List<Execution> scheduleFromJsonValue(JsonValue jsonValue) {+ if (!(jsonValue instanceof JsonArray)) {+ return null;+ }+ JsonArray jsonArray = (JsonArray)jsonValue;+ return IntStream.range(0, jsonArray.length())+ .mapToObj(i -> Execution.fromJsonValue(jsonArray.get(i)))+ .collect(Collectors.toList());+ }++ public JsonValue asJsonValue() {+ return super.asJsonValue();+ }++ public static MacroAttributeCommand fromJsonValue(JsonValue jsonValue) {+ if (!(jsonValue instanceof JsonObject)) {+ return null;+ }+ JsonObject jsonObject = (JsonObject)jsonValue;++ return new MacroAttributeCommand(jsonObject.getBoolean("repeat"), jsonObject.getBoolean("cancel"), scheduleFromJsonValue(jsonObject.getArray("value")));+ }+}