Search in sources :

Example 26 with AttributeRef

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

the class AssetDatapointService method aggregateDatapoints.

public NumberDatapoint[] aggregateDatapoints(AssetAttribute attribute, DatapointInterval datapointInterval, long timestamp) {
    LOG.fine("Aggregating datapoints for: " + attribute);
    AttributeRef attributeRef = attribute.getReferenceOrThrow();
    return persistenceService.doReturningTransaction(entityManager -> entityManager.unwrap(Session.class).doReturningWork(new AbstractReturningWork<NumberDatapoint[]>() {

        @Override
        public NumberDatapoint[] execute(Connection connection) throws SQLException {
            String truncateX;
            String step;
            String interval;
            Function<Timestamp, String> labelFunction;
            SimpleDateFormat dayFormat = new SimpleDateFormat("dd. MMM yyyy");
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
            switch(datapointInterval) {
                case HOUR:
                    truncateX = "minute";
                    step = "1 minute";
                    interval = "1 hour";
                    labelFunction = timeFormat::format;
                    break;
                case DAY:
                    truncateX = "hour";
                    step = "1 hour";
                    interval = "1 day";
                    labelFunction = timeFormat::format;
                    break;
                case WEEK:
                    truncateX = "day";
                    step = "1 day";
                    interval = "7 day";
                    labelFunction = dayFormat::format;
                    break;
                case MONTH:
                    truncateX = "day";
                    step = "1 day";
                    interval = "1 month";
                    labelFunction = dayFormat::format;
                    break;
                case YEAR:
                    truncateX = "month";
                    step = "1 month";
                    interval = "1 year";
                    labelFunction = dayFormat::format;
                    break;
                default:
                    throw new IllegalArgumentException("Can't handle interval: " + datapointInterval);
            }
            StringBuilder query = new StringBuilder();
            query.append("select TS as X, coalesce(AVG_VALUE, null) as Y " + " from ( " + "       select date_trunc(?, GS)::timestamp TS " + "       from generate_series(to_timestamp(?) - ?, to_timestamp(?), ?) GS " + "       ) TS " + "  left join ( " + "       select " + "           date_trunc(?, to_timestamp(TIMESTAMP / 1000))::timestamp as TS, ");
            switch(attribute.getTypeOrThrow().getValueType()) {
                case NUMBER:
                    query.append(" AVG(VALUE::text::numeric) as AVG_VALUE ");
                    break;
                case BOOLEAN:
                    query.append(" AVG(case when VALUE::text::boolean is true then 1 else 0 end) as AVG_VALUE ");
                    break;
                default:
                    throw new IllegalArgumentException("Can't aggregate number datapoints for type of: " + attribute);
            }
            query.append(" from ASSET_DATAPOINT " + "         where " + "           to_timestamp(TIMESTAMP / 1000) >= to_timestamp(?) - ? " + "           and " + "           to_timestamp(TIMESTAMP / 1000) <= to_timestamp(?) " + "           and " + "           ENTITY_ID = ? and ATTRIBUTE_NAME = ? " + "         group by TS " + "  ) DP using (TS) " + " order by TS asc ");
            PreparedStatement st = connection.prepareStatement(query.toString());
            long timestampSeconds = timestamp / 1000;
            st.setString(1, truncateX);
            st.setLong(2, timestampSeconds);
            st.setObject(3, new PGInterval(interval));
            st.setLong(4, timestampSeconds);
            st.setObject(5, new PGInterval(step));
            st.setString(6, truncateX);
            st.setLong(7, timestampSeconds);
            st.setObject(8, new PGInterval(interval));
            st.setLong(9, timestampSeconds);
            st.setString(10, attributeRef.getEntityId());
            st.setString(11, attributeRef.getAttributeName());
            try (ResultSet rs = st.executeQuery()) {
                List<NumberDatapoint> result = new ArrayList<>();
                while (rs.next()) {
                    String label = labelFunction.apply(rs.getTimestamp(1));
                    Number value = rs.getObject(2) != null ? rs.getDouble(2) : null;
                    result.add(new NumberDatapoint(label, value));
                }
                return result.toArray(new NumberDatapoint[result.size()]);
            }
        }
    }));
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef) AbstractReturningWork(org.hibernate.jdbc.AbstractReturningWork) ArrayList(java.util.ArrayList) PGInterval(org.postgresql.util.PGInterval) NumberDatapoint(org.openremote.model.datapoint.NumberDatapoint) SimpleDateFormat(java.text.SimpleDateFormat)

