Przeglądaj źródła

1.告警阈值获取并推送短信
2.边坡日志数据展示
3.数据大屏-数据大厅数据展示

lengfaqiang 2 lat temu
rodzic
commit
c9e586f0df
43 zmienionych plików z 2380 dodań i 543 usunięć
  1. 7 0
      slope-common/slope-common-core/pom.xml
  2. 33 0
      slope-common/slope-common-core/src/main/java/com/sckw/core/utils/StringUtils.java
  3. 189 0
      slope-common/slope-common-excel/src/main/java/com/sckw/excel/utils/DateUtil.java
  4. 39 39
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqSendMessageGateWay.java
  5. 207 206
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqttConfig.java
  6. 20 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/AbstractHandler.java
  7. 28 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/HandlerFactory.java
  8. 0 18
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttCallbackHandler.java
  9. 444 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttDeviceCallbackHandler.java
  10. 42 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttTdengineCallbackHandler.java
  11. 36 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/mqApi/MqttApiHandler.java
  12. 23 4
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/AlarmController.java
  13. 10 1
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/ProjectController.java
  14. 22 3
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/mysql/KwsAlarmMapper.java
  15. 25 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/DevicesMapper.java
  16. 25 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/OriginalMapper.java
  17. 3 1
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/SlopeDataMapper.java
  18. 1 25
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/mysql/KwsAlarmDetail.java
  19. 1 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/mysql/KwsDeviceReference.java
  20. 32 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/tdengine/Devices.java
  21. 25 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/tdengine/Original.java
  22. 22 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/DevicesAlarm.java
  23. 36 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/DevicesItem.java
  24. 37 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/AlarmStatisticsQuery.java
  25. 43 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/SmsMessageParam.java
  26. 42 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/DeviceListBean.java
  27. 34 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ProjectDevicesListVO.java
  28. 60 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ThresholdLogDetailVO.java
  29. 30 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/CommonService.java
  30. 4 4
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/DeviceService.java
  31. 184 5
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java
  32. 57 6
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/ProjectService.java
  33. 2 2
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/TdengineDemoService.java
  34. 72 3
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/api/DetectionApiService.java
  35. 4 0
      slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/task/ReportTemplateTaskService.java
  36. 4 1
      slope-modules/slope-detection/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  37. 5 1
      slope-modules/slope-detection/src/main/resources/bootstrap-lfdc.yml
  38. 2 12
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsAlarmDetailMapper.xml
  39. 305 200
      slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsAlarmMapper.xml
  40. 0 0
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/DeviceMapperBak.xml
  41. 126 0
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/DevicesMapper.xml
  42. 80 0
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/OriginalMapper.xml
  43. 19 10
      slope-modules/slope-detection/src/main/resources/mapper/tdengine/SlopeDataMapper.xml

+ 7 - 0
slope-common/slope-common-core/pom.xml

@@ -50,6 +50,13 @@
             <version>${oss.version}</version>
         </dependency>
 
+        <dependency>
+            <groupId>commons-beanutils</groupId>
+            <artifactId>commons-beanutils</artifactId>
+            <version>1.9.4</version>
+            <scope>compile</scope>
+        </dependency>
+
 
         <dependency>
             <groupId>commons-io</groupId>

+ 33 - 0
slope-common/slope-common-core/src/main/java/com/sckw/core/utils/StringUtils.java

@@ -4,6 +4,7 @@ import com.sckw.core.exception.BusinessException;
 import com.sckw.core.model.constant.Global;
 import com.sckw.core.model.enums.MessageLogEnum;
 
+import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
@@ -891,6 +892,38 @@ public class StringUtils {
         return result;
     }
 
+    /**
+     * 实体类转map
+     * @param t
+     * @return
+     * @param <T>
+     */
+    public static <T> Map<String,Object> entityToMap(T t){
+        Map<String,Object> map = new HashMap<>();
+        //动态获取该类
+        Class clazz = (Class) t.getClass();
+        //取所有属性
+        Field[] fields = clazz.getDeclaredFields();
+        //将fields数组转化为集合使用stream流转换为map
+        map = Arrays.stream(fields).collect(Collectors.toMap(Field::getName, field -> {
+            Object resultObj = null;
+            //屏蔽java语言的访问检查  打开可以访问私有属性的权限
+            field.setAccessible(true);
+            try {
+                resultObj = field.get(t);
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+            } catch (IllegalAccessException e) {
+                e.printStackTrace();
+            }
+            //Optional 类(java.util.Optional) 是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null,表示这个值不存在。原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
+            //是 Java 8 中 Optional 类的一个方法,它的作用是将一个可能为 null 的对象转换为 Optional 对象,并在该对象不为 null 时执行一个函数,否则返回一个默认值。
+            //因为Collectors.toMap(key,value)中的value值不能为空, 所以这里使用Optional.ofNullable().orElse(), 为空则为""
+            return Optional.ofNullable(resultObj).orElse("");
+        }, (k1, k2) -> k2));
+        return map;
+    }
+
     public static void main(String[] args) {
         Map<String, Object> map = new HashMap<>();
         map.put("projectName","项目名称");

+ 189 - 0
slope-common/slope-common-excel/src/main/java/com/sckw/excel/utils/DateUtil.java

@@ -94,10 +94,23 @@ public class DateUtil {
     }
 
 
+    /**
+     * LocalDate 转换成 yyyy-MM-dd
+     *
+     * @param date LocalDate
+     * @return yyyy-MM-dd
+     */
     public static String dateToStr(LocalDate date) {
         return dateToStr(date, "yyyy-MM-dd");
     }
 
+    /**
+     * LocalDate 转换成 pattern 指定格式
+     *
+     * @param date    LocalDate
+     * @param pattern 指定格式
+     * @return
+     */
     public static String dateToStr(LocalDate date, String pattern) {
         String dateStr = date.format(DateTimeFormatter.ofPattern(pattern));
         return dateStr;
@@ -116,6 +129,176 @@ public class DateUtil {
         return LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
     }
 
+    /**
+     * 获取本周的每一天
+     */
+    public static List<LocalDate> getWeekDay() {
+        List<LocalDate> list = new ArrayList<>();
+        // 获取当前日期
+        LocalDate currentDate = LocalDate.now();
+        // 获取本周的周一
+        LocalDate monday = currentDate.with(DayOfWeek.MONDAY);
+
+        // 获取本周的周日
+        LocalDate sunday = currentDate.with(DayOfWeek.SUNDAY);
+
+        // 循环获取本周的所有日期
+        LocalDate date = monday;
+        while (!date.isAfter(sunday)) {
+            System.out.println(date);
+            list.add(date);
+            date = date.plusDays(1);
+        }
+        return list;
+    }
+
+
+    /**
+     * 获取本周的周一和周日
+     * @return yyyy-MM-dd 格式
+     */
+    public static List<String> getWeekMondayAndSunday() {
+        List<String> list = new ArrayList<>();
+        // 获取当前日期
+        LocalDate currentDate = LocalDate.now();
+        // 获取本周的周一
+        LocalDate monday = currentDate.with(DayOfWeek.MONDAY);
+        list.add(cn.hutool.core.date.DateUtil.format(monday.atStartOfDay(), DEF_DATE_FORMAT));
+        // 获取本周的周日
+        LocalDate sunday = currentDate.with(DayOfWeek.SUNDAY);
+        LocalDateTime localDateTime = DateUtil.localDateToLocalDateTimeEnd(sunday);
+        list.add(cn.hutool.core.date.DateUtil.format(localDateTime, DEF_DATE_FORMAT));
+        return list;
+    }
+
+    /**
+     * 获取当前月第一天
+     *
+     * @param month
+     * @return
+     */
+    public static String getFirstDayOfMonth(int month) {
+        Calendar calendar = Calendar.getInstance();
+        // 设置月份
+        calendar.set(Calendar.MONTH, month - 1);
+        // 获取某月最小天数
+        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
+        // 设置日历中月份的最小天数
+        calendar.set(Calendar.DAY_OF_MONTH, firstDay);
+        // 格式化日期
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        String firstDayDate = sdf.format(calendar.getTime());
+        return firstDayDate;
+
+    }
+
+    /**
+     * 获取当前月最后一天
+     *
+     * @param month
+     * @return
+     */
+    public static String getLastDayOfMonth(int month) {
+        Calendar calendar = Calendar.getInstance();
+        // 设置月份
+        calendar.set(Calendar.MONTH, month - 1);
+        // 获取某月最大天数
+        int lastDay = 0;
+        //2月的平年瑞年天数
+        if (month == 2) {
+
+            lastDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);
+        } else {
+            lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
+        }
+        // 设置日历中月份的最大天数
+        calendar.set(Calendar.DAY_OF_MONTH, lastDay);
+        // 格式化日期
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        String lastDayDate = sdf.format(calendar.getTime());
+        return lastDayDate;
+    }
+
+    /**
+     * 获取当前月份的第一天
+     *
+     * @return
+     */
+    public static LocalDate getFirstDayOfMonth() {
+        // 获取当前日期
+        LocalDate currentDate = LocalDate.now();
+        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
+//        System.out.println("当前月份的第一天:" + firstDayOfMonth);
+        return firstDayOfMonth;
+    }
+
+    /**
+     * 当前月份的最后一天
+     *
+     * @return
+     */
+    public static LocalDate getLastDayOfMonth() {
+        LocalDate currentDate = LocalDate.now();
+        YearMonth currentYearMonth = YearMonth.from(currentDate);
+        LocalDate lastDayOfMonth = currentYearMonth.atEndOfMonth();
+//        System.out.println("当前月份的最后一天:" + lastDayOfMonth);
+        return lastDayOfMonth;
+    }
+
+    /**
+     * 获取今年的每一个月份
+     *
+     * @return
+     */
+    public static List<String> getYear() {
+        List<String> list = new ArrayList<>();
+        // 获取当前年份
+        int currentYear = YearMonth.now().getYear();
+        // 循环输出今年的每个月份的时间
+        for (int month = 1; month <= 12; month++) {
+            // 构造表示当前年份和月份的 YearMonth 对象
+            YearMonth yearMonth = YearMonth.of(currentYear, month);
+            // 输出格式化后的日期字符串,你可以根据需要调整日期格式
+            String formattedDate = yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
+            list.add(formattedDate);
+        }
+        return list;
+    }
+
+
+    /**
+     * 获取今年的第一个月份
+     *
+     * @return
+     */
+    public static String getYearFirstMonth() {
+        // 获取当前年份
+        int currentYear = YearMonth.now().getYear();
+        // 获取今年的第一个月份
+        YearMonth firstMonth = YearMonth.of(currentYear, 1);
+        // 输出格式化后的日期字符串,你可以根据需要调整日期格式
+        String formattedFirstMonth = firstMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
+//        System.out.println("今年的第一个月份:" + formattedFirstMonth);
+        return formattedFirstMonth;
+    }
+
+
+    /**
+     * 获取今年的最后一个月份
+     *
+     * @return
+     */
+    public static String getYearLastMonth() {
+        // 获取当前年份
+        int currentYear = YearMonth.now().getYear();
+        // 获取今年的最后一个月份
+        YearMonth lastMonth = YearMonth.of(currentYear, 12);
+        // 输出格式化后的日期字符串,你可以根据需要调整日期格式
+        String formattedLastMonth = lastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
+//        System.out.println("今年的最后一个月份:" + formattedLastMonth);
+        return formattedLastMonth;
+    }
+
     /**
      * yyyy-MM-dd 转换成 LocalDate
      *
@@ -538,6 +721,12 @@ public class DateUtil {
     }
 
     public static void main(String[] args) throws ParseException {
+        String yearLastMonth = getYearLastMonth();
+
+        LocalDate firstDayOfMonth = getFirstDayOfMonth();
+        LocalDate lastDayOfMonth = getLastDayOfMonth();
+        List<LocalDate> weekDay = getWeekDay();
+        List<String> weekDay1 = getWeekMondayAndSunday();
         List<Date> list = new ArrayList<>();
         List<Date> dateTimeSS = getDateTimeDayToDate(LocalDateTime.now(), 7, list);
         System.out.println(dateTimeSS);

+ 39 - 39
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqSendMessageGateWay.java

@@ -1,39 +1,39 @@
-//package com.sckw.slope.detection.common.config;
-//
-//import org.springframework.integration.annotation.MessagingGateway;
-//import org.springframework.integration.mqtt.support.MqttHeaders;
-//import org.springframework.messaging.handler.annotation.Header;
-//import org.springframework.stereotype.Component;
-//
-///**
-// * @author lfdc
-// * @description
-// * @date 2023-10-26 11:10:01
-// */
-//@Component
-//@MessagingGateway(defaultRequestChannel = MqttConfig.CHANNEL_NAME_OUT)
-//public interface MqSendMessageGateWay {
-//    /**
-//     * 默认的消息机制
-//     *
-//     * @param data
-//     */
-//    void sendToMqtt(String data);
-//
-//    /**
-//     * 发送消息 向mqtt指定topic发送消息
-//     *
-//     * @param topic
-//     * @param payload
-//     */
-//    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload);
-//
-//    /**
-//     * 发送消息 向mqtt指定topic发送消息
-//     *
-//     * @param topic 主题
-//     * @param qos   机制
-//     * @param payload   消息
-//     */
-//    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
-//}
+package com.sckw.slope.detection.common.config;
+
+import org.springframework.integration.annotation.MessagingGateway;
+import org.springframework.integration.mqtt.support.MqttHeaders;
+import org.springframework.messaging.handler.annotation.Header;
+import org.springframework.stereotype.Component;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-10-26 11:10:01
+ */
+@Component
+@MessagingGateway(defaultRequestChannel = MqttConfig.CHANNEL_NAME_OUT)
+public interface MqSendMessageGateWay {
+    /**
+     * 默认的消息机制
+     *
+     * @param data
+     */
+    void sendToMqtt(String data);
+
+    /**
+     * 发送消息 向mqtt指定topic发送消息
+     *
+     * @param topic
+     * @param payload
+     */
+    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload);
+
+    /**
+     * 发送消息 向mqtt指定topic发送消息
+     *
+     * @param topic 主题
+     * @param qos   机制
+     * @param payload   消息
+     */
+    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
+}

