Search in sources :

Example 6 with TelemetrySubscriptionUpdate

use of org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method handleWsAttributesSubscriptionByKeys.

private void handleWsAttributesSubscriptionByKeys(TelemetryWebSocketSessionRef sessionRef, AttributesSubscriptionCmd cmd, String sessionId, EntityId entityId, List<String> keys) {
    FutureCallback<List<AttributeKvEntry>> callback = new FutureCallback<List<AttributeKvEntry>>() {

        @Override
        public void onSuccess(List<AttributeKvEntry> data) {
            List<TsKvEntry> attributesData = data.stream().map(d -> new BasicTsKvEntry(d.getLastUpdateTs(), d)).collect(Collectors.toList());
            sendWsMsg(sessionRef, new TelemetrySubscriptionUpdate(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()));
            TbAttributeSubscriptionScope scope = StringUtils.isEmpty(cmd.getScope()) ? TbAttributeSubscriptionScope.ANY_SCOPE : TbAttributeSubscriptionScope.valueOf(cmd.getScope());
            TbAttributeSubscription sub = TbAttributeSubscription.builder().serviceId(serviceId).sessionId(sessionId).subscriptionId(cmd.getCmdId()).tenantId(sessionRef.getSecurityCtx().getTenantId()).entityId(entityId).allKeys(false).keyStates(subState).scope(scope).updateConsumer(DefaultTelemetryWebSocketService.this::sendWsMsg).build();
            oldSubService.addSubscription(sub);
        }

        @Override
        public void onFailure(Throwable e) {
            log.error(FAILED_TO_FETCH_ATTRIBUTES, e);
            TelemetrySubscriptionUpdate update;
            if (e instanceof UnauthorizedException) {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.UNAUTHORIZED, SubscriptionErrorCode.UNAUTHORIZED.getDefaultMsg());
            } else {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_ATTRIBUTES);
            }
            sendWsMsg(sessionRef, update);
        }
    };
    if (StringUtils.isEmpty(cmd.getScope())) {
        accessValidator.validate(sessionRef.getSecurityCtx(), Operation.READ_ATTRIBUTES, entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, keys, callback));
    } else {
        accessValidator.validate(sessionRef.getSecurityCtx(), Operation.READ_ATTRIBUTES, entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, cmd.getScope(), keys, callback));
    }
}
Also used : GetHistoryCmd(org.thingsboard.server.service.telemetry.cmd.v1.GetHistoryCmd) Autowired(org.springframework.beans.factory.annotation.Autowired) AttributesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.AttributesSubscriptionCmd) CloseStatus(org.springframework.web.socket.CloseStatus) TenantId(org.thingsboard.server.common.data.id.TenantId) UnauthorizedException(org.thingsboard.server.service.telemetry.exception.UnauthorizedException) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PreDestroy(javax.annotation.PreDestroy) CmdUpdate(org.thingsboard.server.service.telemetry.cmd.v2.CmdUpdate) Map(java.util.Map) TbServiceInfoProvider(org.thingsboard.server.queue.discovery.TbServiceInfoProvider) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) TbAttributeSubscriptionScope(org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) Function(com.google.common.base.Function) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) Set(java.util.Set) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) ValidationResult(org.thingsboard.server.service.security.ValidationResult) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TenantRateLimitException(org.thingsboard.server.dao.util.TenantRateLimitException) UnsubscribeCmd(org.thingsboard.server.service.telemetry.cmd.v2.UnsubscribeCmd) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) Operation(org.thingsboard.server.service.security.permission.Operation) ValidationCallback(org.thingsboard.server.service.security.ValidationCallback) CustomerId(org.thingsboard.server.common.data.id.CustomerId) TelemetryPluginCmd(org.thingsboard.server.service.telemetry.cmd.v1.TelemetryPluginCmd) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) TimeseriesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.TimeseriesSubscriptionCmd) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AlarmDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.AlarmDataCmd) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Value(org.springframework.beans.factory.annotation.Value) HashSet(java.util.HashSet) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) Service(org.springframework.stereotype.Service) ValidationResultCode(org.thingsboard.server.service.security.ValidationResultCode) EntityId(org.thingsboard.server.common.data.id.EntityId) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) ThingsBoardExecutors(org.thingsboard.common.util.ThingsBoardExecutors) DataConstants(org.thingsboard.server.common.data.DataConstants) AccessValidator(org.thingsboard.server.service.security.AccessValidator) TbTimeseriesSubscription(org.thingsboard.server.service.subscription.TbTimeseriesSubscription) Aggregation(org.thingsboard.server.common.data.kv.Aggregation) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TbEntityDataSubscriptionService(org.thingsboard.server.service.subscription.TbEntityDataSubscriptionService) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Futures(com.google.common.util.concurrent.Futures) UserId(org.thingsboard.server.common.data.id.UserId) SubscriptionErrorCode(org.thingsboard.server.service.telemetry.sub.SubscriptionErrorCode) TelemetryPluginCmdsWrapper(org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper) TbLocalSubscriptionService(org.thingsboard.server.service.subscription.TbLocalSubscriptionService) EntityCountCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) TbAttributeSubscription(org.thingsboard.server.service.subscription.TbAttributeSubscription) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) SubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.SubscriptionCmd) TbAttributeSubscription(org.thingsboard.server.service.subscription.TbAttributeSubscription) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) UnauthorizedException(org.thingsboard.server.service.telemetry.exception.UnauthorizedException) List(java.util.List) ArrayList(java.util.ArrayList) FutureCallback(com.google.common.util.concurrent.FutureCallback) TbAttributeSubscriptionScope(org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope)

