Search in sources :

Example 1 with AlarmSeverity

use of org.thingsboard.server.common.data.alarm.AlarmSeverity in project thingsboard by thingsboard.

the class BaseEdgeTest method extendDeviceProfileData.

private void extendDeviceProfileData(DeviceProfile deviceProfile) {
    DeviceProfileData profileData = deviceProfile.getProfileData();
    List<DeviceProfileAlarm> alarms = new ArrayList<>();
    DeviceProfileAlarm deviceProfileAlarm = new DeviceProfileAlarm();
    deviceProfileAlarm.setAlarmType("High Temperature");
    AlarmRule alarmRule = new AlarmRule();
    alarmRule.setAlarmDetails("Alarm Details");
    AlarmCondition alarmCondition = new AlarmCondition();
    alarmCondition.setSpec(new SimpleAlarmConditionSpec());
    List<AlarmConditionFilter> condition = new ArrayList<>();
    AlarmConditionFilter alarmConditionFilter = new AlarmConditionFilter();
    alarmConditionFilter.setKey(new AlarmConditionFilterKey(AlarmConditionKeyType.ATTRIBUTE, "temperature"));
    NumericFilterPredicate predicate = new NumericFilterPredicate();
    predicate.setOperation(NumericFilterPredicate.NumericOperation.GREATER);
    predicate.setValue(new FilterPredicateValue<>(55.0));
    alarmConditionFilter.setPredicate(predicate);
    alarmConditionFilter.setValueType(EntityKeyValueType.NUMERIC);
    condition.add(alarmConditionFilter);
    alarmCondition.setCondition(condition);
    alarmRule.setCondition(alarmCondition);
    deviceProfileAlarm.setClearRule(alarmRule);
    TreeMap<AlarmSeverity, AlarmRule> createRules = new TreeMap<>();
    createRules.put(AlarmSeverity.CRITICAL, alarmRule);
    deviceProfileAlarm.setCreateRules(createRules);
    alarms.add(deviceProfileAlarm);
    profileData.setAlarms(alarms);
    profileData.setProvisionConfiguration(new AllowCreateNewDevicesDeviceProfileProvisionConfiguration("123"));
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) AlarmRule(org.thingsboard.server.common.data.device.profile.AlarmRule) ArrayList(java.util.ArrayList) SimpleAlarmConditionSpec(org.thingsboard.server.common.data.device.profile.SimpleAlarmConditionSpec) TreeMap(java.util.TreeMap) AlarmConditionFilter(org.thingsboard.server.common.data.device.profile.AlarmConditionFilter) AlarmCondition(org.thingsboard.server.common.data.device.profile.AlarmCondition) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) AllowCreateNewDevicesDeviceProfileProvisionConfiguration(org.thingsboard.server.common.data.device.profile.AllowCreateNewDevicesDeviceProfileProvisionConfiguration) DeviceProfileData(org.thingsboard.server.common.data.device.profile.DeviceProfileData) AlarmConditionFilterKey(org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey)

Example 2 with AlarmSeverity

use of org.thingsboard.server.common.data.alarm.AlarmSeverity in project thingsboard by thingsboard.

the class DefaultAlarmQueryRepository method findAlarmDataByQueryForEntities.