+ 207 - 206
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/MqttConfig.java

@@ -1,207 +1,208 @@
-//package com.sckw.slope.detection.common.config;
-//
-//import com.sckw.slope.detection.consumer.MqttCallbackHandler;
-//import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.context.annotation.Bean;
-//import org.springframework.context.annotation.Configuration;
-//import org.springframework.integration.annotation.ServiceActivator;
-//import org.springframework.integration.channel.DirectChannel;
-//import org.springframework.integration.core.MessageProducer;
-//import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
-//import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
-//import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
-//import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
-//import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
-//import org.springframework.messaging.MessageChannel;
-//import org.springframework.messaging.MessageHandler;
-//
-///**
-// * @author lfdc
-// * @description MQTT配置,生产者
-// * @date 2023-10-26 10:10:59
-// */
-//@Configuration
-//public class MqttConfig {
-//
-//    private static final byte[] WILL_DATA;
-//
-//    static {
-//        WILL_DATA = "offline".getBytes();
-//    }
-//
-//    /**
-//     * mqtt订阅者使用信道名称
-//     */
-//    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
-//    /**
-//     * mqtt发布者信道名称
-//     */
-//    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
-//    /**
-//     * mqtt发送者用户名
-//     */
-//    @Value("${mqtt.send.username}")
-//    private String username;
-//
-//    /**
-//     * mqtt发送者密码
-//     */
-//    @Value("${mqtt.send.password}")
-//    private String password;
-//
-//    /**
-//     * mqtt发送者url
-//     */
-//    @Value("${mqtt.send.url}")
-//    private String hostUrl;
-//    /**
-//     * mqtt发送者客户端id
-//     */
-//    @Value("${mqtt.send.clientId}")
-//    private String clientId;
-//    /**
-//     * mqtt发送者主题
-//     */
-//    @Value("${mqtt.send.topic}")
-//    private String msgTopic;
-//
-//    /**
-//     * mqtt发送者主题
-//     */
-//    @Value("${mqtt.receive.topic}")
-//    private String msgReceiveTopic;
-//
-//    /**
-//     * mqtt发送者超时时间
-//     */
-//    @Value("${mqtt.send.completionTimeout}")
-//    private int completionTimeout;
-//
-//    @Value("${mqtt.send.keepAliveInterval}")
-//    private int keepAliveInterval;
-//
-//    @Value("${mqtt.send.connectionTimeout}")
-//    private int connectionTimeout;
-//
-//    @Autowired
-//    private MqttCallbackHandler mqttCallbackHandler;
-//
-//
-//    /**
-//     * 新建MqttConnectionOptionsBean  MQTT连接器选项
-//     * @return
-//     */
-//    @Bean
-//    public MqttConnectOptions getSenderMqttConnectOptions() {
-//        MqttConnectOptions options = new MqttConnectOptions();
-//        // 设置连接的用户名
-//        if (!username.trim().equals("")) {
-//            //将用户名去掉前后空格
-//            options.setUserName(username);
-//        }
-//        // 设置连接的密码
-//        options.setPassword(password.toCharArray());
-//        // 转化连接的url地址
-//        String[] uris = {hostUrl};
-//        // 设置连接的地址
-//        options.setServerURIs(uris);
-//        // 设置超时时间 单位为秒
-//        options.setConnectionTimeout(completionTimeout);
-//        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
-//        // 但这个方法并没有重连的机制
-//        options.setKeepAliveInterval(keepAliveInterval);
-//        // 设置“遗嘱”消息的话题,若客户端与服务器之间的连接意外中断,服务器将发布客户端的“遗嘱”消息。
-//        //设置超时时间
-//        options.setConnectionTimeout(connectionTimeout);
-//        options.setCleanSession(true);
-//        options.setAutomaticReconnect(true);
-//        return options;
-//    }
-//
-//    /**
-//     * 创建MqttPathClientFactoryBean
-//     */
-//    @Bean
-//    public MqttPahoClientFactory senderMqttClientFactory() {
-//        //创建mqtt客户端工厂
-//        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
-//        //设置mqtt的连接设置
-//        factory.setConnectionOptions(getSenderMqttConnectOptions());
-//        return factory;
-//    }
-//
-//    /**
-//     * 发布者-MQTT信息通道(生产者)
-//     */
-//    @Bean(name = CHANNEL_NAME_OUT)
-//    public MessageChannel mqttOutboundChannel() {
-//        return new DirectChannel();
-//    }
-//
-//
-//    /**
-//     * 发布者-MQTT消息处理器(生产者)  将channel绑定到MqttClientFactory上
-//     *
-//     * @return {@link org.springframework.messaging.MessageHandler}
-//     */
-//    @Bean
-//    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
-//    public MessageHandler mqttOutbound() {
-//        //创建消息处理器
-//        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
-//                clientId + "_pub",
-//                senderMqttClientFactory());
-//        //设置消息处理类型为异步
-//        messageHandler.setAsync(true);
-//        //设置消息的默认主题
-//        messageHandler.setDefaultTopic(msgTopic);
-//        messageHandler.setDefaultRetained(false);
-//        //1.重新连接MQTT服务时,不需要接收该主题最新消息,设置retained为false;
-//        //2.重新连接MQTT服务时,需要接收该主题最新消息,设置retained为true;
-//        return messageHandler;
-//    }
-//
-//
-//    /************                             消费者,订阅者的消费信息                               *****/
-//
-//    /**
-//     * MQTT信息通道(消费者)
-//     */
-//    @Bean(name = CHANNEL_NAME_IN)
-//    public MessageChannel mqttInboundChannel() {
-//        return new DirectChannel();
-//    }
-//
-//    /**
-//     * MQTT消息订阅绑定(消费者)
-//     */
-//    @Bean
-//    public MessageProducer inbound() {
-////        System.out.println("topics:" + msgTopic);
-//        // 可以同时消费(订阅)多个Topic
-//        MqttPahoMessageDrivenChannelAdapter adapter =
-//                new MqttPahoMessageDrivenChannelAdapter(
-//                        clientId + "_sub", senderMqttClientFactory(), msgReceiveTopic.split(","));
-//        adapter.setCompletionTimeout(5000);
-//        adapter.setConverter(new DefaultPahoMessageConverter());
-//        adapter.setQos(0);
-//        // 设置订阅通道
-//        adapter.setOutputChannel(mqttInboundChannel());
-//        return adapter;
-//    }
-//
-//    /**
-//     * MQTT消息处理器(消费者)
-//     */
-//    @Bean
-//    @ServiceActivator(inputChannel = CHANNEL_NAME_IN)
-//    public MessageHandler handler() {
-//        return message -> {
-//            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
-//            String payload = message.getPayload().toString();
+package com.sckw.slope.detection.common.config;
+
+import com.sckw.slope.detection.consumer.mqApi.MqttApiHandler;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.integration.annotation.ServiceActivator;
+import org.springframework.integration.channel.DirectChannel;
+import org.springframework.integration.core.MessageProducer;
+import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
+import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
+import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
+import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
+import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
+import org.springframework.messaging.MessageChannel;
+import org.springframework.messaging.MessageHandler;
+
+/**
+ * @author lfdc
+ * @description MQTT配置,生产者
+ * @date 2023-10-26 10:10:59
+ */
+@Configuration
+public class MqttConfig {
+
+    private static final byte[] WILL_DATA;
+
+    static {
+        WILL_DATA = "offline".getBytes();
+    }
+
+    /**
+     * mqtt订阅者使用信道名称
+     */
+    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
+    /**
+     * mqtt发布者信道名称
+     */
+    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
+    /**
+     * mqtt发送者用户名
+     */
+    @Value("${mqtt.send.username}")
+    private String username;
+
+    /**
+     * mqtt发送者密码
+     */
+    @Value("${mqtt.send.password}")
+    private String password;
+
+    /**
+     * mqtt发送者url
+     */
+    @Value("${mqtt.send.url}")
+    private String hostUrl;
+    /**
+     * mqtt发送者客户端id
+     */
+    @Value("${mqtt.send.clientId}")
+    private String clientId;
+    /**
+     * mqtt发送者主题
+     */
+    @Value("${mqtt.send.topic}")
+    private String msgTopic;
+
+    /**
+     * mqtt发送者主题
+     */
+    @Value("${mqtt.receive.topic}")
+    private String msgReceiveTopic;
+
+    /**
+     * mqtt发送者超时时间
+     */
+    @Value("${mqtt.send.completionTimeout}")
+    private int completionTimeout;
+
+    @Value("${mqtt.send.keepAliveInterval}")
+    private int keepAliveInterval;
+
+    @Value("${mqtt.send.connectionTimeout}")
+    private int connectionTimeout;
+
+    @Autowired
+    private MqttApiHandler mqttApiHandler;
+
+
+    /**
+     * 新建MqttConnectionOptionsBean  MQTT连接器选项
+     * @return
+     */
+    @Bean
+    public MqttConnectOptions getSenderMqttConnectOptions() {
+        MqttConnectOptions options = new MqttConnectOptions();
+        // 设置连接的用户名
+        if (!username.trim().equals("")) {
+            //将用户名去掉前后空格
+            options.setUserName(username);
+        }
+        // 设置连接的密码
+        options.setPassword(password.toCharArray());
+        // 转化连接的url地址
+        String[] uris = {hostUrl};
+        // 设置连接的地址
+        options.setServerURIs(uris);
+        // 设置超时时间 单位为秒
+        options.setConnectionTimeout(completionTimeout);
+        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
+        // 但这个方法并没有重连的机制
+        options.setKeepAliveInterval(keepAliveInterval);
+        // 设置“遗嘱”消息的话题,若客户端与服务器之间的连接意外中断,服务器将发布客户端的“遗嘱”消息。
+        //设置超时时间
+        options.setConnectionTimeout(connectionTimeout);
+        options.setCleanSession(true);
+        options.setAutomaticReconnect(true);
+        return options;
+    }
+
+    /**
+     * 创建MqttPathClientFactoryBean
+     */
+    @Bean
+    public MqttPahoClientFactory senderMqttClientFactory() {
+        //创建mqtt客户端工厂
+        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
+        //设置mqtt的连接设置
+        factory.setConnectionOptions(getSenderMqttConnectOptions());
+        return factory;
+    }
+
+    /**
+     * 发布者-MQTT信息通道(生产者)
+     */
+    @Bean(name = CHANNEL_NAME_OUT)
+    public MessageChannel mqttOutboundChannel() {
+        return new DirectChannel();
+    }
+
+
+    /**
+     * 发布者-MQTT消息处理器(生产者)  将channel绑定到MqttClientFactory上
+     *
+     * @return {@link org.springframework.messaging.MessageHandler}
+     */
+    @Bean
+    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
+    public MessageHandler mqttOutbound() {
+        //创建消息处理器
+        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
+                clientId + "_pub",
+                senderMqttClientFactory());
+        //设置消息处理类型为异步
+        messageHandler.setAsync(true);
+        //设置消息的默认主题
+        messageHandler.setDefaultTopic(msgTopic);
+        messageHandler.setDefaultRetained(false);
+        //1.重新连接MQTT服务时,不需要接收该主题最新消息,设置retained为false;
+        //2.重新连接MQTT服务时,需要接收该主题最新消息,设置retained为true;
+        return messageHandler;
+    }
+
+
+    /************                             消费者,订阅者的消费信息                               *****/
+
+    /**
+     * MQTT信息通道(消费者)
+     */
+    @Bean(name = CHANNEL_NAME_IN)
+    public MessageChannel mqttInboundChannel() {
+        return new DirectChannel();
+    }
+
+    /**
+     * MQTT消息订阅绑定(消费者)
+     */
+    @Bean
+    public MessageProducer inbound() {
+//        System.out.println("topics:" + msgTopic);
+        // 可以同时消费(订阅)多个Topic
+        MqttPahoMessageDrivenChannelAdapter adapter =
+                new MqttPahoMessageDrivenChannelAdapter(
+                        clientId + "_sub", senderMqttClientFactory(), msgReceiveTopic.split(","));
+        adapter.setCompletionTimeout(5000);
+        adapter.setConverter(new DefaultPahoMessageConverter());
+        adapter.setQos(0);
+        // 设置订阅通道
+        adapter.setOutputChannel(mqttInboundChannel());
+        return adapter;
+    }
+
+    /**
+     * MQTT消息处理器(消费者)
+     */
+    @Bean
+    @ServiceActivator(inputChannel = CHANNEL_NAME_IN)
+    public MessageHandler handler() {
+        return message -> {
+            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
+            String payload = message.getPayload().toString();
 //            mqttCallbackHandler.handle(topic, payload);
-//        };
-//    }
-//}
+            mqttApiHandler.handle(topic, payload);
+        };
+    }
+}

