Răsfoiți Sursa

提交回滚代码

lengfaqiang 2 ani în urmă
părinte
comite
f46cd1b5d1
30 a modificat fișierele cu 1110 adăugiri și 564 ștergeri
  1. 0 53
      slope-common/slope-common-core/src/main/java/com/sckw/core/model/enums/IntegrationStatusEnum.java
  2. 5 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqttConfig.java
  3. 476 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttCallbackHandler.java
  4. 82 49
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttDeviceCallbackHandler.java
  5. 35 3
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/AlarmController.java
  6. 3 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/DeviceController.java
  7. 2 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/DeviceModelController.java
  8. 16 8
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/TdengineDemoController.java
  9. 5 19
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/backTrackController.java
  10. 4 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/mysql/KwsAlarmMapper.java
  11. 2 11
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/DevicesMapper.java
  12. 1 1
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/ReportTemplateAddDTO.java
  13. 0 5
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/DeviceQuery.java
  14. 6 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/AlarmLogThresholdVO.java
  15. 11 5
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/KwsAlarmVO.java
  16. 1 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ReportStatementVO.java
  17. 13 70
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/BackTrackService.java
  18. 3 30
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/DeviceModelService.java
  19. 64 55
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/DeviceService.java
  20. 134 37
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java
  21. 21 15
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/ReportTemplateService.java
  22. 11 1
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/TdengineService.java
  23. 64 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/task/ReportTemplateTaskService.java
  24. 46 5
      slope-modules/slope-detection/src/main/resources/bootstrap-lfdc.yml
  25. 67 67
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsAlarmMapper.xml
  26. 1 0
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsProjectMapper.xml
  27. 2 1
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsReportDataMapper.xml
  28. 5 4
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsReportTemplateMapper.xml
  29. 29 116
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/DevicesMapper.xml
  30. 1 1
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/SlopeDataMapper.xml

+ 0 - 53
slope-common/slope-common-core/src/main/java/com/sckw/core/model/enums/IntegrationStatusEnum.java

@@ -1,53 +0,0 @@
-package com.sckw.core.model.enums;
-
-/**
- * @author lfdc
- * @description 设备状态
- * @date 2023-11-01 10:07:23
- */
-public enum IntegrationStatusEnum {
-
-    /**
-     * 识别失败
-     */
-    INTEGRATION_ZERO(0, "0", "未自适应"),
-    /**
-     * 识别中
-     */
-    INTEGRATION_ONE(1, "1", "启用自适应"),
-
-    ;
-
-    public Integer getCode() {
-        return code;
-    }
-
-    public String getStatus() {
-        return status;
-    }
-
-    public String getDestination() {
-        return destination;
-    }
-
-    private final Integer code;
-    private final String status;
-    private final String destination;
-
-    IntegrationStatusEnum(Integer code, String status, String destination) {
-        this.code = code;
-        this.status = status;
-        this.destination = destination;
-    }
-    public static String getDestination(Integer code) {
-        for (IntegrationStatusEnum enums : IntegrationStatusEnum.values()) {
-            if (enums.getCode().equals(code)) {
-                return enums.getDestination();
-            }
-        }
-        return null;
-    }
-
-
-
-}

+ 5 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqttConfig.java

@@ -1,5 +1,6 @@
 package com.sckw.slope.detection.common.config;
 
+import com.sckw.slope.detection.consumer.MqttCallbackHandler;
 import com.sckw.slope.detection.consumer.mqApi.MqttApiHandler;
 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -192,6 +193,8 @@ public class MqttConfig {
         return adapter;
     }
 
+    @Autowired
+    private MqttCallbackHandler mqttCallbackHandler;
     /**
      * MQTT消息处理器(消费者)
      */
@@ -201,8 +204,8 @@ public class MqttConfig {
         return message -> {
             String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
             String payload = message.getPayload().toString();
-//            mqttCallbackHandler.handle(topic, payload);
-            mqttApiHandler.handle(topic, payload);
+            mqttCallbackHandler.handle(topic, payload);
+//            mqttApiHandler.handle(topic, payload);
         };
     }
 }

+ 476 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttCallbackHandler.java

@@ -0,0 +1,476 @@
+package com.sckw.slope.detection.consumer;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.sckw.core.model.constant.NumberConstant;
+import com.sckw.core.model.enums.DictEnum;
+import com.sckw.core.model.enums.DictItemEnum;
+import com.sckw.core.utils.CollectionUtils;
+import com.sckw.core.utils.IdWorker;
+import com.sckw.core.web.response.HttpResult;
+import com.sckw.slope.detection.dao.mysql.*;
+import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
+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.dto.DevicesAlarm;
+import com.sckw.slope.detection.model.dto.DevicesItem;
+import com.sckw.slope.detection.model.dto.SystemDict;
+import com.sckw.slope.detection.model.param.SmsMessageParam;
+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.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;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-11-18 16:11:36
+ */
+@Slf4j
+@Service
+public class MqttCallbackHandler {
+
+    @Value("${sms.url}")
+    private String messageUrl;
+
+    @Autowired
+    CommonService commonService;
+
+    @Autowired
+    DetectionApiService detectionApiService;
+
+    @Autowired
+    SlopeDataMapper slopeDataMapper;
+
+    @Autowired
+    KwsDeviceMapper deviceMapper;
+
+    @Autowired
+    KwsThresholdMapper thresholdMapper;
+
+    @Autowired
+    HandlerFactory handlerFactory;
+
+    @Transactional
+    public HttpResult handle(String topic, String payload) {
+        // 根据topic分别进行消息处理。
+        log.info("MqttDeviceCallbackHandler:" + topic + "|" + payload);
+        System.out.println("处理sharjeck/ai/test/out");
+        try {
+            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
+            String deviceCode = devicesAlarm.getDeviceCode();
+            List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
+                    .eq(KwsDevice::getSnCode, deviceCode)
+                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
+            );
+            KwsDevice device = null;
+            if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
+                device = deviceList.get(0);
+            }
+            if (device == null) {
+                log.error("接收处理数据:{}", payload);
+                log.error("设备数据并未维护,不做处理");
+                return null;
+            }
+            List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
+            if (!CollectionUtils.isEmpty(devicesItemList)) {
+                for (DevicesItem devicesItem : devicesItemList) {
+                    String itemName = devicesItem.getItemName();
+                    String itemValue = devicesItem.getItemValue();
+                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
+                            .eq(KwsThreshold::getDeviceId, device.getId())
+                            .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
+                            .eq(KwsThreshold::getItemName, itemName)
+                    );
+                    if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
+                        continue;
+                    }
+                    Long ts = devicesItem.getTs();
+                    //判断是否满足设备超时离线报警
+                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
+                    //判断是否满足数值超阈值报警
+                    Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
+                    if ("2".equals(map.get("flag"))) {
+                        Long level = Long.valueOf(map.get("level"));
+                        Long thresholdId = Long.valueOf(map.get("thresholdId"));
+                        //阈值表以及明细表存储
+                        insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
+                        /*【露天矿山边坡监测系统】尊敬的管理员,2023-10-01 12:23:34监测到一级告警。
+                            设备名称:位移监测设备-gnss一号机,监测数值:55。123456789N,请尽快处理问题。*/
+                        Map<String, Object> messageMap = new HashMap<>();
+                        pushSmsMessage(messageUrl, device, level, thresholdId, messageMap);
+                    }
+
+                }
+            }
+        } catch (Exception e) {
+            log.error("mqtt消费异常:{}", e.getMessage(), e);
+        }
+        return HttpResult.ok();
+    }
+
+    @Async
+    public void pushSmsMessage(String messageUrl, KwsDevice device, Long level, Long thresholdId, Map<String, Object> messageMap) {
+        Long deviceId = device.getId();
+        KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
+                .eq(KwsProjectDevice::getDeviceId, deviceId)
+                .eq(KwsProjectDevice::getDelFlag, 0)
+                .eq(KwsProjectDevice::getStatus, 0)
+                .orderByDesc(KwsProjectDevice::getCreateTime)
+                .last(" limit 1")
+        );
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getType, NumberConstant.ONE)
+                .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());
+            }
+        }
+        SmsMessageParam param = new SmsMessageParam();
+        param.setCode("123456");
+        param.setType("2");
+        List<String> stringList = new ArrayList<>();
+        stringList.add("18215677925");
+        param.setPushTo(stringList);
+        SmsMessageParam.Content content = new SmsMessageParam.Content();
+        content.setTemplateCode("SMS_262585113");
+        content.setSignName("矿拉拉");
+        SmsMessageParam.TemplateParam templateParam = new SmsMessageParam.TemplateParam();
+        templateParam.setName("123");
+        templateParam.setStart("123");
+        content.setTemplateParam(templateParam);
+        param.setContent(content);
+        detectionApiService.pushSmsMessage(messageUrl, JSONObject.toJSONString(param));
+
+    }
+
+    @Autowired
+    DevicesMapper devicesMapper;
+
+    private void checkDeviceAlarm(String deviceCode, KwsDevice device, String itemValue, Long ts) {
+        Devices devices = tdengineService.selectLastData(deviceCode);
+        if (devices != null) {
+            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) {
+                insertAlarmAndDetail(1L, device, device.getId(), itemValue, ts);
+                // todo 暂未设备告警电话,设备告警不推送短信
+                device.setOnline(1);
+                deviceMapper.updateById(device);
+            } else {
+                device.setOnline(0);
+                deviceMapper.updateById(device);
+            }
+        }
+    }
+
+    @Autowired
+    KwsAlarmMapper alarmMapper;
+
+    @Autowired
+    KwsAlarmDetailMapper alarmDetailMapper;
+
+    @Autowired
+    KwsDeviceRelationMapper deviceRelationMapper;
+
+    @Autowired
+    KwsProjectDeviceMapper projectDeviceMapper;
+
+    @Autowired
+    KwsDeviceReferenceMapper deviceReferenceMapper;
+
+    @Autowired
+    private TdengineService tdengineService;
+
+
+    private Map<String, String> checkThresholdAlarm(DevicesItem devicesItem, List<KwsThreshold> kwsThresholds, KwsDevice device) {
+        String itemName = devicesItem.getItemName();
+        String itemValue = devicesItem.getItemValue();
+        Long deviceId = device.getId();
+        KwsDeviceReference deviceRelation = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
+                .eq(KwsDeviceReference::getDeviceId, deviceId)
+                .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
+                .eq(KwsDeviceReference::getType, "1")
+                .eq(KwsDeviceReference::getItem, itemName)
+        );
+        /**x、y、z要进行偏移量计算  其他数值保持源数据进行计算*/
+        List<String> checkItemName = new ArrayList<>();
+        checkItemName.add(DictItemEnum.ALTITUDE_Z.getValue());
+        checkItemName.add(DictItemEnum.LONGITUDE_X.getValue());
+        checkItemName.add(DictItemEnum.LATITUDE_Y.getValue());
+        //需要计算的阈值
+        if (checkItemName.contains(itemName)) {
+            BigDecimal offset = commonService.computeOffset(itemValue, itemName, deviceRelation);
+            Map<String, Long> maxMap = new HashMap<>();
+            Map<String, Long> minMap = new HashMap<>();
+            List<BigDecimal> maxList = new ArrayList<>();
+            List<BigDecimal> minList = new ArrayList<>();
+            for (KwsThreshold kwsThreshold : kwsThresholds) {
+                maxList.add(new BigDecimal(kwsThreshold.getMax()));
+                minList.add(new BigDecimal(kwsThreshold.getMin()));
+                String max = kwsThreshold.getMax();
+                Long thresholdId = kwsThreshold.getId();
+                String min = kwsThreshold.getMin();
+                Integer level = kwsThreshold.getLevel();
+                /**为了获取最阈值等级*/
+                if (maxMap.get(max) != null) {
+                    Long integer = maxMap.get(max);
+                    if (integer <= level) {
+                        maxMap.put(max, level.longValue());
+                        maxMap.put(level.toString(), thresholdId.longValue());
+                    }
+                }
+                if (minMap.get(min) != null) {
+                    Long integer = minMap.get(min);
+                    if (integer <= level) {
+                        minMap.put(min, level.longValue());
+                        minMap.put(level.toString(), thresholdId.longValue());
+                    }
+                }
+            }
+//        minList = minList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
+            minList = minList.stream().sorted().distinct().collect(Collectors.toList());
+            maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
+            /**计算阈值界限*/
+            BigDecimal max = getMaxNumber(offset, maxList);
+            BigDecimal min = getMinNumber(offset, minList);
+            /**存在阈值触发*/
+            Map<String, String> map = new HashMap<>();
+            map.put("level", "1");
+            map.put("thresholdId", "1");
+            map.put("flag", "1");
+            if (min != null && max != null) {
+                if (max != null) {
+                    Long level = maxMap.get(max);
+                    Long thresholdId = maxMap.get(level.toString());
+                    map.put("level", level.toString());
+                    map.put("thresholdId", thresholdId.toString());
+                    map.put("flag", "2");
+//                    insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
+                }
+                if (min != null) {
+                    Long level = minMap.get(min);
+                    Long thresholdId = minMap.get(level.toString());
+                    map.put("level", level.toString());
+                    map.put("thresholdId", thresholdId.toString());
+                    map.put("flag", "2");
+                }
+            }
+            return map;
+        } else {
+            //直接阈值计算的处理
+            Map<String, Long> maxMap = new HashMap<>();
+            Map<String, Long> minMap = new HashMap<>();
+            List<BigDecimal> maxList = new ArrayList<>();
+            List<BigDecimal> minList = new ArrayList<>();
+            for (KwsThreshold kwsThreshold : kwsThresholds) {
+                maxList.add(new BigDecimal(kwsThreshold.getMax()));
+                minList.add(new BigDecimal(kwsThreshold.getMin()));
+                String max = kwsThreshold.getMax();
+                Long thresholdId = kwsThreshold.getId();
+                String min = kwsThreshold.getMin();
+                Integer level = kwsThreshold.getLevel();
+                /**为了获取最阈值等级*/
+                if (maxMap.get(max) != null) {
+                    Long integer = maxMap.get(max);
+                    if (integer <= level) {
+                        maxMap.put(max, level.longValue());
+                        maxMap.put(level.toString(), thresholdId.longValue());
+                    }
+                }
+                if (minMap.get(min) != null) {
+                    Long integer = minMap.get(min);
+                    if (integer <= level) {
+                        minMap.put(min, level.longValue());
+                        minMap.put(level.toString(), thresholdId.longValue());
+                    }
+                }
+            }
+//        minList = minList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
+            minList = minList.stream().sorted().distinct().collect(Collectors.toList());
+            maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
+            /**计算阈值界限*/
+            BigDecimal max = getMaxNumber(new BigDecimal(itemValue), maxList);
+            BigDecimal min = getMinNumber(new BigDecimal(itemValue), minList);
+            /**存在阈值触发*/
+            Map<String, String> map = new HashMap<>();
+            map.put("level", "1");
+            map.put("thresholdId", "1");
+            map.put("flag", "1");
+            if (min != null && max != null) {
+                if (max != null) {
+                    Long level = maxMap.get(max);
+                    Long thresholdId = maxMap.get(level.toString());
+                    map.put("level", level.toString());
+                    map.put("thresholdId", thresholdId.toString());
+                    map.put("flag", "2");
+//                    insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
+                }
+                if (min != null) {
+                    Long level = minMap.get(min);
+                    Long thresholdId = minMap.get(level.toString());
+                    map.put("level", level.toString());
+                    map.put("thresholdId", thresholdId.toString());
+                    map.put("flag", "2");
+                }
+            }
+            return map;
+        }
+    }
+
+    /**
+     * 保存阈值主表以及明细表
+     *
+     * @param level       阈值等级
+     * @param device      设备
+     * @param thresholdId 阈值id/设备id
+     * @param itemValue   td数据当时检测值
+     * @param ts          td时间
+     */
+    private void insertAlarmAndDetail(Long level, KwsDevice device, Long thresholdId, String itemValue, Long ts) {
+        Long deviceId = device.getId();
+        KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
+                .eq(KwsProjectDevice::getDeviceId, deviceId)
+                .eq(KwsProjectDevice::getDelFlag, 0)
+                .eq(KwsProjectDevice::getStatus, 0)
+                .orderByDesc(KwsProjectDevice::getCreateTime)
+                .last(" limit 1")
+        );
+        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
+                .eq(KwsAlarm::getLevel, level.intValue())
+                .eq(KwsAlarm::getDeviceId, deviceId)
+                .eq(KwsAlarm::getType, NumberConstant.ONE)
+                .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());
+            }
+        }
+        List<KwsAlarm> alarms = alarmMapper.selectList(wrapper);
+        if (CollectionUtils.isEmpty(alarms)) {
+            KwsAlarm alarm = new KwsAlarm();
+            long alarmId = new IdWorker(NumberConstant.ONE).nextId();
+            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("2");
+            alarm.setLevel(level.intValue());
+            alarm.setType(2);
+            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
+            alarm.setCreateTime(localDateTime);
+            alarm.setUpdateTime(localDateTime);
+            alarm.setStatus(0);
+            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.getLogicAlt());
+            alarmDetail.setAlt(device.getLogicAlt());
+            alarmDetail.setCreateTime(localDateTime);
+            alarmDetail.setUpdateTime(localDateTime);
+            alarmDetail.setStatus(0);
+            alarmDetailMapper.insert(alarmDetail);
+        } else {
+            KwsAlarm alarm = alarms.get(0);
+            LocalDateTime localDateTime = new Date(ts).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
+            alarm.setUpdateTime(localDateTime);
+            alarmMapper.updateById(alarm);
+        }
+    }
+
+    /**
+     * 计算最小值
+     *
+     * @param number
+     * @param list
+     * @return
+     */
+    private static BigDecimal getMinNumber(BigDecimal number, List<BigDecimal> list) {
+        for (BigDecimal decimal : list) {
+            if (number.compareTo(decimal) < 0) {
+                return decimal;
+            }
+        }
+        return null;
+    }
+
+    private static BigDecimal getMaxNumber(BigDecimal number, List<BigDecimal> list) {
+        for (BigDecimal decimal : list) {
+            if (number.compareTo(decimal) > 0) {
+                return decimal;
+            }
+        }
+        return null;
+    }
+
+    public static void main(String[] args) {
+        DevicesAlarm alarm = new DevicesAlarm();
+        alarm.setDeviceCode("s8");
+        List<DevicesItem> list = new ArrayList<>();
+        DevicesItem item = new DevicesItem();
+        item.setItemName("alt");
+        item.setItemValue("20.12646584");
+        long time = new Date().getTime();
+        item.setTs(new Date().getTime());
+        String md5 = new MD5Utils().getMd5(String.valueOf(time));
+        item.setGuid(md5);
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String format = simpleDateFormat.format(new Date());
+        item.setTslverId(format);
+        item.setMsgId(format);
+        item.setRawTs(format);
+        list.add(item);
+        alarm.setDevicesItemList(list);
+        String demoTest = "{\"deviceCode\":\"s8\",\"devicesItemList\":[{\"guid\":\"c7653b298bec06eb78be3140b5c2ea9b\",\"itemName\":\"alt\",\"itemValue\":\"20.12646584\",\"msg_id\":\"2023-11-18 14:49:06\",\"raw_ts\":\"2023-11-18 14:49:06\",\"ts\":1700290146508,\"tslver_Id\":\"2023-11-18 14:49:06\"}]}";
+        System.out.println("alarm:" + JSONObject.toJSONString(alarm));
+        List<BigDecimal> maxList = new ArrayList<>();
+        maxList.add(new BigDecimal("52"));
+        maxList.add(new BigDecimal("40"));
+        maxList.add(new BigDecimal("35"));
+        List<BigDecimal> minList = new ArrayList<>();
+        minList.add(new BigDecimal("30"));
+        minList.add(new BigDecimal("26"));
+        minList.add(new BigDecimal("10"));
+        minList = minList.stream().sorted().distinct().collect(Collectors.toList());
+        maxList = maxList.stream().sorted().distinct().collect(Collectors.toList());
+        BigDecimal max = getMaxNumber(new BigDecimal("38"), maxList);
+        System.out.println(max);
+        BigDecimal min = getMinNumber(new BigDecimal("8"), minList);
+        System.out.println(min);
+    }
+}

