Search in sources :

Example 11 with PluginContext

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

the class TelemetryWebsocketMsgHandler method handleWsAttributesSubscriptionByKeys.

private void handleWsAttributesSubscriptionByKeys(PluginContext ctx, PluginWebsocketSessionRef sessionRef, AttributesSubscriptionCmd cmd, String sessionId, EntityId entityId, List<String> keys) {
    PluginCallback<List<AttributeKvEntry>> callback = new PluginCallback<List<AttributeKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<AttributeKvEntry> data) {
            List<TsKvEntry> attributesData = data.stream().map(d -> new BasicTsKvEntry(d.getLastUpdateTs(), d)).collect(Collectors.toList());
            sendWsMsg(ctx, sessionRef, new SubscriptionUpdate(cmd.getCmdId(), attributesData));
            Map<String, Long> subState = new HashMap<>(keys.size());
            keys.forEach(key -> subState.put(key, 0L));
            attributesData.forEach(v -> subState.put(v.getKey(), v.getTs()));
            SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, SubscriptionType.ATTRIBUTES, false, subState, cmd.getScope());
            subscriptionManager.addLocalWsSubscription(ctx, sessionId, entityId, sub);
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error(FAILED_TO_FETCH_ATTRIBUTES, 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_ATTRIBUTES);
            }
            sendWsMsg(ctx, sessionRef, update);
        }
    };
    if (StringUtils.isEmpty(cmd.getScope())) {
        ctx.loadAttributes(entityId, Arrays.asList(DataConstants.allScopes()), keys, callback);
    } else {
        ctx.loadAttributes(entityId, cmd.getScope(), keys, callback);
    }
}
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) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 12 with PluginContext

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

the class TelemetryWebsocketMsgHandler method handleWsAttributesSubscription.

private void handleWsAttributesSubscription(PluginContext ctx, PluginWebsocketSessionRef sessionRef, AttributesSubscriptionCmd cmd, String sessionId, EntityId entityId) {
    PluginCallback<List<AttributeKvEntry>> callback = new PluginCallback<List<AttributeKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<AttributeKvEntry> data) {
            List<TsKvEntry> attributesData = data.stream().map(d -> new BasicTsKvEntry(d.getLastUpdateTs(), d)).collect(Collectors.toList());
            sendWsMsg(ctx, sessionRef, new SubscriptionUpdate(cmd.getCmdId(), attributesData));
            Map<String, Long> subState = new HashMap<>(attributesData.size());
            attributesData.forEach(v -> subState.put(v.getKey(), v.getTs()));
            SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, SubscriptionType.ATTRIBUTES, true, subState, cmd.getScope());
            subscriptionManager.addLocalWsSubscription(ctx, sessionId, entityId, sub);
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error(FAILED_TO_FETCH_ATTRIBUTES, e);
            SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_ATTRIBUTES);
            sendWsMsg(ctx, sessionRef, update);
        }
    };
    if (StringUtils.isEmpty(cmd.getScope())) {
        ctx.loadAttributes(entityId, Arrays.asList(DataConstants.allScopes()), callback);
    } else {
        ctx.loadAttributes(entityId, cmd.getScope(), callback);
    }
}
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) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 13 with PluginContext

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

the class RpcRestMsgHandler method handleDeviceRPCRequest.

