Search in sources :

Example 1 with TbContext

use of org.thingsboard.rule.engine.api.TbContext in project thingsboard by thingsboard.

the class AlarmState method createOrClearAlarms.

public <T> boolean createOrClearAlarms(TbContext ctx, TbMsg msg, T data, SnapshotUpdate update, BiFunction<AlarmRuleState, T, AlarmEvalResult> evalFunction) {
    boolean stateUpdate = false;
    AlarmRuleState resultState = null;
    log.debug("[{}] processing update: {}", alarmDefinition.getId(), data);
    for (AlarmRuleState state : createRulesSortedBySeverityDesc) {
        if (!validateUpdate(update, state)) {
            log.debug("[{}][{}] Update is not valid for current rule state", alarmDefinition.getId(), state.getSeverity());
            continue;
        }
        AlarmEvalResult evalResult = evalFunction.apply(state, data);
        stateUpdate |= state.checkUpdate();
        if (AlarmEvalResult.TRUE.equals(evalResult)) {
            resultState = state;
            break;
        } else if (AlarmEvalResult.FALSE.equals(evalResult)) {
            stateUpdate = clearAlarmState(stateUpdate, state);
        }
    }
    if (resultState != null) {
        TbAlarmResult result = calculateAlarmResult(ctx, resultState);
        if (result != null) {
            pushMsg(ctx, msg, result, resultState);
        }
        stateUpdate = clearAlarmState(stateUpdate, clearState);
    } else if (currentAlarm != null && clearState != null) {
        if (!validateUpdate(update, clearState)) {
            log.debug("[{}] Update is not valid for current clear state", alarmDefinition.getId());
            return stateUpdate;
        }
        AlarmEvalResult evalResult = evalFunction.apply(clearState, data);
        if (AlarmEvalResult.TRUE.equals(evalResult)) {
            stateUpdate = clearAlarmState(stateUpdate, clearState);
            for (AlarmRuleState state : createRulesSortedBySeverityDesc) {
                stateUpdate = clearAlarmState(stateUpdate, state);
            }
            ListenableFuture<AlarmOperationResult> alarmClearOperationResult = ctx.getAlarmService().clearAlarmForResult(ctx.getTenantId(), currentAlarm.getId(), createDetails(clearState), System.currentTimeMillis());
            DonAsynchron.withCallback(alarmClearOperationResult, result -> {
                pushMsg(ctx, msg, new TbAlarmResult(false, false, true, result.getAlarm()), clearState);
            }, throwable -> {
                throw new RuntimeException(throwable);
            });
            currentAlarm = null;
        } else if (AlarmEvalResult.FALSE.equals(evalResult)) {
            stateUpdate = clearAlarmState(stateUpdate, clearState);
        }
    }
    return stateUpdate;
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TbMsg(org.thingsboard.server.common.msg.TbMsg) BiFunction(java.util.function.BiFunction) JacksonUtil(org.thingsboard.common.util.JacksonUtil) DonAsynchron(org.thingsboard.common.util.DonAsynchron) TbAlarmResult(org.thingsboard.rule.engine.action.TbAlarmResult) AlarmConditionKeyType(org.thingsboard.server.common.data.device.profile.AlarmConditionKeyType) TbContext(org.thingsboard.rule.engine.api.TbContext) StringUtils(org.apache.commons.lang3.StringUtils) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) ArrayList(java.util.ArrayList) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) EntityId(org.thingsboard.server.common.data.id.EntityId) JsonNode(com.fasterxml.jackson.databind.JsonNode) AlarmStatus(org.thingsboard.server.common.data.alarm.AlarmStatus) PersistedAlarmRuleState(org.thingsboard.rule.engine.profile.state.PersistedAlarmRuleState) DashboardId(org.thingsboard.server.common.data.id.DashboardId) DataConstants(org.thingsboard.server.common.data.DataConstants) PersistedAlarmState(org.thingsboard.rule.engine.profile.state.PersistedAlarmState) AlarmOperationResult(org.thingsboard.server.dao.alarm.AlarmOperationResult) Alarm(org.thingsboard.server.common.data.alarm.Alarm) ExecutionException(java.util.concurrent.ExecutionException) Slf4j(lombok.extern.slf4j.Slf4j) ServiceQueue(org.thingsboard.server.common.msg.queue.ServiceQueue) List(java.util.List) Data(lombok.Data) AlarmConditionSpecType(org.thingsboard.server.common.data.device.profile.AlarmConditionSpecType) Comparator(java.util.Comparator) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TbAlarmResult(org.thingsboard.rule.engine.action.TbAlarmResult) PersistedAlarmRuleState(org.thingsboard.rule.engine.profile.state.PersistedAlarmRuleState)

