Search in sources :

Example 6 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext in project thingsboard by thingsboard.

the class SubscriptionManager method addRemoteWsSubscription.

public void addRemoteWsSubscription(PluginContext ctx, ServerAddress address, String sessionId, Subscription subscription) {
    EntityId entityId = subscription.getEntityId();
    log.trace("[{}] Registering remote subscription [{}] for device [{}] to [{}]", sessionId, subscription.getSubscriptionId(), entityId, address);
    registerSubscription(sessionId, entityId, subscription);
    if (subscription.getType() == SubscriptionType.ATTRIBUTES) {
        final Map<String, Long> keyStates = subscription.getKeyStates();
        ctx.loadAttributes(entityId, DataConstants.CLIENT_SCOPE, keyStates.keySet(), new PluginCallback<List<AttributeKvEntry>>() {

            @Override
            public void onSuccess(PluginContext ctx, List<AttributeKvEntry> values) {
                List<TsKvEntry> missedUpdates = new ArrayList<>();
                values.forEach(latestEntry -> {
                    if (latestEntry.getLastUpdateTs() > keyStates.get(latestEntry.getKey())) {
                        missedUpdates.add(new BasicTsKvEntry(latestEntry.getLastUpdateTs(), latestEntry));
                    }
                });
                if (!missedUpdates.isEmpty()) {
                    rpcHandler.onSubscriptionUpdate(ctx, address, sessionId, new SubscriptionUpdate(subscription.getSubscriptionId(), missedUpdates));
                }
            }

            @Override
            public void onFailure(PluginContext ctx, Exception e) {
                log.error("Failed to fetch missed updates.", e);
            }
        });
    } else if (subscription.getType() == SubscriptionType.TIMESERIES) {
        long curTs = System.currentTimeMillis();
        List<TsKvQuery> queries = new ArrayList<>();
        subscription.getKeyStates().entrySet().forEach(e -> {
            queries.add(new BaseTsKvQuery(e.getKey(), e.getValue() + 1L, curTs));
        });
        ctx.loadTimeseries(entityId, queries, new PluginCallback<List<TsKvEntry>>() {

            @Override
            public void onSuccess(PluginContext ctx, List<TsKvEntry> missedUpdates) {
                if (!missedUpdates.isEmpty()) {
                    rpcHandler.onSubscriptionUpdate(ctx, address, sessionId, new SubscriptionUpdate(subscription.getSubscriptionId(), missedUpdates));
                }
            }

            @Override
            public void onFailure(PluginContext ctx, Exception e) {
                log.error("Failed to fetch missed updates.", e);
            }
        });
    }
}
Also used : Setter(lombok.Setter) DeviceId(org.thingsboard.server.common.data.id.DeviceId) java.util(java.util) DataConstants(org.thingsboard.server.common.data.DataConstants) Predicate(java.util.function.Predicate) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) Function(java.util.function.Function) SubscriptionType(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionType) Slf4j(lombok.extern.slf4j.Slf4j) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) EntityId(org.thingsboard.server.common.data.id.EntityId) org.thingsboard.server.common.data.kv(org.thingsboard.server.common.data.kv) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback) TelemetryWebsocketMsgHandler(org.thingsboard.server.extensions.core.plugin.telemetry.handlers.TelemetryWebsocketMsgHandler) Subscription(org.thingsboard.server.extensions.core.plugin.telemetry.sub.Subscription) SubscriptionUpdate(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate) ServerAddress(org.thingsboard.server.common.msg.cluster.ServerAddress) TelemetryRpcMsgHandler(org.thingsboard.server.extensions.core.plugin.telemetry.handlers.TelemetryRpcMsgHandler) StringUtils(org.springframework.util.StringUtils) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) SubscriptionUpdate(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate) EntityId(org.thingsboard.server.common.data.id.EntityId) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 7 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext in project thingsboard by thingsboard.

the class TelemetryRestMsgHandler method handleHttpPostAttributes.