+ 20 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/AbstractHandler.java

@@ -0,0 +1,20 @@
+package com.sckw.slope.detection.consumer;
+
+import com.sckw.core.web.response.HttpResult;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-11-15 17:11:03
+ */
+@Service
+public abstract class AbstractHandler {
+    /**
+     * 根据回执信息处理回执
+     *
+     * @param payload
+     * @return
+     */
+    public abstract HttpResult handle(String topic,String payload);
+}

+ 28 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/HandlerFactory.java

@@ -0,0 +1,28 @@
+package com.sckw.slope.detection.consumer;
+
+import com.sckw.core.exception.BusinessException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-11-15 17:11:09
+ */
+@Service
+public class HandlerFactory {
+
+    @Autowired
+    private Map<String, AbstractHandler> handlerMap = new HashMap<>();
+
+    public AbstractHandler getHandler(String type) {
+        AbstractHandler receiptHandler = handlerMap.get(type);
+        if (receiptHandler == null) {
+            throw new BusinessException("mqtt单据类型错误,type=" + type);
+        }
+        return receiptHandler;
+    }
+}

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

@@ -1,18 +0,0 @@
-package com.sckw.slope.detection.consumer;
-
-import org.springframework.stereotype.Service;
-
-/**
- * @author lfdc
- * @description
- * @date 2023-10-26 08:10:45
- */
-@Service
-public class MqttCallbackHandler {
-    public void handle(String topic, String payload) {
-        System.out.println(topic);
-        // 根据topic分别进行消息处理。
-        System.out.println("MqttCallbackHandle:" + topic + "|" + payload);
-    }
-}
-

+ 444 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttDeviceCallbackHandler.java

@@ -0,0 +1,444 @@
+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.SlopeDataMapper;
+import com.sckw.slope.detection.model.dos.mysql.*;
+import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
+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.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.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-10-26 08:10:45
+ */
+@Slf4j
+@Service("sharjeck/ai/test/out")
+public class MqttDeviceCallbackHandler extends AbstractHandler {
+
+    @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");
+        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);
+                }
+
+            }
+        }
+        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));
+
+    }
+
+    private void checkDeviceAlarm(String deviceCode, KwsDevice device, String itemValue, Long ts) {
+        try {
+            SlopeData devices = slopeDataMapper.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 暂未设备告警电话,设备告警不推送短信
+                }
+            }
+        } catch (Exception e) {
+            log.error("判断是否满足设备超时离线报警 error ", e.getMessage(), e);
+        }
+    }
+
+    @Autowired
+    KwsAlarmMapper alarmMapper;
+
+    @Autowired
+    KwsAlarmDetailMapper alarmDetailMapper;
+
+    @Autowired
+    KwsDeviceRelationMapper deviceRelationMapper;
+
+    @Autowired
+    KwsProjectDeviceMapper projectDeviceMapper;
+
+    @Autowired
+    KwsDeviceReferenceMapper deviceReferenceMapper;
+
+
+    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) {
+        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);
+    }
+}
+

+ 42 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttTdengineCallbackHandler.java

@@ -0,0 +1,42 @@
+package com.sckw.slope.detection.consumer;
+
+import com.sckw.core.web.response.HttpResult;
+import com.sckw.slope.detection.service.CommonService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-10-26 08:10:45
+ */
+@Service("test")
+public class MqttTdengineCallbackHandler extends AbstractHandler{
+
+    @Autowired
+    CommonService commonService;
+
+    @Autowired
+     HandlerFactory handlerFactory;
+
+    public HttpResult handle(String topic, String payload) {
+        System.out.println(topic);
+        // 根据topic分别进行消息处理。
+        System.out.println("MqttCallbackHandle:" + topic + "|" + payload);
+//        try {
+//            AbstractHandler handler = handlerFactory.getHandler(topic);
+//            return handler.handle(topic,payload);
+//        } catch (Exception e) {
+//            return HttpResult.error("MQTT回执类型错误");
+////            throw new RuntimeException(e);
+//        }
+//        if ("ssss".equals(topic)) {
+//            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+//            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
+//            String deviceCode = devicesAlarm.getDeviceCode();
+//        }
+        System.out.println("处理test");
+        return HttpResult.ok();
+    }
+}
+

+ 36 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/mqApi/MqttApiHandler.java

@@ -0,0 +1,36 @@
+package com.sckw.slope.detection.consumer.mqApi;
+
+import com.sckw.core.web.response.HttpResult;
+import com.sckw.slope.detection.consumer.AbstractHandler;
+import com.sckw.slope.detection.consumer.HandlerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author lfdc
+ * @description
+ * @date 2023-11-15 17:11:26
+ */
+@Service
+public class MqttApiHandler {
+
+    @Autowired
+    HandlerFactory handlerFactory;
+    public HttpResult handle(String topic, String payload) {
+        System.out.println(topic);
+        // 根据topic分别进行消息处理。
+        System.out.println("MqttCallbackHandle:" + topic + "|" + payload);
+        try {
+            AbstractHandler handler = handlerFactory.getHandler(topic);
+            return handler.handle(topic,payload);
+        } catch (Exception e) {
+            return HttpResult.error("MQTT回执类型错误");
+//            throw new RuntimeException(e);
+        }
+//        if ("ssss".equals(topic)) {
+//            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
+//            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
+//            String deviceCode = devicesAlarm.getDeviceCode();
+//        }
+    }
+}

+ 23 - 4
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/AlarmController.java

@@ -9,6 +9,7 @@ import com.sckw.core.web.response.HttpResult;
 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.excel.KwsAlarmExportVO;
 import com.sckw.slope.detection.service.KwsAlarmService;
 import jakarta.servlet.http.HttpServletRequest;
@@ -16,10 +17,7 @@ import jakarta.servlet.http.HttpServletResponse;
 import jakarta.validation.Valid;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import java.io.IOException;
 import java.util.HashMap;
@@ -81,4 +79,25 @@ public class AlarmController {
         log.info("告警日志-告警明细 threshold_detail param {}", baseList);
         return HttpResult.ok(kwsAlarmService.thresholdDetail(baseList, request));
     }