Example 7 with TelemetrySubscriptionUpdate

use of org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method getSubscriptionCallback.

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

        @Override
        public void onSuccess(List<TsKvEntry> data) {
            sendWsMsg(sessionRef, new TelemetrySubscriptionUpdate(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()));
            TbTimeseriesSubscription sub = TbTimeseriesSubscription.builder().serviceId(serviceId).sessionId(sessionId).subscriptionId(cmd.getCmdId()).tenantId(sessionRef.getSecurityCtx().getTenantId()).entityId(entityId).updateConsumer(DefaultTelemetryWebSocketService.this::sendWsMsg).allKeys(false).keyStates(subState).build();
            oldSubService.addSubscription(sub);
        }

        @Override
        public void onFailure(Throwable e) {
            if (e instanceof TenantRateLimitException || e.getCause() instanceof TenantRateLimitException) {
                log.trace("[{}] Tenant rate limit detected for subscription: [{}]:{}", sessionRef.getSecurityCtx().getTenantId(), entityId, cmd);
            } else {
                log.info(FAILED_TO_FETCH_DATA, e);
            }
            TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            sendWsMsg(sessionRef, update);
        }
    };
}
Also used : TenantRateLimitException(org.thingsboard.server.dao.util.TenantRateLimitException) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) TbTimeseriesSubscription(org.thingsboard.server.service.subscription.TbTimeseriesSubscription) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) List(java.util.List) ArrayList(java.util.ArrayList) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 8 with TelemetrySubscriptionUpdate

use of org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method validateSessionMetadata.

private boolean validateSessionMetadata(TelemetryWebSocketSessionRef sessionRef, int cmdId, String sessionId) {
    WsSessionMetaData sessionMD = wsSessionsMap.get(sessionId);
    if (sessionMD == null) {
        log.warn("[{}] Session meta data not found. ", sessionId);
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmdId, SubscriptionErrorCode.INTERNAL_ERROR, SESSION_META_DATA_NOT_FOUND);
        sendWsMsg(sessionRef, update);
        return false;
    } else {
        return true;
    }
}
Also used : TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate)

Example 9 with TelemetrySubscriptionUpdate

use of org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method validateSubscriptionCmd.

private boolean validateSubscriptionCmd(TelemetryWebSocketSessionRef sessionRef, SubscriptionCmd cmd) {
    if (cmd.getEntityId() == null || cmd.getEntityId().isEmpty()) {
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Device id is empty!");
        sendWsMsg(sessionRef, update);
        return false;
    }
    return true;
}
Also used : TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate)

Example 10 with TelemetrySubscriptionUpdate

use of org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method validateSubscriptionCmd.

private boolean validateSubscriptionCmd(TelemetryWebSocketSessionRef sessionRef, EntityCountCmd cmd) {
    if (cmd.getCmdId() < 0) {
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Cmd id is negative value!");
        sendWsMsg(sessionRef, update);
        return false;
    } else if (cmd.getQuery() == null) {
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Query is empty!");
        sendWsMsg(sessionRef, update);
        return false;
    }
    return true;
}
Also used : TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate)

Aggregations

TelemetrySubscriptionUpdate (org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate)14 ArrayList (java.util.ArrayList)8 List (java.util.List)8 HashMap (java.util.HashMap)7 Collections (java.util.Collections)6 HashSet (java.util.HashSet)6 Map (java.util.Map)6 Set (java.util.Set)6 Collectors (java.util.stream.Collectors)6 Slf4j (lombok.extern.slf4j.Slf4j)6 BasicTsKvEntry (org.thingsboard.server.common.data.kv.BasicTsKvEntry)6 TsKvEntry (org.thingsboard.server.common.data.kv.TsKvEntry)6 FutureCallback (com.google.common.util.concurrent.FutureCallback)5 Optional (java.util.Optional)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 Function (com.google.common.base.Function)4 Futures (com.google.common.util.concurrent.Futures)4 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)4