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;
}
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() + "]"));
}
}
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"));
}
Aggregations