Search in sources :

Example 1 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class ControllerProtocol method onPollingResponse.

/**
 * 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>TIMEOUT (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.
 */
private void onPollingResponse(String deviceName, List<String> sensorNameList, Response response) {
    if (response != null) {
        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);
            ArrayNode statusArray = ValueUtil.convert(responseBodyAsString, ArrayNode.class);
            if (statusArray == null) {
                LOG.warning("### Polling response is not a JSON array or empty: " + responseBodyAsString);
            } else {
                statusArray.forEach(status -> {
                    String name = Optional.ofNullable(status.get("name")).flatMap(ValueUtil::getString).orElse(null);
                    String value = Optional.ofNullable(status.get("value")).flatMap(ValueUtil::getString).orElse(null);
                    /**
                     * For every sensors in the request body, find the linked attributeref and update value by calling {@link #updateAttributeValue}
                     */
                    controller.getSensorsListForDevice(deviceName).stream().filter(entry -> entry.getValue().getSensorName().equals(name)).forEach(e -> this.updateAttributeValue(e.getKey(), value));
                });
            }
        } else if (response.getStatusInfo() == Response.Status.REQUEST_TIMEOUT) {
            LOG.info("### Timeout from polling no changes on Controller side given sensors [device=" + deviceName + ", sensors=" + this.formatSensors(sensorNameList) + "]");
        } else {
            LOG.severe("### Status code received error : " + response.getStatus() + " --> " + response.getStatusInfo().getReasonPhrase());
        }
    } else {
        LOG.severe("### Received null response from polling (due to previous exception)");
    }
    // No matter status code, we're continuing to poll
    this.schedulePollingTask(deviceName);
}
Also used : java.util(java.util) ScheduledFuture(java.util.concurrent.ScheduledFuture) ControllerCommandMapped(org.openremote.agent.protocol.controller.command.ControllerCommandMapped) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) URISyntaxException(java.net.URISyntaxException) AttributeRef(org.openremote.model.attribute.AttributeRef) ValueDescriptor(org.openremote.model.value.ValueDescriptor) ValueUtil(org.openremote.model.util.ValueUtil) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) Level(java.util.logging.Level) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) Future(java.util.concurrent.Future) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) CONNECTION_POOL_SIZE(org.openremote.container.web.WebTargetBuilder.CONNECTION_POOL_SIZE) ConnectException(java.net.ConnectException) SyslogCategory(org.openremote.model.syslog.SyslogCategory) URI(java.net.URI) ControllerCommandBasic(org.openremote.agent.protocol.controller.command.ControllerCommandBasic) AttributeState(org.openremote.model.attribute.AttributeState) URIBuilder(org.apache.http.client.utils.URIBuilder) HTTPProtocol(org.openremote.agent.protocol.http.HTTPProtocol) Logger(java.util.logging.Logger) UnknownHostException(java.net.UnknownHostException) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Response(javax.ws.rs.core.Response) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ProcessingException(javax.ws.rs.ProcessingException) WebTargetBuilder.createClient(org.openremote.container.web.WebTargetBuilder.createClient) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 2 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class MQTTProtocol method doLinkAttribute.

@Override
protected void doLinkAttribute(String assetId, Attribute<?> attribute, MQTTAgentLink agentLink) throws RuntimeException {
    agentLink.getSubscriptionTopic().ifPresent(topic -> {
        Consumer<MQTTMessage<String>> messageConsumer = msg -> updateLinkedAttribute(new AttributeState(assetId, attribute.getName(), msg.payload));
        client.addMessageConsumer(topic, messageConsumer);
        protocolMessageConsumers.put(new AttributeRef(assetId, attribute.getName()), messageConsumer);
    });
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) URIBuilder(org.apache.http.client.utils.URIBuilder) AttributeRef(org.openremote.model.attribute.AttributeRef) HashMap(java.util.HashMap) ValueUtil(org.openremote.model.util.ValueUtil) Logger(java.util.logging.Logger) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) Consumer(java.util.function.Consumer) UniqueIdentifierGenerator(org.openremote.container.util.UniqueIdentifierGenerator) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) Optional(java.util.Optional) SyslogCategory(org.openremote.model.syslog.SyslogCategory) URI(java.net.URI) AttributeState(org.openremote.model.attribute.AttributeState) AttributeRef(org.openremote.model.attribute.AttributeRef)

