Преглед изворни кода

Merge branch 'dev' into sky_v2

15928045575 пре 2 година
родитељ
комит
aa12b69c07

+ 213 - 50
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttCallbackHandler.java

@@ -3,6 +3,7 @@ package com.sckw.slope.detection.consumer;
 import com.alibaba.fastjson2.JSONObject;
 import com.baomidou.dynamic.datasource.annotation.DSTransactional;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.sckw.core.model.constant.Global;
 import com.sckw.core.model.constant.NumberConstant;
 import com.sckw.core.model.enums.AlarmTitleEnum;
 import com.sckw.core.model.enums.AlarmTypeEnum;
@@ -12,11 +13,13 @@ import com.sckw.core.utils.DateUtils;
 import com.sckw.core.utils.IdWorker;
 import com.sckw.core.web.response.HttpResult;
 import com.sckw.log.TraceLog.TraceLog;
+import com.sckw.redis.utils.RedissonUtils;
 import com.sckw.slope.detection.dao.mysql.*;
 import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
 import com.sckw.slope.detection.model.dos.mysql.*;
 import com.sckw.slope.detection.model.dos.tdengine.Devices;
 import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
+import com.sckw.slope.detection.model.dto.AlarmList;
 import com.sckw.slope.detection.model.dto.DevicesAlarm;
 import com.sckw.slope.detection.model.dto.DevicesItem;
 import com.sckw.slope.detection.model.param.SmsMessageParam;
@@ -25,11 +28,13 @@ import com.sckw.slope.detection.service.CommonService;
 import com.sckw.slope.detection.service.TdengineService;
 import com.sckw.slope.detection.service.api.DetectionApiService;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.dubbo.common.utils.MD5Utils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.text.SimpleDateFormat;