private boolean handleHttpPostAttributes(PluginContext ctx, PluginRestMsg msg, RestRequest request, EntityId entityId, String scope) throws ServletException, IOException {
    if (DataConstants.SERVER_SCOPE.equals(scope) || DataConstants.SHARED_SCOPE.equals(scope)) {
        JsonNode jsonNode;
        try {
            jsonNode = jsonMapper.readTree(request.getRequestBody());
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to parse attributes payload: Invalid JSON body!");
        }
        if (jsonNode.isObject()) {
            List<AttributeKvEntry> attributes = extractRequestAttributes(jsonNode);
            if (attributes.isEmpty()) {
                throw new IllegalArgumentException("No attributes data found in request body!");
            }
            ctx.saveAttributes(ctx.getSecurityCtx().orElseThrow(IllegalArgumentException::new).getTenantId(), entityId, scope, attributes, new PluginCallback<Void>() {

                @Override
                public void onSuccess(PluginContext ctx, Void value) {
                    ctx.logAttributesUpdated(msg.getSecurityCtx(), entityId, scope, attributes, null);
                    msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.OK));
                    subscriptionManager.onAttributesUpdateFromServer(ctx, entityId, scope, attributes);
                }

                @Override
                public void onFailure(PluginContext ctx, Exception e) {
                    log.error("Failed to save attributes", e);
                    ctx.logAttributesUpdated(msg.getSecurityCtx(), entityId, scope, attributes, e);
                    handleError(e, msg, HttpStatus.BAD_REQUEST);
                }
            });
            return true;
        }
    }
    return false;
}
Also used : ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) JsonNode(com.fasterxml.jackson.databind.JsonNode) ServletException(javax.servlet.ServletException) UncheckedApiException(org.thingsboard.server.extensions.api.exception.UncheckedApiException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvalidParametersException(org.thingsboard.server.extensions.api.exception.InvalidParametersException)

Example 8 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext in project thingsboard by thingsboard.

the class TelemetryRestMsgHandler method getTsKvListCallback.

private PluginCallback<List<TsKvEntry>> getTsKvListCallback(final PluginRestMsg msg) {
    return new PluginCallback<List<TsKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<TsKvEntry> data) {
            Map<String, List<TsData>> result = new LinkedHashMap<>();
            for (TsKvEntry entry : data) {
                List<TsData> vList = result.get(entry.getKey());
                if (vList == null) {
                    vList = new ArrayList<>();
                    result.put(entry.getKey(), vList);
                }
                vList.add(new TsData(entry.getTs(), entry.getValueAsString()));
            }
            msg.getResponseHolder().setResult(new ResponseEntity<>(result, HttpStatus.OK));
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error("Failed to fetch historical data", e);
            handleError(e, msg, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    };
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) TsData(org.thingsboard.server.extensions.core.plugin.telemetry.TsData) ServletException(javax.servlet.ServletException) UncheckedApiException(org.thingsboard.server.extensions.api.exception.UncheckedApiException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvalidParametersException(org.thingsboard.server.extensions.api.exception.InvalidParametersException) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 9 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext in project thingsboard by thingsboard.

the class TelemetryRuleMsgHandler method handleTelemetryUploadRequest.

@Override
public void handleTelemetryUploadRequest(PluginContext ctx, TenantId tenantId, RuleId ruleId, TelemetryUploadRequestRuleToPluginMsg msg) {
    TelemetryUploadRequest request = msg.getPayload();
    List<TsKvEntry> tsKvEntries = new ArrayList<>();
    for (Map.Entry<Long, List<KvEntry>> entry : request.getData().entrySet()) {
        for (KvEntry kv : entry.getValue()) {
            tsKvEntries.add(new BasicTsKvEntry(entry.getKey(), kv));
        }
    }
    ctx.saveTsData(msg.getDeviceId(), tsKvEntries, msg.getTtl(), new PluginCallback<Void>() {

        @Override
        public void onSuccess(PluginContext ctx, Void data) {
            ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onSuccess(request.getMsgType(), request.getRequestId())));
            subscriptionManager.onLocalSubscriptionUpdate(ctx, msg.getDeviceId(), SubscriptionType.TIMESERIES, s -> prepareSubscriptionUpdate(request, s));
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error("Failed to process telemetry upload request", e);
            ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onError(request.getMsgType(), request.getRequestId(), e)));
        }
    });
}
Also used : DeviceId(org.thingsboard.server.common.data.id.DeviceId) RuleId(org.thingsboard.server.common.data.id.RuleId) java.util(java.util) DataConstants(org.thingsboard.server.common.data.DataConstants) org.thingsboard.server.common.msg.core(org.thingsboard.server.common.msg.core) UpdateAttributesRequestRuleToPluginMsg(org.thingsboard.server.extensions.api.plugins.msg.UpdateAttributesRequestRuleToPluginMsg) SubscriptionManager(org.thingsboard.server.extensions.core.plugin.telemetry.SubscriptionManager) ResponsePluginToRuleMsg(org.thingsboard.server.extensions.api.plugins.msg.ResponsePluginToRuleMsg) BasicAttributeKVMsg(org.thingsboard.server.common.msg.kv.BasicAttributeKVMsg) Collectors(java.util.stream.Collectors) TenantId(org.thingsboard.server.common.data.id.TenantId) SubscriptionType(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionType) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) GetAttributesRequestRuleToPluginMsg(org.thingsboard.server.extensions.api.plugins.msg.GetAttributesRequestRuleToPluginMsg) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) DefaultRuleMsgHandler(org.thingsboard.server.extensions.api.plugins.handlers.DefaultRuleMsgHandler) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback) TelemetryUploadRequestRuleToPluginMsg(org.thingsboard.server.extensions.api.plugins.msg.TelemetryUploadRequestRuleToPluginMsg) Subscription(org.thingsboard.server.extensions.core.plugin.telemetry.sub.Subscription) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) ResponsePluginToRuleMsg(org.thingsboard.server.extensions.api.plugins.msg.ResponsePluginToRuleMsg)

Example 10 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext in project thingsboard by thingsboard.

the class TelemetryWebsocketMsgHandler method handleWsHistoryCmd.