@Override
public PageData<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, AlarmDataQuery query, Collection<EntityId> orderedEntityIds) {
    return transactionTemplate.execute(status -> {
        AlarmDataPageLink pageLink = query.getPageLink();
        QueryContext ctx = new QueryContext(new QuerySecurityContext(tenantId, null, EntityType.ALARM));
        ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList()));
        StringBuilder selectPart = new StringBuilder(FIELDS_SELECTION);
        StringBuilder fromPart = new StringBuilder(" from alarm a ");
        StringBuilder wherePart = new StringBuilder(" where ");
        StringBuilder sortPart = new StringBuilder(" order by ");
        StringBuilder joinPart = new StringBuilder();
        boolean addAnd = false;
        if (pageLink.isSearchPropagatedAlarms()) {
            selectPart.append(" ea.entity_id as entity_id ");
            fromPart.append(JOIN_ENTITY_ALARMS);
            wherePart.append(buildPermissionsQuery(tenantId, ctx));
            addAnd = true;
        } else {
            selectPart.append(" a.originator_id as entity_id ");
        }
        EntityDataSortOrder sortOrder = pageLink.getSortOrder();
        if (sortOrder != null && sortOrder.getKey().getType().equals(EntityKeyType.ALARM_FIELD)) {
            String sortOrderKey = sortOrder.getKey().getKey();
            sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)).append(" ").append(sortOrder.getDirection().name());
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.entity_id in (:entity_ids)");
            } else {
                addAndIfNeeded(wherePart, addAnd);
                addAnd = true;
                wherePart.append(" a.originator_id in (:entity_ids)");
            }
        } else {
            joinPart.append(" inner join (select * from (VALUES");
            int entityIdIdx = 0;
            int lastEntityIdIdx = orderedEntityIds.size() - 1;
            for (EntityId entityId : orderedEntityIds) {
                joinPart.append("(uuid('").append(entityId.getId().toString()).append("'), ").append(entityIdIdx).append(")");
                if (entityIdIdx != lastEntityIdIdx) {
                    joinPart.append(",");
                } else {
                    joinPart.append(")");
                }
                entityIdIdx++;
            }
            joinPart.append(" as e(id, priority)) e ");
            if (pageLink.isSearchPropagatedAlarms()) {
                joinPart.append("on ea.entity_id = e.id");
            } else {
                joinPart.append("on a.originator_id = e.id");
            }
            sortPart.append("e.priority");
        }
        long startTs;
        long endTs;
        if (pageLink.getTimeWindow() > 0) {
            endTs = System.currentTimeMillis();
            startTs = endTs - pageLink.getTimeWindow();
        } else {
            startTs = pageLink.getStartTs();
            endTs = pageLink.getEndTs();
        }
        if (startTs > 0) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addLongParameter("startTime", startTs);
            wherePart.append("a.created_time >= :startTime");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.created_time >= :startTime");
            }
        }
        if (endTs > 0) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addLongParameter("endTime", endTs);
            wherePart.append("a.created_time <= :endTime");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.created_time <= :endTime");
            }
        }
        if (pageLink.getTypeList() != null && !pageLink.getTypeList().isEmpty()) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addStringListParameter("alarmTypes", pageLink.getTypeList());
            wherePart.append("a.type in (:alarmTypes)");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.alarm_type in (:alarmTypes)");
            }
        }
        if (pageLink.getSeverityList() != null && !pageLink.getSeverityList().isEmpty()) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addStringListParameter("alarmSeverities", pageLink.getSeverityList().stream().map(AlarmSeverity::name).collect(Collectors.toList()));
            wherePart.append("a.severity in (:alarmSeverities)");
        }
        if (pageLink.getStatusList() != null && !pageLink.getStatusList().isEmpty()) {
            Set<AlarmStatus> statusSet = toStatusSet(pageLink.getStatusList());
            if (!statusSet.isEmpty()) {
                addAndIfNeeded(wherePart, addAnd);
                addAnd = true;
                ctx.addStringListParameter("alarmStatuses", statusSet.stream().map(AlarmStatus::name).collect(Collectors.toList()));
                wherePart.append(" a.status in (:alarmStatuses)");
            }
        }
        String textSearchQuery = buildTextSearchQuery(ctx, query.getAlarmFields(), pageLink.getTextSearch());
        String mainQuery;
        if (!textSearchQuery.isEmpty()) {
            mainQuery = selectPart.toString() + fromPart.toString() + wherePart.toString();
            mainQuery = String.format("select * from (%s) a %s WHERE %s", mainQuery, joinPart, textSearchQuery);
        } else {
            mainQuery = selectPart.toString() + fromPart.toString() + joinPart.toString() + wherePart.toString();
        }
        String countQuery = String.format("select count(*) from (%s) result", mainQuery);
        long queryTs = System.currentTimeMillis();
        int totalElements;
        try {
            totalElements = jdbcTemplate.queryForObject(countQuery, ctx, Integer.class);
        } finally {
            queryLog.logQuery(ctx, countQuery, System.currentTimeMillis() - queryTs);
        }
        if (totalElements == 0) {
            return AlarmDataAdapter.createAlarmData(pageLink, Collections.emptyList(), totalElements, orderedEntityIds);
        }
        String dataQuery = mainQuery + sortPart;
        int startIndex = pageLink.getPageSize() * pageLink.getPage();
        if (pageLink.getPageSize() > 0) {
            dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex);
        }
        queryTs = System.currentTimeMillis();
        List<Map<String, Object>> rows;
        try {
            rows = jdbcTemplate.queryForList(dataQuery, ctx);
        } finally {
            queryLog.logQuery(ctx, dataQuery, System.currentTimeMillis() - queryTs);
        }
        return AlarmDataAdapter.createAlarmData(pageLink, rows, totalElements, orderedEntityIds);
    });
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) AlarmStatus(org.thingsboard.server.common.data.alarm.AlarmStatus) AlarmDataPageLink(org.thingsboard.server.common.data.query.AlarmDataPageLink) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with AlarmSeverity