+
+    @Log(description = "告警记录-告警明细")
+    @RequestMapping(name = "告警记录-告警明细", value = "/detail", method = RequestMethod.GET)
+    public HttpResult detail(@RequestParam("id") String id, HttpServletRequest request) {
+        log.info("告警记录-告警明细 detail param {}", id);
+        return kwsAlarmService.detail(id, request);
+    }
+
+    @Log(description = "项目告警-图")
+    @RequestMapping(name = "项目告警-图", value = "/projectAlarm", method = RequestMethod.POST)
+    public HttpResult projectAlarm(@Valid @RequestBody AlarmStatisticsQuery query, HttpServletRequest request) {
+        log.info("项目告警-图 projectAlarm param {}", query);
+        return kwsAlarmService.projectAlarm(query, request);
+    }
+
+    @Log(description = "数据告警-图")
+    @RequestMapping(name = "项目告警-图", value = "/dataAlarm", method = RequestMethod.POST)
+    public HttpResult dataAlarm(@Valid @RequestBody AlarmStatisticsQuery query, HttpServletRequest request) {
+        log.info("数据告警-图 dataAlarm param {}", query);
+        return kwsAlarmService.dataAlarm(query, request);
+    }
 }

+ 10 - 1
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/ProjectController.java

@@ -137,7 +137,16 @@ public class ProjectController {
     @Log(description = "数据总览")
     //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
     @RequestMapping(name = "数据总览", value = "/dataScreening", method = RequestMethod.GET)
-    public HttpResult dataScreening(@RequestParam("projectId") String projectId ,HttpServletRequest request) {
+    public HttpResult dataScreening(/*@RequestParam("projectId") */String projectId ,HttpServletRequest request) {
+        log.info("数据总览 dataScreening param:{}", projectId);
         return projectService.dataScreening(projectId);
     }
+
+    @Log(description = "项目查询(项目+设备)")
+    //@RepeatSubmit(interval = 3000, message = "两次请求间隔未超过3秒")
+    @RequestMapping(name = "项目查询(项目+设备)", value = "/projectList", method = RequestMethod.GET)
+    public HttpResult projectList(/*@RequestParam("projectId")*/ String projectId ,HttpServletRequest request) {
+        log.info("项目查询(项目+设备) projectList param:{}", projectId);
+        return projectService.projectList(projectId);
+    }
 }

+ 22 - 3
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/mysql/KwsAlarmMapper.java

@@ -3,8 +3,6 @@ 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.param.DeviceQuery;
-import com.sckw.slope.detection.model.vo.DeviceVo;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
 
@@ -26,5 +24,26 @@ public interface KwsAlarmMapper extends BaseMapper<KwsAlarm> {
 
     int updateByPrimaryKey(KwsAlarm record);
 
-    List<Map<String,Long>> selectByDevicesId(@Param("devicesId") List<Long> devicesId);
+    List<Map<String, Long>> selectByDevicesId(@Param("devicesId") List<Long> devicesId);
+
+    /**
+     * 统计
+     *
+     * @param startTime  开始时间
+     * @param endTime    结束时间
+     * @param projectId  项目
+     * @param mountainId 矿山
+     * @param level 等级
+     * @return
+     */
+    List<Map<String, Object>> getDataAlarmToDay(@Param("startTime") String startTime, @Param("endTime") String endTime,@Param("level") String level,
+                                                @Param("projectId") String projectId, @Param("mountainId") String mountainId);
+
+    List<Map<String, Object>> getDataAlarmToWeek(@Param("startTime") String startTime, @Param("endTime") String endTime, @Param("level") String level,
+                                                 @Param("projectId") String projectId, @Param("mountainId") String mountainId);
+
+    List<Map<String, Object>> getDataAlarmToYear(@Param("startTime") String startTime, @Param("endTime") String endTime, @Param("level") String level,
+                                                  @Param("projectId") String projectId, @Param("mountainId") String mountainId);
+
+    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);
 }

+ 25 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/DevicesMapper.java

@@ -0,0 +1,25 @@
+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.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);
+
+    int updateByPrimaryKey(Devices record);
+}

+ 25 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/OriginalMapper.java

@@ -0,0 +1,25 @@
+package com.sckw.slope.detection.dao.tdengine;
+
+import com.baomidou.dynamic.datasource.annotation.DS;
+import com.sckw.slope.detection.model.dos.tdengine.Original;
+import org.apache.ibatis.annotations.Mapper;
+import org.springframework.stereotype.Repository;
+
+import java.util.Date;
+
+@DS("td")
+@Mapper
+@Repository
+public interface OriginalMapper {
+    int deleteByPrimaryKey(Date ts);
+
+    int insert(Original record);
+
+    int insertSelective(Original record);
+
+    Original selectByPrimaryKey(Date ts);
+
+    int updateByPrimaryKeySelective(Original record);
+
+    int updateByPrimaryKey(Original record);
+}

+ 3 - 1
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/dao/tdengine/SlopeDataMapper.java