private void handleWsHistoryCmd(PluginContext ctx, PluginWebsocketSessionRef sessionRef, GetHistoryCmd cmd) {
    String sessionId = sessionRef.getSessionId();
    WsSessionMetaData sessionMD = wsSessionsMap.get(sessionId);
    if (sessionMD == null) {
        log.warn("[{}] Session meta data not found. ", sessionId);
        SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, SESSION_META_DATA_NOT_FOUND);
        sendWsMsg(ctx, sessionRef, update);
        return;
    }
    if (cmd.getEntityId() == null || cmd.getEntityId().isEmpty() || cmd.getEntityType() == null || cmd.getEntityType().isEmpty()) {
        SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Device id is empty!");
        sendWsMsg(ctx, sessionRef, update);
        return;
    }
    if (cmd.getKeys() == null || cmd.getKeys().isEmpty()) {
        SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Keys are empty!");
        sendWsMsg(ctx, sessionRef, update);
        return;
    }
    EntityId entityId = EntityIdFactory.getByTypeAndId(cmd.getEntityType(), cmd.getEntityId());
    List<String> keys = new ArrayList<>(getKeys(cmd).orElse(Collections.emptySet()));
    List<TsKvQuery> queries = keys.stream().map(key -> new BaseTsKvQuery(key, cmd.getStartTs(), cmd.getEndTs(), cmd.getInterval(), getLimit(cmd.getLimit()), getAggregation(cmd.getAgg()))).collect(Collectors.toList());
    ctx.loadTimeseries(entityId, queries, new PluginCallback<List<TsKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<TsKvEntry> data) {
            sendWsMsg(ctx, sessionRef, new SubscriptionUpdate(cmd.getCmdId(), data));
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            SubscriptionUpdate update;
            if (UnauthorizedException.class.isInstance(e)) {
                update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.UNAUTHORIZED, SubscriptionErrorCode.UNAUTHORIZED.getDefaultMsg());
            } else {
                update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            }
            sendWsMsg(ctx, sessionRef, update);
        }
    });
}
Also used : java.util(java.util) TextPluginWebSocketMsg(org.thingsboard.server.extensions.api.plugins.ws.msg.TextPluginWebSocketMsg) DefaultWebsocketMsgHandler(org.thingsboard.server.extensions.api.plugins.handlers.DefaultWebsocketMsgHandler) org.thingsboard.server.extensions.core.plugin.telemetry.cmd(org.thingsboard.server.extensions.core.plugin.telemetry.cmd) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) EntityId(org.thingsboard.server.common.data.id.EntityId) DataConstants(org.thingsboard.server.common.data.DataConstants) PluginWebsocketSessionRef(org.thingsboard.server.extensions.api.plugins.ws.PluginWebsocketSessionRef) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SubscriptionManager(org.thingsboard.server.extensions.core.plugin.telemetry.SubscriptionManager) IOException(java.io.IOException) PluginWebsocketMsg(org.thingsboard.server.extensions.api.plugins.ws.msg.PluginWebsocketMsg) Collectors(java.util.stream.Collectors) SubscriptionType(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionType) Slf4j(lombok.extern.slf4j.Slf4j) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) BinaryPluginWebSocketMsg(org.thingsboard.server.extensions.api.plugins.ws.msg.BinaryPluginWebSocketMsg) UnauthorizedException(org.thingsboard.server.extensions.api.exception.UnauthorizedException) org.thingsboard.server.common.data.kv(org.thingsboard.server.common.data.kv) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback) SubscriptionUpdate(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate) SubscriptionErrorCode(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionErrorCode) StringUtils(org.springframework.util.StringUtils) WsSessionMetaData(org.thingsboard.server.extensions.api.plugins.ws.WsSessionMetaData) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) SubscriptionUpdate(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) UnauthorizedException(org.thingsboard.server.extensions.api.exception.UnauthorizedException) EntityId(org.thingsboard.server.common.data.id.EntityId) UnauthorizedException(org.thingsboard.server.extensions.api.exception.UnauthorizedException) WsSessionMetaData(org.thingsboard.server.extensions.api.plugins.ws.WsSessionMetaData)

Aggregations

PluginContext (org.thingsboard.server.extensions.api.plugins.PluginContext)14 IOException (java.io.IOException)9 PluginCallback (org.thingsboard.server.extensions.api.plugins.PluginCallback)9 EntityId (org.thingsboard.server.common.data.id.EntityId)6 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 java.util (java.util)5 ServletException (javax.servlet.ServletException)5 Slf4j (lombok.extern.slf4j.Slf4j)5 DataConstants (org.thingsboard.server.common.data.DataConstants)5 SubscriptionState (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState)5 SubscriptionType (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionType)5 SubscriptionUpdate (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 Collectors (java.util.stream.Collectors)4 ResponseEntity (org.springframework.http.ResponseEntity)4 StringUtils (org.springframework.util.StringUtils)4 DeviceId (org.thingsboard.server.common.data.id.DeviceId)4 org.thingsboard.server.common.data.kv (org.thingsboard.server.common.data.kv)4 InvalidParametersException (org.thingsboard.server.extensions.api.exception.InvalidParametersException)4 ToErrorResponseEntity (org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity)4