@@ -134,7 +139,7 @@ public class MqttCallbackHandler extends AbstractHandler {
 //                        ts = ts * 1000;
 //                    }
                     //判断是否满足设备超时离线报警
-                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
+//                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
                     //判断是否满足数值超阈值报警
                     Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
                     if ("2".equals(map.get("flag"))) {
@@ -144,26 +149,14 @@ public class MqttCallbackHandler extends AbstractHandler {
                         long id = insertAlarmAndDetail(level, device, thresholdId, itemValue, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
                         //todo 不适用redis存统计  使用新字段处理
                         /**阈值次数存redis*/
-//                        String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_ONE.getStatus()
-//                                + Global.POUND + AlarmTitleEnum.ALARM_TITLE_TWO.getStatus();
-//                        String number = RedissonUtils.getString(key);
-//                        Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
-//                                .eq(KwsAlarmDetail::getAlarmId, id)
-//                                .eq(KwsAlarmDetail::getStatus, 0)
-//                        );
-//                        if (StringUtils.isBlank(number)) {
-//                            RedissonUtils.putString(key, "1", Global.COMMON_EXPIRE);
-//                        } else {
-//                            RedissonUtils.putString(key, count.toString(), Global.COMMON_EXPIRE);
-//                        }
-
+//                        redisPutAlarmCount(id);
                         /*【露天矿山边坡监测系统】尊敬的管理员,2023-10-01 12:23:34监测到一级告警。
                             设备名称:位移监测设备-gnss一号机,监测数值:55。123456789N,请尽快处理问题。*/
                         Map<String, Object> messageMap = new HashMap<>();
                         pushSmsMessage(messageUrl, device, level, thresholdId, messageMap);
                     }
                     //集成要素阈值告警
-//                    deviceIntegrationsAlarm(device);
+                    deviceIntegrationsAlarm(device,ts);
                 }
             }
         } catch (Exception e) {
@@ -172,7 +165,22 @@ public class MqttCallbackHandler extends AbstractHandler {
         return HttpResult.ok();
     }
 
-    private void deviceIntegrationsAlarm(KwsDevice device) {
+    private void redisPutAlarmCount(long id) {
+        String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_ONE.getStatus()
+                + Global.POUND + AlarmTitleEnum.ALARM_TITLE_TWO.getStatus();
+        String number = RedissonUtils.getString(key);
+        Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
+                .eq(KwsAlarmDetail::getAlarmId, id)
+                .eq(KwsAlarmDetail::getStatus, 0)
+        );
+        if (StringUtils.isBlank(number)) {
+            RedissonUtils.putString(key, "1", Global.COMMON_EXPIRE);
+        } else {
+            RedissonUtils.putString(key, count.toString(), Global.COMMON_EXPIRE);
+        }
+    }
+
+    private void deviceIntegrationsAlarm(KwsDevice device,Long ts) {
         List<KwsDeviceIntegration> deviceIntegrations = deviceIntegrationMapper.selectList(
                 new LambdaQueryWrapper<KwsDeviceIntegration>()
                         .eq(KwsDeviceIntegration::getDeviceId, device.getId())
@@ -196,13 +204,25 @@ public class MqttCallbackHandler extends AbstractHandler {
         String snCode = device.getSnCode();
         intergData = deviceIntegrationMapper.selectListParamsAndInterNameByDeviceId(device.getId());
         if (!Objects.isNull(intergData)) {
-            for (DeviceIntegrationVo inter : intergData) {
+            for (DeviceIntegrationVo deviceIntegration : intergData) {
                 //获取到当前测量值--现在只有单一值
-                List<SlopeData> slopeData = slopeDataMapper.selectListByTwoLine(snCode, inter.getPartNames());
+                List<SlopeData> slopeData = slopeDataMapper.selectListByTwoLine(snCode, deviceIntegration.getPartNames());
                 if (!Objects.isNull(slopeData)) {
-                    double offset = commonService.returnIntegrationData(snCode,slopeData,inter);
+                    List<KwsThreshold> thresholdList = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
+                            .eq(KwsThreshold::getDeviceId, device.getId())
+                            .eq(KwsThreshold::getItemName, deviceIntegration.getPartNames())
+                    );
+                    double offset = commonService.returnIntegrationData(snCode, slopeData, deviceIntegration);
+                    Map<String, String> map = newAlarmCompute(new BigDecimal(offset), thresholdList);
+                    if ("2".equals(map.get("flag"))) {
+                        Long level = Long.valueOf(map.get("level"));
+                        Long thresholdId = Long.valueOf(map.get("thresholdId"));
+                        //阈值表以及明细表存储
+                        long id = insertAlarmAndDetail(level, device, thresholdId, deviceIntegration.getPartNames(), ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
+                        Map<String, Object> messageMap = new HashMap<>();
+                        pushSmsMessage(messageUrl, device, level, thresholdId, messageMap);
+                    }
                 }
-
             }
         }
     }
@@ -304,6 +324,23 @@ public class MqttCallbackHandler extends AbstractHandler {
         checkItemName.add(DictItemEnum.ALTITUDE_Z.getValue());
         checkItemName.add(DictItemEnum.LONGITUDE_X.getValue());
         checkItemName.add(DictItemEnum.LATITUDE_Y.getValue());
+        //放入告警数值-告警等级
+        //放入告警等级-告警主键id
+        Map<String, String> map = new HashMap<>();
+        if (checkItemName.contains(itemName)) {
+            BigDecimal offset = commonService.computeOffset(itemValue, itemName, deviceRelation);
+            map = newAlarmCompute(offset, kwsThresholds);
+        } else {
+            map = newAlarmCompute(new BigDecimal(itemValue), kwsThresholds);
+        }
+//        map = oldAlarmCompute(checkItemName, itemName, itemValue, deviceRelation, kwsThresholds);
+        return map;
+    }
+
+    /**
+     * 之前的阈值告警计算方式
+     */
+    private Map<String, String> oldAlarmCompute(List<String> checkItemName, String itemName, String itemValue, KwsDeviceReference deviceRelation, List<KwsThreshold> kwsThresholds) {
         //需要计算的阈值
         if (checkItemName.contains(itemName)) {
             BigDecimal offset = commonService.computeOffset(itemValue, itemName, deviceRelation);
@@ -445,6 +482,65 @@ public class MqttCallbackHandler extends AbstractHandler {
         }
     }
 
+    private Map<String, String> newAlarmCompute(BigDecimal offset, List<KwsThreshold> kwsThresholds) {
+        //最大值从大到小计算 告警阈值
+        List<AlarmList> maxAlarmList = new ArrayList<>();
+        for (KwsThreshold kwsThreshold : kwsThresholds) {
+            if (kwsThreshold.getMax() != null) {
+                AlarmList alarmList = new AlarmList();
+                alarmList.setLevel(kwsThreshold.getLevel().toString());
+                alarmList.setId(kwsThreshold.getId());
+                alarmList.setValue(new BigDecimal(kwsThreshold.getMax()));
+                maxAlarmList.add(alarmList);
+            }
+        }
+        //最小值从小到大计算 告警阈值
+        List<AlarmList> minAlarmList = new ArrayList<>();
+        for (KwsThreshold kwsThreshold : kwsThresholds) {
+            if (kwsThreshold.getMin() != null) {
+                AlarmList alarmList = new AlarmList();
+                alarmList.setLevel(kwsThreshold.getLevel().toString());
+                alarmList.setId(kwsThreshold.getId());
+                alarmList.setValue(new BigDecimal(kwsThreshold.getMin()));
+                minAlarmList.add(alarmList);
+            }
+        }
+        maxAlarmList = maxAlarmList.stream().sorted(Comparator.comparing(AlarmList::getValue).reversed()).collect(Collectors.toList());
+//            HashMap<Object, Object> maxAlarmMap = kwsThresholds.stream().collect(HashMap::new,
+//                    (m, v) -> m.put(v.getMax(), v.getId()), HashMap::putAll);
+        minAlarmList = minAlarmList.stream().sorted(Comparator.comparing(AlarmList::getValue)).collect(Collectors.toList());
+//            HashMap<Object, Object> mixAlarmMap = kwsThresholds.stream().collect(HashMap::new,
+//                    (m, v) -> m.put(v.getMax(), v.getId()), HashMap::putAll);
+        String maxLevel = getListMaxNumber(offset, maxAlarmList);
+        String minLevel = getListMinNumber(offset, minAlarmList);
+        /**存在阈值触发*/
+        Map<String, String> map = new HashMap<>();
+        map.put("level", "1");
+        map.put("thresholdId", "1");
+        map.put("flag", "1");
+        if (maxLevel != null || minLevel != null) {
+            if (maxLevel != null) {
+                for (AlarmList alarmList : maxAlarmList) {
+                    if (maxLevel.equals(alarmList.getLevel())) {
+                        map.put("level", maxLevel);
+                        map.put("thresholdId", alarmList.getId().toString());
+                        map.put("flag", "2");
+                    }
+                }
+            }
+            if (minLevel != null) {
+                for (AlarmList alarmList : maxAlarmList) {
+                    if (minLevel.equals(alarmList.getLevel())) {
+                        map.put("level", minLevel);
+                        map.put("thresholdId", alarmList.getId().toString());
+                        map.put("flag", "2");
+                    }
+                }
+            }
+        }
+        return map;
+    }
+
     /**
      * 保存阈值主表以及明细表
      *
@@ -456,9 +552,10 @@ public class MqttCallbackHandler extends AbstractHandler {
      * @param alarmTitle  设备类型明细
      * @param type        设备类型
      */
-    private long insertAlarmAndDetail(Long level, KwsDevice device, Long thresholdId,
-                                      String itemValue, Long ts,
-                                      String alarmTitle, Integer type
+    @Transactional
+    public long insertAlarmAndDetail(Long level, KwsDevice device, Long thresholdId,
+                                     String itemValue, Long ts,
+                                     String alarmTitle, Integer type
     ) {
         Long deviceId = device.getId();
         KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
@@ -475,12 +572,15 @@ public class MqttCallbackHandler extends AbstractHandler {
         return alarmId;
     }
 
-    private void insertHistoryRead(Long level, KwsDevice device, Long thresholdId, String itemValue, Long ts, String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
+    public void insertHistoryRead(Long level, KwsDevice device, Long thresholdId, String itemValue, Long ts, String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
         LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
-                .eq(KwsAlarm::getLevel, level.intValue())
-                .eq(KwsAlarm::getDeviceId, deviceId)
                 .eq(KwsAlarm::getStatus, NumberConstant.ONE)
                 .eq(KwsAlarm::getType, type)
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getIsHistory, 1)
+                .eq(KwsAlarm::getTitle, alarmTitle)
+                .eq(KwsAlarm::getDelFlag, 0)
                 .orderByDesc(KwsAlarm::getCreateTime);
         if (projectDevice != null) {
             wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
@@ -490,8 +590,8 @@ public class MqttCallbackHandler extends AbstractHandler {
             }
         }
         long alarmId = new IdWorker(NumberConstant.ONE).nextId();
-        List<KwsAlarm> alarms = alarmMapper.selectList(wrapper);
-        if (CollectionUtils.isEmpty(alarms)) {
+        KwsAlarm alarms = alarmMapper.selectOne(wrapper);
+        if (alarms == null) {
             KwsAlarm alarm = new KwsAlarm();
             String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
             String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
@@ -515,27 +615,18 @@ public class MqttCallbackHandler extends AbstractHandler {
         }
     }
 
-    private long insertUnread(Long level, KwsDevice device, Long thresholdId,
-                              String itemValue, Long ts,
-                              String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
-        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
-                .eq(KwsAlarm::getLevel, level.intValue())
-                .eq(KwsAlarm::getDeviceId, deviceId)
-                .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
-                .eq(KwsAlarm::getType, type)
-                .eq(KwsAlarm::getIsHistory, NumberConstant.ZERO)
-                .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
-                .orderByDesc(KwsAlarm::getCreateTime);
-        if (projectDevice != null) {
-            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
-                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
-            if (projectDevice.getProjectId() != null) {
-                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
-            }
-        }
+    public long insertUnread(Long level, KwsDevice device, Long thresholdId,
+                             String itemValue, Long ts,
+                             String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
+
         long alarmId = new IdWorker(NumberConstant.ONE).nextId();
-        List<KwsAlarm> alarms = alarmMapper.selectList(wrapper);
-        if (CollectionUtils.isEmpty(alarms)) {
+        KwsAlarm alarms = selectAlarmData(level, deviceId, type, alarmTitle, projectDevice);
+//        if (!CollectionUtils.isEmpty() && alarms.size() > 1) {
+//            //去重
+//            checkAlarmData(alarms, level, deviceId, type, alarmTitle, projectDevice);
+//        }
+//        alarms = selectAlarmData(level, deviceId, type, alarmTitle, projectDevice);
+        if (alarms == null) {
             KwsAlarm alarm = new KwsAlarm();
             String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
             String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
@@ -573,8 +664,8 @@ public class MqttCallbackHandler extends AbstractHandler {
             alarmDetail.setIsHistory(NumberConstant.ZERO);
             alarmDetailMapper.insert(alarmDetail);
         } else {
-            alarmId = alarms.get(0).getId();
-            KwsAlarm alarm = alarms.get(0);
+            alarmId = alarms.getId();
+            KwsAlarm alarm = alarms;
             LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
 //            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
             alarm.setUpdateTime(localDateTime);
@@ -611,6 +702,53 @@ public class MqttCallbackHandler extends AbstractHandler {
         return alarmId;
     }
 
+    private KwsAlarm selectAlarmData(Long level, Long deviceId, Integer type, String alarmTitle, KwsProjectDevice projectDevice) {
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
+                .eq(KwsAlarm::getType, type)
+                .eq(KwsAlarm::getTitle, alarmTitle)
+                .eq(KwsAlarm::getIsHistory, NumberConstant.ZERO)
+                .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
+                .orderByDesc(KwsAlarm::getCreateTime);
+        if (projectDevice != null) {
+            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
+                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
+            if (projectDevice.getProjectId() != null) {
+                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
+            }
+        }
+        KwsAlarm alarms = alarmMapper.selectOne(wrapper);
+        return alarms;
+    }
+
+    private void checkAlarmData(List<KwsAlarm> alarms, Long level, Long deviceId, Integer type, String alarmTitle, KwsProjectDevice projectDevice) {
+        for (KwsAlarm alarm : alarms) {
+            List<KwsAlarmDetail> details = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>().eq(KwsAlarmDetail::getAlarmId, alarm.getDeviceId()));
+            if (org.springframework.util.CollectionUtils.isEmpty(details) && details.size() == 0) {
+                alarm.setDelFlag(1);
+                alarmMapper.updateById(alarm);
+            }
+        }
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
+                .eq(KwsAlarm::getType, type)
+                .eq(KwsAlarm::getTitle, alarmTitle)
+                .eq(KwsAlarm::getIsHistory, NumberConstant.ZERO)
+                .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
+                .orderByDesc(KwsAlarm::getCreateTime);
+        if (projectDevice != null) {
+            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
+                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
+            if (projectDevice.getProjectId() != null) {
+                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
+            }
+        }
+    }
+
     /**
      * 计算最小值
      *
@@ -636,6 +774,31 @@ public class MqttCallbackHandler extends AbstractHandler {
         return null;
     }
 
+    private static String getListMaxNumber(BigDecimal number, List<AlarmList> alarmLists) {
+        for (AlarmList list : alarmLists) {
+            if (number.compareTo(list.getValue()) > 0) {
+                return list.getLevel();
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 计算最小值
+     *
+     * @param number
+     * @param alarmLists
+     * @return
+     */
+    private static String getListMinNumber(BigDecimal number, List<AlarmList> alarmLists) {
+        for (AlarmList list : alarmLists) {
+            if (number.compareTo(list.getValue()) < 0) {
+                return list.getLevel();
+            }
+        }
+        return null;
+    }
+
     public static void main(String[] args) {
         String s = "2023-11-30 22:00:00";
         Date date = DateUtils.formatDate(s);

+ 28 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/AlarmList.java

@@ -0,0 +1,28 @@
+package com.sckw.slope.detection.model.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+/**
+ * @author lfdc
+ * @description 阈值计算实体
+ * @date 2023-12-01 17:12:32
+ */
+@Data
+public class AlarmList implements Serializable {
+    /**
+     * 阈值等级
+     */
+    private String level;
+    /**
+     * 阈值id
+     */
+    private Long id;
+    /**
+     * 阈值
+     */
+    private BigDecimal value;
+
+}

+ 4 - 8
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/DeviceIntegrationVo.java

@@ -1,14 +1,10 @@
 package com.sckw.slope.detection.model.vo;
 
 import com.baomidou.mybatisplus.annotation.TableLogic;
-import com.fasterxml.jackson.annotation.JsonFormat;
-import com.sckw.slope.detection.model.dos.mysql.KwsDeviceIntegration;
 import lombok.Data;
 
 import java.io.Serializable;
 import java.time.LocalDateTime;
-import java.util.Date;
-import java.util.List;
 
 /**
  * @author lfdc
@@ -86,22 +82,22 @@ public class DeviceIntegrationVo implements Serializable {
     private String integrationCurrentBaseData;
 
     /**
-     *偏移
+     * 偏移
      */
     private String offset;
 
     /**
-     *当前测量值
+     * 当前测量值
      */
     private String currentData;
 
     /**
-     *当前测量值
+     * 要素名称字符串
      */
     private String partNames;
 
     /**
-     *公式字典值
+     * 公式字典值
      */
     private String formula;
 

+ 1 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java

@@ -244,6 +244,7 @@ public class KwsAlarmService {
                     .eq(KwsAlarm::getDeviceId, alarm.getDeviceId())
                     .eq(KwsAlarm::getCompanyId, alarm.getCompanyId())
                     .eq(KwsAlarm::getIsHistory, NumberConstant.ONE)
+                    .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
             );
             if (historyAlarm != null) {
                 alarmMapper.update(null, new LambdaUpdateWrapper<KwsAlarm>()

+ 1 - 1
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/TdengineService.java

@@ -53,7 +53,7 @@ public class TdengineService {
     }
 
     public Devices selectLastData(String deviceCode) {
-        SlopeData slopeData = slopeDataMapper.selectLastData(deviceCode);
+//        SlopeData slopeData = slopeDataMapper.selectLastData(deviceCode);
         Devices devices = devicesMapper.selectLastData(deviceCode);
         return devices;
     }

+ 294 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/task/DeviceAlarmTaskService.java

@@ -1,8 +1,34 @@
 package com.sckw.slope.detection.service.task;
 
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.sckw.core.model.constant.NumberConstant;
+import com.sckw.core.model.enums.AlarmTitleEnum;
+import com.sckw.core.model.enums.AlarmTypeEnum;
+import com.sckw.core.utils.IdWorker;
+import com.sckw.log.TraceLog.TraceLog;
+import com.sckw.slope.detection.dao.mysql.KwsAlarmDetailMapper;
+import com.sckw.slope.detection.dao.mysql.KwsAlarmMapper;
+import com.sckw.slope.detection.dao.mysql.KwsDeviceMapper;
+import com.sckw.slope.detection.dao.mysql.KwsProjectDeviceMapper;
+import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
+import com.sckw.slope.detection.model.dos.mysql.KwsAlarm;
+import com.sckw.slope.detection.model.dos.mysql.KwsAlarmDetail;
+import com.sckw.slope.detection.model.dos.mysql.KwsDevice;
+import com.sckw.slope.detection.model.dos.mysql.KwsProjectDevice;
+import com.sckw.slope.detection.model.dos.tdengine.Devices;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.CollectionUtils;
+
+import java.time.LocalDateTime;
+import java.util.Date;
+import java.util.List;
 
 /**
  * @author lfdc
@@ -14,4 +40,272 @@ import org.springframework.stereotype.Component;
 @EnableScheduling
 public class DeviceAlarmTaskService {
 
+    @Value("${scheduled.device.enable}")
+    private boolean deviceEnable;
+
+    @Autowired
+    KwsAlarmDetailMapper alarmDetailMapper;
+
+    @Autowired
+    KwsAlarmMapper alarmMapper;
+
+    @Autowired
+    KwsDeviceMapper deviceMapper;
+
+    @Autowired
+    DevicesMapper devicesMapper;
+
+    @Autowired
+    KwsProjectDeviceMapper projectDeviceMapper;
+
+    /**
+     * 设备告警数据
+     */
+    @TraceLog(description = "设备告警数据")
+    @Scheduled(cron = "0 0 */4 * * ? ")
+//    @Scheduled(cron = "* * * * * *")
+    public void deviceAlarm() {
+//        if ("false".equals(deviceEnable)) {
+//            return;
+//        }
+        if (!deviceEnable) {
+            return;
+        }
+        List<KwsDevice> deviceList = deviceMapper.selectList(
+                new LambdaQueryWrapper<KwsDevice>()
+                        .eq(KwsDevice::getDelFlag, 0)
+        );
+        if (!CollectionUtils.isEmpty(deviceList) && deviceList.size() > 0) {
+            for (KwsDevice device : deviceList) {
+                String snCode = device.getSnCode();
+                if (StringUtils.isNotBlank(snCode)) {
+                    Devices devices = null;
+                    try {
+                        devices = devicesMapper.selectLastData(snCode);
+                    } catch (Exception e) {
+                        log.error("select deviceAlarm tdengine device error :{}", e.getMessage(), e);
+                        continue;
+//                        insertAlarmAndDetailByDevice(1L, device, device.getId(), AlarmTitleEnum.ALARM_TITLE_ONE.getStatus(), AlarmTypeEnum.ALARM_TWO.getCode());
+//                        // todo 暂未设备告警电话,设备告警不推送短信
+//                        device.setOnline(1);
+//                        deviceMapper.updateById(device);
+                    }
+                    if (devices == null) {
+                        continue;
+//                        insertAlarmAndDetailByDevice(1L, device, device.getId(), AlarmTitleEnum.ALARM_TITLE_ONE.getStatus(), AlarmTypeEnum.ALARM_TWO.getCode());
+//                        // todo 暂未设备告警电话,设备告警不推送短信
+//                        device.setOnline(1);
+//                        deviceMapper.updateById(device);
+                    }
+                    //判断是否满足设备超时离线报警
+                    checkDeviceAlarm(snCode, device, devices);
+                }
+            }
+        }
+    }
+
+    /**
+     * 去除告警历史数据
+     */
+    @TraceLog(description = "去除告警历史数据")
+    @Scheduled(cron = "0 0 0/2 * * ? ")
+//    @Scheduled(cron = "* * * * * *")
+    public void deleteDeviceAlarm() {
+        List<KwsAlarmDetail> details = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>()
+                .eq(KwsAlarmDetail::getStatus, NumberConstant.ONE)
+                .eq(KwsAlarmDetail::getIsHistory, NumberConstant.ZERO)
+                .eq(KwsAlarmDetail::getDelFlag, NumberConstant.ONE)
+        );
+        if (!CollectionUtils.isEmpty(details)) {
+            details.forEach(alarmDetail -> {
+                alarmDetailMapper.deleteById(alarmDetail);
+            });
+        }
+    }
+
+    private void checkDeviceAlarm(String deviceCode, KwsDevice device, Devices devices) {
+        Date deviceTime = devices.getTs();
+        Date date = new Date();
+        long diff = Math.abs(date.getTime() - deviceTime.getTime());
+        long diffHours = diff / (60 * 60 * 1000) % 24;
+        if (diffHours > 24) {
+            long id = insertAlarmAndDetailByDevice(1L, device, device.getId(), AlarmTitleEnum.ALARM_TITLE_ONE.getStatus(), AlarmTypeEnum.ALARM_TWO.getCode());
+            // todo 暂未设备告警电话,设备告警不推送短信
+            device.setOnline(1);
+            deviceMapper.updateById(device);
+        } else {
+            device.setOnline(0);
+            deviceMapper.updateById(device);
+        }
+    }
+
+    /**
+     * 保存阈值主表以及明细表
+     *
+     * @param level       阈值等级
+     * @param device      设备
+     * @param thresholdId 阈值id/设备id
+     * @param alarmTitle  设备类型明细
+     * @param type        设备类型
+     */
+    @Transactional
+    public long insertAlarmAndDetailByDevice(Long level, KwsDevice device, Long thresholdId,
+                                             String alarmTitle, Integer type
+    ) {
+        Long deviceId = device.getId();
+        KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
+                .eq(KwsProjectDevice::getDeviceId, deviceId)
+                .eq(KwsProjectDevice::getDelFlag, 0)
+                .orderByDesc(KwsProjectDevice::getCreateTime)
+                .last(" limit 1")
+        );
+        //新增未读数据
+        long alarmId = insertUnreadByDevice(level, device, thresholdId, alarmTitle, type, deviceId, projectDevice);
+        //新增历史数据
+        insertHistoryReadByDevice(level, alarmTitle, type, deviceId, projectDevice);
+        return alarmId;
+    }
+
+    private void insertHistoryReadByDevice(Long level, String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getStatus, NumberConstant.ONE)
+                .eq(KwsAlarm::getType, type)
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getIsHistory, 1)
+                .eq(KwsAlarm::getTitle, alarmTitle)
+                .eq(KwsAlarm::getDelFlag, 0)
+                .orderByDesc(KwsAlarm::getCreateTime);
+        if (projectDevice != null) {
+            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
+                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
+            if (projectDevice.getProjectId() != null) {
+                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
+            }
+        }
+        long alarmId = new IdWorker(NumberConstant.ONE).nextId();
+        KwsAlarm alarms = alarmMapper.selectOne(wrapper);
+        if (alarms == null) {
+            KwsAlarm alarm = new KwsAlarm();
+            String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
+            String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
+            String projectId = projectDevice == null ? null :
+                    (projectDevice.getProjectId() == null ? null : projectDevice.getProjectId().toString());
+            alarm.setId(alarmId);
+            alarm.setCompanyId(companyId);
+            alarm.setMountainId(mountainId);
+            alarm.setProjectId(projectId);
+            alarm.setDeviceId(deviceId);
+            alarm.setTitle(alarmTitle);
+            alarm.setLevel(level.intValue());
+            alarm.setType(type);
+            LocalDateTime localDateTime = LocalDateTime.now();
+            alarm.setCreateTime(localDateTime);
+            alarm.setUpdateTime(localDateTime);
+            alarm.setStatus(1);
+            alarm.setTriggerTimes(0);
+            alarm.setIsHistory(1);
+            alarmMapper.insert(alarm);
+        }
+    }
+
+    private long insertUnreadByDevice(Long level, KwsDevice device, Long thresholdId, String alarmTitle, Integer type, Long deviceId, KwsProjectDevice projectDevice) {
+        long alarmId = new IdWorker(NumberConstant.ONE).nextId();
+        KwsAlarm alarms = selectAlarmData(level, deviceId, type, alarmTitle, projectDevice);
+        if (alarms == null) {
+            KwsAlarm alarm = new KwsAlarm();
+            String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
+            String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
+            String projectId = projectDevice == null ? null :
+                    (projectDevice.getProjectId() == null ? null : projectDevice.getProjectId().toString());
+            alarm.setId(alarmId);
+            alarm.setCompanyId(companyId);
+            alarm.setMountainId(mountainId);
+            alarm.setProjectId(projectId);
+            alarm.setDeviceId(deviceId);
+            alarm.setTitle(alarmTitle);
+            alarm.setLevel(level.intValue());
+            alarm.setType(type);
+            LocalDateTime localDateTime = LocalDateTime.now();
+            alarm.setCreateTime(localDateTime);
+            alarm.setUpdateTime(localDateTime);
+            alarm.setStatus(0);
+            alarm.setTriggerTimes(1);
+            alarmMapper.insert(alarm);
+            KwsAlarmDetail alarmDetail = new KwsAlarmDetail();
+            alarmDetail.setId(new IdWorker(NumberConstant.ONE).nextId());
+            alarmDetail.setMountainId(mountainId);
+            alarmDetail.setCompanyId(companyId);
+            alarmDetail.setAlarmId(alarmId);
+            alarmDetail.setPid(thresholdId);
+//            alarmDetail.setVal(itemValue);
+            alarmDetail.setLat(device.getLogicLat());
+            alarmDetail.setLng(device.getLogicLng());
+            alarmDetail.setAlt(device.getLogicAlt());
+            alarmDetail.setCreateTime(localDateTime);
+            alarmDetail.setUpdateTime(localDateTime);
+            alarmDetail.setStatus(0);
+            alarmDetail.setDelFlag(NumberConstant.ZERO);
+            alarmDetail.setIsHistory(NumberConstant.ZERO);
+            alarmDetailMapper.insert(alarmDetail);
+        } else {
+            alarmId = alarms.getId();
+            KwsAlarm alarm = alarms;
+            LocalDateTime localDateTime = LocalDateTime.now();
+//            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
+            alarm.setUpdateTime(localDateTime);
+            alarm.setStatus(0);
+            Long aLong = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>()
+                    .eq(KwsAlarmDetail::getAlarmId, alarmId)
+                    .eq(KwsAlarmDetail::getStatus, 0)
+                    .eq(KwsAlarmDetail::getIsHistory, 0)
+                    .eq(KwsAlarmDetail::getDelFlag, 0)
+            );
+            alarm.setTriggerTimes(aLong.intValue() + 1);
+            alarmMapper.updateById(alarm);
+            String mountainId = projectDevice == null ? null : projectDevice.getMountainId();
+            String companyId = projectDevice == null ? null : projectDevice.getCompanyId();
+            String projectId = projectDevice == null ? null :
+                    (projectDevice.getProjectId() == null ? null : projectDevice.getProjectId().toString());
+            KwsAlarmDetail alarmDetail = new KwsAlarmDetail();
+            alarmDetail.setId(new IdWorker(NumberConstant.TWO).nextId());
+            alarmDetail.setMountainId(mountainId);
+            alarmDetail.setCompanyId(companyId);
+            alarmDetail.setAlarmId(alarm.getId());
+            alarmDetail.setPid(thresholdId);
+//            alarmDetail.setVal(itemValue);
+            alarmDetail.setLat(device.getLogicLat());
+            alarmDetail.setLng(device.getLogicLng());
+            alarmDetail.setAlt(device.getLogicAlt());
+            alarmDetail.setCreateTime(localDateTime);
+            alarmDetail.setUpdateTime(localDateTime);
+            alarmDetail.setStatus(0);
+            alarmDetail.setDelFlag(NumberConstant.ZERO);
+            alarmDetail.setIsHistory(NumberConstant.ZERO);
+            alarmDetailMapper.insert(alarmDetail);
+        }
+        return alarmId;
+    }
+
+
+    private KwsAlarm selectAlarmData(Long level, Long deviceId, Integer type, String alarmTitle, KwsProjectDevice projectDevice) {
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
+                .eq(KwsAlarm::getType, type)
+                .eq(KwsAlarm::getTitle, alarmTitle)
+                .eq(KwsAlarm::getIsHistory, NumberConstant.ZERO)
+                .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
+                .orderByDesc(KwsAlarm::getCreateTime);
+        if (projectDevice != null) {
+            wrapper.eq(KwsAlarm::getProjectId, projectDevice.getProjectId())
+                    .eq(KwsAlarm::getMountainId, projectDevice.getMountainId());
+            if (projectDevice.getProjectId() != null) {
+                wrapper.eq(KwsAlarm::getCompanyId, projectDevice.getCompanyId());
+            }
+        }
+        KwsAlarm alarms = alarmMapper.selectOne(wrapper);
+        return alarms;
+    }
 }

+ 2 - 0
slope-modules/slope-detection/src/main/resources/bootstrap-dev.yml

@@ -57,6 +57,8 @@ sms:
 scheduled:
   template:
     enable: true
+  device:
+    enable: false
 
 #oss上传
 aliyun:

+ 3 - 1
slope-modules/slope-detection/src/main/resources/bootstrap-lfdc.yml

@@ -65,7 +65,7 @@ mqtt:
   # 要消费的topic配置
   receive:
     topic: slopePush/slopePull/test/out,test,slope,sharjeck/ai/test/out,system/iot/original_data_slope,system/iot/device_data_slope,system/iot/deviceDataSlopeDemo
-  isConsume: true
+  isConsume: false
 OkHttpClit:
   url: http://10.10.10.185:9501
 ## 订阅发布使用
@@ -92,6 +92,8 @@ aliyun:
 scheduled:
   template:
     enable: false
+  device:
+    enable: false
 
 mybatis-plus:
   #  mapper-locations: classpath*:/mapper/*/*.xml    #扫描xml文件

+ 1 - 2
slope-modules/slope-detection/src/main/resources/bootstrap.yml

@@ -6,8 +6,7 @@ spring:
     name: slope-detection
 #    name: slope-detection
   profiles:
-
-    active: lfdc
+    active: dev
     #active: ${DEPLOY_MODE:dev}
   main:
     allow-bean-definition-overriding: true

+ 9 - 8
slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsAlarmMapper.xml

@@ -361,6 +361,7 @@
         from kws_alarm
         <where>
             del_flag = 0
+            and trigger_times > 0
             <if test="mountainId != null and mountainId != ''">
                 and mountain_id = #{mountainId}
             </if>
@@ -370,12 +371,12 @@
             <if test="query.alarmInfo != null and query.alarmInfo != ''">
                 and title = #{query.alarmInfo}
             </if>
-            <if test="query.status != null and query.status != ''">
+            <if test="query.status != null">
                 and status = #{query.status}
             </if>
-            <if test="query.status != null and query.status != ''">
-                and is_history = #{query.status}
-            </if>
+<!--            <if test="query.status != null and query.status != ''">-->
+<!--                and is_history = #{query.status}-->
+<!--            </if>-->
             <if test="query.alarmLevel != null and query.alarmLevel != ''">
                 and level = #{query.alarmLevel}
             </if>
@@ -392,7 +393,7 @@
         </include>
         from kws_alarm
         <where>
-            del_flag = 0
+            del_flag = 0 and trigger_times > 0
             <if test="idsList != null and idsList.size() > 0">
                 and id in
                 <foreach collection="idsList" item="item" open="(" close=")" separator=",">
@@ -411,9 +412,9 @@
             <if test="query.status != null and query.status != ''">
                 and status = #{query.status}
             </if>
-            <if test="query.status != null and query.status != ''">
-                and is_history = #{query.status}
-            </if>
+<!--            <if test="query.status != null and query.status != ''">-->
+<!--                and is_history = #{query.status}-->
+<!--            </if>-->
             <if test="query.alarmLevel != null and query.alarmLevel != ''">
                 and level = #{query.alarmLevel}
             </if>