@@ -21,7 +21,7 @@ import java.util.List;
 @Repository
 public interface SlopeDataMapper extends BaseMapper<SlopeData> {
 
-    @Select("select * from devices.slope_data_#{vin}_#{number}")
+    @Select("select * from devicesv2.device_#{number}")
     List<SlopeDataVo> selectAll(@Param("vin") String vin, @Param("number") String number);
 
     List<SlopeDataVo> selectList();
@@ -37,4 +37,6 @@ public interface SlopeDataMapper extends BaseMapper<SlopeData> {
     List<SlopeDataVo> selectListByMaster(@Param("page") Integer page, @Param("pageSize") Integer pageSize);
 
     List<SlopeDataVo> selectListByMasterCount(Integer newPage, Integer pageSize);
+
+    SlopeData selectLastData(@Param("deviceCode") String deviceCode);
 }

+ 1 - 25
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/mysql/KwsAlarmDetail.java

@@ -21,7 +21,7 @@ public class KwsAlarmDetail implements Serializable {
 
     private String companyId;
 
-    private Long projectId;
+//    private Long projectId;
 
     /**
      * 告警id
@@ -30,32 +30,8 @@ public class KwsAlarmDetail implements Serializable {
 
     private Long pid;
 
-    /**
-     * 告警等级
-     */
-    private Integer level;
-
     private String val;
 
-    private String itemName;
-
-    /**
-     * 告警标题
-     */
-
-    private String title;
-
-    /**
-     * 告警内容
-     */
-
-    private String content;
-
-    /**
-     * 1数据告警  2设备告警
-     */
-    private Integer type;
-
     /**
      * 纬度
      */

+ 1 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/mysql/KwsDeviceReference.java

@@ -1,6 +1,5 @@
 package com.sckw.slope.detection.model.dos.mysql;
 
-import com.baomidou.mybatisplus.annotation.TableLogic;
 import com.baomidou.mybatisplus.annotation.TableName;
 import lombok.Data;
 
@@ -84,7 +83,7 @@ public class KwsDeviceReference implements Serializable {
     /**
     * 删除标识
     */
-    @TableLogic(value = "0")
+//    @TableLogic(value = "0")
     private int delFlag;
 
     private static final long serialVersionUID = 1L;

+ 32 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/tdengine/Devices.java

@@ -0,0 +1,32 @@
+package com.sckw.slope.detection.model.dos.tdengine;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * STABLE
+ */
+@Data
+@TableName("devices")
+public class Devices implements Serializable {
+
+    private Date ts;
+
+    private Integer tslverId;
+
+
+    private String line;
+
+
+    private String val;
+
+    private String msgId;
+
+    private Date rawTs;
+    private String guid;
+
+
+}

+ 25 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dos/tdengine/Original.java

@@ -0,0 +1,25 @@
+package com.sckw.slope.detection.model.dos.tdengine;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+    * STABLE
+    */
+@Data
+@TableName("original")
+public class Original implements Serializable {
+
+    private Date ts;
+
+    private String rawStr;
+    /**
+    * TAG
+    */
+    private String guid;
+
+    private static final long serialVersionUID = 1L;
+}

+ 22 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/DevicesAlarm.java

@@ -0,0 +1,22 @@
+package com.sckw.slope.detection.model.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * @author lfdc
+ * @description mqtt消息消费数据
+ * @date 2023-11-15 15:11:50
+ */
+@Data
+public class DevicesAlarm implements Serializable {
+    /**
+     * 设备code
+     */
+    private String deviceCode;
+
+    private List<DevicesItem> devicesItemList;
+
+}

+ 36 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/dto/DevicesItem.java

@@ -0,0 +1,36 @@
+package com.sckw.slope.detection.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * @author lfdc
+ * @description 设备要素
+ * @date 2023-11-15 15:11:53
+ */
+@Data
+public class DevicesItem implements Serializable {
+    /**
+     * 要素名称
+     */
+    private String itemName;
+
+    /**
+     * 要素值
+     */
+    private String itemValue;
+
+    private Long ts;
+    private String guid;
+
+    @JsonProperty("tslver_Id")
+    private String tslverId;
+
+    @JsonProperty("msg_id")
+    private String msgId;
+
+    @JsonProperty("raw_ts")
+    private String rawTs;
+}

+ 37 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/AlarmStatisticsQuery.java

@@ -0,0 +1,37 @@
+package com.sckw.slope.detection.model.param;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * @author lfdc
+ * @description 统计查询
+ * @date 2023-11-15 10:11:12
+ */
+@Data
+public class AlarmStatisticsQuery implements Serializable {
+
+    /**
+     * 今日 1、本周 2、本月 3、全年4
+     */
+    private String latitude;
+
+    /**
+     * 项目id
+     */
+    private String projectId;
+
+    /**
+     * 告警级别
+     */
+    private String level;
+    /**
+     * 开始时间
+     */
+    private String startTime;
+    /**
+     * 结束时间
+     */
+    private String endTime;
+}

+ 43 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/param/SmsMessageParam.java

@@ -0,0 +1,43 @@
+package com.sckw.slope.detection.model.param;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * @author lfdc
+ * @description 发送消息请求参数
+ * @date 2023-11-17 08:11:59
+ */
+@Data
+public class SmsMessageParam implements Serializable {
+
+    /**
+     * 标识code
+     */
+    private String code;
+    /**
+     * 类型
+     */
+    private String type;
+    /**
+     * 手机
+     */
+    private List<String> pushTo;
+
+    private Content content;
+
+    @Data
+    public static class Content implements Serializable{
+        private String templateCode;
+        private String signName;
+        private TemplateParam templateParam;
+    }
+
+    @Data
+    public static class TemplateParam implements Serializable{
+        private String name;
+        private String start;
+    }
+}

+ 42 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/DeviceListBean.java

@@ -0,0 +1,42 @@
+package com.sckw.slope.detection.model.vo;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * @author lfdc
+ * @description 设备数据
+ * @date 2023-11-16 10:11:50
+ */
+@Data
+public class DeviceListBean implements Serializable {
+    /**
+     * 设备名称
+     */
+    private String name;
+    /**
+     * 视频设备、监测设备等
+     */
+    private String attribute;
+    /**
+     * 逻辑纬度(测点布设的值)
+     */
+    private String logicLat;
+    /**
+     * 逻辑经度(测点布设的值)
+     */
+    private String logicLng;
+    /**
+     * 逻辑海拔(测点布设的值)
+     */
+    private String logicAlt;
+    /**
+     * 设备别名
+     */
+    private String alias;
+    /**
+     * 设备ID
+     */
+    private String deviceId;
+}

+ 34 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ProjectDevicesListVO.java

@@ -0,0 +1,34 @@
+package com.sckw.slope.detection.model.vo;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * @author lfdc
+ * @description 查询所有项目以及项目下所有的设备数据
+ * @date 2023-11-16 10:11:48
+ */
+@Data
+public class ProjectDevicesListVO implements Serializable {
+
+
+    /**
+     * 选中区域
+     */
+    private String fence;
+    /**
+     * 项目id
+     */
+    private String projectId;
+    /**
+     * 项目名称
+     */
+    private String projectName;
+    /**
+     * 设备数据
+     */
+    private List<DeviceListBean> deviceList;
+
+}

+ 60 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/model/vo/ThresholdLogDetailVO.java

@@ -0,0 +1,60 @@
+package com.sckw.slope.detection.model.vo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+
+/**
+ * @author lfdc
+ * @description 告警记录-查看详情返回vo
+ * @date 2023-11-15 08:11:56
+ */
+@Data
+public class ThresholdLogDetailVO implements Serializable {
+    /**
+     * 告警类型
+     */
+    private String alarmType;
+    /**
+     * 告警等级
+     */
+    private String alarmLevel;
+    /**
+     * 告警明细
+     */
+    private String alarmTitle;
+    /**
+     * 检测要素
+     */
+    private String itemName;
+    /**
+     * 当前基准值
+     */
+    private BigDecimal currentValue;
+
+    /**
+     * 当前偏移量
+     */
+    private BigDecimal currentOffset;
+    /**
+     * 原始基准值
+     */
+    private BigDecimal originalValue;
+
+    /**
+     * 原始偏移量
+     */
+    private BigDecimal originalOffset;
+    /**
+     * 上次基准值
+     */
+    private BigDecimal lastReferenceValue;
+    /**
+     * 告警时间
+     */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    private LocalDateTime alarmTime;
+}

+ 30 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/CommonService.java

@@ -6,12 +6,14 @@ import com.github.pagehelper.PageInfo;
 import com.sckw.core.exception.BusinessException;
 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.model.enums.MessageLogEnum;
 import com.sckw.core.model.page.PageRes;
 import com.sckw.core.utils.IdWorker;
 import com.sckw.core.web.response.PhpResult;
 import com.sckw.slope.detection.dao.mysql.KwsDictMapper;
 import com.sckw.slope.detection.dao.mysql.KwsLogMapper;
+import com.sckw.slope.detection.model.dos.mysql.KwsDeviceReference;
 import com.sckw.slope.detection.model.dos.mysql.KwsLog;
 import com.sckw.slope.detection.model.dto.HeaderData;
 import com.sckw.slope.detection.model.dto.SystemDict;
@@ -24,6 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import java.math.BigDecimal;
 import java.time.LocalDateTime;
 import java.util.*;
 
@@ -102,6 +105,33 @@ public class CommonService {
         return dictList;
     }
 
+    private static final Long equatorial_circumference = 40075020000L;
+
+    /**
+     * 计算xyz值的偏移量  当前只用于计算偏移数据的offset
+     * @param value
+     * @param itemName
+     * @param deviceRelation
+     * @return
+     */
+    public BigDecimal computeOffset(String value, String itemName, KwsDeviceReference deviceRelation) {
+        BigDecimal offsetValue = new BigDecimal("0.00");
+        if (DictItemEnum.ALTITUDE_Z.getValue().equals(itemName)) {
+            offsetValue = new BigDecimal(value).divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
+        }
+        BigDecimal subtract = new BigDecimal(value).subtract((deviceRelation == null ? new BigDecimal("0.00") : deviceRelation.getCurrentValue()));
+        if (DictItemEnum.LATITUDE_Y.getValue().equals(itemName)) {
+            offsetValue = new BigDecimal(equatorial_circumference).multiply(subtract);
+        }
+        double angleInRadians = 0;
+        if (DictItemEnum.LONGITUDE_X.getValue().equals(itemName)) {
+            double cosValue = Math.cos(angleInRadians);
+            double doubleValue = subtract.divide(new BigDecimal("360"), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
+            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
+        }
+        return offsetValue;
+    }
+
     public int insertLog(MessageLogEnum messageLogEnum, HeaderData headerData, Map<String, Object> logMap, Long operationBy) {
         String content = com.sckw.core.utils.StringUtils.replaceTextVar(messageLogEnum.getContent(), logMap);
         KwsLog log = new KwsLog();

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

@@ -465,9 +465,9 @@ public class DeviceService {
                 //当前测量值-TD获取
                 HashMap<String, Object> currentMeasurement = new HashMap<>();
                 String snCode = kwsDevice.getSnCode();
-                InsTables insTables = insTablesMapper.selectTableIsExit("slope_data_" + snCode);
+                InsTables insTables = insTablesMapper.selectTableIsExit("devicesv2" + snCode);
                 if (insTables == null) {
-                    insTablesMapper.createTable("slope_data_" + snCode);
+                    insTablesMapper.createTable("devicesv2" + snCode);
                 }
                 SlopeData slopeData = slopeDataMapper.selectListByLine(snCode, item);
                 String val = slopeData == null ? null : slopeData.getVal();
@@ -559,9 +559,9 @@ public class DeviceService {
                     if (!CollectionUtils.isEmpty(stringList)) {
                         for (int i = 0; i < stringList.size(); i++) {
                             String snCode = kwsDevice.getSnCode();
-                            InsTables insTables = insTablesMapper.selectTableIsExit("slope_data_" + snCode);
+                            InsTables insTables = insTablesMapper.selectTableIsExit("devicesv2" + snCode);
                             if (insTables == null) {
-                                insTablesMapper.createTable("slope_data_" + snCode);
+                                insTablesMapper.createTable("devicesv2" + snCode);
                             }
                             List<SlopeData> selected = slopeDataMapper.selectListByLineOrderByCreateTime(snCode, stringList.get(i));
                             if (!CollectionUtils.isEmpty(selected)) {

+ 184 - 5
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java

@@ -1,9 +1,11 @@
 package com.sckw.slope.detection.service;
 
+import cn.hutool.core.date.DateUtil;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 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.model.enums.DictEnum;
 import com.sckw.core.model.page.PageRes;
 import com.sckw.core.model.vo.BaseList;
@@ -14,8 +16,10 @@ import com.sckw.slope.detection.model.dos.mysql.*;
 import com.sckw.slope.detection.model.dto.HeaderData;
 import com.sckw.slope.detection.model.dto.SystemDict;
 import com.sckw.slope.detection.model.param.AlarmLogThresholdQuery;
+import com.sckw.slope.detection.model.param.AlarmStatisticsQuery;
 import com.sckw.slope.detection.model.vo.AlarmLogThresholdVO;
 import com.sckw.slope.detection.model.vo.KwsAlarmVO;
+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 jakarta.servlet.http.HttpServletRequest;
@@ -27,6 +31,9 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
 
+import java.math.BigDecimal;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -46,6 +53,9 @@ public class KwsAlarmService {
     @Autowired
     KwsDeviceMapper deviceMapper;
 
+    @Autowired
+    KwsDeviceReferenceMapper deviceReferenceMapper;
+
     @Autowired
     KwsThresholdMapper thresholdMapper;
 
@@ -209,11 +219,11 @@ public class KwsAlarmService {
                 Long pid = detail.getPid();
                 KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
                 ThresholdRecordDetailVO vo = new ThresholdRecordDetailVO();
-                vo.setId(kwsThreshold.getId());
-                vo.setAlarmLevel(detail.getType() == null ? null :
-                        (alarmType == null ? String.valueOf(detail.getType()) : alarmType.get(String.valueOf(detail.getType())).getLabel()));
-                vo.setType(detail.getItemName() == null ? null :
-                        (dictByDictCode == null ? detail.getItemName() : dictByDictCode.get(detail.getItemName()).getLabel()));
+                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());
@@ -225,4 +235,173 @@ public class KwsAlarmService {
         }
         return PageRes.build(info, list);
     }
+
+    public HttpResult detail(String id, HttpServletRequest request) {
+        ThresholdLogDetailVO vo = new ThresholdLogDetailVO();
+        KwsAlarmDetail kwsAlarmDetail = alarmDetailMapper.selectById(Long.parseLong(id));
+        if (kwsAlarmDetail == null) {
+            throw new BusinessException("数据不存在");
+        }
+        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 HttpResult.ok(vo);
+            }
+            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());
+        return HttpResult.ok(vo);
+    }
+
+    public HttpResult dataAlarm(AlarmStatisticsQuery query, HttpServletRequest request) {
+        String startTime = query.getStartTime();
+        String endTime = query.getEndTime();
+        String latitude = query.getLatitude();
+        String projectId = query.getProjectId();
+        String level = query.getLevel();
+        HeaderData headerData = commonService.getHeaderData(request);
+        List<Map<String, Object>> returnList = new ArrayList<>();
+        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(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());
+        } 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());
+        } 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());
+                } 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());
+                } 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());
+                } 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());
+                }
+            }
+        }
+        return HttpResult.ok(returnList);
+    }
+
+    public HttpResult projectAlarm(AlarmStatisticsQuery query, HttpServletRequest request) {
+        String startTime = query.getStartTime();
+        String endTime = query.getEndTime();
+        String latitude = query.getLatitude();
+        String projectId = query.getProjectId();
+        String level = query.getLevel();
+        HeaderData headerData = commonService.getHeaderData(request);
+        List<Map<String, Object>> returnList = new ArrayList<>();
+        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(latitude)) {
+            //按照天纬度统计
+            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
+            startTime = weekMondayAndSunday.get(0);
+            endTime = weekMondayAndSunday.get(1);
+        } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
+            //统计小时的纬度统计
+            startTime = startTime + " 00:00:00";
+            endTime = endTime + " 23:59:59";
+        } 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";
+                } else if ("2".equals(latitude)) {
+                    List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
+                    startTime = weekMondayAndSunday.get(0);
+                    endTime = weekMondayAndSunday.get(1);
+                } 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";
+                } else if ("4".equals(latitude)) {
+                    //查询全年每个月份
+                    startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01" + " 00:00:00";
+                    endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31" + " 23:59:59";
+                }
+            }
+        }
+        returnList = getProjectAlarmList(startTime, endTime, level, projectId, headerData.getMountainId());
+        if (!CollectionUtils.isEmpty(returnList)) {
+            for (Map<String, Object> map : returnList) {
+                String id = map.get("projectId").toString();
+                KwsProject project = projectMapper.selectById(Long.parseLong(id));
+                map.put("projectName", project == null ? id : project.getName());
+            }
+        }
+        return HttpResult.ok(returnList);
+    }
+
+    private List<Map<String, Object>> getProjectAlarmList(String startTime, String endTime, String level, String projectId, String mountainId) {
+        List<Map<String, Object>> list = alarmMapper.getProjectAlarmList(startTime, endTime, level, projectId, mountainId);
+        return list;
+    }
+
+    private List<Map<String, Object>> getDataAlarmToYear(String startTime, String endTime, String level, String projectId, String mountainId) {
+        List<Map<String, Object>> list = alarmMapper.getDataAlarmToYear(startTime, endTime, level, projectId, mountainId);
+        return list;
+    }
+
+    private List<Map<String, Object>> getDataAlarmToWeek(String startTime, String endTime, String level, String projectId, String mountainId) {
+        List<Map<String, Object>> list = alarmMapper.getDataAlarmToWeek(startTime, endTime, level, projectId, mountainId);
+        return list;
+    }
+
+    private List<Map<String, Object>> getDataAlarmToDay(String startTime, String endTime, String level, String projectId, String mountainId) {
+        List<Map<String, Object>> list = alarmMapper.getDataAlarmToDay(startTime, endTime, level, projectId, mountainId);
+        return list;
+    }
+
+
 }

