Search in sources :

Example 1 with FromDeviceRpcResponse

use of org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method processRpcResponseStatus.

private void processRpcResponseStatus(TbActorCtx context, SessionInfoProto sessionInfo, ToDeviceRpcResponseStatusMsg responseMsg) {
    UUID rpcId = new UUID(responseMsg.getRequestIdMSB(), responseMsg.getRequestIdLSB());
    RpcStatus status = RpcStatus.valueOf(responseMsg.getStatus());
    ToDeviceRpcRequestMetadata md = toDeviceRpcPendingMap.get(responseMsg.getRequestId());
    if (md != null) {
        JsonNode response = null;
        if (status.equals(RpcStatus.DELIVERED)) {
            if (md.getMsg().getMsg().isOneway()) {
                toDeviceRpcPendingMap.remove(responseMsg.getRequestId());
                if (rpcSequential) {
                    systemContext.getTbCoreDeviceRpcService().processRpcResponseFromDeviceActor(new FromDeviceRpcResponse(rpcId, null, null));
                }
            } else {
                md.setDelivered(true);
            }
        } else if (status.equals(RpcStatus.TIMEOUT)) {
            Integer maxRpcRetries = md.getMsg().getMsg().getRetries();
            maxRpcRetries = maxRpcRetries == null ? systemContext.getMaxRpcRetries() : Math.min(maxRpcRetries, systemContext.getMaxRpcRetries());
            if (maxRpcRetries <= md.getRetries()) {
                toDeviceRpcPendingMap.remove(responseMsg.getRequestId());
                status = RpcStatus.FAILED;
                response = JacksonUtil.newObjectNode().put("error", "There was a Timeout and all retry attempts have been exhausted. Retry attempts set: " + maxRpcRetries);
            } else {
                md.setRetries(md.getRetries() + 1);
            }
        }
        if (md.getMsg().getMsg().isPersisted()) {
            systemContext.getTbRpcService().save(tenantId, new RpcId(rpcId), status, response);
        }
        if (status != RpcStatus.SENT) {
            sendNextPendingRequest(context);
        }
    } else {
        log.info("[{}][{}] Rpc has already removed from pending map.", deviceId, rpcId);
    }
}
Also used : FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) RpcId(org.thingsboard.server.common.data.id.RpcId) JsonNode(com.fasterxml.jackson.databind.JsonNode) UUID(java.util.UUID) RpcStatus(org.thingsboard.server.common.data.rpc.RpcStatus)

Example 2 with FromDeviceRpcResponse

use of org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method processRpcRequest.

