From 318ebac926b9627a683c4ab90d4e2b7451b1e573 Mon Sep 17 00:00:00 2001
From: baoshiwei <baoshiwei@shlanbao.cn>
Date: 星期三, 18 六月 2025 13:43:55 +0800
Subject: [PATCH] feat(engine): 新增全厂总电量统计功能

---
 src/main/java/com/zhitan/engine/influxdb/InfluxdbRepository.java          |   42 ++++++++++
 src/main/java/com/zhitan/engine/scheduler/DataCleaningScheduler.java      |   38 +++++++++
 src/main/java/com/zhitan/engine/service/DataCleaningService.java          |    7 +
 src/main/java/com/zhitan/engine/service/impl/DataCleaningServiceImpl.java |  101 +++++++++++++++++++++++++
 pom.xml                                                                   |    8 ++
 src/main/resources/application.yml                                        |    8 +-
 6 files changed, 199 insertions(+), 5 deletions(-)

diff --git a/pom.xml b/pom.xml
index 44716f8..97977ca 100644
--- a/pom.xml
+++ b/pom.xml
@@ -120,6 +120,14 @@
                     </execution>
                 </executions>
             </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>9</source>
+                    <target>9</target>
+                </configuration>
+            </plugin>
         </plugins>
         <finalName>${project.artifactId}</finalName>
     </build>
diff --git a/src/main/java/com/zhitan/engine/influxdb/InfluxdbRepository.java b/src/main/java/com/zhitan/engine/influxdb/InfluxdbRepository.java
index 9e669e5..b0fc9f7 100644
--- a/src/main/java/com/zhitan/engine/influxdb/InfluxdbRepository.java
+++ b/src/main/java/com/zhitan/engine/influxdb/InfluxdbRepository.java
@@ -7,6 +7,7 @@
 import com.influxdb.client.WriteApiBlocking;
 import com.influxdb.client.domain.HealthCheck;
 import com.influxdb.client.domain.WritePrecision;
+import com.influxdb.client.write.Point;
 import com.zhitan.engine.enums.CollectionModes;
 import com.zhitan.engine.enums.GroupTimeType;
 import com.zhitan.engine.enums.Quality;
@@ -76,6 +77,16 @@
         write.writeMeasurements(WritePrecision.MS, writePoints);
     }
 
+    /**
+     * 鍐欏叆鍗曚釜鐐逛綅
+     */
+    public void writePoint(Point point) {
+        if (null == point) {
+            return;
+        }
+        WriteApiBlocking writeApi = client.getWriteApiBlocking();
+        writeApi.writePoint(point);
+    }
     public TagValue query(String tagCode, Date time) {
         List<TagValue> values = query(Collections.singletonList(tagCode), time);
         return !values.isEmpty() ? values.get(0) : new TagValue();
@@ -303,6 +314,9 @@
                         config.getMeasurement(), field, startTime, endTime);
                 return 0.0;
             }
+            if (field.contains("total_A")) {
+                System.out.println(values);
+            }
 
             // 璁$畻绱鍊硷紙鏈�鍚庝竴涓�煎噺鍘荤涓�涓�硷級
             Object firstValue = values.get(0);
@@ -323,4 +337,32 @@
             return 0.0;
         }
     }
+
+    public double getLastPoint(String measurement, String tag, String s) {
+        if (client == null || !config.isEnable()) {
+            log.warn("InfluxDB client is not initialized or disabled.");
+            return 0;
+        }
+
+        String query = String.format("from(bucket: \"%s\") " +
+                "|> range(start: -1h) " +
+                "|> filter(fn: (r) => r._measurement == \"%s\" and r._field == \"value\") " +
+                "|> filter(fn: (r) => r.tag == \"%s\") " +
+                "|> last()", config.getBucket(), measurement, s);
+
+        List<FluxTable> tables = client.getQueryApi().query(query, config.getOrg());
+
+        if (tables != null && !tables.isEmpty()) {
+            List<FluxRecord> records = tables.get(0).getRecords();
+            if (records != null && !records.isEmpty()) {
+                FluxRecord record = records.get(0);
+                double value = (double) record.getValue();
+
+                return value;
+            }
+        }
+
+        log.warn("No data found for measurement: {}, tag: {}, field: {}", measurement, tag, s);
+        return 0;
+    }
 }
