Browse Source

完善电度计算方式

hfxc226 2 years ago
parent
commit
61af6f7973

+ 12 - 6
platform-common/src/main/java/com/platform/common/util/DateUtils.java

@@ -464,12 +464,9 @@ public class DateUtils {
     }
 
     public static void main(String[] args) {
-        LocalDate nowDate = LocalDate.now();
-        LocalDateTime time = getFirstDayOfMonth(nowDate);
-        System.out.println(time);
-        LocalDateTime time2 = time.withHour(12).withMinute(10);
-        System.out.println(time2);
-        System.out.println(getDurationHoursStr(time, time2));
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(2022,0,1,0,2, 30);
+        getLastDay(calendar);
     }
 
     /**
@@ -640,5 +637,14 @@ public class DateUtils {
         throw new BusinessException("未知dayOfWeek" + String.valueOf(dayOfWeek));
     }
 
+    /**
+     * 获取前一天时间*
+     * @param calendar
+     */
+    public static void getLastDay(Calendar calendar){
+        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        System.out.println("一个小时前的时间:" + df.format(calendar.getTime()));
+    }
 }
 

+ 2 - 2
platform-iec/src/main/java/com/ydl/iec/util/MySqlUtil.java

@@ -26,11 +26,11 @@ public class MySqlUtil {
     //是否连接数据库
     public static String mysql_open = "false";
     //数据库连接地址
-    public static String mysql_url = "jdbc:mysql://123.60.19.203:5006/hitch-sb";
+    public static String mysql_url = "jdbc:mysql://192.168.16.222:3306/hitch-sb";
     //用户名
     public static String mysql_username = "root";
     //密码
-    public static String mysql_password = "mysql?MYSQLmoniu123";//admindljjk
+    public static String mysql_password = "mydm888";
     //驱动名称
     public static String mysql_driver = "com.mysql.cj.jdbc.Driver";
     // 采集数据,结构:遥测最低,遥测最高;电度最低,电度最高

+ 0 - 10
platform-rest/src/main/java/com/platform/rest/controller/report/StoreReportController.java

@@ -1,30 +1,20 @@
 package com.platform.rest.controller.report;
 
 import cn.hutool.core.collection.CollectionUtil;
-import com.platform.common.bean.AbstractPageResultBean;
 import com.platform.common.util.BeanConverterUtil;
 import com.platform.common.util.DateUtils;
 import com.platform.common.util.R;
-import com.platform.dao.dto.check.CheckJobDTO;
 import com.platform.dao.dto.store.*;
-import com.platform.dao.entity.store.InStoreDetail;
 import com.platform.dao.util.ExcelUtil;
-import com.platform.dao.vo.export.check.ExportCheckJobVO;
 import com.platform.dao.vo.export.store.ExportInStoreDetailVO;
 import com.platform.dao.vo.export.store.ExportOutStoreDetailVO;
-import com.platform.dao.vo.query.check.CheckJobVO;
 import com.platform.dao.vo.query.store.InStoreDetailVO;
-import com.platform.dao.vo.query.store.InStoreFormVO;
 import com.platform.dao.vo.query.store.OutStoreDetailVO;
-import com.platform.dao.vo.query.store.StoreVO;
-import com.platform.dao.vo.report.CheckJobReportVO;
 import com.platform.dao.vo.report.StoreInAndOutReportVO;
 import com.platform.rest.log.annotation.SysLog;
-import com.platform.service.store.InStoreDetailService;
 import com.platform.service.store.SpareStoreService;
 import com.platform.service.store.StoreMonthReportService;
 import lombok.AllArgsConstructor;
-import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletResponse;

+ 55 - 17
platform-service/src/main/java/com/platform/service/big/impl/BigScreenSbInfoServiceImpl.java

@@ -78,6 +78,7 @@ import com.platform.service.util.ExecuteSql;
 import lombok.AllArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.ibatis.exceptions.TooManyResultsException;
+import org.apache.poi.ss.formula.functions.CalendarFieldFunction;
 import org.springframework.core.env.Environment;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
@@ -218,7 +219,18 @@ public class BigScreenSbInfoServiceImpl extends BaseServiceImpl<SbInfoMapper, Sb
         record.setSbName("G01");
         List<RemoteDegreeLogVO> list = remoteDegreeLogMapper.selectList(record);
         JSONArray jSONArray = new JSONArray();
-        if (isDay) {//
+        if (isDay) {// 日报,需要减去上个小时的
+            // 找到前天晚上23点的
+            RemoteDegreeLogDTO lastDay = BeanConverterUtil.copyObjectProperties(record, RemoteDegreeLogDTO.class);
+            Calendar calendar = Calendar.getInstance();
+            calendar.set(lastDay.getYear(), lastDay.getMonth() - 1, lastDay.getDay()-1);
+            DateUtils.getLastDay(calendar);
+            lastDay.setYear(calendar.get(Calendar.YEAR));
+            lastDay.setMonth(calendar.get(Calendar.MONTH) + 1);
+            lastDay.setDay(calendar.get(Calendar.DAY_OF_MONTH));
+            lastDay.setHour(23);
+            List<RemoteDegreeLogVO> lastList = remoteDegreeLogMapper.selectList(lastDay);
+
             for (int i = 0; i < 24; i++) {
                 JSONObject jsonObject = new JSONObject();
                 jsonObject.put("time", i + ":00");
@@ -228,19 +240,45 @@ public class BigScreenSbInfoServiceImpl extends BaseServiceImpl<SbInfoMapper, Sb
                     dictJsonObject.put("name", dict.getLabel());
                     BigDecimal positiveTotal = new BigDecimal(0.00);// 正向有功
                     BigDecimal negativeTotal = new BigDecimal(0.00);// 正向无功
-                    for (RemoteDegreeLogVO log : list) {
-                        if (log.getLine().toString().equals(dict.getValue())) {
-                            if (log.getHour().equals(i)) {
-                                if (log.getType().equals(1)) {
-                                    positiveTotal = positiveTotal.add(new BigDecimal(log.getResult()));
+                    for (RemoteDegreeLogVO degreeLog : list) {
+                        if (degreeLog.getLine().toString().equals(dict.getValue())) {
+                            if (degreeLog.getHour().equals(i)) {
+                                if (degreeLog.getType().equals(1)) {
+                                    positiveTotal = positiveTotal.add(new BigDecimal(degreeLog.getResult()));
+                                    // 找到上个时间
+                                    if(i == 0){// 从昨天找
+                                        Optional<RemoteDegreeLogVO> lastR = lastList.stream().filter(item -> item.getPositionNum().equals(degreeLog.getPositionNum())).findFirst();
+                                        if(lastR.isPresent()){
+                                            log.info(lastR.get().toString());
+                                            positiveTotal = positiveTotal.subtract(new BigDecimal(lastR.get().getResult()));
+                                        }
+                                    }else{// 从今天上个时间找,减去上个小时的数据
+                                        Optional<RemoteDegreeLogVO> lastR = list.stream().filter(item -> item.getPositionNum().equals(degreeLog.getPositionNum()) && item.getHour().equals(degreeLog.getHour()-1)).findFirst();
+                                        if(lastR.isPresent()){
+                                            positiveTotal = positiveTotal.subtract(new BigDecimal(lastR.get().getResult()));
+                                        }
+                                    }
+                                    dictJsonObject.put("positive", positiveTotal.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                                 } else {
-                                    negativeTotal = negativeTotal.add(new BigDecimal(log.getResult()));
+                                    negativeTotal = negativeTotal.add(new BigDecimal(degreeLog.getResult()));
+                                    // 找到上个时间
+                                    if(i == 0){// 从昨天找
+                                        Optional<RemoteDegreeLogVO> lastR = lastList.stream().filter(item -> item.getPositionNum().equals(degreeLog.getPositionNum())).findFirst();
+                                        if(lastR.isPresent()){
+                                            log.info(lastR.get().toString());
+                                            negativeTotal = negativeTotal.subtract(new BigDecimal(lastR.get().getResult()));
+                                        }
+                                    }else{// 从今天上个时间找,减去上个小时的数据
+                                        Optional<RemoteDegreeLogVO> lastR = list.stream().filter(item -> item.getPositionNum().equals(degreeLog.getPositionNum()) && item.getHour().equals(degreeLog.getHour()-1)).findFirst();
+                                        if(lastR.isPresent()){
+                                            negativeTotal = negativeTotal.subtract(new BigDecimal(lastR.get().getResult()));
+                                        }
+                                    }
+                                    dictJsonObject.put("negative", negativeTotal.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                                 }
                             }
                         }
                     }
-                    dictJsonObject.put("positive", positiveTotal.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
-                    dictJsonObject.put("negative", negativeTotal.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).doubleValue());
                     lineArray.add(dictJsonObject);
                 }
                 jsonObject.put("lines", lineArray);
@@ -258,16 +296,16 @@ public class BigScreenSbInfoServiceImpl extends BaseServiceImpl<SbInfoMapper, Sb
                     dictJsonObject.put("name", dict.getLabel());
                     BigDecimal positiveTotal = new BigDecimal(0.00);// 正向有功
                     BigDecimal negativeTotal = new BigDecimal(0.00);// 正向无功,不需要吗,后面可以删除,先保存
-                    for (RemoteDegreeLogVO log : list) {
-                        if (log.getLine() == null) {
-                            throw new BusinessException("设备未设置电力线路, 设备名称:" + log.getSbName() + ", 设备编号:" + log.getSbNo());
+                    for (RemoteDegreeLogVO degreeLog : list) {
+                        if (degreeLog.getLine() == null) {
+                            throw new BusinessException("设备未设置电力线路, 设备名称:" + degreeLog.getSbName() + ", 设备编号:" + degreeLog.getSbNo());
                         }
-                        if (log.getLine().toString().equals(dict.getValue())) {
-                            if (log.getDay().equals(i)) {
-                                if (log.getType().equals(1)) {
-                                    positiveTotal = positiveTotal.add(new BigDecimal(log.getResult()));
+                        if (degreeLog.getLine().toString().equals(dict.getValue())) {
+                            if (degreeLog.getDay().equals(i)) {
+                                if (degreeLog.getType().equals(1)) {
+                                    positiveTotal = positiveTotal.add(new BigDecimal(degreeLog.getResult()));
                                 } else {
-                                    negativeTotal = negativeTotal.add(new BigDecimal(log.getResult()));
+                                    negativeTotal = negativeTotal.add(new BigDecimal(degreeLog.getResult()));
                                 }
                             }
                         }

+ 44 - 0
platform-service/src/main/java/com/platform/service/opc/OpcUAClientService.java

@@ -0,0 +1,44 @@
+package com.platform.service.opc;
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
+import org.eclipse.milo.opcua.sdk.client.api.identity.IdentityProvider;
+import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
+import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Predicate;
+/**
+ * @author yaohj
+ * @date 2020/7/30
+ * OPC UA协议对象接口
+ */
+public interface OpcUAClientService {
+    /**
+     * OPC UA服务器地址和接口
+     */
+    default String getEndpointUrl() {
+        return "opc.tcp://127.0.0.1:49320";
+    }
+    /**
+     * 过滤返回的server endpoint
+     */
+    default Predicate<EndpointDescription> endpointFilter() {
+        return e -> true;
+    }
+    /**
+     * 连接服务器的安全策略
+     * None、Basic128Rsa15、Basic256、Basic256Sha256、Aes128_Sha256_RsaOaep、Aes256_Sha256_RsaPss
+     */
+    default SecurityPolicy getSecurityPolicy() {
+        return SecurityPolicy.None;
+    }
+    /**
+     * 提供身份验证
+     */
+    default IdentityProvider getIdentityProvider() {
+        return new AnonymousProvider();
+    }
+    /**
+     * 实际操作服务、由实现类重写实现
+     */
+    void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception;
+}

+ 41 - 0
platform-service/src/main/java/com/platform/service/opc/impl/OpcUAClientService.java

@@ -0,0 +1,41 @@
+package com.platform.service.opc.impl;
+
+import com.google.common.collect.ImmutableList;
+import com.platform.service.opc.OpcUAClientService;
+import lombok.AllArgsConstructor;
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.stack.core.types.builtin.*;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
+import org.springframework.stereotype.Service;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+@AllArgsConstructor
+@Service("OpcUAClientService")
+class OpcUAClientServiceImpl implements OpcUAClientService {
+    /**
+     * 覆盖接口的方法,建立和OPC UA的服务
+     */
+    @Override
+    public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
+        // 同步建立连接
+        client.connect().get();
+        // 异步读取数据
+        readTagData(client).thenAccept(values -> {
+            DataValue nodeId_Tag1 = values.get(0);
+            DataValue nodeId_Tag2 = values.get(1);
+            System.out.println("#########Tag1=" + nodeId_Tag1.getValue().getValue());
+            System.out.println("#########Tag2=" + nodeId_Tag2.getValue().getValue());
+            future.complete(client);
+        });
+    }
+    /**
+     * 读取标签点的数据
+     */
+    private CompletableFuture<List<DataValue>> readTagData(OpcUaClient client) {
+        NodeId nodeId_Tag1 = new NodeId(2, "Channel1.Device1.Tag1");
+        NodeId nodeId_Tag2 = new NodeId(2, "Channel1.Device1.Tag2");
+        List<NodeId> nodeIds = ImmutableList.of(nodeId_Tag1, nodeId_Tag2);
+        return client.readValues(0.0, TimestampsToReturn.Both, nodeIds);
+    }
+}
+

+ 94 - 0
platform-service/src/main/java/handler/opc/KeyStoreLoader.java

@@ -0,0 +1,94 @@
+package handler.opc;
+
+import org.eclipse.milo.opcua.sdk.server.util.HostnameUtil;
+import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateBuilder;
+import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.regex.Pattern;
+class KeyStoreLoader {
+    private final Logger logger = LoggerFactory.getLogger(getClass());
+    private static final Pattern IP_ADDR_PATTERN = Pattern.compile(
+            "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
+    // 证书别名
+    private static final String CLIENT_ALIAS = "client-ai";
+    // 获取私钥的密码
+    private static final char[] PASSWORD = "password".toCharArray();
+    // 证书对象
+    private X509Certificate clientCertificate;
+    // 密钥对对象
+    private KeyPair clientKeyPair;
+    KeyStoreLoader load(Path baseDir) throws Exception {
+        // 创建一个使用`PKCS12`加密标准的KeyStore。KeyStore在后面将作为读取和生成证书的对象。
+        KeyStore keyStore = KeyStore.getInstance("PKCS12");
+        // PKCS12的加密标准的文件后缀是.pfx,其中包含了公钥和私钥。
+        // 而其他如.der等的格式只包含公钥,私钥在另外的文件中。
+        Path serverKeyStore = baseDir.resolve("example-client.pfx");
+        logger.info("Loading KeyStore at {}", serverKeyStore);
+        // 如果文件不存在则创建.pfx证书文件。
+        if (!Files.exists(serverKeyStore)) {
+            keyStore.load(null, PASSWORD);
+            // 用2048位的RAS算法。`SelfSignedCertificateGenerator`为Milo库的对象。
+            KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
+            // `SelfSignedCertificateBuilder`也是Milo库的对象,用来生成证书。
+            // 中间所设置的证书属性可以自行修改。
+            SelfSignedCertificateBuilder builder = new SelfSignedCertificateBuilder(keyPair)
+                    .setCommonName("Eclipse Milo Example Client")
+                    .setOrganization("digitalpetri")
+                    .setOrganizationalUnit("dev")
+                    .setLocalityName("Folsom")
+                    .setStateName("CA")
+                    .setCountryCode("US")
+                    .setApplicationUri("urn:eclipse:milo:examples:client")
+                    .addDnsName("localhost")
+                    .addIpAddress("127.0.0.1");
+            // Get as many hostnames and IP addresses as we can listed in the certificate.
+            for (String hostname : HostnameUtil.getHostnames("0.0.0.0")) {
+                if (IP_ADDR_PATTERN.matcher(hostname).matches()) {
+                    builder.addIpAddress(hostname);
+                } else {
+                    builder.addDnsName(hostname);
+                }
+            }
+            // 创建证书
+            X509Certificate certificate = builder.build();
+            // 设置对应私钥的别名,密码,证书链
+            keyStore.setKeyEntry(CLIENT_ALIAS, keyPair.getPrivate(), PASSWORD, new X509Certificate[]{certificate});
+            try (OutputStream out = Files.newOutputStream(serverKeyStore)) {
+                // 保存证书到输出流
+                keyStore.store(out, PASSWORD);
+            }
+        } else {
+            try (InputStream in = Files.newInputStream(serverKeyStore)) {
+                // 如果文件存在则读取
+                keyStore.load(in, PASSWORD);
+            }
+        }
+        // 用密码获取对应别名的私钥。
+        Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
+        if (serverPrivateKey instanceof PrivateKey) {
+            // 获取对应别名的证书对象。
+            clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS);
+            // 获取公钥
+            PublicKey serverPublicKey = clientCertificate.getPublicKey();
+            // 创建Keypair对象。
+            clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
+        }
+        return this;
+    }
+    // 返回证书
+    X509Certificate getClientCertificate() {
+        return clientCertificate;
+    }
+    // 返回密钥对
+    KeyPair getClientKeyPair() {
+        return clientKeyPair;
+    }
+}
+