+ 57 - 6
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/ProjectService.java

@@ -846,9 +846,13 @@ public class ProjectService {
                             String dateStart = DateUtil.getDateTimeToHour(date, 24);
                             String dateEnd = DateUtil.localDateTimeFormat(LocalDateTime.now());
                             String snCode = kwsDevice.getSnCode();
-                            InsTables insTables = insTablesMapper.selectTableIsExit("slope_data_" + snCode);
-                            if (insTables == null) {
-                                insTablesMapper.createTable("slope_data_" + snCode);
+                            try {
+                                InsTables insTables = insTablesMapper.selectTableIsExit("devicesv2_" + snCode);
+                                if (insTables == null) {
+                                    insTablesMapper.createTable("devicesv2_" + snCode);
+                                }
+                            } catch (Exception e) {
+                                continue;
                             }
                             List<SlopeData> selected = slopeDataMapper.selectLineList(kwsDevice.getSnCode(), item, dateStart, dateEnd);
                             List<Map<String, Object>> mapList = new ArrayList<>();
@@ -1168,15 +1172,18 @@ public class ProjectService {
 
     public HttpResult dataScreening(String projectId) {
         DataScreeningVO vo = new DataScreeningVO();
-        long count = projectMapper.selectList(new LambdaQueryWrapper<KwsProject>()
-                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(projectId), KwsProject::getId, Long.parseLong(projectId))).stream().count();
+        LambdaQueryWrapper<KwsProject> wrapper = new LambdaQueryWrapper<>();
+        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
+            wrapper.eq(KwsProject::getId, Long.parseLong(projectId));
+        }
+        long count = projectMapper.selectList(wrapper.eq(KwsProject::getDelFlag, 0)).stream().count();
         vo.setProjectTotal(count);
         int deviceCount = deviceMapper.selectCountByProject(projectId);
         vo.setDeviceTotal(deviceCount);
         vo.setDeviceOnlineRate(0);
         LocalDateTime localDateTimeEnd = DateUtil.localDateToLocalDateTimeEnd(LocalDate.now());
         LocalDateTime localDateTimeStart = DateUtil.localDateToLocalDateTimeStart(LocalDate.now());
-        KwsProject project = new KwsProject();
+        KwsProject project = null;
         if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
             project = projectMapper.selectById(projectId);
         }
@@ -1205,4 +1212,48 @@ public class ProjectService {
         vo.setTodayAlarmTotal(CollectionUtils.isEmpty(kwsAlarms) ? 0 : kwsAlarms.size());
         return HttpResult.ok("查询成功", vo);
     }
+
+    public HttpResult projectList(String projectId) {
+        LambdaQueryWrapper<KwsProject> wrapper = new LambdaQueryWrapper<>();
+        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
+            wrapper.eq(KwsProject::getId, projectId);
+        }
+        wrapper.eq(KwsProject::getDelFlag, NumberConstant.ZERO)
+//                .eq(KwsProject::getStatus,NumberConstant.ZERO)
+        ;
+        List<KwsProject> projectList = projectMapper.selectList(wrapper);
+        if (CollectionUtils.isEmpty(projectList)) {
+            return HttpResult.ok();
+        }
+        List<ProjectDevicesListVO> returnList = new ArrayList<>(NumberConstant.TWELVE);
+        projectList.forEach(project -> {
+            ProjectDevicesListVO vo = new ProjectDevicesListVO();
+            Long id = project.getId();
+            KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>()
+                    .eq(KwsProjectArea::getProjectId, id)
+                    .eq(KwsProjectArea::getDelFlag, NumberConstant.ZERO)
+            );
+            vo.setFence(area == null ? null : area.getFence());
+            vo.setProjectId(id.toString());
+            vo.setProjectName(project.getName());
+            List<AffiliationDeviceVO> deviceList = deviceMapper.selectDeviceAllAndProjectData(id.toString());
+            if (!CollectionUtils.isEmpty(deviceList)) {
+                List<DeviceListBean> beans = new ArrayList<>();
+                deviceList.forEach(device -> {
+                    DeviceListBean bean = new DeviceListBean();
+                    bean.setName(device.getName());
+                    bean.setAttribute(device.getAttribute());
+                    bean.setLogicLat(device.getLogicLat());
+                    bean.setLogicLng(device.getLogicLng());
+                    bean.setLogicAlt(device.getLogicLat());
+                    bean.setAlias(device.getAlias());
+                    bean.setDeviceId(device.getDeviceId());
+                    beans.add(bean);
+                });
+                vo.setDeviceList(beans);
+            }
+            returnList.add(vo);
+        });
+        return HttpResult.ok(returnList);
+    }
 }

+ 2 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/TdengineDemoService.java

@@ -48,14 +48,14 @@ public class TdengineDemoService {
     }
 
     public void getTable() {
-        String tableName = "slope_data_6_7";
+        String tableName = "devicesv26_7";
         InsTables insTables = insTablesMapper.selectTableIsExit(tableName);
         if (insTables != null) {
         }
     }
 
     public void createTable() {
-        String tableName = "slope_data_20231108";
+        String tableName = "devicesv220231108";
         insTablesMapper.createTable(tableName);
     }
 }

+ 72 - 3
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/api/DetectionApiService.java

@@ -7,14 +7,16 @@ import com.sckw.core.utils.OkHttpUtils;
 import com.sckw.core.web.response.HttpResult;
 import com.sckw.core.web.response.PhpResult;
 import com.sckw.slope.detection.model.dto.SystemDict;