Example 2 with TbContext

use of org.thingsboard.rule.engine.api.TbContext in project thingsboard by thingsboard.

the class TbCopyAttributesToEntityViewNode method onMsg.

@Override
public void onMsg(TbContext ctx, TbMsg msg) {
    if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || DataConstants.ATTRIBUTES_DELETED.equals(msg.getType()) || DataConstants.ACTIVITY_EVENT.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
        if (!msg.getMetaData().getData().isEmpty()) {
            long now = System.currentTimeMillis();
            String scope = msg.getType().equals(SessionMsgType.POST_ATTRIBUTES_REQUEST.name()) ? DataConstants.CLIENT_SCOPE : msg.getMetaData().getValue(DataConstants.SCOPE);
            ListenableFuture<List<EntityView>> entityViewsFuture = ctx.getEntityViewService().findEntityViewsByTenantIdAndEntityIdAsync(ctx.getTenantId(), msg.getOriginator());
            DonAsynchron.withCallback(entityViewsFuture, entityViews -> {
                for (EntityView entityView : entityViews) {
                    long startTime = entityView.getStartTimeMs();
                    long endTime = entityView.getEndTimeMs();
                    if ((endTime != 0 && endTime > now && startTime < now) || (endTime == 0 && startTime < now)) {
                        if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType()) || DataConstants.ACTIVITY_EVENT.equals(msg.getType()) || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
                            Set<AttributeKvEntry> attributes = JsonConverter.convertToAttributes(new JsonParser().parse(msg.getData()));
                            List<AttributeKvEntry> filteredAttributes = attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)).collect(Collectors.toList());
                            ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes, new FutureCallback<Void>() {

                                @Override
                                public void onSuccess(@Nullable Void result) {
                                    transformAndTellNext(ctx, msg, entityView);
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    ctx.tellFailure(msg, t);
                                }
                            });
                        } else if (DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())) {
                            List<String> attributes = new ArrayList<>();
                            for (JsonElement element : new JsonParser().parse(msg.getData()).getAsJsonObject().get("attributes").getAsJsonArray()) {
                                if (element.isJsonPrimitive()) {
                                    JsonPrimitive value = element.getAsJsonPrimitive();
                                    if (value.isString()) {
                                        attributes.add(value.getAsString());
                                    }
                                }
                            }
                            List<String> filteredAttributes = attributes.stream().filter(attr -> attributeContainsInEntityView(scope, attr, entityView)).collect(Collectors.toList());
                            if (!filteredAttributes.isEmpty()) {
                                ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(), scope, filteredAttributes);
                                transformAndTellNext(ctx, msg, entityView);
                            }
                        }
                    }
                }
                ctx.ack(msg);
            }, t -> ctx.tellFailure(msg, t));
        } else {
            ctx.tellFailure(msg, new IllegalArgumentException("Message metadata is empty"));
        }
    } else {
        ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type [" + msg.getType() + "]"));
    }
}
Also used : ComponentType(org.thingsboard.server.common.data.plugin.ComponentType) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TbMsg(org.thingsboard.server.common.msg.TbMsg) DonAsynchron(org.thingsboard.common.util.DonAsynchron) JsonParser(com.google.gson.JsonParser) TbContext(org.thingsboard.rule.engine.api.TbContext) SUCCESS(org.thingsboard.rule.engine.api.TbRelationTypes.SUCCESS) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) TbNodeException(org.thingsboard.rule.engine.api.TbNodeException) SessionMsgType(org.thingsboard.server.common.msg.session.SessionMsgType) EmptyNodeConfiguration(org.thingsboard.rule.engine.api.EmptyNodeConfiguration) JsonConverter(org.thingsboard.server.common.transport.adaptor.JsonConverter) JsonPrimitive(com.google.gson.JsonPrimitive) Nullable(javax.annotation.Nullable) DataConstants(org.thingsboard.server.common.data.DataConstants) Set(java.util.Set) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) RuleNode(org.thingsboard.rule.engine.api.RuleNode) EntityView(org.thingsboard.server.common.data.EntityView) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TbNodeConfiguration(org.thingsboard.rule.engine.api.TbNodeConfiguration) TbNodeUtils(org.thingsboard.rule.engine.api.util.TbNodeUtils) TbNode(org.thingsboard.rule.engine.api.TbNode) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) EntityView(org.thingsboard.server.common.data.EntityView) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) JsonParser(com.google.gson.JsonParser)