private boolean handleDeviceRPCRequest(PluginContext ctx, final PluginRestMsg msg, TenantId tenantId, DeviceId deviceId, RpcRequest cmd, boolean oneWay) throws JsonProcessingException {
    long timeout = System.currentTimeMillis() + (cmd.getTimeout() != null ? cmd.getTimeout() : defaultTimeout);
    ToDeviceRpcRequestBody body = new ToDeviceRpcRequestBody(cmd.getMethodName(), cmd.getRequestData());
    ctx.checkAccess(deviceId, new PluginCallback<Void>() {

        @Override
        public void onSuccess(PluginContext ctx, Void value) {
            ToDeviceRpcRequest rpcRequest = new ToDeviceRpcRequest(UUID.randomUUID(), msg.getSecurityCtx(), tenantId, deviceId, oneWay, timeout, body);
            rpcManager.process(ctx, new LocalRequestMetaData(rpcRequest, msg.getResponseHolder()));
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            ResponseEntity response;
            if (e instanceof ToErrorResponseEntity) {
                response = ((ToErrorResponseEntity) e).toErrorResponseEntity();
            } else {
                response = new ResponseEntity(HttpStatus.UNAUTHORIZED);
            }
            ctx.logRpcRequest(msg.getSecurityCtx(), deviceId, body, oneWay, Optional.empty(), e);
            msg.getResponseHolder().setResult(response);
        }
    });
    return true;
}
Also used : ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) LocalRequestMetaData(org.thingsboard.server.extensions.core.plugin.rpc.LocalRequestMetaData) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) ToDeviceRpcRequest(org.thingsboard.server.extensions.api.plugins.msg.ToDeviceRpcRequest) ToDeviceRpcRequestBody(org.thingsboard.server.extensions.api.plugins.msg.ToDeviceRpcRequestBody) ServletException(javax.servlet.ServletException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity)

Example 14 with PluginContext

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

the class RpcRuleMsgHandler method handle.

private void handle(final PluginContext ctx, TenantId tenantId, RuleId ruleId, ServerSideRpcCallActionMsg msg) {
    DeviceId deviceId = new DeviceId(UUID.fromString(msg.getDeviceId()));
    ctx.checkAccess(deviceId, new PluginCallback<Void>() {

        @Override
        public void onSuccess(PluginContext dummy, Void value) {
            try {
                List<EntityId> deviceIds;
                if (StringUtils.isEmpty(msg.getFromDeviceRelation()) && StringUtils.isEmpty(msg.getToDeviceRelation())) {
                    deviceIds = Collections.singletonList(deviceId);
                } else if (!StringUtils.isEmpty(msg.getFromDeviceRelation())) {
                    List<EntityRelation> relations = ctx.findByFromAndType(deviceId, msg.getFromDeviceRelation()).get();
                    deviceIds = relations.stream().map(EntityRelation::getTo).collect(Collectors.toList());
                } else {
                    List<EntityRelation> relations = ctx.findByToAndType(deviceId, msg.getFromDeviceRelation()).get();
                    deviceIds = relations.stream().map(EntityRelation::getFrom).collect(Collectors.toList());
                }
                ToDeviceRpcRequestBody body = new ToDeviceRpcRequestBody(msg.getRpcCallMethod(), msg.getRpcCallBody());
                long expirationTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(msg.getRpcCallTimeoutInSec());
                for (EntityId address : deviceIds) {
                    DeviceId tmpId = new DeviceId(address.getId());
                    ctx.checkAccess(tmpId, new PluginCallback<Void>() {

                        @Override
                        public void onSuccess(PluginContext ctx, Void value) {
                            ctx.sendRpcRequest(new ToDeviceRpcRequest(UUID.randomUUID(), null, tenantId, tmpId, true, expirationTime, body));
                            log.trace("[{}] Sent RPC Call Action msg", tmpId);
                        }

                        @Override
                        public void onFailure(PluginContext ctx, Exception e) {
                            log.info("[{}] Failed to process RPC Call Action msg", tmpId, e);
                        }
                    });
                }
            } catch (Exception e) {
                log.info("Failed to process RPC Call Action msg", e);
            }
        }

        @Override
        public void onFailure(PluginContext dummy, Exception e) {
            log.info("[{}] Failed to process RPC Call Action msg", deviceId, e);
        }
    });
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) DeviceId(org.thingsboard.server.common.data.id.DeviceId) RuleException(org.thingsboard.server.extensions.api.rules.RuleException) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) ToDeviceRpcRequest(org.thingsboard.server.extensions.api.plugins.msg.ToDeviceRpcRequest) ToDeviceRpcRequestBody(org.thingsboard.server.extensions.api.plugins.msg.ToDeviceRpcRequestBody) List(java.util.List) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

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