diff --git a/src/main/java/com/zhitan/engine/scheduler/DataCleaningScheduler.java b/src/main/java/com/zhitan/engine/scheduler/DataCleaningScheduler.java
index bc02403..df5b825 100644
--- a/src/main/java/com/zhitan/engine/scheduler/DataCleaningScheduler.java
+++ b/src/main/java/com/zhitan/engine/scheduler/DataCleaningScheduler.java
@@ -98,4 +98,42 @@
             log.error("鎵嬪姩瑙﹀彂{}缁熻浠诲姟鎵ц澶辫触锛歿}", timeType, e.getMessage(), e);
         }
     }
+    @Scheduled(cron = "0 * * * * ?")
+    public void totalElectricityTask() {
+        try {
+            LocalDateTime now = LocalDateTime.now();
+            log.info("寮�濮嬫墽琛屽叏鍘傛�荤數閲忕粺璁′换鍔★紝澶勭悊鏃堕棿锛歿}", now);
+            dataCleaningService.calculateTotalElectricity(now);
+            log.info("鍏ㄥ巶鎬荤數閲忕粺璁′换鍔℃墽琛屽畬鎴�");
+        } catch (Exception e) {
+            log.error("鍏ㄥ巶鎬荤數閲忕粺璁′换鍔℃墽琛屽け璐ワ細{}", e.getMessage(), e);
+        }
+    }
+    
+    /**
+     * 姣忓垎閽熸墽琛屼竴娆★紝缁熻褰撳墠灏忔椂銆佸綋澶┿�佸綋鏈堝拰褰撳勾鐨勭敤鐢甸噺
+     */
+    @Scheduled(cron = "0 * * * * ?")
+    public void periodicElectricityStatisticsTask() {
+        try {
+            LocalDateTime now = LocalDateTime.now();
+            log.info("寮�濮嬫墽琛屽懆鏈熸�х敤鐢甸噺缁熻浠诲姟锛屽鐞嗘椂闂达細{}", now);
+            
+            // 缁熻褰撳墠灏忔椂鐢ㄧ數閲�
+            dataCleaningService.calculateHourlyElectricity(now);
+            
+            // 缁熻褰撳ぉ鐢ㄧ數閲�
+            dataCleaningService.calculateDailyElectricity(now);
+            
+            // 缁熻褰撴湀鐢ㄧ數閲�
+            dataCleaningService.calculateMonthlyElectricity(now);
+            
+            // 缁熻褰撳勾鐢ㄧ數閲�
+            dataCleaningService.calculateYearlyElectricity(now);
+            
+            log.info("鍛ㄦ湡鎬х敤鐢甸噺缁熻浠诲姟鎵ц瀹屾垚");
+        } catch (Exception e) {
+            log.error("鍛ㄦ湡鎬х敤鐢甸噺缁熻浠诲姟鎵ц澶辫触锛歿}", e.getMessage(), e);
+        }
+    }
 }
\ No newline at end of file
diff --git a/src/main/java/com/zhitan/engine/service/DataCleaningService.java b/src/main/java/com/zhitan/engine/service/DataCleaningService.java
index 3c768a6..21fefa3 100644
--- a/src/main/java/com/zhitan/engine/service/DataCleaningService.java
+++ b/src/main/java/com/zhitan/engine/service/DataCleaningService.java
@@ -51,4 +51,11 @@
      * @param dateTime 缁熻鏃堕棿鐐�
      */
     void calculatePeakValleyElectricity(String indexId, LocalDateTime dateTime);
+
+
+    /**
+     * 鍏ㄥ巶鎬荤數閲忕粺璁�
+     * @param dateTime 缁熻鏃堕棿鐐�
+     */
+    void calculateTotalElectricity(LocalDateTime dateTime);
 }
\ No newline at end of file
diff --git a/src/main/java/com/zhitan/engine/service/impl/DataCleaningServiceImpl.java b/src/main/java/com/zhitan/engine/service/impl/DataCleaningServiceImpl.java
index 1d41cd3..9a7a1c3 100644
--- a/src/main/java/com/zhitan/engine/service/impl/DataCleaningServiceImpl.java
+++ b/src/main/java/com/zhitan/engine/service/impl/DataCleaningServiceImpl.java
@@ -1,5 +1,8 @@
 package com.zhitan.engine.service.impl;
 