Example 3 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class StorageSimulatorProtocol method doLinkedAttributeWrite.

@SuppressWarnings("unchecked")
@Override
protected void doLinkedAttributeWrite(Attribute<?> attribute, StorageSimulatorAgentLink agentLink, AttributeEvent event, Object processedValue) {
    // Power attribute is updated only by this protocol not by clients
    if (attribute.getName().equals(POWER.getName())) {
        return;
    }
    updateLinkedAttribute(new AttributeState(event.getAttributeRef(), processedValue));
    // Push write value into the asset and update
    String assetId = event.getAssetId();
    ((Attribute<Object>) attribute).setValue(processedValue);
    ElectricityStorageAsset asset = assetService.findAsset(assetId, ElectricityStorageAsset.class);
    asset.addOrReplaceAttributes(attribute);
    updateStorageAsset(asset);
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) ElectricityStorageAsset(org.openremote.model.asset.impl.ElectricityStorageAsset) Attribute(org.openremote.model.attribute.Attribute)

Example 4 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class ValueUtil method initialiseAssetAttributes.

public static void initialiseAssetAttributes(Asset<?> asset) throws IllegalStateException {
    AssetTypeInfo assetInfo = getAssetInfo(asset.getType()).orElseThrow(() -> new IllegalStateException("Cannot get asset model info for requested asset type: " + asset.getType()));
    asset.getAttributes().addOrReplace(Arrays.stream(assetInfo.getAttributeDescriptors()).filter(attributeDescriptor -> !attributeDescriptor.isOptional()).map(Attribute::new).collect(Collectors.toList()));
}
Also used : Reflections(org.reflections.Reflections) ModelDescriptor(org.openremote.model.ModelDescriptor) com.fasterxml.jackson.databind.node(com.fasterxml.jackson.databind.node) AgentLink(org.openremote.model.asset.agent.AgentLink) BigDecimal(java.math.BigDecimal) AgentDescriptor(org.openremote.model.asset.agent.AgentDescriptor) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) BigInteger(java.math.BigInteger) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ConstraintViolation(javax.validation.ConstraintViolation) java.lang.reflect(java.lang.reflect) Entity(javax.persistence.Entity) ConstructorDetector(com.fasterxml.jackson.databind.cfg.ConstructorDetector) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo) Validator(javax.validation.Validator) JsonAutoDetect(com.fasterxml.jackson.annotation.JsonAutoDetect) NotNull(javax.validation.constraints.NotNull) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) ClasspathHelper(org.reflections.util.ClasspathHelper) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Serializable(java.io.Serializable) ModelDescriptors(org.openremote.model.ModelDescriptors) JsonSchemaGenerator(com.kjetland.jackson.jsonSchema.JsonSchemaGenerator) Agent(org.openremote.model.asset.agent.Agent) IntStream(java.util.stream.IntStream) java.util(java.util) AssetDescriptor(org.openremote.model.asset.AssetDescriptor) Modifier.isStatic(java.lang.reflect.Modifier.isStatic) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Level(java.util.logging.Level) Attribute(org.openremote.model.attribute.Attribute) Validation(javax.validation.Validation) PropertyAccessor(com.fasterxml.jackson.annotation.PropertyAccessor) AssetModelProvider(org.openremote.model.AssetModelProvider) com.fasterxml.jackson.databind(com.fasterxml.jackson.databind) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) Asset(org.openremote.model.asset.Asset) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SerializationHelper(org.hibernate.internal.util.SerializationHelper) ParameterNamesModule(com.fasterxml.jackson.module.paramnames.ParameterNamesModule) SubTypesScanner(org.reflections.scanners.SubTypesScanner) org.openremote.model.value(org.openremote.model.value) Modifier.isPublic(java.lang.reflect.Modifier.isPublic) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) StandardModelProvider(org.openremote.model.StandardModelProvider) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) MODEL_AND_VALUES(org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES) Attribute(org.openremote.model.attribute.Attribute) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo)

Example 5 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class BluetoothMeshProtocol method doLinkAttribute.