Example 3 with TbContext

use of org.thingsboard.rule.engine.api.TbContext in project thingsboard by thingsboard.

the class EntitiesRelatedEntityIdAsyncLoader method findEntityAsync.

public static ListenableFuture<EntityId> findEntityAsync(TbContext ctx, EntityId originator, RelationsQuery relationsQuery) {
    RelationService relationService = ctx.getRelationService();
    EntityRelationsQuery query = buildQuery(originator, relationsQuery);
    ListenableFuture<List<EntityRelation>> asyncRelation = relationService.findByQuery(ctx.getTenantId(), query);
    if (relationsQuery.getDirection() == EntitySearchDirection.FROM) {
        return Futures.transformAsync(asyncRelation, r -> CollectionUtils.isNotEmpty(r) ? Futures.immediateFuture(r.get(0).getTo()) : Futures.immediateFuture(null), MoreExecutors.directExecutor());
    } else if (relationsQuery.getDirection() == EntitySearchDirection.TO) {
        return Futures.transformAsync(asyncRelation, r -> CollectionUtils.isNotEmpty(r) ? Futures.immediateFuture(r.get(0).getFrom()) : Futures.immediateFuture(null), MoreExecutors.directExecutor());
    }
    return Futures.immediateFailedFuture(new IllegalStateException("Unknown direction"));
}
Also used : RelationService(org.thingsboard.server.dao.relation.RelationService) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) RelationsQuery(org.thingsboard.rule.engine.data.RelationsQuery) EntitySearchDirection(org.thingsboard.server.common.data.relation.EntitySearchDirection) RelationsSearchParameters(org.thingsboard.server.common.data.relation.RelationsSearchParameters) TbContext(org.thingsboard.rule.engine.api.TbContext) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) RelationService(org.thingsboard.server.dao.relation.RelationService) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) CollectionUtils(org.apache.commons.collections.CollectionUtils) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityRelationsQuery(org.thingsboard.server.common.data.relation.EntityRelationsQuery) EntityRelationsQuery(org.thingsboard.server.common.data.relation.EntityRelationsQuery) List(java.util.List)

Aggregations

ListenableFuture (com.google.common.util.concurrent.ListenableFuture)3 List (java.util.List)3 TbContext (org.thingsboard.rule.engine.api.TbContext)3 ArrayList (java.util.ArrayList)2 Slf4j (lombok.extern.slf4j.Slf4j)2 DonAsynchron (org.thingsboard.common.util.DonAsynchron)2 DataConstants (org.thingsboard.server.common.data.DataConstants)2 TbMsg (org.thingsboard.server.common.msg.TbMsg)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 FutureCallback (com.google.common.util.concurrent.FutureCallback)1 Futures (com.google.common.util.concurrent.Futures)1 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)1 JsonElement (com.google.gson.JsonElement)1 JsonParser (com.google.gson.JsonParser)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 Comparator (java.util.Comparator)1 Set (java.util.Set)1 ExecutionException (java.util.concurrent.ExecutionException)1 BiFunction (java.util.function.BiFunction)1