void processRpcRequest(TbActorCtx context, ToDeviceRpcRequestActorMsg msg) {
    ToDeviceRpcRequest request = msg.getMsg();
    ToDeviceRpcRequestMsg rpcRequest = creteToDeviceRpcRequestMsg(request);
    long timeout = request.getExpirationTime() - System.currentTimeMillis();
    boolean persisted = request.isPersisted();
    if (timeout <= 0) {
        log.debug("[{}][{}] Ignoring message due to exp time reached, {}", deviceId, request.getId(), request.getExpirationTime());
        if (persisted) {
            createRpc(request, RpcStatus.EXPIRED);
        }
        return;
    } else if (persisted) {
        createRpc(request, RpcStatus.QUEUED);
    }
    boolean sent = false;
    if (systemContext.isEdgesEnabled() && edgeId != null) {
        log.debug("[{}][{}] device is related to edge [{}]. Saving RPC request to edge queue", tenantId, deviceId, edgeId.getId());
        saveRpcRequestToEdgeQueue(request, rpcRequest.getRequestId());
        sent = true;
    } else if (isSendNewRpcAvailable()) {
        sent = rpcSubscriptions.size() > 0;
        Set<UUID> syncSessionSet = new HashSet<>();
        rpcSubscriptions.forEach((key, value) -> {
            sendToTransport(rpcRequest, key, value.getNodeId());
            if (SessionType.SYNC == value.getType()) {
                syncSessionSet.add(key);
            }
        });
        log.trace("Rpc syncSessionSet [{}] subscription after sent [{}]", syncSessionSet, rpcSubscriptions);
        syncSessionSet.forEach(rpcSubscriptions::remove);
    }
    if (persisted) {
        ObjectNode response = JacksonUtil.newObjectNode();
        response.put("rpcId", request.getId().toString());
        systemContext.getTbCoreDeviceRpcService().processRpcResponseFromDeviceActor(new FromDeviceRpcResponse(msg.getMsg().getId(), JacksonUtil.toString(response), null));
    }
    if (!persisted && request.isOneway() && sent) {
        log.debug("[{}] Rpc command response sent [{}]!", deviceId, request.getId());
        systemContext.getTbCoreDeviceRpcService().processRpcResponseFromDeviceActor(new FromDeviceRpcResponse(msg.getMsg().getId(), null, null));
    } else {
        registerPendingRpcRequest(context, msg, sent, rpcRequest, timeout);
    }
    if (sent) {
        log.debug("[{}] RPC request {} is sent!", deviceId, request.getId());
    } else {
        log.debug("[{}] RPC request {} is NOT sent!", deviceId, request.getId());
    }
}
Also used : Arrays(java.util.Arrays) RpcStatus(org.thingsboard.server.common.data.rpc.RpcStatus) KeyValueType(org.thingsboard.server.gen.transport.TransportProtos.KeyValueType) ToDeviceRpcRequestActorMsg(org.thingsboard.server.service.rpc.ToDeviceRpcRequestActorMsg) TenantId(org.thingsboard.server.common.data.id.TenantId) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) SessionType(org.thingsboard.server.gen.transport.TransportProtos.SessionType) FromDeviceRpcResponseActorMsg(org.thingsboard.server.service.rpc.FromDeviceRpcResponseActorMsg) ActorSystemContext(org.thingsboard.server.actors.ActorSystemContext) Rpc(org.thingsboard.server.common.data.rpc.Rpc) AbstractContextAwareMsgProcessor(org.thingsboard.server.actors.shared.AbstractContextAwareMsgProcessor) SubscribeToAttributeUpdatesMsg(org.thingsboard.server.gen.transport.TransportProtos.SubscribeToAttributeUpdatesMsg) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) DeviceAttributesEventNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceAttributesEventNotificationMsg) DeviceCredentialsUpdateNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceCredentialsUpdateNotificationMsg) EdgeId(org.thingsboard.server.common.data.id.EdgeId) GetAttributeResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.GetAttributeResponseMsg) TransportToDeviceActorMsg(org.thingsboard.server.gen.transport.TransportProtos.TransportToDeviceActorMsg) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ClaimDeviceMsg(org.thingsboard.server.gen.transport.TransportProtos.ClaimDeviceMsg) DeviceId(org.thingsboard.server.common.data.id.DeviceId) PageLink(org.thingsboard.server.common.data.page.PageLink) ToTransportUpdateCredentialsProto(org.thingsboard.server.gen.transport.TransportProtos.ToTransportUpdateCredentialsProto) StringUtils(org.thingsboard.server.common.data.StringUtils) Set(java.util.Set) TbActorCtx(org.thingsboard.server.actors.TbActorCtx) UUID(java.util.UUID) SortOrder(org.thingsboard.server.common.data.page.SortOrder) Collectors(java.util.stream.Collectors) EdgeEventActionType(org.thingsboard.server.common.data.edge.EdgeEventActionType) ToServerRpcResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) SubscribeToRPCMsg(org.thingsboard.server.gen.transport.TransportProtos.SubscribeToRPCMsg) TbActorMsg(org.thingsboard.server.common.msg.TbActorMsg) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) DeviceNameOrTypeUpdateMsg(org.thingsboard.rule.engine.api.msg.DeviceNameOrTypeUpdateMsg) TransportProtos(org.thingsboard.server.gen.transport.TransportProtos) GetAttributeRequestMsg(org.thingsboard.server.gen.transport.TransportProtos.GetAttributeRequestMsg) Optional(java.util.Optional) ToDeviceRpcRequestBody(org.thingsboard.server.common.data.rpc.ToDeviceRpcRequestBody) RemoveRpcActorMsg(org.thingsboard.server.service.rpc.RemoveRpcActorMsg) ConcurrentModificationException(java.util.ConcurrentModificationException) AttributeUpdateNotificationMsg(org.thingsboard.server.gen.transport.TransportProtos.AttributeUpdateNotificationMsg) DeviceActorServerSideRpcTimeoutMsg(org.thingsboard.server.common.msg.timeout.DeviceActorServerSideRpcTimeoutMsg) ToDeviceRpcRequestMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMsg) TransportToDeviceActorMsgWrapper(org.thingsboard.server.service.transport.msg.TransportToDeviceActorMsgWrapper) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ToDeviceRpcResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseMsg) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ToDeviceRpcRequest(org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest) Device(org.thingsboard.server.common.data.Device) JacksonUtil(org.thingsboard.common.util.JacksonUtil) HashMap(java.util.HashMap) DeviceEdgeUpdateMsg(org.thingsboard.rule.engine.api.msg.DeviceEdgeUpdateMsg) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) SessionSubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionSubscriptionInfoProto) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMapRemoveEldest(org.thingsboard.common.util.LinkedHashMapRemoveEldest) CollectionUtils(org.apache.commons.collections.CollectionUtils) SessionCloseNotificationProto(org.thingsboard.server.gen.transport.TransportProtos.SessionCloseNotificationProto) KeyValueProto(org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto) SessionEvent(org.thingsboard.server.gen.transport.TransportProtos.SessionEvent) DeviceSessionsCacheEntry(org.thingsboard.server.gen.transport.TransportProtos.DeviceSessionsCacheEntry) TbCallback(org.thingsboard.server.common.msg.queue.TbCallback) Nullable(javax.annotation.Nullable) AttributeKey(org.thingsboard.server.common.data.kv.AttributeKey) DataConstants(org.thingsboard.server.common.data.DataConstants) RpcId(org.thingsboard.server.common.data.id.RpcId) FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) DeviceCredentialsType(org.thingsboard.server.common.data.security.DeviceCredentialsType) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) SessionEventMsg(org.thingsboard.server.gen.transport.TransportProtos.SessionEventMsg) SessionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto) RpcError(org.thingsboard.server.common.data.rpc.RpcError) FutureCallback(com.google.common.util.concurrent.FutureCallback) TsKvProto(org.thingsboard.server.gen.transport.TransportProtos.TsKvProto) Consumer(java.util.function.Consumer) SubscriptionInfoProto(org.thingsboard.server.gen.transport.TransportProtos.SubscriptionInfoProto) ToTransportMsg(org.thingsboard.server.gen.transport.TransportProtos.ToTransportMsg) Futures(com.google.common.util.concurrent.Futures) PageData(org.thingsboard.server.common.data.page.PageData) EdgeEvent(org.thingsboard.server.common.data.edge.EdgeEvent) EdgeEventType(org.thingsboard.server.common.data.edge.EdgeEventType) RelationTypeGroup(org.thingsboard.server.common.data.relation.RelationTypeGroup) ToDeviceRpcResponseStatusMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseStatusMsg) Collections(java.util.Collections) Set(java.util.Set) HashSet(java.util.HashSet) FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ToDeviceRpcRequest(org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest) ToDeviceRpcRequestMsg(org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMsg)

