Skip to content

armgit / core

Public Imported from GitHub
0

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

First init commit for new Controller Protocol

jerome.vervier5b8c209f3a98
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/Controller.java b/agent/src/main/java/org/openremote/agent/protocol/controller/Controller.java
new file mode 100644
index 000000000..dd5efec94
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/Controller.java
@@ -0,0 +1,75 @@
+package org.openremote.agent.protocol.controller;
+
+import org.openremote.model.attribute.AttributeRef;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * Controller class represent a Controller defined in a Manager Agent and store all sensors and commands linked to that Controller agent.
+ *
+ * <p>
+ * Date : 19-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class Controller {
+ private String controllerConfigName;
+
+ private String deviceId;
+
+ private Map<AttributeRef, ControllerSensor> sensorsList = new HashMap<>();
+ private Map<AttributeRef, ControllerCommand> commandsList = new HashMap<>();
+
+ public Controller(String controllerConfigName, String deviceId) {
+ this.controllerConfigName = controllerConfigName;
+ this.deviceId = deviceId;
+ }
+
+ public void addSensor(AttributeRef attributeRef, ControllerSensor sensor) {
+ this.sensorsList.put(attributeRef, sensor);
+ }
+
+ public void addCommand(AttributeRef attributeRef, ControllerCommand command) {
+ this.commandsList.put(attributeRef, command);
+ }
+
+ public ControllerCommand getCommand(AttributeRef attributeRef) {
+ return this.commandsList.get(attributeRef);
+ }
+
+ public Set<Map.Entry<AttributeRef, ControllerSensor>> getSensorsListForDevice(String deviceName) {
+ return this.sensorsList.entrySet().stream().filter(entry -> entry.getValue().getDeviceName().equals(deviceName)).collect(Collectors.toSet());
+ }
+
+ public String getDeviceId() {
+ return this.deviceId;
+ }
+
+ public String getControllerConfigName() {
+ return this.controllerConfigName;
+ }
+
+ public void removeAttributeRef(AttributeRef attributeRef) {
+ this.commandsList.remove(attributeRef);
+ this.sensorsList.remove(attributeRef);
+ }
+
+ /**
+ * Collect every sensorName linked to a deviceName. Look into {@link #sensorsList}.
+ *
+ * @param deviceName device name for which we're looking for sensor's
+ * @return
+ */
+ public List<String> collectSensorNameLinkedToDeviceName(String deviceName) {
+ List<String> sensorNameList = new ArrayList<>();
+
+ for (ControllerSensor controllerSensor : this.sensorsList.values()) {
+ if (controllerSensor.getDeviceName().equals(deviceName) && !sensorNameList.contains(controllerSensor.getSensorName())) {
+ sensorNameList.add(controllerSensor.getSensorName());
+ }
+ }
+
+ return sensorNameList;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerCommand.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerCommand.java
new file mode 100644
index 000000000..e338c49a1
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerCommand.java
@@ -0,0 +1,31 @@
+package org.openremote.agent.protocol.controller;
+
+/**
+ * ControllerCommand represent an executable command on the Controller
+ *
+ * Depending if the command to send to the Controller is based on META {@link ControllerProtocol#META_ATTRIBUTE_COMMAND_NAME } or {@link ControllerProtocol#META_ATTRIBUTE_COMMANDS_MAP}, we'll create an instance of ControllerCommand as {@link org.openremote.agent.protocol.controller.command.ControllerCommandBasic} or {@link org.openremote.agent.protocol.controller.command.ControllerCommandMapped}
+ *
+ * <p>
+ * Date : 31-Aug-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerCommand {
+ private String deviceName;
+
+ public ControllerCommand() {
+ this.deviceName = "";
+ }
+
+ public ControllerCommand(String deviceName) {
+ this.deviceName = deviceName;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public void setDeviceName(String deviceName) {
+ this.deviceName = deviceName;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java
new file mode 100644
index 000000000..b84997f34
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java
@@ -0,0 +1,637 @@
+/*
+ * 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.controller;
+
+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.util.TextUtil.*;
+
+import com.google.gwt.json.client.JSONArray;
+import com.google.gwt.json.client.JSONObject;
+import com.google.gwt.json.client.JSONParser;
+import com.google.gwt.json.client.JSONString;
+import org.apache.http.conn.HttpHostConnectException;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.openremote.agent.protocol.AbstractProtocol;
+import org.openremote.agent.protocol.controller.command.ControllerCommandBasic;
+import org.openremote.agent.protocol.controller.command.ControllerCommandMapped;
+import org.openremote.agent.protocol.http.HttpClientProtocol;
+import org.openremote.agent.protocol.http.WebTargetBuilder;
+import org.openremote.container.Container;
+import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ConnectionStatus;
+import org.openremote.model.attribute.*;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.StringValue;
+import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
+
+import javax.ws.rs.ProcessingException;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import java.net.ConnectException;
+import java.util.*;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * This is a Controller 2.5 protocol to communicate with a running Controller 2.5 instance and getting sensor's status and executing commands.
+ * <p>
+ * Necessary META for Agent setup is {@link #META_PROTOCOL_BASE_URI} and if a basic authentication is active on Controller instance :
+ * {@link #META_PROTOCOL_USERNAME} - {@link #META_PROTOCOL_PASSWORD}
+ * <p>
+ * The protocol communicate with Controller by using Controller REST API.
+ * <p>
+ * The protocol manage two kinds of request :
+ * <ul>
+ * <li>A set of polling requests (one by controller/device name couple) {@link #pollingSensorList}. For each request we just wait for a response 200 (new status) or 403 (timeout after 60 seconds) and relaunch the
+ * same request as soon as we have one of those two responses.</li>
+ * <li>Executing commands provided by Write Attribute with necessary information. There is different kind of situations explained in
+ * {@link org.openremote.agent.protocol.controller.ControllerCommand}</li>
+ * </ul>
+ * <p>
+ *
+ * Two cases are considered :
+ * <ul>
+ * <li>A sensor : if we want to link an attribute to a controller 2.5 sensor to get status we should create an Attribute with proper type
+ * considering the situation (temperature, time,...) and two necessary META {@link #META_ATTRIBUTE_DEVICE_NAME} and
+ * {@link #META_ATTRIBUTE_SENSOR_NAME}</li>
+ * <li>A command : if we want to execute a command on a controller 2.5, we create an attribute with the following available META (see details
+ * in {@link org.openremote.agent.protocol.controller.ControllerCommand}) :
+ * {@link #META_ATTRIBUTE_DEVICE_NAME} or {@link #META_ATTRIBUTE_COMMAND_DEVICE_NAME}, {@link #META_ATTRIBUTE_COMMAND_NAME} or
+ * {@link #META_ATTRIBUTE_COMMANDS_MAP}</li>
+ * </ul>
+ * <p>
+ * <p>
+ * Date : 24-Aug-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerProtocol extends AbstractProtocol {
+
+ private static final Logger LOG = Logger.getLogger(ControllerProtocol.class.getName());
+
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":controllerClient";
+
+ /*--------------- META ITEMS TO BE USED ON PROTOCOL CONFIGURATIONS ---------------*/
+ /**
+ * Base URI for all requests to this server
+ */
+ public static final String META_PROTOCOL_BASE_URI = PROTOCOL_NAME + ":baseUri";
+ /**
+ * Basic authentication username (string)
+ */
+ public static final String META_PROTOCOL_USERNAME = PROTOCOL_NAME + ":username";
+ /**
+ * Basic authentication password (string)
+ */
+ public static final String META_PROTOCOL_PASSWORD = PROTOCOL_NAME + ":password";
+
+ /*--------------- META ITEMS TO BE USED ON LINKED ATTRIBUTES ---------------*/
+ /**
+ * Path to query Controller :
+ * <p>
+ * - status : {@link #META_PROTOCOL_BASE_URI}/devices/{@link #META_ATTRIBUTE_DEVICE_NAME}/status?name={@link #META_ATTRIBUTE_SENSOR_NAME}
+ * - execute command : {@link #META_PROTOCOL_BASE_URI}/devices/{@link #META_ATTRIBUTE_DEVICE_NAME}/commands?name={COMMAND_TO_EXECUTE_DEPENDING_CASE}
+ * - polling : {@link #META_PROTOCOL_BASE_URI}/devices/{@link #META_ATTRIBUTE_DEVICE_NAME}/polling/<DeviceIDFromController/>?name={@link #META_ATTRIBUTE_SENSOR_NAME}&name={@link #META_ATTRIBUTE_SENSOR_NAME}
+ * <p>
+ * For Polling, a global set of all sensor_name has to be maintained as Attribute are added. Those sensor_name will be grouped by device_name
+ * such that we can group them together.
+ * <p>
+ * /
+ * <p>
+ * /**
+ * Device name to query on Controller
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_DEVICE_NAME = PROTOCOL_NAME + ":deviceName";
+ /**
+ * Relative path to endpoint on the server; supports dynamic value insertion, see class javadoc for details
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_SENSOR_NAME = PROTOCOL_NAME + ":sensorName";
+ /**
+ * A command could be execute on a different device name than the device name used for sensor status
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_COMMAND_DEVICE_NAME = PROTOCOL_NAME + ":commandDeviceName";
+ /**
+ * A command name
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_COMMAND_NAME = PROTOCOL_NAME + ":commandName";
+ /**
+ * Relative path to endpoint on the server; supports dynamic value insertion, see class javadoc for details
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_COMMANDS_MAP = PROTOCOL_NAME + ":commandsMap";
+ public static final int HEARTBEAT_DELAY_SECONDS = 5;
+
+ protected static final List<MetaItemDescriptorImpl> PROTOCOL_META_ITEM_DESCRIPTORS = Arrays
+ .asList(new MetaItemDescriptorImpl("PROTOCOL_CONTROLLER_BASE_URI", META_PROTOCOL_BASE_URI, ValueType.STRING, true,
+ REGEXP_PATTERN_BASIC_HTTP_URL, MetaItemDescriptor.PatternFailure.HTTP_URL.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_HTTP_CLIENT_USERNAME", META_PROTOCOL_USERNAME, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY_NO_WHITESPACE,
+ MetaItemDescriptor.PatternFailure.STRING_EMPTY_OR_CONTAINS_WHITESPACE.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_HTTP_CLIENT_PASSWORD", META_PROTOCOL_PASSWORD, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY_NO_WHITESPACE,
+ MetaItemDescriptor.PatternFailure.STRING_EMPTY_OR_CONTAINS_WHITESPACE.name(), 1, null, false));
+
+ public static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Arrays
+ .asList(new MetaItemDescriptorImpl("PROTOCOL_DEVICE_NAME", META_ATTRIBUTE_DEVICE_NAME, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY, MetaItemDescriptor.PatternFailure.STRING_EMPTY.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_SENSOR_NAME", META_ATTRIBUTE_SENSOR_NAME, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY, MetaItemDescriptor.PatternFailure.STRING_EMPTY.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_COMMAND_DEVICE_NAME", META_ATTRIBUTE_COMMAND_DEVICE_NAME, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY, MetaItemDescriptor.PatternFailure.STRING_EMPTY.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_COMMAND_NAME", META_ATTRIBUTE_COMMAND_NAME, ValueType.STRING, false,
+ REGEXP_PATTERN_STRING_NON_EMPTY, MetaItemDescriptor.PatternFailure.STRING_EMPTY.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_COMMANDS_MAP", META_ATTRIBUTE_COMMANDS_MAP, ValueType.OBJECT, false, null, null, 1, null,
+ false));
+
+ /*--------------- Protocol attributes ---------------*/
+ public static final String PROTOCOL_DISPLAY_NAME = "Controller Client";
+ public static final String PROTOCOL_VERSION = "1.0";
+
+ /**
+ * A unique ID to use for polling (see Controller 2.5 polling HTTP API)
+ */
+ public final String DEVICEBASE = "OR3ControllerProtocol";
+
+ private Map<PollingKey, ScheduledFuture> pollingSensorList = new HashMap<>();
+
+ private Map<AttributeRef, Controller> controllersMap = new HashMap<>();
+ private Map<AttributeRef, ResteasyWebTarget> controllersTargetMap = new HashMap<>();
+ private Map<AttributeRef, ScheduledFuture> controllerHeartbeat = new HashMap<>();
+
+ @Override
+ public void init(Container container) throws Exception {
+ super.init(container);
+ WebTargetBuilder.setExecutorService(executorService);
+ }
+
+ @Override
+ protected void doStop(Container container) {
+ WebTargetBuilder.close();
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return new ArrayList<>(PROTOCOL_META_ITEM_DESCRIPTORS);
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ List<MetaItemDescriptor> descriptors = new ArrayList<>(super.getLinkedAttributeMetaItemDescriptors());
+ descriptors.addAll(ATTRIBUTE_META_ITEM_DESCRIPTORS);
+ return descriptors;
+ }
+
+ @Override
+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ String baseURL = protocolConfiguration.getMetaItem(META_PROTOCOL_BASE_URI).flatMap(AbstractValueHolder::getValueAsString)
+ .orElseThrow(() -> new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_BASE_URI));
+
+ WebTargetBuilder webTargetBuilder = new WebTargetBuilder(baseURL);
+
+ String username = protocolConfiguration.getMetaItem(META_PROTOCOL_USERNAME).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
+ String password = protocolConfiguration.getMetaItem(META_PROTOCOL_PASSWORD).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
+
+ if (username != null && password != null) {
+ webTargetBuilder.setBasicAuthentication(username, password);
+ }
+
+ controllersTargetMap.put(protocolConfiguration.getReferenceOrThrow(), webTargetBuilder.build());
+
+ controllersMap.put(protocolConfiguration.getReferenceOrThrow(), new Controller(protocolConfiguration.getName().orElse("NO_NAME"),this.DEVICEBASE + "_" + protocolConfiguration.getName().orElse("NO_NAME") + "_" + protocolConfiguration.getAssetId().orElse("NO_ID")));
+
+ this.updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.DISCONNECTED);
+
+ controllerHeartbeat.put(protocolConfiguration.getReferenceOrThrow(), this.executorService.scheduleWithFixedDelay(() -> this.executeHeartbeat(protocolConfiguration.getReferenceOrThrow(),
+ response -> onHeartbeatResponse(protocolConfiguration.getReferenceOrThrow(), response)), 0, HEARTBEAT_DELAY_SECONDS,
+ TimeUnit.SECONDS));
+ }
+
+ @Override
+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ controllersMap.remove(protocolConfiguration.getReferenceOrThrow());
+ controllersTargetMap.remove(protocolConfiguration.getReferenceOrThrow());
+ controllerHeartbeat.remove(protocolConfiguration.getReferenceOrThrow());
+
+ for(PollingKey key : this.pollingSensorList.keySet()) {
+ if(key.getControllerAgentRef().equals(protocolConfiguration.getReferenceOrThrow())) {
+ this.pollingSensorList.remove(key);
+ }
+ }
+ }
+
+ @Override
+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ String deviceName = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_DEVICE_NAME, StringValue.class, true, true)
+ .map(StringValue::getString).orElse(null);
+
+ String sensorName = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_SENSOR_NAME, StringValue.class, false, true)
+ .map(StringValue::getString).orElse(null);
+
+ String commandDeviceName = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_COMMAND_DEVICE_NAME, StringValue.class, false, true)
+ .map(StringValue::getString).orElse(null);
+
+ String commandName = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_COMMAND_NAME, StringValue.class, false, true)
+ .map(StringValue::getString).orElse(null);
+
+ MultivaluedMap<String, String> commandsMap = Values
+ .getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_COMMANDS_MAP, ObjectValue.class, false, true)
+ .flatMap(objectValue -> HttpClientProtocol.getMultivaluedMap(objectValue, false)).orElse(null);
+
+ /**
+ * Build Sensor Status info for polling request
+ */
+ if (sensorName != null) {
+ controllersMap.get(protocolConfiguration.getReferenceOrThrow()).addSensor(attribute.getReferenceOrThrow(), new ControllerSensor(deviceName, sensorName));
+
+ //Properly stop previously existing polling on device name --> use of false parameter
+ PollingKey pollingKey = new PollingKey(deviceName, protocolConfiguration.getReferenceOrThrow());
+
+ if (pollingSensorList.containsKey(pollingKey)) {
+ pollingSensorList.get(pollingKey).cancel(true);
+ }
+
+ //Put new polling on a new device name or update previous
+ this.schedulePollingTask(pollingKey);
+ }
+
+ /**
+ * If linked Attribute contains command info, we build {@link org.openremote.agent.protocol.controller.ControllerCommand } depending on
+ * attribute information.
+ */
+ if (commandName != null || commandsMap != null) {
+ //If no command specific device name is set, then we're using deviceName
+ if (commandDeviceName == null && deviceName != null) {
+ commandDeviceName = deviceName;
+ }
+
+ if (commandName != null) {
+ controllersMap.get(protocolConfiguration.getReferenceOrThrow()).addCommand(attribute.getReferenceOrThrow(), new ControllerCommandBasic(commandDeviceName, commandName));
+ } else {
+ assert commandsMap != null && commandsMap.size() > 0;
+
+ controllersMap.get(protocolConfiguration.getReferenceOrThrow()).addCommand(attribute.getReferenceOrThrow(), new ControllerCommandMapped(commandDeviceName, computeCommandsMapFromMultiValue(commandsMap)));
+ }
+ }
+ }
+
+ /**
+ * Clearing elements if an attribute is unlinked from Controller Agent
+ * We don't have to clear {@link #pollingSensorList} as a check is done before scheduling task {@link #schedulePollingTask}
+ *
+ * @param attribute
+ * @param protocolConfiguration
+ */
+ @Override
+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ controllersMap.get(protocolConfiguration.getReferenceOrThrow()).removeAttributeRef(attribute.getReferenceOrThrow());
+ }
+
+ /**
+ * Write action on a linked attribute mean we execute a command on the Controller. It induce a HTTP request and manage it's return code. (No value
+ * is returned from the execution of a command)
+ *
+ * @param event
+ * @param protocolConfiguration
+ */
+ @Override
+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {
+ LOG.fine("### Process Linked Attribute Write");
+
+ AttributeRef attributeRef = event.getAttributeRef();
+
+ ControllerCommand controllerCommand = controllersMap.get(protocolConfiguration.getReferenceOrThrow()).getCommand(attributeRef);
+
+ HttpClientProtocol.HttpClientRequest request = RequestBuilder.buildCommandRequest(controllerCommand, event, this.controllersTargetMap.get(protocolConfiguration.getReferenceOrThrow()));
+
+ executeAttributeWriteRequest(request, protocolConfiguration.getReferenceOrThrow(), response -> onAttributeWriteResponse(response));
+ }
+
+ /**
+ * Convert commands map received as {@link MultivaluedMap} into a simple {@link Map}
+ *
+ * @param multivaluedMap
+ * @return
+ */
+ private Map<String, String> computeCommandsMapFromMultiValue(MultivaluedMap<String, String> multivaluedMap) {
+ Map<String, String> commandsMap = new HashMap<>();
+
+ for (Map.Entry<String, List<String>> entry : multivaluedMap.entrySet()) {
+ commandsMap.put(entry.getKey(), entry.getValue().get(0));
+ }
+
+ return commandsMap;
+ }
+
+ /**
+ * Compute the polling request for a given deviceName and controller. Method check all registered sensor's (linked to the Protocol) and collect all sensor's name
+ * to put them into polling request
+ *
+ * @param pollingKey Device name and controller agent reference on which we're polling
+ *
+ * @return {@link ScheduledFuture} task to keep a track on
+ */
+ private ScheduledFuture computePollingTask(PollingKey pollingKey) {
+ List<String> sensorNameList = this.controllersMap.get(pollingKey.getControllerAgentRef()).collectSensorNameLinkedToDeviceName(pollingKey.getDeviceName());
+
+ if(sensorNameList.isEmpty()) {
+ return null;
+ }
+
+ return executorService.schedule(() -> executePollingRequest(pollingKey, sensorNameList,
+ response -> onPollingResponse(pollingKey, sensorNameList, response)), 0);
+ }
+
+ /**
+ * Polling Request execution if a Connection issue (exception) occurs, we check the nature {@link #checkIfConnectionRefused(Exception, AttributeRef)}
+ *
+ * @param pollingKey device name and controller agent ref on which we'll polling
+ * @param sensorList list of sensors to catch status
+ * @param responseConsumer Consumer for onResponse treatment
+ */
+ private void executePollingRequest(PollingKey pollingKey, List<String> sensorList, Consumer<Response> responseConsumer) {
+ LOG.info("### Polling Request for device [device=" + pollingKey.getDeviceName() + ", sensors=" + this.formatSensors(sensorList) + "]");
+
+ HttpClientProtocol.HttpClientRequest httpClientRequest = RequestBuilder
+ .buildStatusPollingRequest(pollingKey.getDeviceName(), sensorList, this.controllersMap.get(pollingKey.getControllerAgentRef()).getDeviceId(), this.controllersTargetMap.get(pollingKey.getControllerAgentRef()));
+
+ Response response = null;
+
+ try {
+ response = httpClientRequest.invoke(null);
+
+ this.updateConnectionStatus(pollingKey.getControllerAgentRef(), ConnectionStatus.CONNECTED);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE,
+ "### Exception thrown whilst doing polling request [device=" + pollingKey.getDeviceName() + ", sensors=" + this.formatSensors(sensorList) + "]",
+ e);
+
+ this.checkIfConnectionRefused(e, pollingKey.getControllerAgentRef());
+ }
+
+ responseConsumer.accept(response);
+ }
+
+ /**
+ * Polling request should return three different responses :
+ * <ul>
+ * <li>OK (200) : new values are available for at least one of the sensor provided in queryParam</li>
+ * <li>TIMEOUET (408) : during the last 60 seconds following the start of the request, none of the sensors have new values</li>
+ * <li>Others : error</li>
+ * </ul>
+ * <p>
+ * In every case, we should start a new polling request directly. Only the 200 response induce an update of every linked attribute having a sensor
+ * status updated.
+ *
+ * @param pollingKey device name and controller agent ref on which polling has been execute
+ * @param sensorNameList sensors requested
+ * @param response Response received from request
+ */
+ private void onPollingResponse(PollingKey pollingKey, List<String> sensorNameList, Response response) {
+ if (response.getStatusInfo() == Response.Status.OK) {
+ String responseBodyAsString = response.readEntity(String.class);
+
+ LOG.info("### New sensors status received");
+ LOG.finer("### Polling request body response : " + responseBodyAsString);
+
+ JSONArray responseBody = (JSONArray) JSONParser.parseStrict(responseBodyAsString);
+
+ for (int i = 0; i < responseBody.size(); i++) {
+ JSONObject status = (JSONObject) responseBody.get(i);
+
+ JSONString name = (JSONString) status.get("name");
+ JSONString value = (JSONString) status.get("value");
+
+ /**
+ * For every sensors in the request body, find the linked attributeref and update value by calling {@link updateAttributeValue}
+ */
+ this.controllersMap.get(pollingKey.getControllerAgentRef()).getSensorsListForDevice(pollingKey.getDeviceName()).stream().filter(entry -> entry.getValue().getSensorName().equals(name.stringValue())).forEach(e -> this.updateAttributeValue(e.getKey(), value.stringValue()));
+ }
+ } else if (response.getStatusInfo() == Response.Status.REQUEST_TIMEOUT) {
+ LOG.info("### Timeout from polling no changes on Controller side given sensors [device=" + pollingKey.getDeviceName() + ", sensors=" + this
+ .formatSensors(sensorNameList) + "]");
+ } else {
+ LOG.severe("### Status code received error : " + response.getStatus() + " --> " + response.getStatusInfo().getReasonPhrase());
+ }
+
+ //No matter status code, we're continuing to pull
+ this.schedulePollingTask(pollingKey);
+ }
+
+ /**
+ * Update linked attribute with new value. We should take care of attribute type and format
+ *
+ * @param attributeRef
+ * @param value
+ */
+ private void updateAttributeValue(AttributeRef attributeRef, String value) {
+ AttributeValueType attributeType = this.linkedAttributes.get(attributeRef).getTypeOrThrow();
+
+ ValueType valueType = attributeType.getValueType();
+ try {
+ switch (valueType) {
+ case BOOLEAN:
+ this.updateLinkedAttribute(new AttributeState(attributeRef, Values.create(Boolean.parseBoolean(value))));
+ break;
+ case NUMBER:
+ this.updateLinkedAttribute(new AttributeState(attributeRef, Values.create(Double.parseDouble(value))));
+ break;
+ default:
+ this.updateLinkedAttribute(new AttributeState(attributeRef, Values.create(value)));
+ }
+ } catch(NumberFormatException e) {
+ LOG.severe("### Error in parsing NUMBER value [" + value + "]");
+ this.updateLinkedAttribute(new AttributeState(attributeRef, Values.create(0.0)));
+ }
+ }
+
+ private void executeAttributeWriteRequest(HttpClientProtocol.HttpClientRequest request, AttributeRef protocolRef, Consumer<Response> responseConsumer) {
+ Response response = null;
+
+ try {
+ response = request.invoke(null);
+
+ this.updateConnectionStatus(protocolRef, ConnectionStatus.CONNECTED);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "### Exception thrown whilst doing attribute write request", e);
+
+ this.checkIfConnectionRefused(e, protocolRef);
+ }
+
+ responseConsumer.accept(response);
+ }
+
+ private void onAttributeWriteResponse(Response response) {
+ if (response != null) {
+ LOG.fine("### Response from command (204 is a valid and success return) : " + response.getStatus());
+ if(response.getStatus() != 204) {
+ LOG.severe("### Linked attribute Write request return with an error (different from 204) : " + response.getStatusInfo().getReasonPhrase());
+ }
+ } else {
+ LOG.warning("### Response set to null");
+ }
+ }
+
+ private String formatSensors(List<String> sensorList) {
+ String sensors = "";
+
+ for (String sensor : sensorList) {
+ sensors += sensor + ",";
+ }
+
+ return sensors.substring(0, (sensors.length() - 1));
+ }
+
+ /**
+ * {@link #checkIfConnectionRefused(Exception, AttributeRef)} check the exception received from a request execution to see if it's not a
+ * connection issue. If it is the case, we'll start a heartbeat task until we get a new signal. Heartbeat is done evey
+ * {@link #HEARTBEAT_DELAY_SECONDS} seconds.
+ *
+ * @param e is the exception thrown by invoking the request
+ * @param protocolRef is the reference to Protocol configuration (to update status,...)
+ */
+ private void checkIfConnectionRefused(Exception e, AttributeRef protocolRef) {
+ if (e.getCause() instanceof HttpHostConnectException) {
+ HttpHostConnectException e2 = (HttpHostConnectException) e.getCause();
+
+ if (e2.getCause() instanceof ConnectException) {
+ ConnectException e3 = (ConnectException) e2;
+
+ LOG.log(Level.SEVERE, "### Connection refused : " + e3.getMessage());
+
+ this.updateConnectionStatus(protocolRef, ConnectionStatus.DISCONNECTED);
+
+ //Starting a heartbeat Task until connection is OK
+ if (!this.controllerHeartbeat.containsKey(protocolRef) || this.controllerHeartbeat.get(protocolRef).isCancelled()) {
+ this.controllerHeartbeat.put(protocolRef, this.executorService
+ .scheduleWithFixedDelay(() -> this.executeHeartbeat(protocolRef, response -> onHeartbeatResponse(protocolRef, response)),
+ 0, HEARTBEAT_DELAY_SECONDS, TimeUnit.SECONDS));
+ }
+ }
+ }
+ }
+
+ /**
+ * {@link #updateConnectionStatus(AttributeRef, ConnectionStatus)} method will update the Protocol Connection status (disconnected or connected)
+ * and will manage to relaunch all the polling requests if it move from disconnected to connected status.
+ *
+ * @param protocolRef
+ * @param status
+ */
+ private void updateConnectionStatus(AttributeRef protocolRef, ConnectionStatus status) {
+ ConnectionStatus previousStatus = this.getStatus(this.getLinkedProtocolConfiguration(protocolRef));
+
+ this.updateStatus(protocolRef, status);
+
+ if (status.equals(ConnectionStatus.CONNECTED) && previousStatus.equals(ConnectionStatus.DISCONNECTED)) {
+ //Relaunch polling
+ if(this.pollingSensorList.isEmpty()) {
+ LOG.info("### no polling to restart for " + protocolRef.getAttributeName() + "...");
+ }
+ for (PollingKey key : this.pollingSensorList.keySet()) {
+ if(key.getControllerAgentRef().equals(protocolRef)) {
+ this.schedulePollingTask(key);
+ }
+ }
+ }
+
+ if (status.equals(ConnectionStatus.DISCONNECTED)) {
+ for (ScheduledFuture task : this.pollingSensorList.values()) {
+ task.cancel(true);
+ }
+ }
+ }
+
+ /**
+ * Hearbeat is used when connection with Controller 2.x is lost and is running until connection is back
+ *
+ * @param protocolRef
+ * @param responseConsumer
+ */
+ private void executeHeartbeat(AttributeRef protocolRef, Consumer<Response> responseConsumer) {
+ LOG.info("### Heartbeat check on " + protocolRef.getAttributeName() + "...");
+
+ HttpClientProtocol.HttpClientRequest checkRequest = RequestBuilder.buildCheckRequest(this.controllersTargetMap.get(protocolRef));
+
+ Response response = null;
+
+ try {
+ response = checkRequest.invoke(null);
+ } catch (ProcessingException e) {
+ LOG.log(Level.SEVERE, "### Check for " + this.controllersMap.get(protocolRef).getControllerConfigName() + " doesn't succeed", e);
+ }
+
+ responseConsumer.accept(response);
+ }
+
+ private void onHeartbeatResponse(AttributeRef protocolRef, Response response) {
+ //if we don't have any connection issue, we stop the heartbeat check
+ if (response != null && (response.getStatusInfo().equals(Response.Status.OK) || response.getStatusInfo().equals(Response.Status.FOUND))) {
+ LOG.info("### Heartbeat check on " + protocolRef.getAttributeName() + " succeed !");
+ this.updateConnectionStatus(protocolRef, ConnectionStatus.CONNECTED);
+ //cancel has to be the last step
+ LOG.info("### Stop Heartbeat task for " + protocolRef.getAttributeName());
+ this.controllerHeartbeat.get(protocolRef).cancel(true);
+ } else {
+ if (response != null) {
+ LOG.severe("### Heartbeat check response is " + response.getStatus());
+ }
+ LOG.severe("### Heartbeat check on " + protocolRef.getAttributeName() + " failed !");
+ }
+ }
+
+ /**
+ * Scheduling of a polling request
+ *
+ * We check if there is sensor to poll for the given device name.
+ *
+ * @param key
+ */
+ private void schedulePollingTask(PollingKey key) {
+ ScheduledFuture scheduledFuture = computePollingTask(key);
+
+ if(scheduledFuture != null) {
+ pollingSensorList.put(key, scheduledFuture);
+ }
+ }
+
+ @Override
+ public String getProtocolName() {
+ return PROTOCOL_NAME;
+ }
+
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return PROTOCOL_VERSION;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerSensor.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerSensor.java
new file mode 100644
index 000000000..b0f7e2f8a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerSensor.java
@@ -0,0 +1,38 @@
+package org.openremote.agent.protocol.controller;
+
+/**
+ * ControllerSensor represents a sensor on a device
+ * <p>
+ * Date : 03-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerSensor {
+ private String deviceName;
+ private String sensorName;
+
+ public ControllerSensor() {
+
+ }
+
+ public ControllerSensor(String deviceName, String sensorName) {
+ this.deviceName = deviceName;
+ this.sensorName = sensorName;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public void setDeviceName(String deviceName) {
+ this.deviceName = deviceName;
+ }
+
+ public String getSensorName() {
+ return sensorName;
+ }
+
+ public void setSensorName(String sensorName) {
+ this.sensorName = sensorName;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/PollingKey.java b/agent/src/main/java/org/openremote/agent/protocol/controller/PollingKey.java
new file mode 100644
index 000000000..b6775bd14
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/PollingKey.java
@@ -0,0 +1,59 @@
+package org.openremote.agent.protocol.controller;
+
+import org.openremote.model.attribute.AttributeRef;
+
+import java.util.Objects;
+
+/**
+ * Couple used for polling request by device name/defined controller
+ * <p>
+ * Date : 19-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class PollingKey {
+ private String deviceName;
+ private AttributeRef controllerAgentRef;
+
+ public PollingKey() {
+ }
+
+ public PollingKey(String deviceName, AttributeRef controllerAgentRef) {
+ this.deviceName = deviceName;
+ this.controllerAgentRef = controllerAgentRef;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public void setDeviceName(String deviceName) {
+ this.deviceName = deviceName;
+ }
+
+ public AttributeRef getControllerAgentRef() {
+ return controllerAgentRef;
+ }
+
+ public void setControllerAgentRef(AttributeRef controllerAgentRef) {
+ this.controllerAgentRef = controllerAgentRef;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ PollingKey that = (PollingKey) o;
+ return Objects.equals(deviceName, that.deviceName) && Objects.equals(controllerAgentRef, that.controllerAgentRef);
+ }
+
+ @Override
+ public int hashCode() {
+
+ return Objects.hash(deviceName, controllerAgentRef);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/RequestBuilder.java b/agent/src/main/java/org/openremote/agent/protocol/controller/RequestBuilder.java
new file mode 100644
index 000000000..5b7eb8859
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/RequestBuilder.java
@@ -0,0 +1,132 @@
+/*
+ * 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.controller;
+
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.openremote.agent.protocol.controller.command.ControllerCommandBasic;
+import org.openremote.agent.protocol.controller.command.ControllerCommandMapped;
+import org.openremote.agent.protocol.http.HttpClientProtocol;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Values;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.logging.Logger;
+
+/**
+ * Request's builder created for {@link ControllerProtocol}
+ *
+ * <p>
+ * Date : 03-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class RequestBuilder {
+ private static final Logger LOG = Logger.getLogger(RequestBuilder.class.getName());
+
+ /**
+ * Default header used for every request.
+ * We're working with JSON object in response
+ *
+ * @return
+ */
+ private static MultivaluedMap<String, String> getDefaultHeaders() {
+ MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
+
+ headers.addAll("Accept", MediaType.APPLICATION_JSON);
+
+ return headers;
+ }
+
+ public static HttpClientProtocol.HttpClientRequest buildCommandRequest(ControllerCommand controllerCommand, AttributeEvent event, ResteasyWebTarget webTarget) {
+ MultivaluedMap<String, String> queryParam = new MultivaluedHashMap<>();
+ Optional<ObjectValue> body = null;
+
+ //This part could be put in a Wrapper
+ if(controllerCommand instanceof ControllerCommandBasic) {
+ String commandName = ((ControllerCommandBasic) controllerCommand).getCommandName();
+ queryParam.add("name", commandName);
+
+ if(event.getValue().isPresent()) {
+ body = Values.parse("{\"parameter\": \"" + event.getValue().orElse(null).toString() + "\"}");
+ }
+ } else {
+ Map<String, String> actionCommandLink = ((ControllerCommandMapped) controllerCommand).getActionCommandLink();
+
+ String attributeValue = event.getValue().orElse(null).toString();
+
+ String correspondingCommandName = actionCommandLink.get(attributeValue);
+
+ queryParam.add("name", correspondingCommandName);
+ }
+
+ return new HttpClientProtocol.HttpClientRequest(
+ webTarget,
+ "/rest/devices/" + controllerCommand.getDeviceName() + "/commands",
+ "POST",
+ getDefaultHeaders(),
+ queryParam,
+ null,
+ false,
+ false,
+ body == null ? null : body.get(),
+ MediaType.APPLICATION_JSON
+ );
+ }
+
+ public static HttpClientProtocol.HttpClientRequest buildStatusPollingRequest(String deviceName, List<String> sensorsName, String deviceId, ResteasyWebTarget webTarget) {
+ MultivaluedMap<String, String> queryParam = new MultivaluedHashMap<>();
+
+ queryParam.addAll("name", sensorsName);
+
+ return new HttpClientProtocol.HttpClientRequest(
+ webTarget,
+ "/rest/devices/" + deviceName + "/polling/" + deviceId,
+ "GET",
+ getDefaultHeaders(),
+ queryParam,
+ null,
+ false,
+ false,
+ null,
+ MediaType.APPLICATION_JSON
+ );
+ }
+
+ public static HttpClientProtocol.HttpClientRequest buildCheckRequest(ResteasyWebTarget webTarget) {
+ return new HttpClientProtocol.HttpClientRequest(
+ webTarget,
+ "",
+ "GET",
+ null,
+ null,
+ null,
+ false,
+ false,
+ null,
+ null
+ );
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandBasic.java b/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandBasic.java
new file mode 100644
index 000000000..00d1845a9
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandBasic.java
@@ -0,0 +1,38 @@
+package org.openremote.agent.protocol.controller.command;
+
+import org.openremote.agent.protocol.controller.ControllerCommand;
+import org.openremote.agent.protocol.http.HttpClientProtocol;
+import org.openremote.model.attribute.AttributeRef;
+
+import java.util.function.Consumer;
+
+/**
+ * A ControllerCommandBasic represent a configuration to execute a Controller 2.5 command with just a command name (command parameter is managed at
+ * launch depending on linked attribute value {@link org.openremote.agent.protocol.controller.ControllerProtocol#executeAttributeWriteRequest(HttpClientProtocol.HttpClientRequest, AttributeRef, Consumer)}).
+ * <p>
+ * <p>
+ * Date : 03-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerCommandBasic extends ControllerCommand {
+ private String commandName;
+
+ public ControllerCommandBasic() {
+ super();
+ this.commandName = "";
+ }
+
+ public ControllerCommandBasic(String deviceName, String commandName) {
+ super(deviceName);
+ this.commandName = commandName;
+ }
+
+ public String getCommandName() {
+ return commandName;
+ }
+
+ public void setCommandName(String commandName) {
+ this.commandName = commandName;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandMapped.java b/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandMapped.java
new file mode 100644
index 000000000..df887d969
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/command/ControllerCommandMapped.java
@@ -0,0 +1,59 @@
+package org.openremote.agent.protocol.controller.command;
+
+import org.openremote.agent.protocol.controller.ControllerCommand;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A ControllerCommandMapped represent a configuration to execute a Controller 2.5 command where exact command name to execute depend on a linked
+ * attribute value and the match between linked attribute value and command name is stored in a map where key is attribute value and value is the
+ * command name to execute
+ *
+ * <h2>Example:</h2>
+ * Control a fan with 3 speeds: low, mid, high
+ * <ul>
+ * <li>Controller 2.x: a command to read the state of the fan and a sensor associated with it + commands with no parameter to turn fan off, set it
+ * to low speed, medium speed or high speed</li>
+ * <li>Manager 3.0: a read-write attribute (enum if it exists or string). Its value reflects the state of the sensor. If it is written to,
+ * appropriate command is sent to controller based on written value.</li>
+ * </ul>
+ * <h3>Mapping:</h3>
+ * The end user defines the device_name and sensor_name to read the attribute value + the device_name for command execution and a mapping table for
+ * the command execution e.g.
+ * <blockquote><pre>
+ * {@code
+ * {
+ * "off": "cmd1",
+ * "low": "cmd2",
+ * "mid": "cmd3",
+ * "high": "cmd4"
+ * }
+ * }
+ * </pre></blockquote>
+ * <p>
+ * Date : 03-Sep-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerCommandMapped extends ControllerCommand {
+ private Map<String, String> actionCommandLink;
+
+ public ControllerCommandMapped() {
+ super();
+ this.actionCommandLink = new HashMap<>();
+ }
+
+ public ControllerCommandMapped(String deviceName, Map<String, String> actionCommandLink) {
+ super(deviceName);
+ this.actionCommandLink = actionCommandLink;
+ }
+
+ public Map<String, String> getActionCommandLink() {
+ return actionCommandLink;
+ }
+
+ public void setActionCommandLink(Map<String, String> actionCommandLink) {
+ this.actionCommandLink = actionCommandLink;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
index 7e2af7841..1baa060f2 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
@@ -149,7 +149,7 @@ import static org.openremote.model.util.TextUtil.*;
*/
public class HttpClientProtocol extends AbstractProtocol {
- protected static class HttpClientRequest {
+ public static class HttpClientRequest {
protected String path;
public String method;
@@ -165,7 +165,7 @@ public class HttpClientProtocol extends AbstractProtocol {
protected boolean updateConnectionStatus;
protected boolean pagingEnabled;
- protected HttpClientRequest(WebTarget client,
+ public HttpClientRequest(WebTarget client,
String path,
String method,
MultivaluedMap<String, String> headers,
diff --git a/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol b/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
index 265497bf3..99f2a05f6 100644
--- a/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
+++ b/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
@@ -4,4 +4,5 @@ org.openremote.agent.protocol.timer.TimerProtocol
org.openremote.agent.protocol.knx.KNXProtocol
org.openremote.agent.protocol.velbus.VelbusSocketProtocol
org.openremote.agent.protocol.velbus.VelbusSerialProtocol
-org.openremote.agent.protocol.http.HttpClientProtocol
\ No newline at end of file
+org.openremote.agent.protocol.http.HttpClientProtocol
+org.openremote.agent.protocol.controller.ControllerProtocol
\ No newline at end of file
diff --git a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
index 548038e0a..8114eaa09 100644
--- a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
+++ b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
@@ -381,6 +381,12 @@ metaItemDisplayName[PROTOCOL_HTTP_CLIENT_QUERY_PARAMETERS]=HTTP query parameters
metaItemDisplayName[PROTOCOL_HTTP_CLIENT_FAILURE_CODES]=HTTP response failure codes
metaItemDisplayName[PROTOCOL_HTTP_CLIENT_HEADERS]=HTTP headers
metaItemDisplayName[PROTOCOL_FILTERS]=Protocol response filters
+metaItemDisplayName[PROTOCOL_DEVICE_NAME]=Controller Device name
+metaItemDisplayName[PROTOCOL_SENSOR_NAME]=Controller Sensor name
+metaItemDisplayName[PROTOCOL_COMMAND_DEVICE_NAME]=Controller Device name for command
+metaItemDisplayName[PROTOCOL_COMMAND_NAME]=Controller Command name
+metaItemDisplayName[PROTOCOL_COMMANDS_MAP]=Controller Commands map
+metaItemDisplayName[PROTOCOL_CONTROLLER_BASE_URI]=Controller Base URI
attributeLinkConverterValues=Converter values
attributeLinkNewConverterValue=New converter value
enterConverterValue=Enter converter value
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ControllerIntegrationSetupTasks.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ControllerIntegrationSetupTasks.java
new file mode 100644
index 000000000..df4fdaa71
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ControllerIntegrationSetupTasks.java
@@ -0,0 +1,36 @@
+package org.openremote.manager.setup.builtin;
+
+import org.openremote.container.Container;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.setup.AbstractSetupTasks;
+import org.openremote.manager.setup.Setup;
+
+import java.util.List;
+
+/**
+ * Java class description...
+ * <p>
+ * Date : 09-Aug-18
+ *
+ * @author jerome.vervier
+ */
+public class ControllerIntegrationSetupTasks extends AbstractSetupTasks {
+ @Override
+ public List<Setup> createTasks(Container container) {
+
+ // Basic vs Keycloak identity provider
+ if (container.getService(ManagerIdentityService.class).isKeycloakEnabled()) {
+ addTask(new ManagerCleanSetup(container));
+ addTask(new KeycloakCleanSetup(container));
+ addTask(new KeycloakInitSetup(container));
+ addTask(new KeycloakDemoSetup(container));
+ addTask(new ManagerControllerIntegrationSetup(container));
+ } else {
+ addTask(new ManagerCleanSetup(container));
+ addTask(new BasicIdentityInitSetup(container));
+ addTask(new ManagerControllerIntegrationSetup(container));
+ }
+
+ return getTasks();
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerControllerIntegrationSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerControllerIntegrationSetup.java
new file mode 100644
index 000000000..746250a42
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerControllerIntegrationSetup.java
@@ -0,0 +1,93 @@
+package org.openremote.manager.setup.builtin;
+
+import static org.openremote.model.asset.AssetType.AGENT;
+import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;
+
+import org.openremote.agent.protocol.controller.ControllerProtocol;
+import org.openremote.container.Container;
+import org.openremote.manager.setup.AbstractManagerSetup;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.security.Tenant;
+import org.openremote.model.value.Values;
+
+/**
+ * ManagerControllerIntegrationSetup use HttpClientProtocol to communicate with openremote Controller 2 REST API.
+ *
+ * First step is to read information from sensor (READ) : OK.
+ * Next step is to send command (WRITE) : Still confusing how to write only?.
+ * Next step is to consider READ/WRITE
+ *
+ * <p>
+ * Date : 09-Aug-18
+ *
+ * @author jerome.vervier
+ */
+public class ManagerControllerIntegrationSetup extends AbstractManagerSetup {
+ private final String baseUrl = "http://10.129.15.70:8688/controller";
+
+ public String masterRealmId;
+
+ public ManagerControllerIntegrationSetup(Container container) {
+ super(container);
+ }
+
+ @Override
+ public void onStart() throws Exception {
+ KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);
+ Tenant masterTenant = keycloakDemoSetup.masterTenant;
+ masterRealmId = masterTenant.getId();
+
+ Asset building = new Asset("Building", AssetType.BUILDING);
+ building.setRealmId(masterRealmId);
+ building = assetStorageService.merge(building);
+
+ Asset controllerAgent = new Asset("Controller Agent", AGENT, building);
+ controllerAgent.setAttributes(
+ initProtocolConfiguration(new AssetAttribute("controllerConfig"), ControllerProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ ControllerProtocol.META_PROTOCOL_BASE_URI,
+ Values.create(baseUrl)
+ )
+ )
+ );
+
+ controllerAgent = assetStorageService.merge(controllerAgent);
+
+ building = assetStorageService.merge(building);
+
+ /*Asset deviceDay = new Asset("Device date", AssetType.THING, building);
+
+ AssetAttribute dayTime = new AssetAttribute("CurrentDateTime", STRING);
+ dayTime.addMeta(
+ AgentLink.asAgentLinkMetaItem(controllerAgent.getAttribute("controllerConfig").get().getReferenceOrThrow()),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_DEVICE_NAME, Values.create("DateTime")),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_SENSOR_NAME, Values.create("DisplayDate_Sensor")),
+ new MetaItem(AssetMeta.READ_ONLY, Values.create(true))
+ );
+
+ deviceDay.addAttributes(dayTime);
+
+ Asset writeCommand = new Asset("Exec Google Command", AssetType.THING, building);
+
+ AssetAttribute callGoogleCommand = new AssetAttribute("callGoogleCommand", NUMBER);
+ callGoogleCommand.addMeta(
+ AgentLink.asAgentLinkMetaItem(controllerAgent.getAttribute("controllerConfig").get().getReferenceOrThrow()),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_DEVICE_NAME, Values.create("DateTime")),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_COMMAND_NAME, Values.create("callGoogleCommand"))
+ );
+
+ writeCommand.addAttributes(callGoogleCommand);
+
+ writeCommand = assetStorageService.merge(writeCommand);
+
+ deviceDay = assetStorageService.merge(deviceDay);
+
+ controllerAgent = assetStorageService.merge(controllerAgent);
+
+ building = assetStorageService.merge(building);*/
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy
new file mode 100644
index 000000000..0dab04062
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy
@@ -0,0 +1,370 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.test.protocol.controller
+
+import org.jboss.resteasy.spi.ResteasyUriInfo
+import org.jboss.resteasy.util.BasicAuthHelper
+import org.openremote.agent.protocol.controller.ControllerProtocol
+import org.openremote.agent.protocol.http.WebTargetBuilder
+import org.openremote.manager.agent.AgentService
+import org.openremote.manager.asset.AssetProcessingService
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.model.Constants
+import org.openremote.model.asset.Asset
+import org.openremote.model.asset.AssetAttribute
+import org.openremote.model.asset.AssetMeta
+import org.openremote.model.asset.AssetType
+import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.asset.agent.ProtocolConfiguration
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.attribute.AttributeValueType
+import org.openremote.model.attribute.MetaItem
+import org.openremote.model.value.ObjectValue
+import org.openremote.model.value.Values
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Shared
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import javax.ws.rs.client.ClientRequestContext
+import javax.ws.rs.client.ClientRequestFilter
+import javax.ws.rs.core.HttpHeaders
+import javax.ws.rs.core.MediaType
+import javax.ws.rs.core.Response
+import javax.ws.rs.core.UriInfo
+
+/**
+ *
+ * Java class description...
+ *
+ * Date : 13-Sep-18
+ *
+ * @author jerome.vervier
+ *
+ */
+
+class ControllerProtocolTest extends Specification implements ManagerContainerTrait {
+ def CONTROLLERPROTOCOL_ATTRIBUTE_NAME = "testcontrollerConfig"
+ def CONTROLLERPROTOCOL_ATTRIBUTE_NAME2 = "testcontrollerConfig2"
+ def CONTROLLERPROTOCOL_ATTRIBUTE_NAME3 = "testcontrollerConfig3"
+
+ @Shared
+ def mockServer = new ClientRequestFilter() {
+ private int commandCount = 0
+ private int pollCount = 0
+
+ @Override
+ void filter(ClientRequestContext requestContext) throws IOException, ConnectException {
+ def requestUri = requestContext.uri
+ def requestPath = requestUri.scheme + "://" + requestUri.host + (requestUri.port.toString().size() != 0 ? (":" + requestUri.port) : "") + requestUri.path
+
+ def pollingReq = requestUri.path ==~ /\/controller\/rest\/devices\/MyDevice\/polling\/OR3ControllerProtocol_[0-9a-zA-Z]*_[0-9a-zA-Z]*/
+
+ if(pollingReq) {
+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)
+ def queryParams = uriInfo.getQueryParameters(true)
+
+ if (queryParams.get("name").size() == 2 && queryParams.getFirst("name") == "my_sensor1" && queryParams.get("name").get(1) == "my_sensor2"){
+ requestContext.abortWith(
+ Response.ok("[{\"name\": \"my_sensor1\", \"value\": \"newValue1\"},{\"name\": \"my_sensor2\", \"value\": \"newValue2\"}]", MediaType.APPLICATION_JSON).build()
+ )
+ pollCount++
+ return
+ } else if (queryParams.get("name").size() == 2 && queryParams.getFirst("name") == "my_sensor1b" && queryParams.get("name").get(1) == "my_sensor2"){
+ requestContext.abortWith(
+ Response.ok("[{\"name\": \"my_sensor2\", \"value\": \"newValue2\"}]", MediaType.APPLICATION_JSON).build()
+ )
+ pollCount++
+ return
+ } else if (queryParams.get("name").size() == 1 && queryParams.getFirst("name") == "my_sensor1a"){
+ requestContext.abortWith(
+ Response.ok("[{\"name\": \"my_sensor1a\", \"value\": \"newValue1a\"}]", MediaType.APPLICATION_JSON).build()
+ )
+ pollCount++
+ return
+ } else {
+ requestContext.abortWith(Response.serverError().build())
+ return
+ }
+ } else {
+ switch (requestPath) {
+ case "http://mockapi:8688/controller":
+ requestContext.abortWith(Response.ok().build())
+ return
+ break
+ case "http://basicauthmockapi:8688/controller":
+ def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
+ if (authHeader != null) {
+ def usernameAndPassword = BasicAuthHelper.parseHeader(authHeader)
+ if (usernameAndPassword != null
+ && usernameAndPassword[0] == "testuser"
+ && usernameAndPassword[1] == "password1") {
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ } else {
+ requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build())
+ return
+ }
+ break
+ case "http://disconnectedmockapi:8688/controller":
+ throw new ConnectException("Server not available")
+ return
+ break
+ }
+
+ if(requestContext.method == "POST") {
+ switch (requestPath) {
+ case "http://mockapi:8688/controller/rest/devices/DeviceName2/commands":
+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)
+ def queryParams = uriInfo.getQueryParameters(true)
+ if (queryParams.get("name").size() == 1 && queryParams.getFirst("name") == "my_command") {
+ requestContext.abortWith(
+ Response.ok().build()
+ )
+ commandCount++
+ return
+ } else {
+ requestContext.abortWith(Response.serverError().build())
+ return
+ }
+ break
+ case "http://mockapi:8688/controller/rest/devices/MyDevice/commands":
+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)
+ def queryParams = uriInfo.getQueryParameters(true)
+ if (queryParams.get("name").size() == 1 && queryParams.getFirst("name") == "my_command") {
+ String bodyStr = (String)requestContext.getEntity()
+ ObjectValue body = Values.<ObjectValue>parse(bodyStr).orElse(null)
+
+ if (body.get("parameter").isPresent() && body.get("parameter").orElse(null).toString() == "a_parameter") {
+ requestContext.abortWith(Response.ok().build())
+ commandCount++
+ return
+ } else {
+ requestContext.abortWith(Response.serverError().build())
+ return
+ }
+ } else {
+ requestContext.abortWith(Response.serverError().build())
+ return
+ }
+ break
+ }
+ }
+ }
+ }
+ }
+
+ def cleanupSpec() {
+ WebTargetBuilder.close()
+ }
+
+ def cleanup() {
+ mockServer.commandCount = 0
+ mockServer.pollCount = 0
+ }
+
+ def "Check Controller connection"() {
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1)
+
+ when: "the container starts"
+ def serverPort = findEphemeralPort()
+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())
+ def controllerProtocol = container.getService(ControllerProtocol.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def agentService = container.getService(AgentService.class)
+
+ then: "the container should be running"
+ conditions.eventually {
+ assert container.isRunning()
+ }
+
+ when: "the web target builder is configured to use the mock server"
+ // Need to do this here as HTTP protocol must be initialised first
+ WebTargetBuilder.initClient()
+ if (!WebTargetBuilder.client.configuration.isRegistered(mockServer)) {
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
+ }
+
+ and: "an agent with a Controller protocol configuration is created"
+ def agent = new Asset()
+ agent.setRealmId(Constants.MASTER_REALM)
+ agent.setName("Test Agent")
+ agent.setType(AssetType.AGENT)
+ agent.setAttributes(
+ ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME), ControllerProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ ControllerProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("http://mockapi:8688/controller")
+ )
+ )
+ )
+
+ and: "the agent is added to the asset service"
+ agent = assetStorageService.merge(agent)
+ def controllerRef = assetStorageService.find(agent.id, true).getAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME).get().getReferenceOrThrow()
+
+ then: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME))
+
+ assert status == ConnectionStatus.CONNECTED
+ assert controllerProtocol.controllerHeartbeat.get(controllerRef).isCancelled()
+ }
+
+ when: "an asset is created with attributes linked to the controller protocol configuration"
+ def asset = new Asset("Test Asset", AssetType.THING, agent)
+ asset.setAttributes(
+ // attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
+ new AssetAttribute("sensor", AttributeValueType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME).toArrayValue()),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_DEVICE_NAME, Values.create("MyDevice")),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_SENSOR_NAME, Values.create("my_sensor1a")),
+ new MetaItem(AssetMeta.READ_ONLY, Values.create(true))
+ ),
+ new AssetAttribute("command", AttributeValueType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME).toArrayValue()),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_DEVICE_NAME, Values.create("MyDevice")),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_COMMAND_NAME, Values.create("my_command"))
+ )
+ )
+
+ and: "the asset is merged into the asset service"
+ asset = assetStorageService.merge(asset)
+
+ and: "pollings should occurs"
+ while(mockServer.pollCount < 6) {
+
+ }
+
+ and: "value should be updated"
+ def newAsset = assetStorageService.find(asset.getId(), true)
+
+ then:
+ conditions.eventually {
+ assert controllerProtocol.controllersMap.get(controllerRef).getSensorsListForDevice("MyDevice").size() == 1
+ assert controllerProtocol.pollingSensorList.size() == 1
+ assert mockServer.commandCount == 0
+ assert mockServer.pollCount > 0
+ assert newAsset.getAttribute("sensor").flatMap({it.getValueAsString()}).orElse("") == "newValue1a"
+ }
+
+ when: "another protocol is added linked to an unavailable controller"
+ agent.addAttributes(ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME2), ControllerProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ ControllerProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("http://disconnectedmockapi:8688/controller")
+ )
+ ))
+
+ and: "the agent is added to the asset service"
+ agent = assetStorageService.merge(agent)
+ def controllerRef2 = assetStorageService.find(agent.id, true).getAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME2).get().getReferenceOrThrow()
+
+ then: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status2 = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME2))
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME))
+
+ assert status2 == ConnectionStatus.DISCONNECTED
+ assert status == ConnectionStatus.CONNECTED
+ assert !controllerProtocol.controllerHeartbeat.get(controllerRef2).isCancelled()
+ assert controllerProtocol.controllerHeartbeat.get(controllerRef).isCancelled()
+ }
+
+ when: "another protocol for command with map"
+ agent.addAttributes(ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME3), ControllerProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ ControllerProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("http://mockapi:8688/controller")
+ )
+ ))
+
+ and: "the agent is added to the asset service"
+ agent = assetStorageService.merge(agent)
+ def controllerRef3 = assetStorageService.find(agent.id, true).getAttribute(CONTROLLERPROTOCOL_ATTRIBUTE_NAME3).get().getReferenceOrThrow()
+
+ then: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME3))
+
+ assert status == ConnectionStatus.CONNECTED
+ assert controllerProtocol.controllerHeartbeat.get(controllerRef3).isCancelled()
+ }
+
+ when: "an asset is created with attributes linked to the controller protocol configuration"
+ def asset2 = new Asset("Test Asset2", AssetType.THING, agent)
+ asset2.setAttributes(
+ // attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
+ new AssetAttribute("command", AttributeValueType.STRING, Values.create("command1"))
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, CONTROLLERPROTOCOL_ATTRIBUTE_NAME3).toArrayValue()),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_DEVICE_NAME, Values.create("DeviceName2")),
+ new MetaItem(ControllerProtocol.META_ATTRIBUTE_COMMANDS_MAP, Values.<ObjectValue>parse(/{"command1": "my_command", "command2": "wrong"}/).get())
+ )
+ )
+
+ and: "the asset is merged into the asset service"
+ asset2 = assetStorageService.merge(asset2)
+
+ and: "a linked attribute value is updated"
+ def attributeEvent = new AttributeEvent(asset2.id,
+ "command",
+ Values.create("command1"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then:
+ conditions.eventually {
+ assert controllerProtocol.controllersTargetMap.size() == 3
+ assert mockServer.commandCount == 1
+ }
+
+ and: "another linked attribute value is updated with no value"
+ def attributeEvent2 = new AttributeEvent(asset.id,
+ "command",
+ null)
+ assetProcessingService.sendAttributeEvent(attributeEvent2)
+
+ then:
+ conditions.eventually {
+ assert mockServer.commandCount == 1
+ }
+
+ and: "another linked attribute value is updated with a value"
+ def attributeEvent3 = new AttributeEvent(asset.id,
+ "command",
+ Values.create("a_parameter"))
+ assetProcessingService.sendAttributeEvent(attributeEvent3)
+
+ then:
+ conditions.eventually {
+ assert mockServer.commandCount == 2
+ assert true
+ }
+ }
+}
\ No newline at end of file