+import com.sckw.slope.detection.model.param.SmsMessageParam;
 import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.dubbo.common.utils.MD5Utils;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Service;
 
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import java.io.IOException;
+import java.util.*;
 
 /**
  * @author lfdc
@@ -139,4 +141,71 @@ public class DetectionApiService {
 
         return result;
     }
+
+    public static void main(String[] args) throws Exception {
+        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);
+        Map<String, String> headerMap = new HashMap<>();
+        headerMap.put("sign", new MD5Utils().getMd5("sign"));
+        headerMap.put("account", "zhangsan");
+        headerMap.put("msgId", "msgid");
+        pushSmsMessage("http://10.10.10.149:8830/msg_api/push", JSONObject.toJSONString(param));
+    }
+
+    private static OkHttpClient client = new OkHttpClient();
+
+    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
+
+    public static JSONObject pushSmsMessage(String url, String json) {
+        RequestBody body = RequestBody.create(JSON, json);
+//        Request.Builder builder = new Request.Builder();
+//        Map<String, Object> map = new HashMap<>();
+//        if (map != null) {
+//            for (Map.Entry<String, Object> entry : map.entrySet()) {
+//                String key = entry.getKey();
+//                Object value = entry.getValue();
+//                builder.addHeader(key, value.toString());
+//            }
+//        }
+//        builder.post(body);
+//        Request request = builder.build();
+        Request request = new Request.Builder()
+                .url(url)
+                .addHeader("sign", new MD5Utils().getMd5("sign"))
+                .addHeader("account", "zhangsan")
+                .addHeader("msgId", "msgld")
+                .post(body)
+                .build();
+        try {
+            Response response = client.newCall(request).execute();
+            System.out.println(JSONObject.toJSONString(response));
+            System.out.println("请求响应状态码:" + response.code());
+            if (response.isSuccessful()) {
+                String responseBody = response.body().string();
+                log.info("响应信息:{}", responseBody);
+                return JSONObject.parseObject(responseBody);
+            } else {
+                int code = response.code();
+                JSONObject resp = new JSONObject();
+                resp.put("code", code);
+                resp.put("success", false);
+                resp.put("message", "http状态响应异常");
+                return resp;
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
 }

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

@@ -3,6 +3,7 @@ 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;
@@ -43,6 +44,9 @@ public class ReportTemplateTaskService {
                     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) {

+ 4 - 1
slope-modules/slope-detection/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

@@ -1 +1,4 @@
-#com.sckw.slope.detection.common.config.MultipleDataSourceConfig
+#com.sckw.slope.detection.common.config.MultipleDataSourceConfig
+#com.sckw.slope.detection.consumer.AbstractHandler
+com.sckw.slope.detection.consumer.HandlerFactory
+#com.sckw.slope.detection.consumer.MqttCallbackHandler

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

@@ -48,7 +48,11 @@ mqtt:
   receive:
     topic: slopePush/slopePull/test/out,test,slope,sharjeck/ai/test/out
 OkHttpClit:
-  url: "http://10.10.10.185:9501"
+  url: http://10.10.10.185:9501
+sms:
+  url: http://10.10.10.223:8830/msg_api/push
+
+
 #oss上传
 aliyun:
   oss:

+ 2 - 12
slope-modules/slope-detection/src/main/resources/mapper/mysql/KwsAlarmDetailMapper.xml

@@ -7,15 +7,11 @@
     <id column="id" jdbcType="BIGINT" property="id" />
     <result column="mountain_id" jdbcType="VARCHAR" property="mountainId" />
     <result column="company_id" jdbcType="VARCHAR" property="companyId" />
-    <result column="project_id" jdbcType="BIGINT" property="projectId" />
+<!--    <result column="project_id" jdbcType="BIGINT" property="projectId" />-->
     <result column="alarm_id" jdbcType="BIGINT" property="alarmId" />
     <result column="pid" jdbcType="BIGINT" property="pid" />
     <result column="val" jdbcType="VARCHAR" property="val" />
 <!--    <result column="item_name" jdbcType="VARCHAR" property="itemName" />-->
-    <result column="level" jdbcType="INTEGER" property="level" />
-    <result column="title" jdbcType="VARCHAR" property="title" />
-    <result column="content" jdbcType="VARCHAR" property="content" />
-    <result column="type" jdbcType="INTEGER" property="type" />
     <result column="lat" jdbcType="VARCHAR" property="lat" />
     <result column="lng" jdbcType="VARCHAR" property="lng" />
     <result column="alt" jdbcType="VARCHAR" property="alt" />
@@ -25,7 +21,7 @@
   </resultMap>
   <sql id="Base_Column_List">
     <!--@mbg.generated-->
-    id, mountain_id, company_id, project_id, alarm_id, `level`, title, content, `type`, 
+    id, mountain_id, company_id, alarm_id,
     lat, lng, alt, create_time, update_time, `status`,val,pid
   </sql>
   <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
@@ -53,9 +49,6 @@
       <if test="companyId != null">
         company_id,
       </if>
-      <if test="projectId != null">
-        project_id,
-      </if>
       <if test="alarmId != null">
         alarm_id,
       </if>
@@ -100,9 +93,6 @@
       <if test="companyId != null">
         #{companyId,jdbcType=VARCHAR},
       </if>
-      <if test="projectId != null">
-        #{projectId,jdbcType=BIGINT},
-      </if>
       <if test="alarmId != null">
         #{alarmId,jdbcType=BIGINT},
       </if>

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

@@ -1,210 +1,315 @@
 <?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.mysql.KwsAlarmMapper">
-  <resultMap id="BaseResultMap" type="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
-    <!--@mbg.generated-->
-    <!--@Table kws_alarm-->
-    <id column="id" jdbcType="BIGINT" property="id" />
-    <result column="title" jdbcType="VARCHAR" property="title" />
-    <result column="company_id" jdbcType="VARCHAR" property="companyId" />
-    <result column="mountain_id" jdbcType="VARCHAR" property="mountainId" />
-    <result column="project_id" jdbcType="VARCHAR" property="projectId" />
-    <result column="device_id" jdbcType="VARCHAR" property="deviceId" />
-    <result column="level" jdbcType="INTEGER" property="level" />
-    <result column="type" jdbcType="INTEGER" property="type" />
-    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
-    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
-    <result column="status" jdbcType="TINYINT" property="status" />
-  </resultMap>
-  <sql id="Base_Column_List">
-    <!--@mbg.generated-->
-    id,  title,`level`, `type`,  create_time,
-    `status`,company_id,mountain_id,project_id,update_time,device_id
-  </sql>
-  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
-    <!--@mbg.generated-->
-    select 
-    <include refid="Base_Column_List" />
-    from kws_alarm
-    where id = #{id,jdbcType=BIGINT}
-  </select>
-
-  <select id="selectByDevicesId" parameterType="java.lang.String" resultType="java.util.Map">
-    <!--@mbg.generated-->
-    select count(id) as count,pid,type
-    from kws_alarm
-    where 1 = 1
-    <if test="devicesId != null and devicesId.size()>0">
-      AND pid IN
-      <foreach collection="devicesId" open="(" close=")" item="item" separator=",">
-        #{item}
-      </foreach>
-    </if>
- group by pid,type
-  </select>
-
-  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
-    <!--@mbg.generated-->
-    delete from kws_alarm
-    where id = #{id,jdbcType=BIGINT}
-  </delete>
-  <insert id="insert" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
-    <!--@mbg.generated-->
-    insert into kws_alarm (id, pid, title, 
-      val, content, `level`, 
-      `type`, lat, lng, alt, 
-      create_time, trigger_times, `status`
-      )
-    values (#{id,jdbcType=BIGINT}, #{pid,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, 
-      #{val,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR}, #{level,jdbcType=INTEGER}, 
-      #{type,jdbcType=INTEGER}, #{lat,jdbcType=VARCHAR}, #{lng,jdbcType=VARCHAR}, #{alt,jdbcType=VARCHAR}, 
-      #{createTime,jdbcType=TIMESTAMP}, #{triggerTimes,jdbcType=INTEGER}, #{status,jdbcType=TINYINT}
-      )
-  </insert>
-  <insert id="insertSelective" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
-    <!--@mbg.generated-->
-    insert into kws_alarm
-    <trim prefix="(" suffix=")" suffixOverrides=",">
-      <if test="id != null">
+    <resultMap id="BaseResultMap" type="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
+        <!--@mbg.generated-->
+        <!--@Table kws_alarm-->
+        <id column="id" jdbcType="BIGINT" property="id"/>
+        <result column="title" jdbcType="VARCHAR" property="title"/>
+        <result column="company_id" jdbcType="VARCHAR" property="companyId"/>
+        <result column="mountain_id" jdbcType="VARCHAR" property="mountainId"/>
+        <result column="project_id" jdbcType="VARCHAR" property="projectId"/>
+        <result column="device_id" jdbcType="VARCHAR" property="deviceId"/>
+        <result column="level" jdbcType="INTEGER" property="level"/>
+        <result column="type" jdbcType="INTEGER" property="type"/>
+        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
+        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
+        <result column="status" jdbcType="TINYINT" property="status"/>
+    </resultMap>
+    <sql id="Base_Column_List">
+        <!--@mbg.generated-->
         id,
-      </if>
-      <if test="pid != null">
-        pid,
-      </if>
-      <if test="title != null">
         title,
-      </if>
-      <if test="val != null">
-        val,
-      </if>
-      <if test="content != null">
-        content,
-      </if>
-      <if test="level != null">
         `level`,
-      </if>
-      <if test="type != null">
         `type`,
-      </if>
-      <if test="lat != null">
-        lat,
-      </if>
-      <if test="lng != null">
-        lng,
-      </if>
-      <if test="alt != null">
-        alt,
-      </if>
-      <if test="createTime != null">
         create_time,
-      </if>
-      <if test="triggerTimes != null">
-        trigger_times,
-      </if>
-      <if test="status != null">
         `status`,
-      </if>
-    </trim>
-    <trim prefix="values (" suffix=")" suffixOverrides=",">
-      <if test="id != null">
-        #{id,jdbcType=BIGINT},
-      </if>
-      <if test="pid != null">
-        #{pid,jdbcType=BIGINT},
-      </if>
-      <if test="title != null">
-        #{title,jdbcType=VARCHAR},
-      </if>
-      <if test="val != null">
-        #{val,jdbcType=VARCHAR},
-      </if>
-      <if test="content != null">
-        #{content,jdbcType=VARCHAR},
-      </if>
-      <if test="level != null">
-        #{level,jdbcType=INTEGER},
-      </if>
-      <if test="type != null">
-        #{type,jdbcType=INTEGER},
-      </if>
-      <if test="lat != null">
-        #{lat,jdbcType=VARCHAR},
-      </if>
-      <if test="lng != null">
-        #{lng,jdbcType=VARCHAR},
-      </if>
-      <if test="alt != null">
-        #{alt,jdbcType=VARCHAR},
-      </if>
-      <if test="createTime != null">
-        #{createTime,jdbcType=TIMESTAMP},
-      </if>
-      <if test="triggerTimes != null">
-        #{triggerTimes,jdbcType=INTEGER},
-      </if>
-      <if test="status != null">
-        #{status,jdbcType=TINYINT},
-      </if>
-    </trim>
-  </insert>
-  <update id="updateByPrimaryKeySelective" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
-    <!--@mbg.generated-->
-    update kws_alarm
-    <set>
-      <if test="pid != null">
-        pid = #{pid,jdbcType=BIGINT},
-      </if>
-      <if test="title != null">
-        title = #{title,jdbcType=VARCHAR},
-      </if>
-      <if test="val != null">
-        val = #{val,jdbcType=VARCHAR},
-      </if>
-      <if test="content != null">
-        content = #{content,jdbcType=VARCHAR},
-      </if>
-      <if test="level != null">
-        `level` = #{level,jdbcType=INTEGER},
-      </if>
-      <if test="type != null">
-        `type` = #{type,jdbcType=INTEGER},
-      </if>
-      <if test="lat != null">
-        lat = #{lat,jdbcType=VARCHAR},
-      </if>
-      <if test="lng != null">
-        lng = #{lng,jdbcType=VARCHAR},
-      </if>
-      <if test="alt != null">
-        alt = #{alt,jdbcType=VARCHAR},
-      </if>
-      <if test="createTime != null">
-        create_time = #{createTime,jdbcType=TIMESTAMP},
-      </if>
-      <if test="triggerTimes != null">
-        trigger_times = #{triggerTimes,jdbcType=INTEGER},
-      </if>
-      <if test="status != null">
-        `status` = #{status,jdbcType=TINYINT},
-      </if>
-    </set>
-    where id = #{id,jdbcType=BIGINT}
-  </update>
-  <update id="updateByPrimaryKey" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
-    <!--@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}
-    where id = #{id,jdbcType=BIGINT}
-  </update>
+        company_id,
+        mountain_id,
+        project_id,
+        update_time,
+        device_id
+    </sql>
+    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
+        <!--@mbg.generated-->
+        select
+        <include refid="Base_Column_List"/>
+        from kws_alarm
+        where id = #{id,jdbcType=BIGINT}
+    </select>
+
+    <select id="selectByDevicesId" parameterType="java.lang.String" resultType="java.util.Map">
+        <!--@mbg.generated-->
+        select count(id) as count,pid,type
+        from kws_alarm
+        where 1 = 1
+        <if test="devicesId != null and devicesId.size() > 0">
+            AND pid IN
+            <foreach collection="devicesId" open="(" close=")" item="item" separator=",">
+                #{item}
+            </foreach>
+        </if>
+        group by pid, type
+    </select>
+
+    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
+        <!--@mbg.generated-->
+        delete
+        from kws_alarm
+        where id = #{id,jdbcType=BIGINT}
+    </delete>
+    <insert id="insertSelective" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
+        <!--@mbg.generated-->
+        insert into kws_alarm
+        <trim prefix="(" suffix=")" suffixOverrides=",">
+            <if test="id != null">
+                id,
+            </if>
+            <if test="pid != null">
+                pid,
+            </if>
+            <if test="title != null">
+                title,
+            </if>
+            <if test="val != null">
+                val,
+            </if>
+            <if test="content != null">
+                content,
+            </if>
+            <if test="level != null">
+                `level`,
+            </if>
+            <if test="type != null">
+                `type`,
+            </if>
+            <if test="lat != null">
+                lat,
+            </if>
+            <if test="lng != null">
+                lng,
+            </if>
+            <if test="alt != null">
+                alt,
+            </if>
+            <if test="createTime != null">
+                create_time,
+            </if>
+            <if test="triggerTimes != null">
+                trigger_times,
+            </if>
+            <if test="status != null">
+                `status`,
+            </if>
+        </trim>
+        <trim prefix="values (" suffix=")" suffixOverrides=",">
+            <if test="id != null">
+                #{id,jdbcType=BIGINT},
+            </if>
+            <if test="pid != null">
+                #{pid,jdbcType=BIGINT},
+            </if>
+            <if test="title != null">
+                #{title,jdbcType=VARCHAR},
+            </if>
+            <if test="val != null">
+                #{val,jdbcType=VARCHAR},
+            </if>
+            <if test="content != null">
+                #{content,jdbcType=VARCHAR},
+            </if>
+            <if test="level != null">
+                #{level,jdbcType=INTEGER},
+            </if>
+            <if test="type != null">
+                #{type,jdbcType=INTEGER},
+            </if>
+            <if test="lat != null">
+                #{lat,jdbcType=VARCHAR},
+            </if>
+            <if test="lng != null">
+                #{lng,jdbcType=VARCHAR},
+            </if>
+            <if test="alt != null">
+                #{alt,jdbcType=VARCHAR},
+            </if>
+            <if test="createTime != null">
+                #{createTime,jdbcType=TIMESTAMP},
+            </if>
+            <if test="triggerTimes != null">
+                #{triggerTimes,jdbcType=INTEGER},
+            </if>
+            <if test="status != null">
+                #{status,jdbcType=TINYINT},
+            </if>
+        </trim>
+    </insert>
+    <update id="updateByPrimaryKeySelective" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
+        <!--@mbg.generated-->
+        update kws_alarm
+        <set>
+            <if test="pid != null">
+                pid = #{pid,jdbcType=BIGINT},
+            </if>
+            <if test="title != null">
+                title = #{title,jdbcType=VARCHAR},
+            </if>
+            <if test="val != null">
+                val = #{val,jdbcType=VARCHAR},
+            </if>
+            <if test="content != null">
+                content = #{content,jdbcType=VARCHAR},
+            </if>
+            <if test="level != null">
+                `level` = #{level,jdbcType=INTEGER},
+            </if>
+            <if test="type != null">
+                `type` = #{type,jdbcType=INTEGER},
+            </if>
+            <if test="lat != null">
+                lat = #{lat,jdbcType=VARCHAR},
+            </if>
+            <if test="lng != null">
+                lng = #{lng,jdbcType=VARCHAR},
+            </if>
+            <if test="alt != null">
+                alt = #{alt,jdbcType=VARCHAR},
+            </if>
+            <if test="createTime != null">
+                create_time = #{createTime,jdbcType=TIMESTAMP},
+            </if>
+            <if test="triggerTimes != null">
+                trigger_times = #{triggerTimes,jdbcType=INTEGER},
+            </if>
+            <if test="status != null">
+                `status` = #{status,jdbcType=TINYINT},
+            </if>
+        </set>
+        where id = #{id,jdbcType=BIGINT}
+    </update>
+    <update id="updateByPrimaryKey" parameterType="com.sckw.slope.detection.model.dos.mysql.KwsAlarm">
+        <!--@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}
+        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
+        (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
+        <where>
+            <if test="mountainId != null and mountainId != ''">
+                and b.mountain_id = #{mountainId}
+            </if>
+            <if test="level != null and level != ''">
+                and a.level = #{level}
+            </if>
+        </where>
+        ) 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}
+        GROUP BY dateTime
+        ORDER BY dateTime ASC;
+    </select>
+
+    <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
+        (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
+        <where>
+            <if test="mountainId != null and mountainId != ''">
+                and a.mountain_id=#{mountainId}
+            </if>
+            <if test="projectId != null and projectId != ''">
+                and a.project_id=#{projectId}
+            </if>
+            <if test="level != null and level != ''">
+                and a.level=#{level}
+            </if>
+        </where>
+        GROUP BY DATE_FORMAT(b.create_time, '%Y-%m-%d')) b ON a.date = b.date_time
+    </select>
+
+    <select id="getDataAlarmToYear" resultType="java.util.Map">
+        SELECT a.dateTime            AS dateTime,
+               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
+        <where>
+            <if test="mountainId != null and mountainId != ''">
+                and a.mountain_id = #{mountainId}
+            </if>
+            <if test="projectId != null and projectId != ''">
+                and a.project_id = #{projectId}
+            </if>
+            <if test="level != null and level != ''">
+                and a.level = #{level}
+            </if>
+        </where>
+        GROUP BY DATE_FORMAT(b.create_time, '%Y-%m')) b ON a.dateTime = b.dateTime
+    </select>
+
+    <select id="getProjectAlarmList" resultType="java.util.Map">
+        SELECT
+            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
+        GROUP BY a.project_id
+    </select>
 </mapper>

+ 0 - 0
slope-modules/slope-detection/src/main/resources/mapper/tdengine/DeviceMapper.xml → slope-modules/slope-detection/src/main/resources/mapper/tdengine/DeviceMapperBak.xml


+ 126 - 0
slope-modules/slope-detection/src/main/resources/mapper/tdengine/DevicesMapper.xml

@@ -0,0 +1,126 @@
+<?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">
+        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>
+</mapper>

+ 80 - 0
slope-modules/slope-detection/src/main/resources/mapper/tdengine/OriginalMapper.xml

@@ -0,0 +1,80 @@
+<?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.OriginalMapper">
+  <resultMap id="BaseResultMap" type="com.sckw.slope.detection.model.dos.tdengine.Original">
+    <!--@mbg.generated-->
+    <!--@Table original-->
+    <id column="ts" jdbcType="TIMESTAMP" property="ts" />
+    <result column="raw_str" jdbcType="VARCHAR" property="rawStr" />
+    <result column="guid" jdbcType="VARCHAR" property="guid" />
+  </resultMap>
+  <sql id="Base_Column_List">
+    <!--@mbg.generated-->
+    ts, raw_str, guid
+  </sql>
+  <select id="selectByPrimaryKey" parameterType="java.util.Date" resultMap="BaseResultMap">
+    <!--@mbg.generated-->
+    select 
+    <include refid="Base_Column_List" />
+    from devicesv2.original
+    where ts = #{ts,jdbcType=TIMESTAMP}
+  </select>
+  <delete id="deleteByPrimaryKey" parameterType="java.util.Date">
+    <!--@mbg.generated-->
+    delete from devicesv2.original
+    where ts = #{ts,jdbcType=TIMESTAMP}
+  </delete>
+  <insert id="insert" parameterType="com.sckw.slope.detection.model.dos.tdengine.Original">
+    <!--@mbg.generated-->
+    insert into devicesv2.original (ts, raw_str, guid
+      )
+    values (#{ts,jdbcType=TIMESTAMP}, #{rawStr,jdbcType=VARCHAR}, #{guid,jdbcType=VARCHAR}
+      )
+  </insert>
+  <insert id="insertSelective" parameterType="com.sckw.slope.detection.model.dos.tdengine.Original">
+    <!--@mbg.generated-->
+    insert into original
+    <trim prefix="(" suffix=")" suffixOverrides=",">
+      <if test="ts != null">
+        ts,
+      </if>
+      <if test="rawStr != null">
+        raw_str,
+      </if>
+      <if test="guid != null">
+        guid,
+      </if>
+    </trim>
+    <trim prefix="values (" suffix=")" suffixOverrides=",">
+      <if test="ts != null">
+        #{ts,jdbcType=TIMESTAMP},
+      </if>
+      <if test="rawStr != null">
+        #{rawStr,jdbcType=VARCHAR},
+      </if>
+      <if test="guid != null">
+        #{guid,jdbcType=VARCHAR},
+      </if>
+    </trim>
+  </insert>
+  <update id="updateByPrimaryKeySelective" parameterType="com.sckw.slope.detection.model.dos.tdengine.Original">
+    <!--@mbg.generated-->
+    update devicesv2.original
+    <set>
+      <if test="rawStr != null">
+        raw_str = #{rawStr,jdbcType=VARCHAR},
+      </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.Original">
+    <!--@mbg.generated-->
+    update devicesv2.original
+    set raw_str = #{rawStr,jdbcType=VARCHAR},
+      guid = #{guid,jdbcType=VARCHAR}
+    where ts = #{ts,jdbcType=TIMESTAMP}
+  </update>
+</mapper>

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

@@ -6,7 +6,7 @@
         <!--@mbg.generated-->
         <!--@Table slope_data-->
         <id column="ts" jdbcType="TIMESTAMP" property="ts"/>
-        <result column="rawId" jdbcType="TIMESTAMP" property="rawId"/>
+        <result column="rawTs" jdbcType="TIMESTAMP" property="rawId"/>
         <result column="tslverId" jdbcType="TINYINT" property="tslverId"/>
         <result column="guid" jdbcType="VARCHAR" property="guid"/>
         <result column="line" jdbcType="VARCHAR" property="line"/>
@@ -19,7 +19,7 @@
     <select id="selectList" resultType="com.sckw.slope.detection.model.vo.SlopeDataVo">
         <!--        ts, raw_id , device_id, item_name as itemName, item_value as itemValue, create_time as createTime-->
         SELECT ts,
-               raw_id      as rawId,
+               raw_ts      as rawId,
                tslver_id   as tslverId,
                guid,
                line,
@@ -28,11 +28,12 @@
                msg_id      as msgId,
                name,
                json_text   as jsonText
-        FROM devices.slope_data_6_7
+        FROM devicesv2.device_67
     </select>
 
     <sql id="Base_List">
         ts,
+        raw_ts      as rawId,
         tslver_id   as tslverId,
         line,
         val
@@ -41,7 +42,7 @@
         SELECT
         <include refid="Base_List">
         </include>
-        FROM devices.slope_data_#{snCode}
+        FROM devicesv2.device_#{snCode}
         where line = #{item}
         order by ts desc limit 1
     </select>
@@ -50,15 +51,15 @@
         SELECT
         <include refid="Base_List">
         </include>
-        FROM devices.slope_data_#{snCode}
+        FROM devicesv2.device_#{snCode}
         where line = #{item}
         order by ts desc limit 2
     </select>
 
     <insert id="insertData" parameterType="com.sckw.slope.detection.model.dos.tdengine.SlopeData">
-        <!--        insert into devices.slope_data_202_2021-->
-        insert into devices.slope_data_#{slopeData.serialNumber} using devices.slope_data (#{slopeData.tagsTitle}) tags (#{slopeData.tags})
-            (ts, raw_id, tslver_id, guid, line, val, create_time)
+        <!--        insert into devices.devicesv2202_2021-->
+        insert into devicesv2.devices_#{slopeData.serialNumber} using devicesv2.devices (#{slopeData.tagsTitle}) tags (#{slopeData.tags})
+            (ts, raw_ts, tslver_id, guid, line, val, create_time)
         VALUES (#{slopeData.ts}, #{slopeData.rawId},
         #{slopeData.tslverId}, #{slopeData.guid},
         #{slopeData.line}, #{slopeData.val}, #{slopeData.createTime})
@@ -92,7 +93,7 @@
         SELECT
         <include refid="Base_List">
         </include>
-        FROM devices.slope_data
+        FROM devicesv2.devices
 <!--        <if test="(page != null and page !='') and ( pageSize != null and pageSize != '')">-->
         <if test="page != null and pageSize != null ">
             limit #{page},#{pageSize}
@@ -115,6 +116,14 @@
         SELECT
         <include refid="Base_List">
         </include>
-        FROM devices.slope_data
+        FROM devicesv2.devices
+    </select>
+
+    <select id="selectLastData" resultType="com.sckw.slope.detection.model.dos.tdengine.SlopeData">
+        SELECT
+        <include refid="Base_List">
+        </include>
+        FROM devicesv2.device_#{deviceCode}
+        order by ts desc limit 1
     </select>
 </mapper>