Search in sources :

Example 1 with PluginCallback

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

the class DeviceMessagingRuleMsgHandler method processSendMsg.

private void processSendMsg(PluginContext ctx, PendingRpcRequestMetadata requestMd, ToServerRpcRequestMsg request) {
    JsonObject params = new JsonParser().parse(request.getParams()).getAsJsonObject();
    String targetDeviceIdStr = params.get(DEVICE_ID).getAsString();
    DeviceId targetDeviceId = DeviceId.fromString(targetDeviceIdStr);
    boolean oneWay = isOneWay(params);
    long timeout = getTimeout(params);
    if (timeout <= 0) {
        replyWithError(ctx, requestMd, "Timeout can't be negative!");
    } else if (timeout > configuration.getMaxTimeout()) {
        replyWithError(ctx, requestMd, "Timeout is too large!");
    } else {
        ctx.getDevice(targetDeviceId, new PluginCallback<Device>() {

            @Override
            public void onSuccess(PluginContext ctx, Device targetDevice) {
                UUID uid = UUID.randomUUID();
                if (targetDevice == null) {
                    replyWithError(ctx, requestMd, RpcError.NOT_FOUND);
                } else if (!requestMd.getCustomerId().isNullUid() && requestMd.getTenantId().equals(targetDevice.getTenantId()) && requestMd.getCustomerId().equals(targetDevice.getCustomerId())) {
                    pendingMsgs.put(uid, requestMd);
                    log.trace("[{}] Forwarding {} to [{}]", uid, params, targetDeviceId);
                    ToDeviceRpcRequestBody requestBody = new ToDeviceRpcRequestBody(ON_MSG_METHOD_NAME, GSON.toJson(params.get("body")));
                    ctx.sendRpcRequest(new ToDeviceRpcRequest(uid, null, targetDevice.getTenantId(), targetDeviceId, oneWay, System.currentTimeMillis() + timeout, requestBody));
                } else {
                    replyWithError(ctx, requestMd, RpcError.FORBIDDEN);
                }
            }

            @Override
            public void onFailure(PluginContext ctx, Exception e) {
                replyWithError(ctx, requestMd, RpcError.INTERNAL);
            }
        });
    }
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Device(org.thingsboard.server.common.data.Device) JsonObject(com.google.gson.JsonObject) RuleException(org.thingsboard.server.extensions.api.rules.RuleException) JsonParser(com.google.gson.JsonParser) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 2 with PluginCallback

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

the class TelemetryWebsocketMsgHandler method getSubscriptionCallback.

private PluginCallback<List<TsKvEntry>> getSubscriptionCallback(final PluginWebsocketSessionRef sessionRef, final TimeseriesSubscriptionCmd cmd, final String sessionId, final EntityId entityId, final long startTs, final List<String> keys) {
    return new PluginCallback<List<TsKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<TsKvEntry> data) {
            sendWsMsg(ctx, sessionRef, new SubscriptionUpdate(cmd.getCmdId(), data));
            Map<String, Long> subState = new HashMap<>(keys.size());
            keys.forEach(key -> subState.put(key, startTs));
            data.forEach(v -> subState.put(v.getKey(), v.getTs()));
            SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, SubscriptionType.TIMESERIES, false, subState, cmd.getScope());
            subscriptionManager.addLocalWsSubscription(ctx, sessionId, entityId, sub);
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error(FAILED_TO_FETCH_DATA, e);
            SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            sendWsMsg(ctx, sessionRef, update);
        }
    };
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) 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) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 3 with PluginCallback

use of org.thingsboard.server.extensions.api.plugins.PluginCallback 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 4 with PluginCallback

use of org.thingsboard.server.extensions.api.plugins.PluginCallback 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 5 with PluginCallback

use of org.thingsboard.server.extensions.api.plugins.PluginCallback 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)

Aggregations

PluginCallback (org.thingsboard.server.extensions.api.plugins.PluginCallback)9 PluginContext (org.thingsboard.server.extensions.api.plugins.PluginContext)9 IOException (java.io.IOException)5 java.util (java.util)5 Slf4j (lombok.extern.slf4j.Slf4j)5 DataConstants (org.thingsboard.server.common.data.DataConstants)5 EntityId (org.thingsboard.server.common.data.id.EntityId)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 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Collectors (java.util.stream.Collectors)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 UnauthorizedException (org.thingsboard.server.extensions.api.exception.UnauthorizedException)4 SubscriptionManager (org.thingsboard.server.extensions.core.plugin.telemetry.SubscriptionManager)4 EntityIdFactory (org.thingsboard.server.common.data.id.EntityIdFactory)3 DefaultWebsocketMsgHandler (org.thingsboard.server.extensions.api.plugins.handlers.DefaultWebsocketMsgHandler)3 PluginWebsocketSessionRef (org.thingsboard.server.extensions.api.plugins.ws.PluginWebsocketSessionRef)3