Search in sources :

Example 11 with AttributeState

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

the class HTTPProtocol method onPollingResponse.

protected void onPollingResponse(HttpClientRequest request, Response response, AttributeRef attributeRef, HTTPAgentLink agentLink) {
    int responseCode = response != null ? response.getStatus() : 500;
    Object value = null;
    if (response != null && response.hasEntity() && response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
        try {
            boolean binaryMode = agent.getMessageConvertBinary().orElse(agentLink.isMessageConvertBinary());
            boolean hexMode = agent.getMessageConvertHex().orElse(agentLink.isMessageConvertHex());
            if (hexMode || binaryMode) {
                byte[] bytes = response.readEntity(byte[].class);
                value = hexMode ? ProtocolUtil.bytesToHexString(bytes) : ProtocolUtil.bytesToBinaryString(bytes);
            } else {
                value = response.readEntity(String.class);
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Error occurred whilst trying to read response body", e);
            response.close();
        }
    } else {
        LOG.fine(prefixLogMessage("Request returned an un-successful response code (" + responseCode + "):" + request.requestTarget.getUriBuilder().build().toString()));
        return;
    }
    if (attributeRef != null) {
        updateLinkedAttribute(new AttributeState(attributeRef, value));
        // Look for any attributes that also want to use this polling response
        synchronized (pollingLinkedAttributeMap) {
            Set<AttributeRef> linkedRefs = pollingLinkedAttributeMap.get(attributeRef);
            if (linkedRefs != null) {
                Object finalValue = value;
                linkedRefs.forEach(ref -> updateLinkedAttribute(new AttributeState(ref, finalValue)));
            }
        }
    }
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) AttributeRef(org.openremote.model.attribute.AttributeRef) URISyntaxException(java.net.URISyntaxException)

Example 12 with AttributeState

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

the class StorageSimulatorProtocol method updateStorageAsset.

protected void updateStorageAsset(ElectricityStorageAsset storageAsset) {
    if (storageAsset == null) {
        LOG.finest("Storage asset not set so skipping update");
        return;
    }
    String assetId = storageAsset.getId();
    Instant previousTimestamp = lastUpdateMap.remove(assetId);
    ScheduledFuture<?> scheduledFuture = simulationMap.remove(assetId);
    if (scheduledFuture != null) {
        scheduledFuture.cancel(true);
    }
    boolean setpointLinked = getLinkedAttributes().containsKey(new AttributeRef(assetId, POWER_SETPOINT.getName()));
    boolean powerLinked = getLinkedAttributes().containsKey(new AttributeRef(assetId, POWER.getName()));
    boolean levelLinked = getLinkedAttributes().containsKey(new AttributeRef(assetId, ENERGY_LEVEL.getName()));
    if (!setpointLinked || !powerLinked || !levelLinked) {
        LOG.fine("Not all required attributes are linked or don't have values (setpoint, power and energy level): " + assetId);
        return;
    }
    Instant now = Instant.now();
    double setpoint = storageAsset.getPowerSetpoint().orElse(0d);
    double capacity = storageAsset.getEnergyCapacity().orElse(0d);
    double power = storageAsset.getPower().orElse(0d);
    double level = storageAsset.getEnergyLevel().orElse(0d);
    int minPercentage = storageAsset.getEnergyLevelPercentageMin().orElse(0);
    int maxPercentage = storageAsset.getEnergyLevelPercentageMax().orElse(100);
    capacity = Math.max(0d, capacity);
    level = Math.max(0d, Math.min(capacity, level));
    double maxLevel = (((double) maxPercentage) / 100d) * capacity;
    double minLevel = (((double) minPercentage) / 100d) * capacity;
    if (capacity <= 0d) {
        LOG.info("Storage asset capacity is 0 so not usable: " + assetId);
        level = 0d;
        setpoint = 0d;
    }
    if (capacity > 0 && power != 0d && previousTimestamp != null) {
        // Calculate energy delta since last execution
        Duration duration = Duration.between(previousTimestamp, now);
        long seconds = duration.getSeconds();
        if (seconds > 0) {
            double deltaHours = seconds / 3600d;
            // Export efficiency < 1 means more energy is consumed to produce requested power
            double efficiency = power > 0 ? ((double) storageAsset.getEfficiencyImport().orElse(100)) / 100d : (1d / (((double) storageAsset.getEfficiencyExport().orElse(100)) / 100d));
            double energyDelta = power * deltaHours * efficiency;
            double newLevel = Math.max(0d, Math.min(capacity, level + energyDelta));
            energyDelta = newLevel - level;
            level = newLevel;
            if (energyDelta > 0) {
                updateLinkedAttribute(new AttributeState(storageAsset.getId(), ElectricityStorageAsset.ENERGY_IMPORT_TOTAL.getName(), storageAsset.getEnergyImportTotal().orElse(0d) + energyDelta));
            } else {
                updateLinkedAttribute(new AttributeState(storageAsset.getId(), ElectricityStorageAsset.ENERGY_EXPORT_TOTAL.getName(), storageAsset.getEnergyExportTotal().orElse(0d) - energyDelta));
            }
        }
    }
    power = (setpoint < 0 && level <= minLevel) || (setpoint > 0 && level >= maxLevel) ? 0d : setpoint;
    if (power > 0d && !storageAsset.isSupportsImport().orElse(false)) {
        LOG.fine("Setpoint is requesting power import but asset does not support it: " + storageAsset);
        power = 0d;
    } else if (power < 0d && !storageAsset.isSupportsExport().orElse(false)) {
        LOG.fine("Setpoint is requesting power export but asset does not support it: " + storageAsset);
        power = 0d;
    }
    updateLinkedAttribute(new AttributeState(assetId, POWER.getName(), power));
    updateLinkedAttribute(new AttributeState(assetId, ENERGY_LEVEL.getName(), level));
    updateLinkedAttribute(new AttributeState(assetId, ENERGY_LEVEL_PERCENTAGE.getName(), capacity <= 0d ? 0 : (int) ((level / capacity) * 100)));
    if (power != 0d) {
        lastUpdateMap.put(assetId, now);
        simulationMap.put(assetId, scheduleUpdate(assetId));
    }
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) AttributeRef(org.openremote.model.attribute.AttributeRef) Instant(java.time.Instant) Duration(java.time.Duration)

Example 13 with AttributeState

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

the class ProtocolUtil method createGenericAttributeMessageConsumer.

public static Consumer<String> createGenericAttributeMessageConsumer(String assetId, Attribute<?> attribute, AgentLink<?> agentLink, Supplier<Long> currentMillisSupplier, Consumer<AttributeState> stateConsumer) {
    ValueFilter[] matchFilters = agentLink.getMessageMatchFilters().orElse(null);
    ValuePredicate matchPredicate = agentLink.getMessageMatchPredicate().orElse(null);
    if (matchPredicate == null) {
        return null;
    }
    return message -> {
        if (!TextUtil.isNullOrEmpty(message)) {
            Object messageFiltered = applyValueFilters(message, matchFilters);
            if (messageFiltered != null) {
                if (matchPredicate.asPredicate(currentMillisSupplier).test(messageFiltered)) {
                    Protocol.LOG.finest("Inbound message meets attribute matching meta so writing state to state consumer for attribute: asssetId=" + assetId + ", attribute=" + attribute.getName());
                    stateConsumer.accept(new AttributeState(assetId, attribute.getName(), message));
                }
            }
        }
    };
}
Also used : NULL_LITERAL(org.openremote.model.util.ValueUtil.NULL_LITERAL) Protocol(org.openremote.model.asset.agent.Protocol) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Hex(org.apache.commons.codec.binary.Hex) ValueUtil(org.openremote.model.util.ValueUtil) DYNAMIC_VALUE_PLACEHOLDER(org.openremote.model.asset.agent.Protocol.DYNAMIC_VALUE_PLACEHOLDER) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Level(java.util.logging.Level) ValueUtil.applyValueFilters(org.openremote.model.util.ValueUtil.applyValueFilters) AgentLink(org.openremote.model.asset.agent.AgentLink) Attribute(org.openremote.model.attribute.Attribute) Locale(java.util.Locale) TextUtil(org.openremote.model.util.TextUtil) JsonNodeType(com.fasterxml.jackson.databind.node.JsonNodeType) AttributeState(org.openremote.model.attribute.AttributeState) ValueType(org.openremote.model.value.ValueType) BinaryCodec(org.apache.commons.codec.binary.BinaryCodec) ValuePredicate(org.openremote.model.query.filter.ValuePredicate) Pair(org.openremote.model.util.Pair) Consumer(java.util.function.Consumer) ValueFilter(org.openremote.model.value.ValueFilter) TsIgnore(org.openremote.model.util.TsIgnore) Optional(java.util.Optional) AttributeLink(org.openremote.model.attribute.AttributeLink) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) AttributeState(org.openremote.model.attribute.AttributeState) ValuePredicate(org.openremote.model.query.filter.ValuePredicate) ValueFilter(org.openremote.model.value.ValueFilter)

Aggregations

AttributeState (org.openremote.model.attribute.AttributeState)13 Attribute (org.openremote.model.attribute.Attribute)6 AttributeRef (org.openremote.model.attribute.AttributeRef)6 AttributeEvent (org.openremote.model.attribute.AttributeEvent)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Consumer (java.util.function.Consumer)4 Logger (java.util.logging.Logger)4 SyslogCategory (org.openremote.model.syslog.SyslogCategory)4 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)3 Container (org.openremote.model.Container)3 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)3 ValueUtil (org.openremote.model.util.ValueUtil)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 List (java.util.List)2 Optional (java.util.Optional)2 Future (java.util.concurrent.Future)2 Level (java.util.logging.Level)2 AssetTreeNode (org.openremote.model.asset.AssetTreeNode)2 AgentLink.getOrThrowAgentLinkProperty (org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty)2