+import com.influxdb.client.domain.WritePrecision;
+import com.influxdb.client.write.Point;
+import com.zhitan.engine.config.InfluxDBConfig;
 import com.zhitan.engine.influxdb.InfluxdbRepository;
 import com.zhitan.engine.entity.*;
 import com.zhitan.engine.repository.*;
@@ -20,13 +23,18 @@
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
+import static java.util.List.*;
+
 /**
  * 鏁版嵁娓呮礂鏈嶅姟瀹炵幇绫�
  */
 @Slf4j
 @Service
 public class DataCleaningServiceImpl implements DataCleaningService {
-
+    private final String TAG = "tag";
+    private final String FIELD_VALUE = "value";
+    @Autowired
+    private InfluxDBConfig influxDBConfig;
     @Autowired
     private InfluxdbRepository influxdbRepository;
 
@@ -164,6 +172,97 @@
     }
 
     @Override
+    public void calculateTotalElectricity(LocalDateTime dateTime) {
+        log.info("寮�濮嬫墽琛屽叏鍘傛�荤數閲忕粺璁★紝鏃堕棿鐐癸細{}", dateTime);
+        
+        // 瀹氫箟闇�瑕佺粺璁$殑鐢佃〃缃戝叧鍒楄〃
+        List<String> gatewayCodes = new java.util.ArrayList<>(List.of("00601925032100028432", "00601925032100026840", "00601925032100028685", "00601925032100027392", "00601925032100028050", "00601925032100028751"));
+        gatewayCodes.add("00601925032100026275");
+        gatewayCodes.add("00601925032100028117");
+        gatewayCodes.add("00601925032100028814");
+        gatewayCodes.add("00601925032100028990");
+        gatewayCodes.add("00601925032100031307");
+
+
+        // 瀹氫箟闇�瑕佺粺璁$殑鍙傛暟绫诲瀷鍙婂叾缁熻鏂瑰紡
+        Map<String, String> parameterTypes = new java.util.HashMap<>(Map.of(
+                "ActiveZT", "SUM" // 姝e悜鎬绘湁鍔熺數鑳� - 姹傚拰
+                , "ActiveZN", "SUM" // 姝e悜鎬绘棤鍔熺數鑳� - 姹傚拰
+                , "ActiveElectricity", "SUM" // 鏈夊姛鐢佃兘 - 姹傚拰
+                , "NoActiveElectricity", "SUM" // 鏃犲姛鍔熺巼 - 姹傚拰
+                , "ExpZN", "SUM" // 鍙嶅悜鎬绘棤鍔熺數鑳� - 姹傚拰
+                , "Exp", "SUM" // 鍙嶅悜鏈夊姛鐢佃兘 - 姹傚拰
+                , "ActivePow", "SUM" // 姝e悜鏈夊姛鍔熺巼 - 姹傚拰
+                , "VoltageUAB", "AVG" // 鎬荤數鍘� - 骞冲潎鍊�
+                , "VoltageUBC", "AVG" // 鎬荤數鍘� - 骞冲潎鍊�
+                , "VoltageUCA", "AVG" // 鎬荤數鍘� - 骞冲潎鍊�
+//            ,"CurrentA", "SUM" // 鎬荤數娴� - 姹傚拰
+//            ,"CurrentB", "SUM" // 鎬荤數娴� - 姹傚拰
+//            ,"CurrentC", "SUM" // 鎬荤數娴� - 姹傚拰
+//            ,"Io", "SUM" // 鎬荤數娴� - 姹傚拰
+//            ,"VoltageA", "AVG" // 鎬荤數鍘� - 骞冲潎鍊�
+//            ,"VoltageB", "AVG" // 鎬荤數鍘� - 骞冲潎鍊�
+//            ,"VoltageC", "AVG"
+        ));
+        parameterTypes.put("CurrentA", "SUM");
+        parameterTypes.put("CurrentB", "SUM");
+        parameterTypes.put("CurrentC", "SUM");
+        parameterTypes.put("Io", "SUM");
+        parameterTypes.put("VoltageA", "AVG");
+        parameterTypes.put("VoltageB", "AVG");
+        parameterTypes.put("VoltageC", "AVG");
+        
+        // 璁$畻鏃堕棿鑼冨洿锛堝綋鍓嶅垎閽燂級
+        LocalDateTime startTime = dateTime.withSecond(0).withNano(0);
+        LocalDateTime endTime = startTime.plusMinutes(1);
+        
+        // 閬嶅巻鎵�鏈夊弬鏁扮被鍨嬭繘琛岀粺璁�
+        parameterTypes.forEach((paramType, calcType) -> {
+            try {
+                double totalValue = 0;
+                int meterCount = 0;
+                
+                // 閬嶅巻鎵�鏈夌綉鍏充笅鐨勭數琛�
+                for (String gatewayCode : gatewayCodes) {
+                    // 閬嶅巻姣忎釜缃戝叧涓嬬殑8涓數琛�
+                    for (int i = 1; i <= 8; i++) {
+                        // 鏋勫缓tag鍚嶇О鏍煎紡锛氱綉鍏崇紪鍙穇鐢佃〃搴忓彿_鍙傛暟绫诲瀷
+                        // 绀轰緥锛�00601925032100028432_1_ActiveZT
+                        String tag = String.format("%s_%d_%s", gatewayCode, i, paramType);
+                        // 鏌ヨ鏈�鍚庝竴娆′繚瀛樻暟鎹�
+
+                        Double value = influxdbRepository.getLastPoint(influxDBConfig.getMeasurement(),TAG,tag);
+                        if (value != null) {
+                            totalValue +=  value ;
+                            meterCount++;
+                        }
+                    }
+                }
+                
+                // 璁$畻鏈�缁堝��
+                double finalValue = "SUM".equals(calcType) ? totalValue : (meterCount > 0 ? totalValue / meterCount : 0);
+                
+                // 淇濆瓨鎬昏〃鏁版嵁
+                String totalTag = "total_" + paramType;
+
+                Point point = Point
+                        .measurement(influxDBConfig.getMeasurement())
+                        .addTag(TAG, totalTag)
+                        .addField(FIELD_VALUE, finalValue)
+                        .time(Instant.now(), WritePrecision.S);
+
+                influxdbRepository.writePoint(point);
+                
+                log.info("缁熻瀹屾垚锛歿}={} ({}涓數琛�)", totalTag, finalValue, meterCount);
+            } catch (Exception e) {
+                log.error("缁熻鍙傛暟{}澶辫触锛歿}", paramType, e.getMessage(), e);
+            }
+        });
+        
+        log.info("鍏ㄥ巶鎬荤數閲忕粺璁″畬鎴愶紝鏃堕棿鐐癸細{}", dateTime);
+    }
+
+    @Override
     @Transactional
     public void calculatePeakValleyElectricity(String indexId, LocalDateTime dateTime) {
         log.info("寮�濮嬭绠楀皷宄板钩璋风敤鐢甸噺锛岀储寮旾D锛歿}锛屾椂闂寸偣锛歿}", indexId, dateTime);
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index d879e65..4a50a53 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -5,7 +5,7 @@
   
   # 鏁版嵁搴撻厤缃�
   datasource:
-    url: jdbc:postgresql://localhost:5432/postgres
+    url: jdbc:postgresql://192.168.0.24:5432/postgres
     username: postgres
     password: 123456
     driver-class-name: org.postgresql.Driver
@@ -22,19 +22,19 @@
 
 # InfluxDB閰嶇疆
 influxdb:
-  host: "http://localhost:8086"
+  host: "http://192.168.0.24:8086"
   #淇敼涓鸿嚜宸辩殑鏃跺簭搴撹闂畂rg
   org: "lanbao"
   #淇敼涓鸿嚜宸辩殑鏃跺簭搴揵ucket
   bucket: "nygl"
   #淇敼涓鸿嚜宸辩殑鏃跺簭搴撹闂畉oken
-  token: "AminQagYp5rjb09mFPYvriK0T0vlF-zmwboqtUzdcq3nkXNuhnEpMuG_Ht5vtfWC4xBIVOThvoxy5reTer9XcQ=="
+  token: "i8WwVZz3RvkEVF3qGaY8uIDXTFEe2PzjgrKebDzcxlYGKnR-kOK5Hf1S5G4z3p-lc9UO7MQS4qKGL4lIeHSw1A=="
   measurement: data
   enable: true
 
 # 鏈嶅姟鍣ㄩ厤缃�
 server:
-  port: 8082
+  port: 8090
   servlet:
     context-path: /
 

--
Gitblit v1.9.3