Przeglądaj źródła

峰平谷 统计

guoqiang 6 miesięcy temu
rodzic
commit
3157514f27

+ 23 - 17
jeecg-module-gather/src/main/java/org/jeecg/modules/fpgJob/LeanModelStatistics.java

@@ -19,6 +19,7 @@ import org.jeecg.modules.peaksAndValleysTimeConfig.entity.SystemVariable;
 import org.jeecg.modules.peaksAndValleysTimeConfig.service.IPeaksAndValleysTimeConfigService;
 import org.jeecg.modules.peaksAndValleysTimeConfig.service.ISystemVariableService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Sort;
 import org.springframework.data.mongodb.core.MongoTemplate;
 import org.springframework.data.mongodb.core.query.Criteria;
 import org.springframework.data.mongodb.core.query.Query;
@@ -156,7 +157,7 @@ public class LeanModelStatistics {
             // 采集点组合
 //            List<String> idsPoint = devicePointList.stream().map(DevicePoint::getId).collect(Collectors.toList());
             // 查询设备对应数据
-            LambdaQueryWrapper<FpgGatherData> fpgGatherQuery = new LambdaQueryWrapper<FpgGatherData>().isNull(FpgGatherData::getFpgTotalUpdatetime).eq(FpgGatherData::getDeviceInformationId, deviceInformationlinfo.getId());
+            LambdaQueryWrapper<FpgGatherData> fpgGatherQuery = new LambdaQueryWrapper<FpgGatherData>().isNull(FpgGatherData::getFpgTotalUpdatetime).eq(FpgGatherData::getDeviceInformationId, deviceInformationlinfo.getId()).isNotNull(FpgGatherData::getRunCurrent).isNotNull(FpgGatherData::getActivePower).orderByAsc(FpgGatherData::getCreateTime);
             List<FpgGatherData> fpgGatherList = fpgGatherDataService.list(fpgGatherQuery);
 
             // 系统变量查询
@@ -195,25 +196,23 @@ public class LeanModelStatistics {
                     // 运行时常
                     BigDecimal runTime = new BigDecimal("300");
                     // 电流
-                    BigDecimal selectricCurrent = fpgGatherData.getRunCurrent();
+                    BigDecimal selectricCurrent = fpgGatherData.getRunCurrent().compareTo(new BigDecimal("0.00")) > 0 ? fpgGatherData.getRunCurrent().divide(new BigDecimal(12), 6, RoundingMode.HALF_UP) : fpgGatherData.getRunCurrent();
                     // 设备启停统计 start
                     String startStopMonKey = "total_startstop";
                     DeviceStatiscsModelData startStopStatiscsData = new DeviceStatiscsModelData(fpgGatherData, startStopMonKey, dayDate, classs, curentDate, curentDate);
                     // 组合mongodb条件
                     Query queryStartStop = new Query()
                             .addCriteria(Criteria.where("deviceRegionId").is(fpgGatherData.getDeviceRegionId()))
-                            .addCriteria(Criteria.where("deviceInformationId").is(fpgGatherData.getDeviceInformationId()));
-                    // 设备停止 start
-                    if(fpgGatherData.getRunCurrent().compareTo(new BigDecimal(systemVariable.getDefaultValue())) < 0){ // 设备停止运行 直接更新停止时间结束不用统计任何东西
-//                        queryStartStop.addCriteria(Criteria.where("deviceStopTime").is(null));
-                        UpdateDefinition updateStartStop = new Update()
-                                .set("updateTime", curentDate).set("deviceStopTime", DateUtils.date2Str(curentDate, DateUtils.datetimeFormat.get()));
-                        mongoTemplate.updateFirst(queryStartStop, updateStartStop, DeviceStatiscsModelMongodb.class, startStopMonKey);
-                        return;
-                    } else { // 设备运行状态
-                        // 查找上一次运行记录
-                        DeviceStatiscsModelMongodb startStopMongo = mongoTemplate.findOne(queryStartStop, DeviceStatiscsModelMongodb.class, startStopMonKey);
-                        if(startStopMongo != null){
+                            .addCriteria(Criteria.where("deviceInformationId").is(fpgGatherData.getDeviceInformationId())).with(Sort.by(Sort.Order.desc("deviceStartTime")));
+                    // 查找设备运行记录
+                    DeviceStatiscsModelMongodb startStopMongo = mongoTemplate.findOne(queryStartStop, DeviceStatiscsModelMongodb.class, startStopMonKey);
+                    if(startStopMongo != null){
+                        if(fpgGatherData.getRunCurrent().compareTo(new BigDecimal(systemVariable.getDefaultValue())) < 0){ // 设备停止运行 直接更新停止时间结束不用统计任何东西
+                            UpdateDefinition updateStartStop = new Update()
+                                    .set("updateTime", curentDate).set("deviceStopTime", DateUtils.date2Str(curentDate, DateUtils.datetimeFormat.get()));
+                            mongoTemplate.updateFirst(queryStartStop, updateStartStop, DeviceStatiscsModelMongodb.class, startStopMonKey);
+                            return;
+                        } else { // 设备运行累加
                             // 历史数据
                             BigDecimal oldPower = startStopMongo.getPower() == null ? new BigDecimal("0.00") : startStopMongo.getPower();
                             BigDecimal oldRunTime = startStopMongo.getIngTime() == null ? new BigDecimal("0.00") : startStopMongo.getIngTime();
@@ -225,7 +224,13 @@ public class LeanModelStatistics {
                                     .set("ingTime", oldRunTime.add(runTime))
                                     .set("updateTime", curentDate);
                             mongoTemplate.updateFirst(queryStartStop, updateStartStop, FpgStatiscsModelMongodb.class, startStopMonKey);
-                        } else { // 直接插入
+                        }
+                    } else { // 直接插入
+                        if(fpgGatherData.getRunCurrent().compareTo(new BigDecimal(systemVariable.getDefaultValue())) > 0){ // 运行中计入启停记录
+                            startStopStatiscsData.setPower(runPower);
+                            startStopStatiscsData.setDeviceStopTime(null);
+                            startStopStatiscsData.setIngTime(runTime);
+                            startStopStatiscsData.setSelectricCurrent(runTime);
                             mongoTemplate.insert(startStopStatiscsData, startStopMonKey);
                         }
                     }
@@ -329,11 +334,12 @@ public class LeanModelStatistics {
         List<FpgGatherData> fpgGatherUpdateList= new ArrayList<>();
         // 遍历设备集合
         fpgLeanModellist.forEach(fpgLeanModeInfo -> {
-            LambdaQueryWrapper<FpgGatherData> fpgGatherQuery = new LambdaQueryWrapper<FpgGatherData>().isNull(FpgGatherData::getFpgModelUpdatetime);
+            LambdaQueryWrapper<FpgGatherData> fpgGatherQuery = new LambdaQueryWrapper<FpgGatherData>().isNull(FpgGatherData::getFpgModelUpdatetime).isNotNull(FpgGatherData::getRunCurrent).isNotNull(FpgGatherData::getActivePower);
             // 检测是否配置设备特殊条件
             if(oConvertUtils.isNotEmpty(fpgLeanModeInfo.getDeviceInformationIds()) && oConvertUtils.isNotEmpty(fpgLeanModeInfo.getDeviceInformationIds())){
                 fpgGatherQuery.in(FpgGatherData::getDeviceInformationId, Arrays.asList(fpgLeanModeInfo.getDeviceInformationIds().split(",")));
             }
+            fpgGatherQuery.orderByAsc(FpgGatherData::getCreateTime);
             List<FpgGatherData> fpgGatherList = fpgGatherDataService.list(fpgGatherQuery);
             // 处理数据业务逻辑
             fpgGatherList.forEach(fpgGatherData -> { // 循环处理采集数据处理
@@ -413,7 +419,7 @@ public class LeanModelStatistics {
                         // 功率 5 分钟上报一次  除以 12
                         BigDecimal activePower = fpgGatherData.getActivePower() == null ? new BigDecimal("0.00") : fpgGatherData.getActivePower().divide(new BigDecimal("12"), 6, RoundingMode.HALF_UP);
                         // 电流
-                        BigDecimal selectricCurrent = fpgGatherData.getRunCurrent() == null ? new BigDecimal("0.00") : fpgGatherData.getRunCurrent();
+                        BigDecimal selectricCurrent = fpgGatherData.getRunCurrent() == null ? new BigDecimal("0.00") : fpgGatherData.getRunCurrent().divide(new BigDecimal("12"), 6, RoundingMode.HALF_UP);
                         BigDecimal runTime = new BigDecimal("300");
                         BigDecimal oldPower = fpgStatiscsModelMongo.getPower() == null ? new BigDecimal("0.00") : fpgStatiscsModelMongo.getPower();
                         BigDecimal oldingTime = fpgStatiscsModelMongo.getIngTime() == null ? new BigDecimal("0.00") : fpgStatiscsModelMongo.getIngTime();

+ 3 - 3
jeecg-module-gather/src/main/java/org/jeecg/modules/gatherData/entity/DeviceStatiscsModelData.java

@@ -102,9 +102,9 @@ public class DeviceStatiscsModelData {
         // 基础信息配置
         this.deviceRegionId = fpgGather.getDeviceRegionId(); // 区域id
         this.deviceInformationId = fpgGather.getDeviceInformationId(); // 设备id
-        this.ingTime = new BigDecimal("0.00"); // 累计时长
-        this.selectricCurrent = new BigDecimal("0.00"); // 累计总电流
-        this.power = new BigDecimal("0.00"); // 累计功率
+        this.ingTime = new BigDecimal("300"); // 累计时长
+        this.selectricCurrent = fpgGather.getRunCurrent(); // 累计总电流
+        this.power = fpgGather.getActivePower(); // 累计功率
         this.classs = classs;
         if("total_day_powerproportioncurrent".equals(totalType)){ // 日统计尖峰平谷数据(功率+占比+电流+运行时长)
             this.topsPower = new BigDecimal("0.00"); // 功率

+ 0 - 1
jeecg-module-gather/src/main/java/org/jeecg/modules/gatherData/entity/FpgGatherData.java

@@ -96,7 +96,6 @@ public class FpgGatherData implements Serializable {
     @ApiModelProperty(value = "峰平谷模型使用完成更新")
     private java.util.Date fpgModelUpdatetime;
 
-
     /**峰平谷类型*/
     @Excel(name = "事件告警使用状态", width = 15)
     @ApiModelProperty(value = "事件告警使用状态")

+ 0 - 64
jeecg-module-gather/src/main/java/org/jeecg/modules/utils/ConnectionUtils.java

@@ -1,64 +0,0 @@
-package org.jeecg.modules.utils;
-
-import java.sql.*;
-
-/**
- * @author llp
- * date: 2024-11-29 13:20
- * Description: PostgreSQL 连接工具类
- */
-public class ConnectionUtils {
-
-    // PostgreSQL JDBC 连接URL
-    private static final String URL = "jdbc:postgresql://192.168.13.197:5432/epower?useUnicode=true&ssl=false&currentSchema=history";
-    private static final String USERNAME = "postgres"; // PostgreSQL 用户名
-    private static final String PASSWORD = "1qaz2wsx..";     // PostgreSQL 密码
-
-    /**
-     * 获取连接
-     * */
-    public static Connection getConnection() throws Exception {
-        // 加载 PostgreSQL JDBC 驱动
-        Class.forName("org.postgresql.Driver");
-        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
-    }
-
-    /**
-     * 关闭连接
-     * */
-    public static void closeConnection(Connection conn) {
-        try {
-            if (conn != null) {
-                conn.close();
-            }
-        } catch (SQLException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * 关闭 SQL 执行对象
-     * */
-    public static void closeStatement(Statement stmt) {
-        try {
-            if (stmt != null) {
-                stmt.close();
-            }
-        } catch (SQLException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * 关闭结果集
-     * */
-    public static void closeResultSet(ResultSet rs) {
-        try {
-            if (rs != null) {
-                rs.close();
-            }
-        } catch (SQLException e) {
-            e.printStackTrace();
-        }
-    }
-}

+ 52 - 0
jeecg-module-gather/src/main/java/org/jeecg/modules/utils/PostgreSQLUtil.java

@@ -0,0 +1,52 @@
+package org.jeecg.modules.utils;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class PostgreSQLUtil {
+
+    private static HikariDataSource dataSource;
+
+    static {
+        HikariConfig config = new HikariConfig();
+        config.setJdbcUrl("jdbc:postgresql://192.168.13.197:5432/epower?useUnicode=true&ssl=false&currentSchema=history");
+        config.setUsername("postgres");
+        config.setPassword("1qaz2wsx..");
+        config.setDriverClassName("org.postgresql.Driver");
+        config.setMaximumPoolSize(10); // 最大连接数
+        config.setMinimumIdle(5);      // 最小空闲连接数
+        config.setIdleTimeout(30000);  // 空闲连接超时时间(毫秒)
+        config.setConnectionTimeout(30000); // 连接超时时间(毫秒)
+        config.setMaxLifetime(1800000); // 连接最大生命周期(毫秒)
+
+        dataSource = new HikariDataSource(config);
+    }
+
+    public static Connection getConnection() throws SQLException {
+        return dataSource.getConnection();
+    }
+
+    public static void close(Connection connection) {
+        if (connection != null) {
+            try {
+                connection.close();
+            } catch (SQLException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    // 关闭连接池
+    public static void shutdown() {
+        if (dataSource != null) {
+            dataSource.close();
+        }
+    }
+
+    private PostgreSQLUtil() {
+        // 私有构造函数,防止实例化
+    }
+}

+ 0 - 239
jeecg-module-gather/src/main/java/org/jeecg/modules/watch/MysqlWatch.java

@@ -1,239 +0,0 @@
-package org.jeecg.modules.watch;
-
-import com.alibaba.fastjson.JSON;
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import lombok.extern.slf4j.Slf4j;
-import org.jeecg.modules.device.entity.DeviceInformation;
-import org.jeecg.modules.device.mapper.DeviceInformationMapper;
-import org.jeecg.modules.device.mapper.DeviceRegionMapper;
-import org.jeecg.modules.devicePoint.entity.DevicePoint;
-import org.jeecg.modules.devicePoint.mapper.DevicePointMapper;
-import org.jeecg.modules.gatherData.entity.FpgGatherData;
-import org.jeecg.modules.gatherData.entity.FpgGatherDataMongo;
-import org.jeecg.modules.gatherData.mapper.FpgGatherDataMapper;
-import org.jeecg.modules.peaksAndValleysTimeConfig.entity.SystemVariable;
-import org.jeecg.modules.peaksAndValleysTimeConfig.service.ISystemVariableService;
-import org.jeecg.modules.utils.ConnectionUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.scheduling.annotation.EnableAsync;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-
-import java.math.BigDecimal;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@Slf4j
-@EnableAsync
-@Component
-public class MysqlWatch {
-
-    @Autowired
-    DeviceRegionMapper deviceRegionMapper;
-
-    @Autowired
-    DeviceInformationMapper deviceInformationMapper;
-
-    @Autowired
-    DevicePointMapper devicePointMapper;
-
-    @Autowired
-    FpgGatherDataMapper fpgGatherDataMapper;
-
-    @Autowired
-    ISystemVariableService systemVariableService;
-
-    @Autowired
-    MongoTemplate mongoTemplate;
-
-
-    @Scheduled(cron = "0 0/1 * * * ?")
-    public void getTsData() {
-        Connection connection = null;
-        Statement statement = null;
-        ResultSet resultSet = null;
-        try {
-            connection = ConnectionUtils.getConnection();
-
-            // 用于存放合并后的 FpgGatherData,键为 "DeviceInformationId-CreateTime"
-            Map<String, FpgGatherData> mergedDataMap = new HashMap<>();
-
-            LambdaQueryWrapper<DeviceInformation> informationLambdaQueryWrapper = new LambdaQueryWrapper<>();
-            List<DeviceInformation> devices = deviceInformationMapper.selectList(informationLambdaQueryWrapper);
-
-            // 遍历所有设备
-            for (DeviceInformation device : devices) {
-                LambdaQueryWrapper<DevicePoint> devicePointLambdaQueryWrapper = new LambdaQueryWrapper<>();
-                devicePointLambdaQueryWrapper.eq(DevicePoint::getDeviceId, device.getId());
-                List<DevicePoint> devicePoints = devicePointMapper.selectList(devicePointLambdaQueryWrapper);
-
-                // 查询 FpgGatherData 表中 该设备下的createTime 最新的一条记录
-                LambdaQueryWrapper<FpgGatherData> fpgGatherDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
-                fpgGatherDataLambdaQueryWrapper.eq(FpgGatherData::getDeviceInformationId, device.getId());
-                fpgGatherDataLambdaQueryWrapper
-                        .orderByDesc(FpgGatherData::getCreateTime) // 按 createTime 降序排序
-                        .last("LIMIT 1"); // 只取一条记录
-
-                // 执行查询
-                FpgGatherData latestData = fpgGatherDataMapper.selectOne(fpgGatherDataLambdaQueryWrapper);
-
-                // 获取最新记录的 createTime
-                Date latestCreateTime1 = null;
-                if (latestData != null) {
-                    latestCreateTime1 = latestData.getCreateTime();
-
-                } else {
-                    // 如果没有找到记录,给一个默认时间
-                    latestCreateTime1 = new Date(0); // 默认时间设置为 1970-01-01 00:00:00
-                }
-                // 遍历设备点
-                for (DevicePoint point : devicePoints) {
-
-                    // 假设 latestCreateTime 是从 FpgGatherData 中获取的最新 createTime
-                    Date latestCreateTime = latestCreateTime1;
-
-                    // 格式化 latestCreateTime 为 "yyyy-MM-dd HH:mm:ss" 格式的字符串
-                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-                    String formattedTime = dateFormat.format(latestCreateTime);
-                    String sql = "SELECT * FROM ts_value WHERE tagname='" + point.getPointCode() +
-                            "' AND timestamp > '" + formattedTime + "' ORDER BY timestamp DESC";
-                    statement = connection.createStatement();
-                    resultSet = statement.executeQuery(sql);
-
-                    // 遍历查询到的实时数据
-                    while (resultSet.next()) {
-                        Date timestamp = dateFormat.parse(resultSet.getString("timestamp"));
-                        BigDecimal value = new BigDecimal(resultSet.getString("value"));
-
-                        // 生成分组键
-                        String groupKey = device.getId() + "-" + dateFormat.format(timestamp);
-
-                        // 获取或创建 FpgGatherData
-                        FpgGatherData fpgGatherData = mergedDataMap.getOrDefault(groupKey, new FpgGatherData());
-                        fpgGatherData.setDeviceInformationId(device.getId());
-                        fpgGatherData.setDeviceRegionId(device.getDeviceRegionId());
-                        fpgGatherData.setCreateTime(timestamp);
-                        fpgGatherData.setUpdateTime(timestamp);
-
-                        // 处理 DevicePointId 的拼接
-                        String devicePointIdValue = fpgGatherData.getDevicePointId();
-                        String pointIdStr = point.getId().toString();
-                        if ("Ia".equals(point.getCurrentPower())) {
-                            // "Ia" 的 pointId 放在最前
-                            devicePointIdValue = (devicePointIdValue == null || devicePointIdValue.isEmpty())
-                                    ? pointIdStr
-                                    : pointIdStr + (devicePointIdValue.contains(pointIdStr) ? "" : "," + devicePointIdValue);
-                        } else if ("P".equals(point.getCurrentPower())) {
-                            // "P" 的 pointId 放在最后
-                            devicePointIdValue = (devicePointIdValue == null || devicePointIdValue.isEmpty())
-                                    ? pointIdStr
-                                    : (devicePointIdValue.contains(pointIdStr) ? devicePointIdValue : devicePointIdValue + "," + pointIdStr);
-                        }
-                        fpgGatherData.setDevicePointId(devicePointIdValue);
-
-                        // 处理数据点类型和值的累计
-                        if ("Ia".equals(point.getCurrentPower())) {
-                            fpgGatherData.setRunCurrent(
-                                    (fpgGatherData.getRunCurrent() == null ? BigDecimal.ZERO : fpgGatherData.getRunCurrent()).add(value)
-                            );
-                        } else if ("P".equals(point.getCurrentPower())) {
-                            fpgGatherData.setActivePower(
-                                    (fpgGatherData.getActivePower() == null ? BigDecimal.ZERO : fpgGatherData.getActivePower()).add(value)
-                            );
-                        }
-
-                        // 更新到 Map
-                        mergedDataMap.put(groupKey, fpgGatherData);
-                    }
-                }
-            }
-
-            // 保存合并数据到数据库
-            for (FpgGatherData data : mergedDataMap.values()) {
-                // 检查数据库中是否存在相同 DeviceInformationId 和 CreateTime 的记录
-                FpgGatherData existingData = fpgGatherDataMapper.selectOne(
-                        new LambdaQueryWrapper<FpgGatherData>()
-                                .eq(FpgGatherData::getDeviceInformationId, data.getDeviceInformationId())
-                                .eq(FpgGatherData::getCreateTime, data.getCreateTime())
-                );
-                // 根据采集到的数据 创建时间,跟峰平谷配置的时间,判断属于哪个时段(尖、峰、平、谷)
-                QueryWrapper<SystemVariable> queryWrapper = new QueryWrapper<>();
-                queryWrapper.eq("variable_address", "sys_run_current_limit");
-                queryWrapper.eq("status", 0);
-                SystemVariable systemVariable = systemVariableService.getOne(queryWrapper);
-
-                // 如果 systemVariable 为空,则不执行后续操作
-                if (systemVariable == null) {
-                    log.info("{}{}", "fpg_close系统变量未配置正常状态的运行电流限制!", JSON.toJSON(data));
-                } else {
-                    DeviceInformation deviceInformation = deviceInformationMapper.selectOne(
-                            new LambdaQueryWrapper<DeviceInformation>()
-                                    .eq(DeviceInformation::getId, data.getDeviceInformationId())
-                    );
-
-                    // 比较大小
-                    int result = compareStringWithBigDecimal(systemVariable.getDefaultValue(), data.getRunCurrent());
-
-                    if (result > 0) {
-                        deviceInformation.setStatus("1");
-                    } else if (result < 0) {
-                        deviceInformation.setStatus("0");
-                    }
-
-                    // 只有在 systemVariable 不为空时才进行更新操作
-                    deviceInformationMapper.updateById(deviceInformation);
-                }
-
-                // 如果不存在则插入
-                if (existingData == null) {
-                    fpgGatherDataMapper.insert(data);
-                }
-
-                // 转为 MongoDB 对象并同步
-                FpgGatherDataMongo mongoData = new FpgGatherDataMongo();
-                mongoData.setDeviceInformationId(data.getDeviceInformationId());
-                mongoData.setDeviceRegionId(data.getDeviceRegionId());
-                mongoData.setCreateTime(data.getCreateTime());
-                mongoData.setUpdateTime(data.getUpdateTime());
-                mongoData.setRunCurrent(data.getRunCurrent());
-                mongoData.setActivePower(data.getActivePower());
-
-                Query query = new Query();
-                query.addCriteria(Criteria.where("deviceInformationId").is(data.getDeviceInformationId()))
-                        .addCriteria(Criteria.where("createTime").is(data.getCreateTime()));
-
-                // 如果 MongoDB 中不存在记录则插入
-                FpgGatherDataMongo existingMongoData = mongoTemplate.findOne(query, FpgGatherDataMongo.class, "fpgGatherData");
-                if (existingMongoData == null) {
-                    mongoTemplate.save(mongoData, "fpgGatherData");
-                }
-            }
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        } finally {
-            ConnectionUtils.closeConnection(connection);
-            ConnectionUtils.closeStatement(statement);
-            ConnectionUtils.closeResultSet(resultSet);
-        }
-    }
-
-
-    public static int compareStringWithBigDecimal(String str, BigDecimal bd) {
-        // 将 String 转换为 BigDecimal
-        BigDecimal strAsBigDecimal = new BigDecimal(str);
-
-        // 使用 BigDecimal 的 compareTo 方法比较
-        return strAsBigDecimal.compareTo(bd);
-    }
-
-}

+ 210 - 0
jeecg-module-gather/src/main/java/org/jeecg/modules/watch/PostgreSQLWatch.java

@@ -0,0 +1,210 @@
+package org.jeecg.modules.watch;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import lombok.extern.slf4j.Slf4j;
+import org.jeecg.common.util.DateUtils;
+import org.jeecg.modules.device.entity.DeviceInformation;
+import org.jeecg.modules.device.mapper.DeviceInformationMapper;
+import org.jeecg.modules.device.mapper.DeviceRegionMapper;
+import org.jeecg.modules.devicePoint.entity.DevicePoint;
+import org.jeecg.modules.devicePoint.mapper.DevicePointMapper;
+import org.jeecg.modules.gatherData.entity.FpgGatherData;
+import org.jeecg.modules.gatherData.mapper.FpgGatherDataMapper;
+import org.jeecg.modules.peaksAndValleysTimeConfig.entity.SystemVariable;
+import org.jeecg.modules.peaksAndValleysTimeConfig.service.ISystemVariableService;
+import org.jeecg.modules.utils.PostgreSQLUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.mongodb.core.MongoTemplate;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.math.BigDecimal;
+import java.sql.*;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Slf4j
+@EnableAsync
+@Component
+public class PostgreSQLWatch {
+
+    @Autowired
+    DeviceRegionMapper deviceRegionMapper;
+
+    @Autowired
+    DeviceInformationMapper deviceInformationMapper;
+
+    @Autowired
+    DevicePointMapper devicePointMapper;
+
+    @Autowired
+    FpgGatherDataMapper fpgGatherDataMapper;
+
+    @Autowired
+    ISystemVariableService systemVariableService;
+
+    @Autowired
+    MongoTemplate mongoTemplate;
+
+    @Scheduled(fixedDelay = 2000)
+    public void getTsData() {
+        Connection connection = null;
+        PreparedStatement statement = null;
+        ResultSet resultSet = null;
+        log.info("抓取采集数据");
+        try {
+            // 建立链接
+            connection = PostgreSQLUtil.getConnection();;
+            boolean isClosed = connection.isClosed();
+            LambdaQueryWrapper<DeviceInformation> informationLambdaQueryWrapper = new LambdaQueryWrapper<>();
+            List<DeviceInformation> devices = deviceInformationMapper.selectList(informationLambdaQueryWrapper);
+            // 遍历所有设备
+            for (DeviceInformation device : devices) {
+                LambdaQueryWrapper<DevicePoint> devicePointLambdaQueryWrapper = new LambdaQueryWrapper<>();
+                devicePointLambdaQueryWrapper.eq(DevicePoint::getDeviceId, device.getId());
+                List<DevicePoint> devicePoints = devicePointMapper.selectList(devicePointLambdaQueryWrapper);
+                // 查询 FpgGatherData 表中 该设备下的createTime 最新的一条记录
+                LambdaQueryWrapper<FpgGatherData> fpgGatherDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
+                fpgGatherDataLambdaQueryWrapper.eq(FpgGatherData::getDeviceInformationId, device.getId());
+                fpgGatherDataLambdaQueryWrapper
+                        .orderByDesc(FpgGatherData::getCreateTime) // 按 createTime 降序排序
+                        .last("LIMIT 1"); // 只取一条记录
+                // 执行查询
+                FpgGatherData latestData = fpgGatherDataMapper.selectOne(fpgGatherDataLambdaQueryWrapper);
+                // 获取最新记录的 createTime
+                Date latestCreateTime1 = null;
+                if (latestData != null) {
+                    latestCreateTime1 = latestData.getCreateTime();
+                } else {
+                    // 如果没有找到记录,给一个默认时间
+                    latestCreateTime1 = new Date(0); // 默认时间设置为 1970-01-01 00:00:00
+                }
+                // 根据采集到的数据 创建时间,跟峰平谷配置的时间,判断属于哪个时段(尖、峰、平、谷)
+                QueryWrapper<SystemVariable> queryWrapper = new QueryWrapper<>();
+                queryWrapper.eq("variable_address", "sys_run_current_limit");
+                queryWrapper.eq("status", 0);
+                SystemVariable systemVariable = systemVariableService.getOne(queryWrapper);
+                // 生成PointCode集合
+                List<String> pointCodeList = devicePoints.stream().map(DevicePoint::getPointCode).collect(Collectors.toList());
+                List<String> pointIdList = devicePoints.stream().map(DevicePoint::getId).collect(Collectors.toList());
+                // pointCodeList转换String
+                String pointCodeListStr = String.join("','", pointCodeList);
+                String pointIdListStrs = String.join(",", pointIdList);
+                // 日期转字符串
+                String formattedTime = DateUtils.date2Str(latestCreateTime1, DateUtils.datetimeFormat.get());
+                String sql = String.format("SELECT * FROM ts_value WHERE tagname IN ('%s') AND timestamp > '%s' ORDER BY timestamp ASC", pointCodeListStr, formattedTime);
+                statement = connection.prepareStatement(sql);
+                resultSet = statement.executeQuery();
+                // 遍历查询到的实时数据
+                while (resultSet.next()) {
+                    DevicePoint point = devicePointMapper.selectOne(
+                            new LambdaQueryWrapper<DevicePoint>()
+                                    .eq(DevicePoint::getPointCode, resultSet.getString("tagname") )
+                    );
+                    log.info(resultSet.getString("tagname") + "////////" + resultSet.getString("timestamp") + "////////" + resultSet.getString("value"));
+                    Date timestamp = DateUtils.str2Date(resultSet.getString("timestamp"), DateUtils.datetimeFormat.get());
+                    BigDecimal value = new BigDecimal(resultSet.getString("value"));
+                    // 检查FpgGatherData 数据库中是否存在相同 DeviceInformationId 和 CreateTime 的记录
+                    FpgGatherData fpgGatherData = fpgGatherDataMapper.selectOne(
+                            new LambdaQueryWrapper<FpgGatherData>()
+                                    .eq(FpgGatherData::getDeviceInformationId, point.getDeviceId())
+                                    .eq(FpgGatherData::getCreateTime, timestamp)
+                    );
+                    if (fpgGatherData == null) { // 直接新增
+                        FpgGatherData fpgGatherInsert = new FpgGatherData();
+                        fpgGatherInsert.setCreateTime(timestamp);
+                        // 处理电流+电压
+                        if ("Ia".equals(point.getCurrentPower())) {
+                            fpgGatherInsert.setRunCurrent(value);
+                        } else if ("P".equals(point.getCurrentPower())) {
+                            fpgGatherInsert.setActivePower(value);
+                        }
+                        fpgGatherInsert.setDevicePointId(pointIdListStrs);
+                        fpgGatherInsert.setDeviceInformationId(point.getDeviceId());
+                        fpgGatherInsert.setDeviceRegionId(device.getDeviceRegionId());
+                        log.info("新增----数据处理---");
+                        log.info(JSON.toJSONString(fpgGatherInsert));
+                        fpgGatherDataMapper.insert(fpgGatherInsert);
+                    } else { // 编辑处理
+                        log.info("修改---前数据----数据处理---" + value);
+                        log.info(JSON.toJSONString(fpgGatherData));
+                        // 处理数据点类型和值的累计
+                        if ("Ia".equals(point.getCurrentPower())) {
+                            BigDecimal runCurrent = fpgGatherData.getRunCurrent() == null ? value : fpgGatherData.getRunCurrent().add(value);
+                            fpgGatherData.setRunCurrent(runCurrent);
+                        } else if ("P".equals(point.getCurrentPower())) {
+                            BigDecimal activePower = fpgGatherData.getActivePower() == null ? value : fpgGatherData.getActivePower().add(value);
+                            fpgGatherData.setActivePower(activePower);
+                        }
+                        fpgGatherData.setId(fpgGatherData.getId());
+                        log.info("修改---后数据----数据处理---");
+                        log.info(JSON.toJSONString(fpgGatherData));
+                        fpgGatherDataMapper.updateById(fpgGatherData);
+                    }
+                    // 如果 systemVariable 为空,则不执行后续操作 更新设备状态
+                    if ("Ia".equals(point.getCurrentPower()) && systemVariable == null) {
+                        log.info("{}{}", "fpg_close系统变量未配置正常状态的运行电流限制!", JSON.toJSON(fpgGatherData));
+                    } else if("Ia".equals(point.getCurrentPower())) {
+                        DeviceInformation deviceInformation = deviceInformationMapper.selectOne(
+                                new LambdaQueryWrapper<DeviceInformation>()
+                                        .eq(DeviceInformation::getId, point.getDeviceId())
+                        );
+                        // 比较大小
+                        int result = compareStringWithBigDecimal(systemVariable.getDefaultValue(), value);
+                        if (result > 0) {
+                            deviceInformation.setStatus("1");
+                        } else if (result < 0) {
+                            deviceInformation.setStatus("0");
+                        }
+                        // 只有在 systemVariable 不为空时才进行更新操作
+                        deviceInformationMapper.updateById(deviceInformation);
+                    }
+                }
+                // 关闭连接
+                resultSet.close();
+                statement.close();
+            }
+        } catch (Exception e) {
+            // 关闭连接
+            log.info(e.getMessage());
+        } finally {
+            PostgreSQLUtil.close(connection);
+        }
+    }
+
+
+    public static int compareStringWithBigDecimal(String str, BigDecimal bd) {
+        // 将 String 转换为 BigDecimal
+        BigDecimal strAsBigDecimal = new BigDecimal(str);
+
+        // 使用 BigDecimal 的 compareTo 方法比较
+        return strAsBigDecimal.compareTo(bd);
+    }
+
+
+//    public static void main(String[] args) {
+//        Connection connection = null;
+//        PreparedStatement preparedStatement = null;
+//        ResultSet resultSet = null;
+//        try {
+//            int i = 0;
+//            connection = PostgreSQLUtil.getConnection();
+//            String sql = "SELECT * FROM ts_value WHERE tagname = 'YC.10330' AND timestamp > '2024-12-03 11:20:01' ORDER BY timestamp ASC";
+//            preparedStatement = connection.prepareStatement(sql);
+//            resultSet = preparedStatement.executeQuery();
+//            while (resultSet.next()) {
+//                i++;
+//                log.info("{}{}", "查询的数据结果:", "时间:" + resultSet.getString("timestamp") + "电流值" + resultSet.getString("value"));
+//            }
+//            log.info("{}{}",">>>>>>>>>>>>>>>>>>查询PG总条数:", i);
+//        } catch (SQLException e) {
+//            log.info("{}",">>>>>>>>>>>>>>>>>>查询PG总条数:");
+//        } finally {
+//
+//        }
+//    }
+}

+ 2 - 2
jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml

@@ -169,8 +169,8 @@ spring:
           slow-sql-millis: 5000
       datasource:
         master:
-          url: jdbc:mysql://127.0.0.1/lg?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
-#          url: jdbc:mysql://123.57.213.14/jeecg-boot?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
+#          url: jdbc:mysql://127.0.0.1/lg?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
+          url: jdbc:mysql://123.57.213.14/jeecg-boot?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
           username: root
           password: 1qaz2wsx@..
           driver-class-name: com.mysql.cj.jdbc.Driver