Example 3 with FromDeviceRpcResponse

use of org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse in project thingsboard by thingsboard.

the class DefaultTbCoreDeviceRpcService method processRpcResponseFromRuleEngine.

@Override
public void processRpcResponseFromRuleEngine(FromDeviceRpcResponse response) {
    log.trace("[{}] Received response to server-side RPC request from rule engine: [{}]", response.getId(), response);
    UUID requestId = response.getId();
    Consumer<FromDeviceRpcResponse> consumer = localToRuleEngineRpcRequests.remove(requestId);
    if (consumer != null) {
        consumer.accept(response);
    } else {
        log.trace("[{}] Unknown or stale rpc response received [{}]", requestId, response);
    }
}
Also used : FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) UUID(java.util.UUID)

Example 4 with FromDeviceRpcResponse

use of org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method processServerSideRpcTimeout.

void processServerSideRpcTimeout(TbActorCtx context, DeviceActorServerSideRpcTimeoutMsg msg) {
    ToDeviceRpcRequestMetadata requestMd = toDeviceRpcPendingMap.remove(msg.getId());
    if (requestMd != null) {
        log.debug("[{}] RPC request [{}] timeout detected!", deviceId, msg.getId());
        if (requestMd.getMsg().getMsg().isPersisted()) {
            systemContext.getTbRpcService().save(tenantId, new RpcId(requestMd.getMsg().getMsg().getId()), RpcStatus.EXPIRED, null);
        }
        systemContext.getTbCoreDeviceRpcService().processRpcResponseFromDeviceActor(new FromDeviceRpcResponse(requestMd.getMsg().getMsg().getId(), null, requestMd.isSent() ? RpcError.TIMEOUT : RpcError.NO_ACTIVE_CONNECTION));
        if (!requestMd.isDelivered()) {
            sendNextPendingRequest(context);
        }
    }
}
Also used : FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) RpcId(org.thingsboard.server.common.data.id.RpcId)