use of org.thingsboard.server.common.data.alarm.AlarmSeverity in project thingsboard by thingsboard.

the class AlarmState method calculateAlarmResult.

private TbAlarmResult calculateAlarmResult(TbContext ctx, AlarmRuleState ruleState) {
    AlarmSeverity severity = ruleState.getSeverity();
    if (currentAlarm != null) {
        // TODO: In some extremely rare cases, we might miss the event of alarm clear (If one use in-mem queue and restarted the server) or (if one manipulated the rule chain).
        // Maybe we should fetch alarm every time?
        currentAlarm.setEndTs(System.currentTimeMillis());
        AlarmSeverity oldSeverity = currentAlarm.getSeverity();
        // Skip update if severity is decreased.
        if (severity.ordinal() <= oldSeverity.ordinal()) {
            currentAlarm.setDetails(createDetails(ruleState));
            if (!oldSeverity.equals(severity)) {
                currentAlarm.setSeverity(severity);
                currentAlarm = ctx.getAlarmService().createOrUpdateAlarm(currentAlarm);
                return new TbAlarmResult(false, false, true, false, currentAlarm);
            } else {
                currentAlarm = ctx.getAlarmService().createOrUpdateAlarm(currentAlarm);
                return new TbAlarmResult(false, true, false, false, currentAlarm);
            }
        } else {
            return null;
        }
    } else {
        currentAlarm = new Alarm();
        currentAlarm.setType(alarmDefinition.getAlarmType());
        currentAlarm.setStatus(AlarmStatus.ACTIVE_UNACK);
        currentAlarm.setSeverity(severity);
        long startTs = dataSnapshot.getTs();
        if (startTs == 0L) {
            startTs = System.currentTimeMillis();
        }
        currentAlarm.setStartTs(startTs);
        currentAlarm.setEndTs(currentAlarm.getStartTs());
        currentAlarm.setDetails(createDetails(ruleState));
        currentAlarm.setOriginator(originator);
        currentAlarm.setTenantId(ctx.getTenantId());
        currentAlarm.setPropagate(alarmDefinition.isPropagate());
        currentAlarm.setPropagateToOwner(alarmDefinition.isPropagateToOwner());
        currentAlarm.setPropagateToTenant(alarmDefinition.isPropagateToTenant());
        if (alarmDefinition.getPropagateRelationTypes() != null) {
            currentAlarm.setPropagateRelationTypes(alarmDefinition.getPropagateRelationTypes());
        }
        currentAlarm = ctx.getAlarmService().createOrUpdateAlarm(currentAlarm);
        boolean updated = currentAlarm.getStartTs() != currentAlarm.getEndTs();
        return new TbAlarmResult(!updated, updated, false, false, currentAlarm);
    }
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) Alarm(org.thingsboard.server.common.data.alarm.Alarm) TbAlarmResult(org.thingsboard.rule.engine.action.TbAlarmResult)

Example 4 with AlarmSeverity

use of org.thingsboard.server.common.data.alarm.AlarmSeverity in project thingsboard by thingsboard.

the class ProfileState method updateDeviceProfile.