+ 82 - 49
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttDeviceCallbackHandler.java

@@ -9,16 +9,19 @@ import com.sckw.core.utils.CollectionUtils;
 import com.sckw.core.utils.IdWorker;
 import com.sckw.core.web.response.HttpResult;
 import com.sckw.slope.detection.dao.mysql.*;
+import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
 import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
 import com.sckw.slope.detection.model.dos.mysql.*;
-import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
+import com.sckw.slope.detection.model.dos.tdengine.Devices;
 import com.sckw.slope.detection.model.dto.DevicesAlarm;
 import com.sckw.slope.detection.model.dto.DevicesItem;
 import com.sckw.slope.detection.model.dto.SystemDict;
 import com.sckw.slope.detection.model.param.SmsMessageParam;
 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.dubbo.common.utils.MD5Utils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
@@ -26,6 +29,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
 import java.time.LocalDateTime;
 import java.time.ZoneOffset;
 import java.util.*;
@@ -66,58 +70,62 @@ public class MqttDeviceCallbackHandler extends AbstractHandler {
         // 根据topic分别进行消息处理。
         log.info("MqttDeviceCallbackHandler:" + topic + "|" + payload);
         System.out.println("处理sharjeck/ai/test/out");
-        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
-        DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
-        String deviceCode = devicesAlarm.getDeviceCode();
-        List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
-                .eq(KwsDevice::getSnCode, deviceCode)
-                .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
-        );
-        KwsDevice device = null;
-        if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
-            device = deviceList.get(0);
-        }
-        if (device == null) {
-            log.error("接收处理数据:{}", payload);
-            log.error("设备数据并未维护,不做处理");
-            return null;
-        }
-        List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
-        if (!CollectionUtils.isEmpty(devicesItemList)) {
-            for (DevicesItem devicesItem : devicesItemList) {
-                String itemName = devicesItem.getItemName();
-                String itemValue = devicesItem.getItemValue();
-                List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
-                        .eq(KwsThreshold::getDeviceId, device.getId())
-                        .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
-                        .eq(KwsThreshold::getItemName, itemName)
-                );
-                if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
-                    continue;
-                }
-                Long ts = devicesItem.getTs();
-                //判断是否满足设备超时离线报警
-                checkDeviceAlarm(deviceCode, device, itemValue, ts);
-                //判断是否满足数值超阈值报警
-                Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
-                if ("2".equals(map.get("flag"))) {
-                    Long level = Long.valueOf(map.get("level"));
-                    Long thresholdId = Long.valueOf(map.get("thresholdId"));
-                    //阈值表以及明细表存储
-                    insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
-                    /*【露天矿山边坡监测系统】尊敬的管理员,2023-10-01 12:23:34监测到一级告警。
-                        设备名称:位移监测设备-gnss一号机,监测数值:55。123456789N,请尽快处理问题。*/
-                    Map<String, Object> messageMap = new HashMap<>();
-                    pushSmsMessage(messageUrl,device,level,thresholdId,messageMap);
-                }
+        try {
+            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
+            String deviceCode = devicesAlarm.getDeviceCode();
+            List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
+                    .eq(KwsDevice::getSnCode, deviceCode)
+                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
+            );
+            KwsDevice device = null;
+            if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
+                device = deviceList.get(0);
+            }
+            if (device == null) {
+                log.error("接收处理数据:{}", payload);
+                log.error("设备数据并未维护,不做处理");
+                return null;
+            }
+            List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
+            if (!CollectionUtils.isEmpty(devicesItemList)) {
+                for (DevicesItem devicesItem : devicesItemList) {
+                    String itemName = devicesItem.getItemName();
+                    String itemValue = devicesItem.getItemValue();
+                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
+                            .eq(KwsThreshold::getDeviceId, device.getId())
+                            .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
+                            .eq(KwsThreshold::getItemName, itemName)
+                    );
+                    if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
+                        continue;
+                    }
+                    Long ts = devicesItem.getTs();
+                    //判断是否满足设备超时离线报警
+                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
+                    //判断是否满足数值超阈值报警
+                    Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
+                    if ("2".equals(map.get("flag"))) {
+                        Long level = Long.valueOf(map.get("level"));
+                        Long thresholdId = Long.valueOf(map.get("thresholdId"));
+                        //阈值表以及明细表存储
+                        insertAlarmAndDetail(level, device, thresholdId, itemValue, ts);
+                        /*【露天矿山边坡监测系统】尊敬的管理员,2023-10-01 12:23:34监测到一级告警。
+                            设备名称:位移监测设备-gnss一号机,监测数值:55。123456789N,请尽快处理问题。*/
+                        Map<String, Object> messageMap = new HashMap<>();
+                        pushSmsMessage(messageUrl, device, level, thresholdId, messageMap);
+                    }
 
+                }
             }
+        } catch (Exception e) {
+            log.error("mqtt消费异常:{}", e.getMessage(), e);
         }
         return HttpResult.ok();
     }
 
     @Async