Example 5 with FromDeviceRpcResponse

use of org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse in project thingsboard by thingsboard.

the class DeviceActorMessageProcessor method processRpcResponses.

private void processRpcResponses(TbActorCtx context, SessionInfoProto sessionInfo, ToDeviceRpcResponseMsg responseMsg) {
    UUID sessionId = getSessionId(sessionInfo);
    log.debug("[{}] Processing rpc command response [{}]", deviceId, sessionId);
    ToDeviceRpcRequestMetadata requestMd = toDeviceRpcPendingMap.remove(responseMsg.getRequestId());
    boolean success = requestMd != null;
    if (success) {
        boolean hasError = StringUtils.isNotEmpty(responseMsg.getError());
        try {
            String payload = hasError ? responseMsg.getError() : responseMsg.getPayload();
            systemContext.getTbCoreDeviceRpcService().processRpcResponseFromDeviceActor(new FromDeviceRpcResponse(requestMd.getMsg().getMsg().getId(), payload, null));
            if (requestMd.getMsg().getMsg().isPersisted()) {
                RpcStatus status = hasError ? RpcStatus.FAILED : RpcStatus.SUCCESSFUL;
                JsonNode response;
                try {
                    response = JacksonUtil.toJsonNode(payload);
                } catch (IllegalArgumentException e) {
                    response = JacksonUtil.newObjectNode().put("error", payload);
                }
                systemContext.getTbRpcService().save(tenantId, new RpcId(requestMd.getMsg().getMsg().getId()), status, response);
            }
        } finally {
            if (hasError && !requestMd.isDelivered()) {
                sendNextPendingRequest(context);
            }
        }
    } else {
        log.debug("[{}] Rpc command response [{}] is stale!", deviceId, responseMsg.getRequestId());
    }
}
Also used : FromDeviceRpcResponse(org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse) RpcId(org.thingsboard.server.common.data.id.RpcId) JsonNode(com.fasterxml.jackson.databind.JsonNode) UUID(java.util.UUID) RpcStatus(org.thingsboard.server.common.data.rpc.RpcStatus)

Aggregations

FromDeviceRpcResponse (org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse)10 UUID (java.util.UUID)8 RpcId (org.thingsboard.server.common.data.id.RpcId)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 RpcStatus (org.thingsboard.server.common.data.rpc.RpcStatus)3 RpcError (org.thingsboard.server.common.data.rpc.RpcError)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 FutureCallback (com.google.common.util.concurrent.FutureCallback)1 Futures (com.google.common.util.concurrent.Futures)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)1 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 ConcurrentModificationException (java.util.ConcurrentModificationException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1