Example 27 with AttributeRef

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

the class AbstractProtocol method unlinkAttribute.

@Override
public final void unlinkAttribute(String assetId, Attribute<?> attribute) throws Exception {
    withLock(getProtocolName() + "::unlinkAttributes", () -> {
        AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
        if (linkedAttributes.remove(attributeRef) != null) {
            dynamicAttributes.remove(attributeRef);
            doUnlinkAttribute(assetId, attribute, agent.getAgentLink(attribute));
        }
    });
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef)

Example 28 with AttributeRef

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

the class AbstractProtocol method linkAttribute.

@Override
public final void linkAttribute(String assetId, Attribute<?> attribute) throws Exception {
    withLock(getProtocolName() + "::linkAttribute", () -> {
        AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
        if (linkedAttributes.containsKey(attributeRef)) {
            LOG.warning("Attribute is already linked to this protocol so ignoring: " + attributeRef);
            return;
        }
        // Need to add to map before actual linking as protocols may want to update the value as part of
        // linking process and without entry in the map any update would be blocked
        linkedAttributes.put(attributeRef, attribute);
        if (hasDynamicWriteValue(agent.getAgentLink(attribute))) {
            dynamicAttributes.add(attributeRef);
        }
        try {
            doLinkAttribute(assetId, attribute, agent.getAgentLink(attribute));
        } catch (Exception e) {
            linkedAttributes.remove(attributeRef);
            throw new RuntimeException(e);
        }
    });
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef)

Example 29 with AttributeRef

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

the class WebsocketAgentProtocol method doLinkAttribute.

@Override
protected void doLinkAttribute(String assetId, Attribute<?> attribute, WebsocketAgentLink agentLink) {
    Optional<WebsocketSubscription[]> subscriptions = agentLink.getWebsocketSubscriptions();
    AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
    subscriptions.ifPresent(websocketSubscriptions -> {
        Runnable task = () -> doSubscriptions(clientHeaders, websocketSubscriptions);
        addAttributeConnectedTask(attributeRef, task);
        if (client.getConnectionStatus() == ConnectionStatus.CONNECTED) {
            executorService.schedule(task, 1000, TimeUnit.MILLISECONDS);
        }
    });
    Consumer<String> messageConsumer = ProtocolUtil.createGenericAttributeMessageConsumer(assetId, attribute, agent.getAgentLink(attribute), timerService::getCurrentTimeMillis, this::updateLinkedAttribute);
    if (messageConsumer != null) {
        protocolMessageConsumers.add(new Pair<>(attributeRef, messageConsumer));
    }
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef)

Example 30 with AttributeRef

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

the class UDPProtocol method doUnlinkAttribute.

@Override
protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
    AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
    protocolMessageConsumers.removeIf(attributeRefConsumerPair -> attributeRefConsumerPair.key.equals(attributeRef));
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef)

Aggregations

AttributeRef (org.openremote.model.attribute.AttributeRef)42 Logger (java.util.logging.Logger)9 AttributeEvent (org.openremote.model.attribute.AttributeEvent)8 AttributeState (org.openremote.model.attribute.AttributeState)8 Attribute (org.openremote.model.attribute.Attribute)7 List (java.util.List)6 Level (java.util.logging.Level)6 Container (org.openremote.model.Container)6 SyslogCategory (org.openremote.model.syslog.SyslogCategory)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 ScheduledFuture (java.util.concurrent.ScheduledFuture)5 Consumer (java.util.function.Consumer)5 Asset (org.openremote.model.asset.Asset)5 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 HashMap (java.util.HashMap)4 TimeUnit (java.util.concurrent.TimeUnit)4 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)4 AssetStorageService (org.openremote.manager.asset.AssetStorageService)4 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)4