-    public void pushSmsMessage(String messageUrl, KwsDevice device,Long level,Long thresholdId,Map<String, Object> messageMap) {
+    public void pushSmsMessage(String messageUrl, KwsDevice device, Long level, Long thresholdId, Map<String, Object> messageMap) {
         Long deviceId = device.getId();
         KwsProjectDevice projectDevice = projectDeviceMapper.selectOne(new LambdaQueryWrapper<KwsProjectDevice>()
                 .eq(KwsProjectDevice::getDeviceId, deviceId)
@@ -152,13 +160,16 @@ public class MqttDeviceCallbackHandler extends AbstractHandler {
         templateParam.setStart("123");
         content.setTemplateParam(templateParam);
         param.setContent(content);
-        detectionApiService.pushSmsMessage(messageUrl,JSONObject.toJSONString(param));
+        detectionApiService.pushSmsMessage(messageUrl, JSONObject.toJSONString(param));
 
     }
 
+    @Autowired
+    DevicesMapper devicesMapper;
+
     private void checkDeviceAlarm(String deviceCode, KwsDevice device, String itemValue, Long ts) {
         try {
-            SlopeData devices = slopeDataMapper.selectLastData(deviceCode);
+            Devices devices = tdengineService.selectLastData(deviceCode);
             if (devices != null) {
                 Date deviceTime = devices.getTs();
                 Date date = new Date();
@@ -169,7 +180,7 @@ public class MqttDeviceCallbackHandler extends AbstractHandler {
                     // todo 暂未设备告警电话,设备告警不推送短信
                     device.setOnline(1);
                     deviceMapper.updateById(device);
-                }else {
+                } else {
                     device.setOnline(0);
                     deviceMapper.updateById(device);
                 }
@@ -194,6 +205,9 @@ public class MqttDeviceCallbackHandler extends AbstractHandler {
     @Autowired
     KwsDeviceReferenceMapper deviceReferenceMapper;
 
+    @Autowired
+    private  TdengineService tdengineService;
+
 
     private Map<String, String> checkThresholdAlarm(DevicesItem devicesItem, List<KwsThreshold> kwsThresholds, KwsDevice device) {
         String itemName = devicesItem.getItemName();
@@ -429,6 +443,25 @@ public class MqttDeviceCallbackHandler extends AbstractHandler {
     }
 
     public static void main(String[] args) {
+        DevicesAlarm alarm = new DevicesAlarm();
+        alarm.setDeviceCode("s8");
+        List<DevicesItem> list = new ArrayList<>();
+        DevicesItem item = new DevicesItem();
+        item.setItemName("alt");
+        item.setItemValue("20.12646584");
+        long time = new Date().getTime();
+        item.setTs(new Date().getTime());
+        String md5 = new MD5Utils().getMd5(String.valueOf(time));
+        item.setGuid(md5);
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String format = simpleDateFormat.format(new Date());
+        item.setTslverId(format);
+        item.setMsgId(format);
+        item.setRawTs(format);
+        list.add(item);
+        alarm.setDevicesItemList(list);
+        String demoTest = "{\"deviceCode\":\"s8\",\"devicesItemList\":[{\"guid\":\"c7653b298bec06eb78be3140b5c2ea9b\",\"itemName\":\"alt\",\"itemValue\":\"20.12646584\",\"msg_id\":\"2023-11-18 14:49:06\",\"raw_ts\":\"2023-11-18 14:49:06\",\"ts\":1700290146508,\"tslver_Id\":\"2023-11-18 14:49:06\"}]}";
+        System.out.println("alarm:" + JSONObject.toJSONString(alarm));
         List<BigDecimal> maxList = new ArrayList<>();
         maxList.add(new BigDecimal("52"));
         maxList.add(new BigDecimal("40"));

+ 35 - 3
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/AlarmController.java

@@ -10,6 +10,8 @@ import com.sckw.excel.annotation.ExcelContext;
 import com.sckw.excel.utils.ExcelUtil;
 import com.sckw.slope.detection.model.param.AlarmLogThresholdQuery;
 import com.sckw.slope.detection.model.param.AlarmStatisticsQuery;
+import com.sckw.slope.detection.model.vo.ThresholdLogDetailVO;
+import com.sckw.slope.detection.model.vo.ThresholdRecordDetailVO;
 import com.sckw.slope.detection.model.vo.excel.KwsAlarmExportVO;
 import com.sckw.slope.detection.service.KwsAlarmService;
 import jakarta.servlet.http.HttpServletRequest;
@@ -73,13 +75,28 @@ public class AlarmController {
         return HttpResult.ok(HttpStatus.SUCCESS_CODE, "导出成功", filePathMap);
     }
 
-    @Log(description = "告警日志-告警明细")
-    @RequestMapping(name = "告警日志-告警明细", value = "/thresholdDetail", method = RequestMethod.POST)
+    @Log(description = "告警通知-详情/告警日志-告警明细")
+    @RequestMapping(name = "告警通知-详情", value = "/thresholdDetail", method = RequestMethod.POST)
     public HttpResult thresholdDetail(@Valid @RequestBody PublicBaseList baseList, HttpServletRequest request) {
-        log.info("告警日志-告警明细 threshold_detail param {}", baseList);
+        log.info("告警通知-详情 threshold_detail param {}", baseList);
         return HttpResult.ok(kwsAlarmService.thresholdDetail(baseList, request));
     }
 
+    @Log(description = "告警记录-导出详情明细")
+    @RequestMapping(name = "告警记录-导出详情明细", value = "/exportDetail", method = RequestMethod.POST)
+    public HttpResult exportDetail(@Valid @RequestBody PublicBaseList baseList, HttpServletRequest request, HttpServletResponse response) throws IOException {
+        log.info("告警记录-导出详情明细 exportDetail param {}", baseList);
+        List<ThresholdRecordDetailVO> list = kwsAlarmService.exportDetail(baseList, request);
+        if (org.springframework.util.CollectionUtils.isEmpty(list)) {
+            return HttpResult.ok(HttpStatus.SUCCESS_CODE, "暂无数据,请确认");
+        }
+        ExcelContext excelContext = KwsAlarmExportVO.class.getAnnotation(ExcelContext.class);
+        String filePath = ExcelUtil.exportByExcelUploadingToOss(response, list, excelContext.fileName() + ".xlsx", KwsAlarmExportVO.class);
+        Map<String, String> filePathMap = new HashMap<>();
+        filePathMap.put("filePath", filePath);
+        return HttpResult.ok(filePathMap);
+    }
+
     @Log(description = "告警记录-告警明细")
     @RequestMapping(name = "告警记录-告警明细", value = "/detail", method = RequestMethod.GET)
     public HttpResult detail(@RequestParam("id") String id, HttpServletRequest request) {
@@ -87,6 +104,21 @@ public class AlarmController {
         return kwsAlarmService.detail(id, request);
     }
 
+    @Log(description = "告警记录-告警明细")
+    @RequestMapping(name = "告警记录-告警明细", value = "/exportDetailById", method = RequestMethod.GET)
+    public HttpResult exportDetailById(@RequestParam("id") String id, HttpServletRequest request,HttpServletResponse response) throws IOException {
+        log.info("告警记录-告警明细 detail param {}", id);
+        List<ThresholdLogDetailVO> thresholdLogDetailVOS = kwsAlarmService.exportDetailById(id, request);
+        if (org.springframework.util.CollectionUtils.isEmpty(thresholdLogDetailVOS)) {
+            return HttpResult.ok(HttpStatus.SUCCESS_CODE, "暂无数据,请确认");
+        }
+        ExcelContext excelContext = KwsAlarmExportVO.class.getAnnotation(ExcelContext.class);
+        String filePath = ExcelUtil.exportByExcelUploadingToOss(response, thresholdLogDetailVOS, excelContext.fileName() + ".xlsx", KwsAlarmExportVO.class);
+        Map<String, String> filePathMap = new HashMap<>();
+        filePathMap.put("filePath", filePath);
+        return HttpResult.ok(filePath);
+    }
+
     @Log(description = "数据告警-图-项目/项目告警-图")
     @RequestMapping(name = "项目告警-图", value = "/projectAlarm", method = RequestMethod.POST)
     public HttpResult projectAlarm(@Valid @RequestBody AlarmStatisticsQuery query, HttpServletRequest request) {

+ 3 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/DeviceController.java

@@ -34,9 +34,10 @@ public class DeviceController {
     @Log(description = "设备删除")
     //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
     @RequestMapping(name = "设备删除", value = "/dels", method = RequestMethod.GET)
-    public HttpResult dels(@RequestParam("ids") @NotBlank(message = "设备id不能为空") String ids, HttpServletRequest request) {
+    public HttpResult dels(@RequestParam("ids") @NotBlank(message = "设备id不能为空") String ids) {
         log.info("设备删除 delete param:{}", ids);
-        return deviceService.dels(ids,request);
+        return deviceService.dels(ids
+        );
     }
 
     @Log(description = "所属设备查询")

+ 2 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/DeviceModelController.java

@@ -35,9 +35,9 @@ public class DeviceModelController {
     @Log(description = "设备型号删除")
     //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
     @RequestMapping(name = "设备型号删除", value = "/dels", method = RequestMethod.GET)
-    public HttpResult dels(@RequestParam("ids") @NotBlank(message = "设备id不能为空") String ids, HttpServletRequest response) {
+    public HttpResult dels(@RequestParam("ids") @NotBlank(message = "设备id不能为空") String ids) {
         log.info("设备型号删除 delete param:{}", ids);
-        return deviceModelService.dels(ids,response);
+        return deviceModelService.dels(ids);
     }
 
 

+ 16 - 8
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/TdengineDemoController.java

@@ -1,6 +1,7 @@
 package com.sckw.slope.detection.controller;
 
-import com.sckw.slope.detection.service.TdengineDemoService;
+import com.sckw.slope.detection.model.dos.tdengine.Devices;
+import com.sckw.slope.detection.service.TdengineService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -16,20 +17,27 @@ import org.springframework.web.bind.annotation.RestController;
 public class TdengineDemoController {
 
     @Autowired
-    TdengineDemoService tdengineDemoService;
+    TdengineService tdengineDemoService;
 
-    @RequestMapping(value = "/tdengine",method = RequestMethod.GET)
-    public void tdengineDemo(){
+    @RequestMapping(value = "/tdengine", method = RequestMethod.GET)
+    public void tdengineDemo() {
         tdengineDemoService.tdengineDemo();
+
+
+    }
+
+    @RequestMapping(value = "/getDevicesDemo", method = RequestMethod.GET)
+    public void getDevicesDemo() {
+        Devices devices= tdengineDemoService.selectLastData("f1beaa4b9d85f26f288bb3b8e72a6aa0");
     }
 
-    @RequestMapping(value = "/getTable",method = RequestMethod.GET)
-    public void getTable(){
+    @RequestMapping(value = "/getTable", method = RequestMethod.GET)
+    public void getTable() {
         tdengineDemoService.getTable();
     }
 
-    @RequestMapping(value = "/createTable",method = RequestMethod.GET)
-    public void createTable(){
+    @RequestMapping(value = "/createTable", method = RequestMethod.GET)
+    public void createTable() {
         tdengineDemoService.createTable();
     }
 }

+ 5 - 19
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/backTrackController.java

@@ -43,17 +43,17 @@ public class backTrackController {
     @Log(description = "返回要素所属于的设备")
     //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
     @RequestMapping(name = "返回要素所属于的设备", value = "/getDeviceByParts", method = RequestMethod.GET)
-    public HttpResult getDeviceByParts(@RequestParam("parts") String parts,@RequestParam("projectId") String projectId) {
-        log.info("返回要素所属于的设备 getDeviceByParts param :{},projectId:{}",parts,projectId);
-        return backTrackService.getDeviceByParts(parts,projectId);
+    public HttpResult getDeviceByParts(@RequestParam("parts") String parts) {
+        log.info("返回要素所属于的设备 getDeviceByParts param :{}",parts);
+        return backTrackService.getDeviceByParts(parts);
     }
 
     @Log(description = "返回设备折线图")
     //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
     @RequestMapping(name = "返回设备折线图", value = "/getDeviceChart", method = RequestMethod.GET)
-    public HttpResult getDeviceChart(@RequestParam("deviceId") String deviceId,@RequestParam("snCode") String snCode, @RequestParam("part") String part, @RequestParam("dateStart") String dateStart, @RequestParam("dateEnd") String dateEnd, @RequestParam("original") Integer original) {
+    public HttpResult getDeviceChart(@RequestParam("deviceId") String deviceId,@RequestParam("snCode") String snCode, @RequestParam("part") String part, @RequestParam("dateStart") String dateStart, @RequestParam("dateEnd") String dateEnd) {
         log.info("返回设备折线图 getDeviceChart param :{},part:{}",deviceId,part);
-        return backTrackService.getDeviceChart(deviceId,snCode,part,dateStart,dateEnd,original);
+        return backTrackService.getDeviceChart(deviceId,snCode,part,dateStart,dateEnd);
     }
 
 
@@ -80,21 +80,7 @@ public class backTrackController {
         log.info("新增集成分析 integrationAdd param:{}", JSONObject.toJSONString(Vo));
         return HttpResult.ok(backTrackService.integrationAdd(Vo, request));
     }
-    @Log(description = "修改集成分析")
-    //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
-    @RequestMapping(name = "修改集成分析", value = "/integrationUpdate", method = RequestMethod.POST)
-    public HttpResult integrationUpdate(@Valid @RequestBody IntegrationVo Vo, HttpServletRequest request) {
-        log.info("修改集成分析 integrationUpdate param:{}", JSONObject.toJSONString(Vo));
-        return HttpResult.ok(backTrackService.integrationUpdate(Vo, request));
-    }
 
-    @Log(description = "返回选择设备的所有要素")
-    //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
-    @RequestMapping(name = "返回选择设备的所有要素", value = "/getPartsByDeviceId", method = RequestMethod.GET)
-    public HttpResult getPartsByDeviceId(@RequestParam("deviceId") String deviceId) {
-        log.info("返回选择设备的所有要素 getPartsByDeviceId deviceId:{}",deviceId);
-        return backTrackService.getPartsByDeviceId(deviceId);
-    }
 
 
 }

+ 4 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/mysql/KwsAlarmMapper.java

@@ -3,6 +3,7 @@ package com.sckw.slope.detection.dao.mysql;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.sckw.slope.detection.model.dos.mysql.KwsAlarm;
+import com.sckw.slope.detection.model.vo.AlarmLogThresholdVO;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
 
@@ -49,4 +50,7 @@ public interface KwsAlarmMapper extends BaseMapper<KwsAlarm> {
     List<Map<String, Object>> getProjectAlarmList(@Param("startTime") String startTime, @Param("endTime") String endTime,
                                                   @Param("level") String level, @Param("projectId") String projectId,
                                                   @Param("mountainId") String mountainId, @Param("type") Integer type);
+
+    List<AlarmLogThresholdVO> selectDetailList();
+
 }

+ 2 - 11
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/DevicesMapper.java

@@ -3,23 +3,14 @@ package com.sckw.slope.detection.dao.tdengine;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.sckw.slope.detection.model.dos.tdengine.Devices;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
 import org.springframework.stereotype.Repository;
 
-import java.util.Date;
-
 @DS("td")
 @Mapper
 @Repository
 public interface DevicesMapper {
-    int deleteByPrimaryKey(Date ts);
-
-    int insert(Devices record);
-
-    int insertSelective(Devices record);
-
-    Devices selectByPrimaryKey(Date ts);
 
-    int updateByPrimaryKeySelective(Devices record);
+    Devices selectLastData(@Param("deviceCode") String deviceCode);
 
-    int updateByPrimaryKey(Devices record);
 }

+ 1 - 1
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/ReportTemplateAddDTO.java

@@ -41,7 +41,7 @@ public class ReportTemplateAddDTO implements Serializable {
     /**
      * 生效状态
      */
-    @NotBlank(message = "生效状态不能为空")
+//    @NotBlank(message = "生效状态不能为空")
     private String status;
 
 }

+ 0 - 5
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/DeviceQuery.java

@@ -64,9 +64,4 @@ public class DeviceQuery {
      */
 
     private String status;
-    /**
-     * 设备名称
-     */
-
-    private String deviceName;
 }

+ 6 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/AlarmLogThresholdVO.java

@@ -25,6 +25,12 @@ public class AlarmLogThresholdVO implements Serializable {
      */
     private String title;
 
+
+    /**
+     * 告警标题
+     */
+    private String itemName;
+
     /**
      * 告警触发数值
      */

+ 11 - 5
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/KwsAlarmVO.java

@@ -42,11 +42,6 @@ public class KwsAlarmVO implements Serializable {
      */
     private String content;
 
-    /**
-     * 告警等级
-     */
-    private String level;
-
     /**
      * 1数据告警  2设备告警
      */
@@ -82,11 +77,22 @@ public class KwsAlarmVO implements Serializable {
      */
     private String deviceName;
 
+    /**
+     * 设备名称
+     */
+    private String deviceId;
+
     /**
      * 项目名称
      */
     private String projectName;
 
+    /**
+     * 告警标题
+     */
+    private String title;
+
+
     /**
      * 告警类型
      */

+ 1 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ReportStatementVO.java

@@ -5,7 +5,6 @@ import lombok.Data;
 import lombok.NoArgsConstructor;
 
 import java.io.Serializable;
-import java.math.BigDecimal;
 import java.time.LocalDateTime;
 
 /**
@@ -49,7 +48,7 @@ public class ReportStatementVO implements Serializable {
     /**
      * 文件大小
      */
-    private BigDecimal fileSize;
+    private String fileSize;
 
 
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

+ 13 - 70
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/BackTrackService.java

@@ -11,7 +11,10 @@ import com.sckw.core.exception.BusinessException;
 import com.sckw.core.exception.SystemException;
 import com.sckw.core.model.constant.Global;
 import com.sckw.core.model.constant.NumberConstant;
-import com.sckw.core.model.enums.*;
+import com.sckw.core.model.enums.DeviceEnum;
+import com.sckw.core.model.enums.DictEnum;
+import com.sckw.core.model.enums.DictItemEnum;
+import com.sckw.core.model.enums.MessageLogEnum;
 import com.sckw.core.model.page.PageRes;
 import com.sckw.core.utils.IdWorker;
 import com.sckw.core.utils.StringUtils;
@@ -87,34 +90,29 @@ public class BackTrackService {
         List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
                 .in(KwsDeviceReference::getDeviceId, devicesId)
                 .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
-                .groupBy(KwsDeviceReference::getItem)
         );
         return HttpResult.ok(references);
     }
 
-    public HttpResult getDeviceByParts(String parts,String projectId) {
-        //获取项目中的设备
-        List<DeviceDataDTO> listDevice = deviceMapper.selectDeviceAllNotDeviceRelation(projectId);
-        List<String> devicesId = listDevice.stream().map(DeviceDataDTO::getDeviceId).toList();
+    public HttpResult getDeviceByParts(String parts) {
         //在获取设备的要素
         String[] arr = parts.split(",");
         List<String> list = Arrays.asList(arr);
         List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
-                .in(KwsDeviceReference::getItem, list)
-                .in(KwsDeviceReference::getDeviceId, devicesId)
+                .in(KwsDeviceReference::getId, list)
                 .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
         );
         //获取对应的设备
-        List<Long> devicesIds = references.stream().map(KwsDeviceReference::getDeviceId).toList();
+        List<Long> devicesId = references.stream().map(KwsDeviceReference::getDeviceId).toList();
 
         List<KwsDevice> devices = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
-                .in(KwsDevice::getId, devicesIds)
+                .in(KwsDevice::getId, devicesId)
                 .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
         );
         return HttpResult.ok(devices);
     }
 
-    public HttpResult getDeviceChart(String devicesId,String snCode, String parts, String dateStart,String dateEnd,Integer original) {
+    public HttpResult getDeviceChart(String devicesId,String snCode, String parts, String dateStart,String dateEnd) {
         Map<String, Object> returnData = new HashMap<>();
         //在获取设备的要素
         List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
@@ -141,16 +139,10 @@ public class BackTrackService {
             if(!parts.isEmpty() && !parts.contains(element.getItem())){
                 continue;
             }
-            BigDecimal currentValue =  new BigDecimal("0.00");
-            if(original == 1){
-                currentValue = element.getOriginalValue();//以原始基准参考
-            }else{
-                currentValue = element.getCurrentValue();//以当前基准参考
-            }
-
+            BigDecimal currentValue = element.getCurrentValue();//当前要素的基准值
 
             BigDecimal offsetValue = new BigDecimal("0.00");
-            List<Object> datemap = new ArrayList<>();
+            Map<String, Object> datemap = new HashMap<>();
             Date date = new Date();
             List<SlopeData> selected = slopeDataMapper.selectLineList(snCode, element.getItem(), dateStart, dateEnd);
             if(!Objects.isNull((selected))) {
@@ -171,10 +163,7 @@ public class BackTrackService {
                     }else{//如果是其他
                         offsetValue = subtract;
                     }
-                    Map<String, Object> temp = new HashMap<>();
-                    temp.put("time",key);
-                    temp.put("offset",offsetValue);
-                    datemap.add(temp);
+                    datemap.put(key, offsetValue);
                 }
                 mapList.put(element.getItem(), datemap);
             }
@@ -233,7 +222,7 @@ public class BackTrackService {
     }
 
     /**
-     * 新增集成元素
+     * 新增设备
      *
      * @param vo 请求参数
      * @param request   http流
@@ -264,52 +253,6 @@ public class BackTrackService {
         integration.setDelFlag(zero);
         integration.setMountainId(headerData.getCompanyId());
         integrationMapper.insert(integration);
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", integration.getIntegrationName());
-        logMap.put("type", IntegrationStatusEnum.getDestination(Byte.toUnsignedInt(integration.getStatus())));
-        commonService.insertLog(MessageLogEnum.INTEGRATION_ADD, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
-        return HttpResult.ok();
-    }
-
-    /**
-     * 修改集成分析
-     *
-     * @param vo 请求参数
-     * @param request   http流
-     * @return 返回值
-     */
-    @Transactional
-    public HttpResult integrationUpdate(IntegrationVo vo, HttpServletRequest request) {
-        KwsIntegration has = integrationMapper.selectOne(new LambdaQueryWrapper<KwsIntegration>()
-                .eq(KwsIntegration::getId, vo.getId())
-                .eq(KwsIntegration::getDelFlag, 0)
-        );
-        if (Objects.isNull(has)) {
-            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.INTEGRATION_NOT_EXISTS);
-        }
-        HeaderData headerData = commonService.getHeaderData(request);
-        KwsIntegration integration = new KwsIntegration();
-        BeanUtils.copyProperties(vo, integration);
-        Date now = new Date();
-        integration.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
-        integration.setUpdateTime(now);
-        integrationMapper.updateById(integration);
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", integration.getIntegrationName());
-        logMap.put("type", IntegrationStatusEnum.getDestination(Byte.toUnsignedInt(integration.getStatus())));
-        commonService.insertLog(MessageLogEnum.INTEGRATION_ADD, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok();
     }
-
-    public HttpResult getPartsByDeviceId(String deviceId) {
-        //在获取设备的要素
-        String[] arr = deviceId.split(",");
-        List<String> list = Arrays.asList(arr);
-        List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
-                .in(KwsDeviceReference::getDeviceId, list)
-                .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
-        );
-
-        return HttpResult.ok(references);
-    }
 }

+ 3 - 30
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/DeviceModelService.java

@@ -6,15 +6,11 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
 import com.sckw.core.exception.BusinessException;
-import com.sckw.core.exception.SystemException;
 import com.sckw.core.model.constant.NumberConstant;
 import com.sckw.core.model.enums.DeviceEnum;
 import com.sckw.core.model.enums.DictEnum;
-import com.sckw.core.model.enums.IntegrationStatusEnum;
-import com.sckw.core.model.enums.MessageLogEnum;
 import com.sckw.core.model.page.PageRes;
 import com.sckw.core.utils.StringUtils;
-import com.sckw.core.web.constant.HttpStatus;
 import com.sckw.core.web.response.HttpResult;
 import com.sckw.slope.detection.dao.mysql.KwsDeviceModelMapper;
 import com.sckw.slope.detection.dao.mysql.KwsDeviceModelPartMapper;
@@ -103,10 +99,6 @@ public class DeviceModelService {
         deviceModel.setDelFlag(NumberConstant.ZERO);
         deviceModel.setMountainId(headerData.getCompanyId());
         kwsDeviceModelMapper.insert(deviceModel);
-        //新增log
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", deviceModel.getName());
-        commonService.insertLog(MessageLogEnum.MODEL_ADD, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok();
     }
 
@@ -165,37 +157,18 @@ public class DeviceModelService {
         device.setUpdateBy(Long.parseLong(commonService.getHeaderData(response).getUpdateBy()));
         device.setUpdateTime(now);
         kwsDeviceModelMapper.updateById(device);
-
-        //新增log
-        HeaderData headerData = commonService.getHeaderData(response);
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", device.getName());
-        commonService.insertLog(MessageLogEnum.MODEL_UPDATE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok();
     }
 
     @Transactional
-    public HttpResult dels(String ids, HttpServletRequest response) {
-        KwsDeviceModel has = kwsDeviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
-                .eq(KwsDeviceModel::getId, ids)
-                .eq(KwsDeviceModel::getDelFlag, 0)
-        );
-        if (Objects.isNull(has)) {
-            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.MODEL_NOT_EXISTS);
-        }
-
-        //List<Long> list = StringUtils.splitStrToList(ids, Long.class);
+    public HttpResult dels(String ids) {
+        List<Long> list = StringUtils.splitStrToList(ids, Long.class);
         int update = kwsDeviceModelMapper.update(null, new LambdaUpdateWrapper<KwsDeviceModel>()
-                .eq(KwsDeviceModel::getId, ids)
+                .in(KwsDeviceModel::getId, list)
                 .set(KwsDeviceModel::getDelFlag, NumberConstant.ONE));
         if (update < 1) {
             throw new BusinessException("删除型号异常");
         }
-        //新增log
-        HeaderData headerData = commonService.getHeaderData(response);
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", has.getName());
-        commonService.insertLog(MessageLogEnum.MODEL_DELETE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok("删除型号成功");
     }
 }

+ 64 - 55
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/DeviceService.java

@@ -96,27 +96,14 @@ public class DeviceService {
 
 
     @Transactional
-    public HttpResult dels(String ids, HttpServletRequest response) {
-        KwsDevice device = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>()
-                .eq(KwsDevice::getId, ids));
-        if(Objects.isNull(device)){
-            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.DEVICE_NOT_EXISTS);
-        }
-        //List<Long> list = StringUtils.splitStrToList(ids, Long.class);
+    public HttpResult dels(String ids) {
+        List<Long> list = StringUtils.splitStrToList(ids, Long.class);
         int update = deviceMapper.update(null, new LambdaUpdateWrapper<KwsDevice>()
-                .in(KwsDevice::getId, ids)
+                .in(KwsDevice::getId, list)
                 .set(KwsDevice::getDelFlag, NumberConstant.ONE));
         if (update < 1) {
             throw new BusinessException("删除设备异常");
         }
-        //获取新增设备的型号
-        HeaderData headerData = commonService.getHeaderData(response);
-        KwsDeviceModel model = deviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
-                .eq(KwsDeviceModel::getId, device.getModelId()));
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", device.getName());
-        logMap.put("type", model.getName());
-        commonService.insertLog(MessageLogEnum.DEVICE_DELETE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok("删除设备成功");
     }
 
@@ -149,7 +136,7 @@ public class DeviceService {
             if (!CollectionUtils.isEmpty(alarmData)) {
                 for (int i = 0; i < alarmData.size(); i++) {
                     Map<String, Long> map = alarmData.get(i);
-                    if (map.get("device_id").toString().equals(vo.getId().toString())) {
+                    if (map.get("pid").toString().equals(vo.getId().toString())) {
                         vo.setDataErrorCount(map.get("count"));
                         vo.setDeviceErrorCount(map.get("count"));
                     }
@@ -207,15 +194,6 @@ public class DeviceService {
             deIntergration.setUpdateTime(now);
             deviceIntegrationMapper.insert(deIntergration);
         }
-
-        //新增log
-        //获取新增设备的型号
-        KwsDeviceModel model = deviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
-                .eq(KwsDeviceModel::getId, device.getModelId()));
-        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-        logMap.put("name", device.getName());
-        logMap.put("type", model.getName());
-        commonService.insertLog(MessageLogEnum.DEVICE_ADD, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
         return HttpResult.ok();
     }
 
@@ -290,7 +268,49 @@ public class DeviceService {
 
 
 
+        //vo.setReference(references);
+        //获取td里面的要数数据
+        /*List<Map<String, DeviceOutputValueVO>> mapList = new ArrayList<>();
+        if (!CollectionUtils.isEmpty(references)) {
+            vo.setReference(references);
+            references.forEach(re -> {
+                String snCode = device.getSnCode();
+                String item = re.getItem();
+                Date date = new Date();
+                BigDecimal decimal = new BigDecimal("0.00");
+                String dateStart = DateUtil.getLastWeekDateEndToString(6);
+                String dateEnd = LocalDateTime.now().toString();
+                List<SlopeData> selected = slopeDataMapper.selectLineList(snCode, item, dateStart,dateEnd);
+                List<Map<String, Object>> mapListXy = new ArrayList<>();
+                if (!CollectionUtils.isEmpty(selected)) {
+                    for (int i = 0; i < selected.size(); i++) {
+                        Map<String, Object> map = new HashMap<>();
+                        SlopeData currSlopeData = selected.get(i);
+                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
+                        String key = simpleDateFormat.format(currSlopeData.getTs());
+                        SlopeData lastSlopeData = selected.get(i + 1);
+                        Date localDateTime = currSlopeData.getTs();
+                        long epochMilli1 = 0L;
+                        String val2 = "0";
+                        Date localDateTime1 = lastSlopeData.getTs();
+                        if (lastSlopeData != null) {
+                            epochMilli1 = localDateTime1.getTime();
+                            val2 = lastSlopeData.getVal();
+                        }
+                        long epochMilli = localDateTime.getTime();
+                        epochMilli1 = localDateTime1.getTime();
+                        String val1 = currSlopeData.getVal();
+                        long t = (epochMilli - epochMilli1) / (60 * 60 * 1000);
+                        long val = Long.parseLong(val1) - Long.parseLong(val2);
+                        decimal = BigDecimal.valueOf(val).divide((new BigDecimal(t).multiply(new BigDecimal(t))), 9, BigDecimal.ROUND_HALF_UP);
+                        map.put(key, decimal);
+                        mapListXy.add(map);
+                    }
+                }
+                vo.setMonitor(mapListXy);
+            });
 
+        }*/
         return HttpResult.ok(vo);
     }
 
@@ -360,39 +380,28 @@ public class DeviceService {
                     .set(KwsDeviceIntegration::getDelFlag, NumberConstant.ONE)
                     .set(KwsDeviceIntegration::getUpdateBy,Long.parseLong(headerData.getUpdateBy()) )
                     .set(KwsDeviceIntegration::getUpdateTime, now));
-            //if (update < 1) {
-                //throw new BusinessException("删除设备集成要素异常");
-            //}
+            if (update < 1) {
+                throw new BusinessException("删除设备集成要素异常");
+            }
 
             //新增到数据表kws_device_Integration
             KwsDeviceIntegration deIntergration = new KwsDeviceIntegration();
             String[] temp;//接收分割后的数组
-            if(!deviceAdd.getIntegrationId().isEmpty()){
-                temp = deviceAdd.getIntegrationId().split(Global.COMMA);
-
-                for (int i = 0; i < temp.length; i++) {
-                    long interId = new IdWorker(NumberConstant.ONE).nextId();
-                    deIntergration.setId(interId);
-                    deIntergration.setDeviceId(Long.parseLong(deviceAdd.getId()));
-                    deIntergration.setMountainId(headerData.getCompanyId());
-                    deIntergration.setIntegrationId(Long.parseLong(temp[i]));
-                    deIntergration.setCreateBy(Long.parseLong(headerData.getCreateBy()));
-                    deIntergration.setCreateTime(now);
-                    deIntergration.setStatus(NumberConstant.ZERO);
-                    deIntergration.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
-                    deIntergration.setUpdateTime(now);
-                    deviceIntegrationMapper.insert(deIntergration);
-                }
+            temp = deviceAdd.getIntegrationId().split(Global.COMMA);
+
+            for (int i = 0; i < temp.length; i++) {
+                long interId = new IdWorker(NumberConstant.ONE).nextId();
+                deIntergration.setId(interId);
+                deIntergration.setDeviceId(Long.parseLong(deviceAdd.getId()));
+                deIntergration.setMountainId(headerData.getCompanyId());
+                deIntergration.setIntegrationId(Long.parseLong(temp[i]));
+                deIntergration.setCreateBy(Long.parseLong(headerData.getCreateBy()));
+                deIntergration.setCreateTime(now);
+                deIntergration.setStatus(NumberConstant.ZERO);
+                deIntergration.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
+                deIntergration.setUpdateTime(now);
+                deviceIntegrationMapper.insert(deIntergration);
             }
-
-            //新增log
-            //获取新增设备的型号
-            KwsDeviceModel model = deviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
-                    .eq(KwsDeviceModel::getId, device.getModelId()));
-            Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
-            logMap.put("name", device.getName());
-            logMap.put("type", model.getName());
-            commonService.insertLog(MessageLogEnum.DEVICE_UPDATE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
             return HttpResult.ok();
         }
 
@@ -624,7 +633,7 @@ public class DeviceService {
                 BigDecimal offset = value.subtract(reference.getValue());
                 kwsDeviceReference.setOffset(offset);
                 kwsDeviceReference.setCurrentValue(reference.getValue());
-                kwsDeviceReference.setOriginalValue(reference.getOriginalValue());
+                kwsDeviceReference.setOriginalValue(value);
             }
             kwsDeviceReference.setId(interId);
             kwsDeviceReference.setDeviceId(deviceId);

+ 134 - 37
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java

@@ -67,30 +67,34 @@ public class KwsAlarmService {
 
     public PageRes logSelectAll(AlarmLogThresholdQuery query) {
         PageHelper.startPage(query.getPage(), query.getPageSize());
-        List<KwsAlarm> kwsAlarms = alarmMapper.selectList(new LambdaQueryWrapper<KwsAlarm>()
-                .eq(KwsAlarm::getStatus, 0)
-                .orderByDesc(KwsAlarm::getCreateTime));
-        PageInfo<AlarmLogThresholdVO> info = new PageInfo<AlarmLogThresholdVO>();
-        List<AlarmLogThresholdVO> list = new ArrayList<>();
-        if (CollectionUtils.isEmpty(kwsAlarms)) {
-            return PageRes.build(info, kwsAlarms);
+//        List<KwsAlarm> kwsAlarms = alarmMapper.selectList(new LambdaQueryWrapper<KwsAlarm>()
+//                .eq(KwsAlarm::getStatus, 0)
+//                .orderByDesc(KwsAlarm::getCreateTime));
+        List<AlarmLogThresholdVO> list = alarmMapper.selectDetailList();
+        PageInfo<AlarmLogThresholdVO> info = new PageInfo<AlarmLogThresholdVO>(list);
+//        List<AlarmLogThresholdVO> list = new ArrayList<>();
+        if (CollectionUtils.isEmpty(list)) {
+            return PageRes.build(info, list);
         }
         Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
-        if (!CollectionUtils.isEmpty(kwsAlarms)) {
-            kwsAlarms.forEach(KwsAlarm -> {
-                AlarmLogThresholdVO vo = new AlarmLogThresholdVO();
-                vo.setId(KwsAlarm.getId());
-                vo.setMountainId(KwsAlarm.getMountainId());
-                vo.setTitle(KwsAlarm.getTitle());
-                KwsProject project = projectMapper.selectById(Long.parseLong(KwsAlarm.getProjectId()));
-                vo.setProjectId(KwsAlarm.getProjectId());
+        Map<String, SystemDict> modelPart = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+        if (!CollectionUtils.isEmpty(list)) {
+            for (AlarmLogThresholdVO vo : list) {
+                vo.setId(vo.getId());
+                vo.setMountainId(vo.getMountainId());
+                vo.setItemName(vo.getVal() == null ? null : (modelPart == null ? vo.getVal() :
+                        (modelPart.get(vo.getVal()) == null ? vo.getVal() : modelPart.get(vo.getVal()).getLabel())));
+                vo.setTitle(vo.getTitle());
+                KwsProject project = projectMapper.selectById(Long.parseLong(vo.getProjectId()));
+                vo.setProjectId(vo.getProjectId());
                 vo.setProjectName(project == null ? null : project.getName());
 //                vo.setContent(KwsAlarm.getContent());
-                vo.setLevel(KwsAlarm.getLevel() == null ? null :
-                        (thresholdLevel == null ? String.valueOf(KwsAlarm.getLevel()) : thresholdLevel.get(KwsAlarm.getLevel()).getLabel()));
-                vo.setCreateTime(KwsAlarm.getCreateTime());
-                list.add(vo);
-            });
+                vo.setLevel(vo.getLevel() == null ? null :
+                        (thresholdLevel == null ? String.valueOf(vo.getLevel()) :
+                                (thresholdLevel.get(vo.getLevel()) == null ? vo.getLevel().toString() : thresholdLevel.get(vo.getLevel()).getLabel())));
+                vo.setCreateTime(vo.getCreateTime());
+//                list.add(vo);
+            }
         }
         return PageRes.build(info, list);
     }
@@ -107,7 +111,7 @@ public class KwsAlarmService {
         }
         List<KwsAlarm> list = alarmMapper.selectList(wrapper);
         List<KwsAlarmVO> alarmVOS = new ArrayList<>();
-        PageInfo<KwsAlarm> info = new PageInfo<KwsAlarm>();
+        PageInfo<KwsAlarm> info = new PageInfo<KwsAlarm>(list);
         if (CollectionUtils.isEmpty(list)) {
             return PageRes.build(info, alarmVOS);
         }
@@ -124,14 +128,15 @@ public class KwsAlarmService {
             );
             KwsAlarmVO vo = new KwsAlarmVO();
             BeanUtils.copyProperties(kwsAlarm, vo);
-            vo.setLevel(kwsAlarm.getLevel() == null ? null :
+            vo.setDeviceId(kwsAlarm.getDeviceId().toString());
+            vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                     (thresholdLevel == null ? String.valueOf(kwsAlarm.getLevel()) : thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
             vo.setType(kwsAlarm.getType() == null ? null :
                     (alarmType == null ? String.valueOf(kwsAlarm.getType()) : alarmType.get(String.valueOf(kwsAlarm.getType())).getLabel()));
             vo.setDeviceName(kwsDevice == null ? kwsAlarm.getDeviceId().toString() : kwsDevice.getName());
             vo.setProjectName(project == null ? kwsAlarm.getProjectId() : project.getName());
-            vo.setAlarmLevel(kwsAlarm.getTitle() == null ? null :
-                    (alarmDetailType == null ? kwsAlarm.getTitle() : alarmDetailType.get(kwsAlarm.getTitle()).getLabel()));
+            vo.setTitle(kwsAlarm.getTitle() == null ? null :
+                    (alarmDetailType == null ? kwsAlarm.getTitle() : (alarmDetailType.get(kwsAlarm.getTitle()) == null ? kwsAlarm.getTitle() : alarmDetailType.get(kwsAlarm.getTitle()).getLabel())));
             vo.setStartTime(kwsAlarm.getCreateTime());
             vo.setEndTime(kwsAlarm.getUpdateTime());
             Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>().eq(KwsAlarmDetail::getAlarmId, kwsAlarm.getId()));
@@ -147,7 +152,8 @@ public class KwsAlarmService {
         List<Long> list = com.sckw.core.utils.StringUtils.splitStrToList(ids, Long.class);
         list.forEach(id -> {
             int update = alarmMapper.update(null, new LambdaUpdateWrapper<KwsAlarm>()
-                    .eq(KwsAlarm::getStatus, 1)
+                    .set(KwsAlarm::getStatus, 1)
+                    .eq(KwsAlarm::getId, id)
             );
         });
         return HttpResult.ok("消息已读");
@@ -205,13 +211,14 @@ public class KwsAlarmService {
         PageHelper.startPage(baseList.getPage(), baseList.getPageSize());
         List<KwsAlarmDetail> detailList = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>()
                 .eq(KwsAlarmDetail::getAlarmId, Long.parseLong(id)));
-        PageInfo<ThresholdRecordDetailVO> info = new PageInfo();
-        if (!CollectionUtils.isEmpty(detailList)) {
+        PageInfo<ThresholdRecordDetailVO> info = new PageInfo(detailList);
+        if (CollectionUtils.isEmpty(detailList)) {
             return PageRes.build(info, detailList);
         }
         List<ThresholdRecordDetailVO> list = new ArrayList<>();
         Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
-        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
+//        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
+        Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
         if ("1".equals(kwsAlarm.getType())) {
 
         } else {
@@ -220,15 +227,15 @@ public class KwsAlarmService {
                 KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
                 ThresholdRecordDetailVO vo = new ThresholdRecordDetailVO();
                 vo.setId(detail.getId());
-                vo.setAlarmLevel(kwsAlarm.getType() == null ? null :
-                        (alarmType == null ? String.valueOf(kwsAlarm.getType()) : alarmType.get(String.valueOf(kwsAlarm.getType())).getLabel()));
+                vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
+                        (thresholdLevel == null ? String.valueOf(kwsAlarm.getLevel()) : thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
                 vo.setType(kwsThreshold.getItemName() == null ? null :
                         (dictByDictCode == null ? kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getLabel()));
                 vo.setValue(detail.getVal());
                 vo.setItemName(kwsThreshold.getItemName());
                 vo.setPhone(kwsThreshold.getPhones());
                 KwsDevice kwsDevice = deviceMapper.selectById(kwsThreshold.getDeviceId());
-                vo.setLocation(kwsDevice == null ? null : kwsDevice.getLogicAlt() + " " + kwsDevice.getLogicLat() + "" + kwsDevice.getLogicLng());
+                vo.setLocation(kwsDevice == null ? null : kwsDevice.getLogicAlt() + ";" + kwsDevice.getLogicLat() + ";" + kwsDevice.getLogicLng());
                 vo.setCreateTime(detail.getCreateTime());
                 list.add(vo);
             }
@@ -252,6 +259,11 @@ public class KwsAlarmService {
                 return HttpResult.ok(vo);
             }
             String itemName = kwsThreshold.getItemName();
+            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+            itemName = itemName == null ? null :
+                    (dictByDictCode == null ?
+                            itemName : (dictByDictCode.get(itemName) == null ?
+                            itemName : dictByDictCode.get(itemName).getLabel()));
             Long deviceId = kwsThreshold.getDeviceId();
             KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                     .eq(KwsDeviceReference::getDelFlag, 0)
@@ -419,34 +431,34 @@ public class KwsAlarmService {
             startTime = weekMondayAndSunday.get(0);
             endTime = weekMondayAndSunday.get(1);
             //按照天纬度统计
-            returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+            returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(), type);
         } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
             startTime = startTime + " 00:00:00";
             endTime = endTime + " 23:59:59";
             //统计小时的纬度统计
-            returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+            returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(), type);
         } else {
             if (latitude != null) {
                 if ("1".equals(latitude)) {
                     startTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
                     endTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
-                    returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+                    returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(), type);
                 } else if ("2".equals(latitude)) {
                     List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
                     startTime = weekMondayAndSunday.get(0);
                     endTime = weekMondayAndSunday.get(1);
-                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(), type);
                 } else if ("3".equals(latitude)) {
                     LocalDate firstDayOfMonth = com.sckw.excel.utils.DateUtil.getFirstDayOfMonth();
                     startTime = com.sckw.excel.utils.DateUtil.dateToStr(firstDayOfMonth, "yyyy-MM-dd") /*+ " 00:00:00"*/;
                     LocalDate lastDayOfMonth = com.sckw.excel.utils.DateUtil.getLastDayOfMonth();
                     endTime = com.sckw.excel.utils.DateUtil.dateToStr(lastDayOfMonth, "yyyy-MM-dd")/* + " 23:59:59"*/;
-                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(), type);
                 } else if ("4".equals(latitude)) {
                     //查询全年每个月份
                     startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01";
                     endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31";
-                    returnList = getDataAlarmToYear(startTime, endTime, level, projectId, headerData.getMountainId(),type);
+                    returnList = getDataAlarmToYear(startTime, endTime, level, projectId, headerData.getMountainId(), type);
                 }
             }
         }
@@ -501,4 +513,89 @@ public class KwsAlarmService {
         }
         return HttpResult.ok(returnList);
     }
+
+    public List<ThresholdRecordDetailVO> exportDetail(PublicBaseList baseList, HttpServletRequest request) {
+        String id = baseList.getId();
+        KwsAlarm kwsAlarm = alarmMapper.selectById(id);
+        List<KwsAlarmDetail> detailList = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>()
+                .eq(KwsAlarmDetail::getAlarmId, Long.parseLong(id)));
+        List<ThresholdRecordDetailVO> list = new ArrayList<>();
+        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
+        if ("1".equals(kwsAlarm.getType())) {
+
+        } else {
+            for (KwsAlarmDetail detail : detailList) {
+                Long pid = detail.getPid();
+                KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
+                ThresholdRecordDetailVO vo = new ThresholdRecordDetailVO();
+                vo.setId(detail.getId());
+                vo.setAlarmLevel(kwsAlarm.getType() == null ? null :
+                        (alarmType == null ? String.valueOf(kwsAlarm.getType()) : alarmType.get(String.valueOf(kwsAlarm.getType())).getLabel()));
+                vo.setType(kwsThreshold.getItemName() == null ? null :
+                        (dictByDictCode == null ? kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getLabel()));
+                vo.setValue(detail.getVal());
+                vo.setItemName(kwsThreshold.getItemName());
+                vo.setPhone(kwsThreshold.getPhones());
+                KwsDevice kwsDevice = deviceMapper.selectById(kwsThreshold.getDeviceId());
+                vo.setLocation(kwsDevice == null ? null : kwsDevice.getLogicAlt() + " " + kwsDevice.getLogicLat() + "" + kwsDevice.getLogicLng());
+                vo.setCreateTime(detail.getCreateTime());
+                list.add(vo);
+            }
+        }
+        return list;
+    }
+
+    public List<ThresholdLogDetailVO> exportDetailById(String id, HttpServletRequest request) {
+        List<ThresholdLogDetailVO> exportList = new ArrayList<>();
+        ThresholdLogDetailVO vo = new ThresholdLogDetailVO();
+        KwsAlarmDetail kwsAlarmDetail = alarmDetailMapper.selectById(Long.parseLong(id));
+        if (kwsAlarmDetail == null) {
+            return exportList;
+        }
+        Long alarmId = kwsAlarmDetail.getAlarmId();
+        Long pid = kwsAlarmDetail.getPid();
+        KwsAlarm kwsAlarm = alarmMapper.selectById(alarmId);
+        Integer type = kwsAlarm.getType();
+        if (2 == type) {
+            KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
+            if (kwsThreshold == null) {
+                return exportList;
+            }
+            String itemName = kwsThreshold.getItemName();
+            Long deviceId = kwsThreshold.getDeviceId();
+            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
+                    .eq(KwsDeviceReference::getDelFlag, 0)
+                    .eq(KwsDeviceReference::getDeviceId, deviceId)
+                    .eq(KwsDeviceReference::getItem, itemName)
+            );
+            if (deviceReference != null) {
+                vo.setItemName(itemName);
+                vo.setCurrentValue(deviceReference.getCurrentValue());
+                vo.setCurrentOffset(deviceReference.getOffset());
+                vo.setOriginalValue(deviceReference.getOriginalValue());
+                vo.setOriginalOffset(new BigDecimal("0.00"));
+                KwsDeviceReference lastDeviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
+                        .eq(KwsDeviceReference::getDelFlag, 1)
+                        .eq(KwsDeviceReference::getDeviceId, deviceId)
+                        .eq(KwsDeviceReference::getItem, itemName)
+                        .orderByDesc(KwsDeviceReference::getUpdateTime)
+                        .last("limit 1")
+                );
+                vo.setLastReferenceValue(lastDeviceReference == null ? null : lastDeviceReference.getCurrentValue());
+            }
+        }
+        Map<String, SystemDict> levelDict = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
+        Map<String, SystemDict> typeDict = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
+        Map<String, SystemDict> alarmDetailTypeDict = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
+        vo.setAlarmType(kwsAlarm.getType() == null ? null :
+                (typeDict == null ? String.valueOf(kwsAlarm.getType()) : typeDict.get(String.valueOf(kwsAlarm.getType())).getValue()));
+        vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
+                (levelDict == null ? String.valueOf(kwsAlarm.getLevel()) : levelDict.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
+        vo.setAlarmTitle(kwsAlarm.getTitle() == null ? null :
+                (alarmDetailTypeDict == null ? kwsAlarm.getTitle() : alarmDetailTypeDict.get(kwsAlarm.getTitle()).getLabel()));
+        vo.setAlarmTime(kwsAlarmDetail.getCreateTime());
+        exportList.add(vo);
+        return exportList;
+    }
 }

+ 21 - 15
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/ReportTemplateService.java

@@ -67,24 +67,30 @@ public class ReportTemplateService {
         KwsReportTemplate template = new KwsReportTemplate();
         long id = new IdWorker(NumberConstant.ONE).nextId();
         template.setId(id);
+        template.setProjectId(projectId);
+        template.setMountainId(headerData.getMountainId());
         template.setName(reportTemplateDTO.getName());
         template.setCompanyId(headerData.getCompanyId());
         String type = reportTemplateDTO.getType();
+        String status = reportTemplateDTO.getStatus();
+//        if (Objects.isNull(status)) {
+//            status = ReportEnum.FORBIDDEN.getStatus();
+//        }
         String tabulationTime = "";
-        if (ReportTypeEnum.DAY.getStatus().equals(type)) {
-            tabulationTime = ReportTypeEnum.DAY.getValue();
-        } else if (ReportTypeEnum.WEEK.getStatus().equals(type)) {
-            tabulationTime = ReportTypeEnum.WEEK.getValue();
-        } else if (ReportTypeEnum.MONTH.getStatus().equals(type)) {
-            tabulationTime = ReportTypeEnum.MONTH.getValue();
-        } else {
-            throw new BusinessException("报表类型错误");
-        }
-        template.setTabulationTime(tabulationTime);
+//        if (ReportTypeEnum.DAY.getStatus().equals(type)) {
+//            tabulationTime = ReportTypeEnum.DAY.getValue();
+//        } else if (ReportTypeEnum.WEEK.getStatus().equals(type)) {
+//            tabulationTime = ReportTypeEnum.WEEK.getValue();
+//        } else if (ReportTypeEnum.MONTH.getStatus().equals(type)) {
+//            tabulationTime = ReportTypeEnum.MONTH.getValue();
+//        } else {
+//            throw new BusinessException("报表类型错误");
+//        }
+        template.setTabulationTime(type);
         template.setType(Integer.valueOf(reportTemplateDTO.getType()));
         template.setPartNames(reportTemplateDTO.getPartNames());
         template.setIntergrationNames(reportTemplateDTO.getIntergrationNames());
-        template.setStatus(Integer.valueOf(reportTemplateDTO.getStatus()));
+        template.setStatus(Integer.valueOf(status));
         template.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
         LocalDateTime now = LocalDateTime.now();
         template.setCreateTime(now);
@@ -176,7 +182,7 @@ public class ReportTemplateService {
         logMap.put("templateName", template.getName());
         MessageLogEnum messageLogEnum = MessageLogEnum.FORBIDDEN_REPORT_TEMPLATE;
         if (isEnable.isFlag()) {
-             messageLogEnum = MessageLogEnum.FORBIDDEN_REPORT_TEMPLATE;
+            messageLogEnum = MessageLogEnum.FORBIDDEN_REPORT_TEMPLATE;
         }
         commonService.insertLog(messageLogEnum, headerData, logMap, headerData.getUpdateBy() == null ?
                 null : Long.parseLong(headerData.getUpdateBy()));
@@ -221,10 +227,10 @@ public class ReportTemplateService {
                 .set(KwsReportTemplate::getUpdateBy, (headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy())))
                 .set(KwsReportTemplate::getStatus, NumberConstant.ONE)
         );
-       reportDataMapper.update(null, new LambdaUpdateWrapper<KwsReportData>()
+        reportDataMapper.update(null, new LambdaUpdateWrapper<KwsReportData>()
                 .eq(KwsReportData::getTemplateId, Long.parseLong(id))
-               .set(KwsReportData::getDelFlag,NumberConstant.ONE)
-       );
+                .set(KwsReportData::getDelFlag, NumberConstant.ONE)
+        );
         KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                 .eq(KwsProject::getId, Long.parseLong(template.getProjectId())));
         Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);

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

@@ -1,8 +1,10 @@
 package com.sckw.slope.detection.service;
 
 import com.alibaba.fastjson2.JSONObject;
+import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
 import com.sckw.slope.detection.dao.tdengine.InsTablesMapper;
 import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
+import com.sckw.slope.detection.model.dos.tdengine.Devices;
 import com.sckw.slope.detection.model.dos.tdengine.InsTables;
 import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
 import com.sckw.slope.detection.model.vo.SlopeDataVo;
@@ -18,13 +20,16 @@ import java.util.List;
  * @date 2023-10-25 09:10:15
  */
 @Service
-public class TdengineDemoService {
+public class TdengineService {
     @Autowired
     SlopeDataMapper slopeDataMapper;
 
     @Autowired
     InsTablesMapper insTablesMapper;
 
+    @Autowired
+    private DevicesMapper devicesMapper;
+
     public void tdengineDemo() {
         List<SlopeDataVo> list = slopeDataMapper.selectAll("6", "7");
         System.out.println(JSONObject.toJSONString(list));
@@ -47,6 +52,11 @@ public class TdengineDemoService {
         int insert = slopeDataMapper.insertData(data);
     }
 
+    public Devices selectLastData(String deviceCode) {
+        Devices devices = devicesMapper.selectLastData(deviceCode);
+        return devices;
+    }
+
     public void getTable() {
         String tableName = "devicesv26_7";
         InsTables insTables = insTablesMapper.selectTableIsExit(tableName);

+ 64 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/task/ReportTemplateTaskService.java

@@ -0,0 +1,64 @@
+package com.sckw.slope.detection.service.task;
+
+import cn.hutool.core.date.DateUtil;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.sckw.core.model.enums.ReportTypeEnum;
+import com.sckw.core.utils.StringUtils;
+import com.sckw.slope.detection.dao.mysql.KwsReportTemplateMapper;
+import com.sckw.slope.detection.model.dos.mysql.KwsReportTemplate;
+import jakarta.annotation.Resource;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.stereotype.Component;
+import org.springframework.util.CollectionUtils;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+/**
+ * @author lfdc
+ * @description 报表任务
+ * @date 2023-11-10 11:11:25
+ */
+
+@Slf4j
+@Component
+@EnableScheduling
+public class ReportTemplateTaskService {
+
+    @Resource
+    KwsReportTemplateMapper reportTemplateMapper;
+
+    /**
+     * 报表生成定时任务
+     */
+    //    @Scheduled(cron = "0 0 0 ? * *")
+    public void templateTask() {
+        List<KwsReportTemplate> kwsReportTemplates = reportTemplateMapper.selectList(new LambdaQueryWrapper<KwsReportTemplate>()
+                .eq(KwsReportTemplate::getStatus, 0)
+                .eq(KwsReportTemplate::getDelFlag, 0));
+        if (!CollectionUtils.isEmpty(kwsReportTemplates)) {
+            for (KwsReportTemplate kwsReportTemplate : kwsReportTemplates) {
+                Integer type = kwsReportTemplate.getType();
+                if (ReportTypeEnum.DAY.getCode() == type) {
+                    LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
+                    LocalDateTime dateEnd = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeEnd(localDateTime.toLocalDate());
+                    LocalDateTime dateStart = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeStart(localDateTime.toLocalDate());
+                    String partNames = kwsReportTemplate.getPartNames();
+                    String intergrationNames = kwsReportTemplate.getIntergrationNames();
+                    List<String> stringList = StringUtils.splitStrToList(partNames, String.class);
+
+                }
+                if (ReportTypeEnum.WEEK.getCode() == type) {
+                    if (2 != DateUtil.thisDayOfWeekEnum().getValue()) {
+                        continue;
+                    }
+                }
+                if (ReportTypeEnum.MONTH.getCode() == type) {
+
+                }
+            }
+        }
+
+    }
+}

+ 46 - 5
slope-modules/slope-detection/src/main/resources/bootstrap-lfdc.yml

@@ -1,4 +1,21 @@
 spring:
+  datasource:
+    dynamic:
+      # seata: true
+      primary: master #设置默认的数据源或者数据源组,默认值即为master
+      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
+      datasource:
+        master:
+          url: jdbc:mysql://10.10.10.230:3306/sckw_slope?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
+          username: sckw_dev
+          password: Yy123...
+          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
+        td:
+          url: jdbc:TAOS-RS://10.10.10.221:6041/devicesV2?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8
+          username: root
+          password: taosdata
+          driver-class-name: com.taosdata.jdbc.rs.RestfulDriver
+          pool-name: Data_trans_HikariCP
   cloud:
     nacos:
       discovery:
@@ -28,15 +45,15 @@ mqtt:
     #完成超时时间
     completionTimeout: 3000
     #通过mqtt发送消息验证所需用户名
-    username: sckw
+    username: test
     #通过mqtt发送消息验证所需密码
-    password: sckw123456
+    password: test
     #连接的mqtt地址
-    url: tcp://47.108.205.7:1883
+    url: tcp://10.10.10.225
     #客户端id
-    clientId: mqttx_12411c5cec1
+    clientId: mqttx_12411c5c1ec1
     #推送主题  后面跟着#是监控下面所有的话题
-    topic: slope
+    topic: slope#
     #topic: my-test
     # 会话心跳时间
     keepAliveInterval: 20
@@ -47,6 +64,30 @@ mqtt:
   # 要消费的topic配置
   receive:
     topic: slopePush/slopePull/test/out,test,slope,sharjeck/ai/test/out
+#mqtt:
+#  send:
+#    #完成超时时间
+#    completionTimeout: 3000
+#    #通过mqtt发送消息验证所需用户名
+#    username: sckw
+#    #通过mqtt发送消息验证所需密码
+#    password: sckw123456
+#    #连接的mqtt地址
+#    url: tcp://47.108.205.7:1883
+#    #客户端id
+#    clientId: mqttx_12411c5cec1
+#    #推送主题  后面跟着#是监控下面所有的话题
+#    topic: slope#
+#    #topic: my-test
+#    # 会话心跳时间
+#    keepAliveInterval: 20
+#    # 设置连接超时时间
+#    connectionTimeout: 3000
+#    timeout: 10
+#    keepalive: 20
+#  # 要消费的topic配置
+#  receive:
+#    topic: slopePush/slopePull/test/out,test,slope,sharjeck/ai/test/out
 OkHttpClit:
   url: http://10.10.10.185:9501
 sms:

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

@@ -40,16 +40,16 @@
 
     <select id="selectByDevicesId" parameterType="java.lang.String" resultType="java.util.Map">
         <!--@mbg.generated-->
-        select count(id) as count,device_id,type
+        select count(id) as count,pid,type
         from kws_alarm
         where 1 = 1
         <if test="devicesId != null and devicesId.size() > 0">
-            AND device_id IN
+            AND pid IN
             <foreach collection="devicesId" open="(" close=")" item="item" separator=",">
                 #{item}
             </foreach>
         </if>
-        group by device_id, type
+        group by pid, type
     </select>
 
     <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
@@ -191,39 +191,39 @@
         <!--@mbg.generated-->
         update kws_alarm
         set pid           = #{pid,jdbcType=BIGINT},
-        title         = #{title,jdbcType=VARCHAR},
-        val           = #{val,jdbcType=VARCHAR},
-        content       = #{content,jdbcType=VARCHAR},
-        `level`       = #{level,jdbcType=INTEGER},
-        `type`        = #{type,jdbcType=INTEGER},
-        lat           = #{lat,jdbcType=VARCHAR},
-        lng           = #{lng,jdbcType=VARCHAR},
-        alt           = #{alt,jdbcType=VARCHAR},
-        create_time   = #{createTime,jdbcType=TIMESTAMP},
-        trigger_times = #{triggerTimes,jdbcType=INTEGER},
-        `status`      = #{status,jdbcType=TINYINT}
+            title         = #{title,jdbcType=VARCHAR},
+            val           = #{val,jdbcType=VARCHAR},
+            content       = #{content,jdbcType=VARCHAR},
+            `level`       = #{level,jdbcType=INTEGER},
+            `type`        = #{type,jdbcType=INTEGER},
+            lat           = #{lat,jdbcType=VARCHAR},
+            lng           = #{lng,jdbcType=VARCHAR},
+            alt           = #{alt,jdbcType=VARCHAR},
+            create_time   = #{createTime,jdbcType=TIMESTAMP},
+            trigger_times = #{triggerTimes,jdbcType=INTEGER},
+            `status`      = #{status,jdbcType=TINYINT}
         where id = #{id,jdbcType=BIGINT}
     </update>
 
     <select id="getDataAlarmToDay" resultType="java.util.Map">
         SELECT DATE_FORMAT(h.h, '%Y-%m-%d %H:00:00') AS dateTime, COUNT(t.id) AS number
         FROM (SELECT #{startTime} + INTERVAL n HOUR AS h
-        FROM (
-        SELECT 0 AS n
-        UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
-        UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
-        UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
-        UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20
-        UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23
-        ) hours) h
-        LEFT JOIN
+              FROM (
+                  SELECT 0 AS n
+                  UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
+                  UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
+                  UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
+                  UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL SELECT 20
+                  UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23
+                  ) hours) h
+            LEFT JOIN
         (SELECT a.id,
-        a.create_time,
-        b.project_id  as projectId,
-        b.company_id  as companyId,
-        b.mountain_id as mountainId
-        FROM kws_alarm_detail a
-        LEFT JOIN kws_alarm b ON a.alarm_id = b.id
+                a.create_time,
+                b.project_id  as projectId,
+                b.company_id  as companyId,
+                b.mountain_id as mountainId
+         FROM kws_alarm_detail a
+                  LEFT JOIN kws_alarm b ON a.alarm_id = b.id
         <where>
             <if test="type != null and type != ''">
                 and b.type =#{type}
@@ -238,7 +238,7 @@
         ) t
         ON DATE_FORMAT(t.create_time, '%Y-%m-%d %H') = DATE_FORMAT(h.h, '%Y-%m-%d %H')
         WHERE h.h BETWEEN #{startTime}
-        AND #{endTime}
+                  AND #{endTime}
         GROUP BY dateTime
         ORDER BY dateTime ASC;
     </select>
@@ -246,27 +246,27 @@
     <select id="getDataAlarmToWeek" resultType="java.util.Map">
         SELECT a.date as dateTime, COALESCE(b.number, 0) as number
         from (select date_add(#{startTime}, interval row1 DAY) date
-        from
-        (
-        SELECT @row := @row + 1 as row1 FROM
-        (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union
-        all select 6 union all select 7 union all select 8 union all select 9) t, (select 0 union all select 1 union all
-        select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union
-        all select 8 union all select 9) t2, (select 0 union all select 1 union all select 2 union all select 3 union
-        all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union
-        all select 6 union all select 7 union all select 8 union all select 9) t4, (SELECT @row := -1) r
-        ) se
-        where date_add(#{startTime}
-        , interval row1 DAY) &lt;= #{endTime}) a
-        LEFT JOIN
+              from
+                  (
+                  SELECT @row := @row + 1 as row1 FROM
+                  (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union
+                  all select 6 union all select 7 union all select 8 union all select 9) t, (select 0 union all select 1 union all
+                  select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union
+                  all select 8 union all select 9) t2, (select 0 union all select 1 union all select 2 union all select 3 union
+                  all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union
+                  all select 6 union all select 7 union all select 8 union all select 9) t4, (SELECT @row := -1) r
+                  ) se
+              where date_add(#{startTime}
+                  , interval row1 DAY) &lt;= #{endTime}) a
+            LEFT JOIN
         (SELECT count(b.id)   as                       number,
-        DATE_FORMAT(b.create_time, '%Y-%m-%d') date_time,
-        a.project_id  as                       projectId,
-        a.company_id  as                       companyId,
-        a.mountain_id as                       mountainId
-        FROM kws_alarm a
-        LEFT JOIN
-        kws_alarm_detail b on a.id = b.alarm_id
+                DATE_FORMAT(b.create_time, '%Y-%m-%d') date_time,
+                a.project_id  as                       projectId,
+                a.company_id  as                       companyId,
+                a.mountain_id as                       mountainId
+         FROM kws_alarm a
+                  LEFT JOIN
+              kws_alarm_detail b on a.id = b.alarm_id
         <where>
             <if test="type != null and type != ''">
                 and a.type =#{type}
@@ -286,16 +286,16 @@
 
     <select id="getDataAlarmToYear" resultType="java.util.Map">
         SELECT a.dateTime            AS dateTime,
-        COALESCE(b.number, 0) AS num
+               COALESCE(b.number, 0) AS num
         FROM (SELECT DATE_FORMAT(DATE_ADD(#{startTime}, INTERVAL ROW1 MONTH ), '%Y-%m') dateTime
-        FROM (SELECT @ROW := @ROW + 1 AS row1
-        FROM
-        (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4, ( SELECT @ROW := - 1 ) r) se
-        WHERE date_add(#{startTime}, INTERVAL row1 MONTH ) &lt;= #{endTime}) a
-        LEFT JOIN (SELECT count(b.id) AS                      number,
-        DATE_FORMAT(b.create_time, '%Y-%m') dateTime
-        FROM kws_alarm a
-        LEFT JOIN kws_alarm_detail b ON a.id = b.alarm_id
+              FROM (SELECT @ROW := @ROW + 1 AS row1
+                    FROM
+                        (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3, (select 0 union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4, ( SELECT @ROW := - 1 ) r) se
+              WHERE date_add(#{startTime}, INTERVAL row1 MONTH ) &lt;= #{endTime}) a
+            LEFT JOIN (SELECT count(b.id) AS                      number,
+                              DATE_FORMAT(b.create_time, '%Y-%m') dateTime
+                       FROM kws_alarm a
+                                LEFT JOIN kws_alarm_detail b ON a.id = b.alarm_id
         <where>
             <if test="type != null and type != ''">
                 and a.type =#{type}
@@ -315,15 +315,15 @@
 
     <select id="getProjectAlarmList" resultType="java.util.Map">
         SELECT
-        project_id as projectId,COUNT(DISTINCT a.id) as alarmTotal
+            project_id as projectId,COUNT(DISTINCT a.id) as alarmTotal
         FROM
-        kws_alarm a
-        LEFT JOIN kws_alarm_detail b ON a.id = b.alarm_id
-        <where>
-            <if test="type != null and type != ''">
-                and a.type =#{type}
-            </if>
-        </where>
+            kws_alarm a
+                LEFT JOIN kws_alarm_detail b ON a.id = b.alarm_id
+            <where>
+               <if test="type != null and type != ''">
+                   and a.type =#{type}
+               </if>
+            </where>
         GROUP BY a.project_id
     </select>
 

+ 1 - 0
slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsProjectMapper.xml

@@ -134,6 +134,7 @@
         <if test="deviceQuery.name != null and deviceQuery.name != ''">
             and c.name like concat('%', #{deviceQuery.name}, '%')
         </if>
+        order by b.create_time desc
     </select>
 
     <select id="selectDeviceNotBindList" resultType="com.sckw.slope.detection.model.vo.ProjectDeviceVO">

+ 2 - 1
slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsReportDataMapper.xml

@@ -299,6 +299,7 @@
       SELECT b.`name`       AS reportName,
              b.type         AS reportType,
              a.project_name AS projectName,
+             a.project_id AS projectId,
              a.file_size    AS fileSize,
              a.create_time  AS createTime,
              a.id           as id
@@ -314,7 +315,7 @@
           and b.name like concat('%', #{query.reportName}
               , '%')
       </if>
-      <if test="query.reportName != null and query.reportName != ''">
+      <if test="query.reportType != null and query.reportType != ''">
           and b.type = #{query.reportType}
       </if>
       <if test="query.startTime != null and query.startTime != ''">

+ 5 - 4
slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsReportTemplateMapper.xml

@@ -181,10 +181,11 @@
     <select id="selectListByReportNameAndProjectIdAndCompany"
             resultType="com.sckw.slope.detection.model.vo.ReportStatementVO">
         SELECT STATUS,
-               `name`      AS reportName,
-               type        AS reportType,
-               project_id  AS projectId,
-               create_time AS createTime
+               `name`          AS reportName,
+               type            AS reportType,
+               project_id      AS projectId,
+               tabulation_time AS tabulationTime,
+               create_time     AS createTime
         FROM kws_report_template
         WHERE del_flag = 0
         <if test="query.projectId != null and query.projectId != ''">

+ 29 - 116
slope-modules/slope-detection/src/main/resources/mapper/tdengine/DevicesMapper.xml

@@ -1,126 +1,39 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.sckw.slope.detection.dao.tdengine.DevicesMapper">
-  <resultMap id="BaseResultMap" type="com.sckw.slope.detection.model.dos.tdengine.Devices">
-    <!--@mbg.generated-->
-    <!--@Table devices-->
-    <id column="ts" jdbcType="TIMESTAMP" property="ts" />
-    <result column="tslver_id" jdbcType="INTEGER" property="tslverId" />
-    <result column="line" jdbcType="VARCHAR" property="line" />
-    <result column="val" jdbcType="VARCHAR" property="val" />
-    <result column="msg_id" jdbcType="VARCHAR" property="msgId" />
-    <result column="raw_ts" jdbcType="TIMESTAMP" property="rawTs" />
-    <result column="guid" jdbcType="VARCHAR" property="guid" />
-  </resultMap>
-  <sql id="Base_Column_List">
-    <!--@mbg.generated-->
-    ts, tslver_id, line, val, msg_id, raw_ts, guid
-  </sql>
-  <select id="selectByPrimaryKey" parameterType="java.util.Date" resultMap="BaseResultMap">
-    <!--@mbg.generated-->
-    select 
-    <include refid="Base_Column_List" />
-    from devicesv2.devices
-    where ts = #{ts,jdbcType=TIMESTAMP}
-  </select>
-  <delete id="deleteByPrimaryKey" parameterType="java.util.Date">
-    <!--@mbg.generated-->
-    delete from devicesv2.devices
-    where ts = #{ts,jdbcType=TIMESTAMP}
-  </delete>
-  <insert id="insert" parameterType="com.sckw.slope.detection.model.dos.tdengine.Devices">
-    <!--@mbg.generated-->
-    insert into devicesv2.devices (ts, tslver_id, line,
-      val, msg_id, raw_ts, 
-      guid)
-    values (#{ts,jdbcType=TIMESTAMP}, #{tslverId,jdbcType=INTEGER}, #{line,jdbcType=VARCHAR}, 
-      #{val,jdbcType=VARCHAR}, #{msgId,jdbcType=VARCHAR}, #{rawTs,jdbcType=TIMESTAMP}, 
-      #{guid,jdbcType=VARCHAR})
-  </insert>
-  <insert id="insertSelective" parameterType="com.sckw.slope.detection.model.dos.tdengine.Devices">
-    <!--@mbg.generated-->
-    insert into devicesv2.devices
-    <trim prefix="(" suffix=")" suffixOverrides=",">
-      <if test="ts != null">
+    <resultMap id="BaseResultMap" type="com.sckw.slope.detection.model.dos.tdengine.Devices">
+        <!--@mbg.generated-->
+        <!--@Table devices-->
+        <id column="ts" jdbcType="TIMESTAMP" property="ts"/>
+        <result column="tslver_id" jdbcType="INTEGER" property="tslverId"/>
+        <result column="line" jdbcType="VARCHAR" property="line"/>
+        <result column="val" jdbcType="VARCHAR" property="val"/>
+        <result column="msg_id" jdbcType="VARCHAR" property="msgId"/>
+        <result column="raw_ts" jdbcType="TIMESTAMP" property="rawTs"/>
+        <result column="guid" jdbcType="VARCHAR" property="guid"/>
+    </resultMap>
+    <sql id="Base_Column_List">
+        <!--@mbg.generated-->
         ts,
-      </if>
-      <if test="tslverId != null">
         tslver_id,
-      </if>
-      <if test="line != null">
         line,
-      </if>
-      <if test="val != null">
         val,
-      </if>
-      <if test="msgId != null">
         msg_id,
-      </if>
-      <if test="rawTs != null">
         raw_ts,
-      </if>
-      <if test="guid != null">
-        guid,
-      </if>
-    </trim>
-    <trim prefix="values (" suffix=")" suffixOverrides=",">
-      <if test="ts != null">
-        #{ts,jdbcType=TIMESTAMP},
-      </if>
-      <if test="tslverId != null">
-        #{tslverId,jdbcType=INTEGER},
-      </if>
-      <if test="line != null">
-        #{line,jdbcType=VARCHAR},
-      </if>
-      <if test="val != null">
-        #{val,jdbcType=VARCHAR},
-      </if>
-      <if test="msgId != null">
-        #{msgId,jdbcType=VARCHAR},
-      </if>
-      <if test="rawTs != null">
-        #{rawTs,jdbcType=TIMESTAMP},
-      </if>
-      <if test="guid != null">
-        #{guid,jdbcType=VARCHAR},
-      </if>
-    </trim>
-  </insert>
-  <update id="updateByPrimaryKeySelective" parameterType="com.sckw.slope.detection.model.dos.tdengine.Devices">
-    <!--@mbg.generated-->
-    update devicesv2.devices
-    <set>
-      <if test="tslverId != null">
-        tslver_id = #{tslverId,jdbcType=INTEGER},
-      </if>
-      <if test="line != null">
-        line = #{line,jdbcType=VARCHAR},
-      </if>
-      <if test="val != null">
-        val = #{val,jdbcType=VARCHAR},
-      </if>
-      <if test="msgId != null">
-        msg_id = #{msgId,jdbcType=VARCHAR},
-      </if>
-      <if test="rawTs != null">
-        raw_ts = #{rawTs,jdbcType=TIMESTAMP},
-      </if>
-      <if test="guid != null">
-        guid = #{guid,jdbcType=VARCHAR},
-      </if>
-    </set>
-    where ts = #{ts,jdbcType=TIMESTAMP}
-  </update>
-  <update id="updateByPrimaryKey" parameterType="com.sckw.slope.detection.model.dos.tdengine.Devices">
-    <!--@mbg.generated-->
-    update devicesv2.devices
-    set tslver_id = #{tslverId,jdbcType=INTEGER},
-      line = #{line,jdbcType=VARCHAR},
-      val = #{val,jdbcType=VARCHAR},
-      msg_id = #{msgId,jdbcType=VARCHAR},
-      raw_ts = #{rawTs,jdbcType=TIMESTAMP},
-      guid = #{guid,jdbcType=VARCHAR}
-    where ts = #{ts,jdbcType=TIMESTAMP}
-  </update>
+        guid
+    </sql>
+    <sql id="Base_List">
+        ts,
+        raw_ts    as rawId,
+        tslver_id as tslverId,
+        line,
+        val
+    </sql>
+    <select id="selectLastData" resultType="com.sckw.slope.detection.model.dos.tdengine.Devices">
+        SELECT
+        <include refid="Base_List">
+        </include>
+        FROM devicesv2.device_${deviceCode}
+        order by ts desc limit 1
+    </select>
 </mapper>

+ 1 - 1
slope-modules/slope-detection/src/main/resources/mapper/tdengine/SlopeDataMapper.xml

@@ -123,7 +123,7 @@
         SELECT
         <include refid="Base_List">
         </include>
-        FROM devicesv2.device_#{deviceCode}
+        FROM devicesv2.device_${deviceCode}
         order by ts desc limit 1
     </select>
 </mapper>