void updateDeviceProfile(DeviceProfile deviceProfile) {
    this.deviceProfile = deviceProfile;
    alarmSettings.clear();
    alarmCreateKeys.clear();
    alarmClearKeys.clear();
    entityKeys.clear();
    if (deviceProfile.getProfileData().getAlarms() != null) {
        alarmSettings.addAll(deviceProfile.getProfileData().getAlarms());
        for (DeviceProfileAlarm alarm : deviceProfile.getProfileData().getAlarms()) {
            Map<AlarmSeverity, Set<AlarmConditionFilterKey>> createAlarmKeys = alarmCreateKeys.computeIfAbsent(alarm.getId(), id -> new HashMap<>());
            alarm.getCreateRules().forEach(((severity, alarmRule) -> {
                var ruleKeys = createAlarmKeys.computeIfAbsent(severity, id -> new HashSet<>());
                for (var keyFilter : alarmRule.getCondition().getCondition()) {
                    entityKeys.add(keyFilter.getKey());
                    ruleKeys.add(keyFilter.getKey());
                    addDynamicValuesRecursively(keyFilter.getPredicate(), entityKeys, ruleKeys);
                }
                addEntityKeysFromAlarmConditionSpec(alarmRule);
            }));
            if (alarm.getClearRule() != null) {
                var clearAlarmKeys = alarmClearKeys.computeIfAbsent(alarm.getId(), id -> new HashSet<>());
                for (var keyFilter : alarm.getClearRule().getCondition().getCondition()) {
                    entityKeys.add(keyFilter.getKey());
                    clearAlarmKeys.add(keyFilter.getKey());
                    addDynamicValuesRecursively(keyFilter.getPredicate(), entityKeys, clearAlarmKeys);
                }
                addEntityKeysFromAlarmConditionSpec(alarm.getClearRule());
            }
        }
    }
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) DynamicValue(org.thingsboard.server.common.data.query.DynamicValue) Getter(lombok.Getter) AlarmRule(org.thingsboard.server.common.data.device.profile.AlarmRule) AlarmConditionKeyType(org.thingsboard.server.common.data.device.profile.AlarmConditionKeyType) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) HashMap(java.util.HashMap) DynamicValueSourceType(org.thingsboard.server.common.data.query.DynamicValueSourceType) HashSet(java.util.HashSet) AccessLevel(lombok.AccessLevel) KeyFilterPredicate(org.thingsboard.server.common.data.query.KeyFilterPredicate) AlarmConditionFilterKey(org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) Map(java.util.Map) DurationAlarmConditionSpec(org.thingsboard.server.common.data.device.profile.DurationAlarmConditionSpec) AlarmConditionSpec(org.thingsboard.server.common.data.device.profile.AlarmConditionSpec) ComplexFilterPredicate(org.thingsboard.server.common.data.query.ComplexFilterPredicate) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) List(java.util.List) RepeatingAlarmConditionSpec(org.thingsboard.server.common.data.device.profile.RepeatingAlarmConditionSpec) SimpleKeyFilterPredicate(org.thingsboard.server.common.data.query.SimpleKeyFilterPredicate) AlarmConditionSpecType(org.thingsboard.server.common.data.device.profile.AlarmConditionSpecType) Collections(java.util.Collections) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) HashSet(java.util.HashSet) Set(java.util.Set) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) HashSet(java.util.HashSet)

Aggregations

AlarmSeverity (org.thingsboard.server.common.data.alarm.AlarmSeverity)4 DeviceProfileAlarm (org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 AlarmConditionFilterKey (org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey)2 AlarmRule (org.thingsboard.server.common.data.device.profile.AlarmRule)2 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Set (java.util.Set)1 TreeMap (java.util.TreeMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 AccessLevel (lombok.AccessLevel)1 Getter (lombok.Getter)1 TbAlarmResult (org.thingsboard.rule.engine.action.TbAlarmResult)1 DeviceProfile (org.thingsboard.server.common.data.DeviceProfile)1 Alarm (org.thingsboard.server.common.data.alarm.Alarm)1 AlarmStatus (org.thingsboard.server.common.data.alarm.AlarmStatus)1