@Override
protected synchronized void doLinkAttribute(String assetId, Attribute<?> attribute, BluetoothMeshAgentLink agentLink) throws RuntimeException {
    if (meshNetwork == null) {
        return;
    }
    final AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
    Integer appKeyIndex = getOrThrowAgentLinkProperty(agentLink.getAppKeyIndex(), "Bluetooth Mesh Application Key Index");
    String modelName = getOrThrowAgentLinkProperty(agentLink.getModelName(), "Bluetooth Mesh Model Name");
    Integer modelId = toModelId(modelName, attributeRef);
    if (modelId == null) {
        return;
    }
    String addressAsString = getOrThrowAgentLinkProperty(agentLink.getAddress(), "Bluetooth Mesh Address");
    Integer address = toIntegerAddress(addressAsString, attributeRef);
    if (address == null) {
        return;
    }
    LOG.info("Linking Bluetooth Mesh attribute: [address: '" + String.format("0x%04X", address) + "', model: '" + modelName + "', appKeyIndex: '" + appKeyIndex + "'] - " + attributeRef);
    Class<?> clazz = (attribute == null ? null : attribute.getType().getType());
    Consumer<Object> sensorValueConsumer = value -> updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, clazz)));
    sensorValueConsumerMap.put(attributeRef, sensorValueConsumer);
    meshNetwork.addMeshModel(address, modelId, appKeyIndex);
    meshNetwork.addSensorValueConsumer(address, modelId, sensorValueConsumer);
    if (meshNetwork.isConnected()) {
        meshNetwork.sendMeshGetCommand(address, modelId);
    }
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) BluetoothCentralManager(com.welie.blessed.BluetoothCentralManager) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) AttributeRef(org.openremote.model.attribute.AttributeRef) HashMap(java.util.HashMap) ThingAsset(org.openremote.model.asset.impl.ThingAsset) BluetoothPeripheral(com.welie.blessed.BluetoothPeripheral) AGENT_LINK(org.openremote.model.value.MetaItemType.AGENT_LINK) Future(java.util.concurrent.Future) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BluetoothCommandStatus(com.welie.blessed.BluetoothCommandStatus) SyslogCategory(org.openremote.model.syslog.SyslogCategory) LinkedList(java.util.LinkedList) MeshParserUtils(org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils) AssetTreeNode(org.openremote.model.asset.AssetTreeNode) AttributeState(org.openremote.model.attribute.AttributeState) ValueType(org.openremote.model.value.ValueType) Asset(org.openremote.model.asset.Asset) MetaItemType(org.openremote.model.value.MetaItemType) ValueFormat(org.openremote.model.value.ValueFormat) ProtocolAssetDiscovery(org.openremote.model.protocol.ProtocolAssetDiscovery) ScanResult(com.welie.blessed.ScanResult) Logger(java.util.logging.Logger) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) MetaItem(org.openremote.model.attribute.MetaItem) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) SigModelParser(org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser) BluetoothCentralManagerCallback(com.welie.blessed.BluetoothCentralManagerCallback) AgentLink.getOrThrowAgentLinkProperty(org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty) AttributeState(org.openremote.model.attribute.AttributeState) AttributeRef(org.openremote.model.attribute.AttributeRef)

Aggregations

Attribute (org.openremote.model.attribute.Attribute)18 Logger (java.util.logging.Logger)13 Level (java.util.logging.Level)11 AttributeEvent (org.openremote.model.attribute.AttributeEvent)10 Consumer (java.util.function.Consumer)9 Container (org.openremote.model.Container)9 ValueUtil (org.openremote.model.util.ValueUtil)9 java.util (java.util)8 AttributeState (org.openremote.model.attribute.AttributeState)8 SyslogCategory (org.openremote.model.syslog.SyslogCategory)8 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)7 AttributeRef (org.openremote.model.attribute.AttributeRef)7 Pair (org.openremote.model.util.Pair)7 MetaItemType (org.openremote.model.value.MetaItemType)7 Asset (org.openremote.model.asset.Asset)6 Map (java.util.Map)5 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)5 TimeUnit (java.util.concurrent.TimeUnit)5 Collectors (java.util.stream.Collectors)5 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)5