浏览代码

Merge branch 'master' of C:\Users\86159\git_repos\water-iot with conflicts.

pengdi@zoniot.com 4 年之前
父节点
当前提交
613b11f1c4
共有 42 个文件被更改,包括 988 次插入464 次删除
  1. 118 0
      iot-data-processor/.mvn/wrapper/MavenWrapperDownloader.java
  2. 二进制
      iot-data-processor/.mvn/wrapper/maven-wrapper.jar
  3. 2 0
      iot-data-processor/.mvn/wrapper/maven-wrapper.properties
  4. 118 0
      iot-data-receiver/.mvn/wrapper/MavenWrapperDownloader.java
  5. 二进制
      iot-data-receiver/.mvn/wrapper/maven-wrapper.jar
  6. 2 0
      iot-data-receiver/.mvn/wrapper/maven-wrapper.properties
  7. 118 0
      smart-city-common/.mvn/wrapper/MavenWrapperDownloader.java
  8. 二进制
      smart-city-common/.mvn/wrapper/maven-wrapper.jar
  9. 2 0
      smart-city-common/.mvn/wrapper/maven-wrapper.properties
  10. 2 2
      smart-city-data-migrate/src/main/resources/application-dev.properties
  11. 14 0
      smart-city-dispatcher/target/classes/application-dev.properties
  12. 19 0
      smart-city-dispatcher/target/classes/application-prd.properties
  13. 15 0
      smart-city-dispatcher/target/classes/application-sit.properties
  14. 14 0
      smart-city-dispatcher/target/classes/application-test.properties
  15. 13 0
      smart-city-dispatcher/target/classes/application-uat.properties
  16. 2 0
      smart-city-dispatcher/target/classes/application.properties
  17. 二进制
      smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/Application.class
  18. 二进制
      smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/api/SwaggerConfig.class
  19. 二进制
      smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/vo/CommonResponseVO.class
  20. 二进制
      smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/web/DataAccessaController.class
  21. 23 0
      smart-city-dispatcher/target/classes/logback-spring.xml
  22. 15 0
      smart-city-dispatcher/target/classes/sql/DeviceDateBase.sql
  23. 16 16
      smart-city-platform/src/main/java/com/bz/smart_city/controller/RealTimeMonitorController.java
  24. 10 9
      smart-city-platform/src/main/java/com/bz/smart_city/controller/water/WaterMeterReadController.java
  25. 9 2
      smart-city-platform/src/main/java/com/bz/smart_city/dao/DeviceDataDimMapper.java
  26. 8 0
      smart-city-platform/src/main/java/com/bz/smart_city/dao/MeterReadRecordMapper.java
  27. 39 0
      smart-city-platform/src/main/java/com/bz/smart_city/dto/DeviceDataQueryDTO.java
  28. 61 0
      smart-city-platform/src/main/java/com/bz/smart_city/dto/MeterReadRecordQueryDTO.java
  29. 6 8
      smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/WaterMeterReadJob.java
  30. 16 14
      smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/WaterMeterReadJobV2.java
  31. 3 0
      smart-city-platform/src/main/java/com/bz/smart_city/service/DeviceDataService.java
  32. 15 32
      smart-city-platform/src/main/java/com/bz/smart_city/service/MeterReadRecordService.java
  33. 54 28
      smart-city-platform/src/main/java/com/bz/smart_city/service/clearing/impl/ClearingRecordServiceImpl.java
  34. 14 15
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataDimServiceImpl.java
  35. 25 20
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataPushServiceImpl.java
  36. 28 0
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataServiceImpl.java
  37. 135 72
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataTimeOutServiceImpl.java
  38. 40 213
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/MeterReadRecordServiceImpl.java
  39. 2 1
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/StatMeterReadRateByBuildingServiceImpl.java
  40. 19 19
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/ZunYiNewRegionSyncServiceImpl.java
  41. 9 11
      smart-city-platform/src/main/java/com/bz/smart_city/service/impl/assistant/AcceptManagerServiceImpl.java
  42. 2 2
      smart-city-platform/src/test/java/com/bz/smart_city/MeterReadRecordServiceTests.java

+ 118 - 0
iot-data-processor/.mvn/wrapper/MavenWrapperDownloader.java

@@ -0,0 +1,118 @@
+/*
+ * Copyright 2007-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+    private static final String WRAPPER_VERSION = "0.5.6";
+    /**
+     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+     */
+    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+            + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+
+    /**
+     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+     * use instead of the default one.
+     */
+    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+            ".mvn/wrapper/maven-wrapper.properties";
+
+    /**
+     * Path where the maven-wrapper.jar will be saved to.
+     */
+    private static final String MAVEN_WRAPPER_JAR_PATH =
+            ".mvn/wrapper/maven-wrapper.jar";
+
+    /**
+     * Name of the property which should be used to override the default download url for the wrapper.
+     */
+    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+    public static void main(String args[]) {
+        System.out.println("- Downloader started");
+        File baseDirectory = new File(args[0]);
+        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+        // If the maven-wrapper.properties exists, read it and check if it contains a custom
+        // wrapperUrl parameter.
+        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+        String url = DEFAULT_DOWNLOAD_URL;
+        if (mavenWrapperPropertyFile.exists()) {
+            FileInputStream mavenWrapperPropertyFileInputStream = null;
+            try {
+                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+                Properties mavenWrapperProperties = new Properties();
+                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+            } catch (IOException e) {
+                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+            } finally {
+                try {
+                    if (mavenWrapperPropertyFileInputStream != null) {
+                        mavenWrapperPropertyFileInputStream.close();
+                    }
+                } catch (IOException e) {
+                    // Ignore ...
+                }
+            }
+        }
+        System.out.println("- Downloading from: " + url);
+
+        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
+                System.out.println(
+                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+            }
+        }
+        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+        try {
+            downloadFileFromURL(url, outputFile);
+            System.out.println("Done");
+            System.exit(0);
+        } catch (Throwable e) {
+            System.out.println("- Error downloading");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
+            String username = System.getenv("MVNW_USERNAME");
+            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
+            Authenticator.setDefault(new Authenticator() {
+                @Override
+                protected PasswordAuthentication getPasswordAuthentication() {
+                    return new PasswordAuthentication(username, password);
+                }
+            });
+        }
+        URL website = new URL(urlString);
+        ReadableByteChannel rbc;
+        rbc = Channels.newChannel(website.openStream());
+        FileOutputStream fos = new FileOutputStream(destination);
+        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+        fos.close();
+        rbc.close();
+    }
+
+}

二进制
iot-data-processor/.mvn/wrapper/maven-wrapper.jar


+ 2 - 0
iot-data-processor/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,2 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

+ 118 - 0
iot-data-receiver/.mvn/wrapper/MavenWrapperDownloader.java

@@ -0,0 +1,118 @@
+/*
+ * Copyright 2007-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+    private static final String WRAPPER_VERSION = "0.5.6";
+    /**
+     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+     */
+    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+            + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+
+    /**
+     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+     * use instead of the default one.
+     */
+    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+            ".mvn/wrapper/maven-wrapper.properties";
+
+    /**
+     * Path where the maven-wrapper.jar will be saved to.
+     */
+    private static final String MAVEN_WRAPPER_JAR_PATH =
+            ".mvn/wrapper/maven-wrapper.jar";
+
+    /**
+     * Name of the property which should be used to override the default download url for the wrapper.
+     */
+    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+    public static void main(String args[]) {
+        System.out.println("- Downloader started");
+        File baseDirectory = new File(args[0]);
+        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+        // If the maven-wrapper.properties exists, read it and check if it contains a custom
+        // wrapperUrl parameter.
+        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+        String url = DEFAULT_DOWNLOAD_URL;
+        if (mavenWrapperPropertyFile.exists()) {
+            FileInputStream mavenWrapperPropertyFileInputStream = null;
+            try {
+                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+                Properties mavenWrapperProperties = new Properties();
+                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+            } catch (IOException e) {
+                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+            } finally {
+                try {
+                    if (mavenWrapperPropertyFileInputStream != null) {
+                        mavenWrapperPropertyFileInputStream.close();
+                    }
+                } catch (IOException e) {
+                    // Ignore ...
+                }
+            }
+        }
+        System.out.println("- Downloading from: " + url);
+
+        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
+                System.out.println(
+                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+            }
+        }
+        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+        try {
+            downloadFileFromURL(url, outputFile);
+            System.out.println("Done");
+            System.exit(0);
+        } catch (Throwable e) {
+            System.out.println("- Error downloading");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
+            String username = System.getenv("MVNW_USERNAME");
+            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
+            Authenticator.setDefault(new Authenticator() {
+                @Override
+                protected PasswordAuthentication getPasswordAuthentication() {
+                    return new PasswordAuthentication(username, password);
+                }
+            });
+        }
+        URL website = new URL(urlString);
+        ReadableByteChannel rbc;
+        rbc = Channels.newChannel(website.openStream());
+        FileOutputStream fos = new FileOutputStream(destination);
+        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+        fos.close();
+        rbc.close();
+    }
+
+}

二进制
iot-data-receiver/.mvn/wrapper/maven-wrapper.jar


+ 2 - 0
iot-data-receiver/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,2 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

+ 118 - 0
smart-city-common/.mvn/wrapper/MavenWrapperDownloader.java

@@ -0,0 +1,118 @@
+/*
+ * Copyright 2007-present the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.util.Properties;
+
+public class MavenWrapperDownloader {
+
+    private static final String WRAPPER_VERSION = "0.5.6";
+    /**
+     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
+     */
+    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+            + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+
+    /**
+     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
+     * use instead of the default one.
+     */
+    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
+            ".mvn/wrapper/maven-wrapper.properties";
+
+    /**
+     * Path where the maven-wrapper.jar will be saved to.
+     */
+    private static final String MAVEN_WRAPPER_JAR_PATH =
+            ".mvn/wrapper/maven-wrapper.jar";
+
+    /**
+     * Name of the property which should be used to override the default download url for the wrapper.
+     */
+    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
+
+    public static void main(String args[]) {
+        System.out.println("- Downloader started");
+        File baseDirectory = new File(args[0]);
+        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
+
+        // If the maven-wrapper.properties exists, read it and check if it contains a custom
+        // wrapperUrl parameter.
+        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
+        String url = DEFAULT_DOWNLOAD_URL;
+        if (mavenWrapperPropertyFile.exists()) {
+            FileInputStream mavenWrapperPropertyFileInputStream = null;
+            try {
+                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
+                Properties mavenWrapperProperties = new Properties();
+                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
+                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
+            } catch (IOException e) {
+                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
+            } finally {
+                try {
+                    if (mavenWrapperPropertyFileInputStream != null) {
+                        mavenWrapperPropertyFileInputStream.close();
+                    }
+                } catch (IOException e) {
+                    // Ignore ...
+                }
+            }
+        }
+        System.out.println("- Downloading from: " + url);
+
+        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
+        if (!outputFile.getParentFile().exists()) {
+            if (!outputFile.getParentFile().mkdirs()) {
+                System.out.println(
+                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
+            }
+        }
+        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
+        try {
+            downloadFileFromURL(url, outputFile);
+            System.out.println("Done");
+            System.exit(0);
+        } catch (Throwable e) {
+            System.out.println("- Error downloading");
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
+        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
+            String username = System.getenv("MVNW_USERNAME");
+            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
+            Authenticator.setDefault(new Authenticator() {
+                @Override
+                protected PasswordAuthentication getPasswordAuthentication() {
+                    return new PasswordAuthentication(username, password);
+                }
+            });
+        }
+        URL website = new URL(urlString);
+        ReadableByteChannel rbc;
+        rbc = Channels.newChannel(website.openStream());
+        FileOutputStream fos = new FileOutputStream(destination);
+        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
+        fos.close();
+        rbc.close();
+    }
+
+}

二进制
smart-city-common/.mvn/wrapper/maven-wrapper.jar


+ 2 - 0
smart-city-common/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,2 @@
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
+wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

+ 2 - 2
smart-city-data-migrate/src/main/resources/application-dev.properties

@@ -43,5 +43,5 @@ spring.redis.lettuce.pool.max-idle=8
 spring.redis.lettuce.pool.min-idle=1
 spring.redis.lettuce.shutdown-timeout=300
 #############################################Ç¨ÒÆÅäÖÃ##############################################
-data.migrate.begin.date=20200701
-data.migrate.end.date=20200701
+data.migrate.begin.date=20200702
+data.migrate.end.date=20200705

+ 14 - 0
smart-city-dispatcher/target/classes/application-dev.properties

@@ -0,0 +1,14 @@
+server.port=8071
+
+#日志配置
+logging.level.root=info
+logging.path=c:/tmp
+#kafka配置
+spring.kafka.bootstrap-servers=114.135.61.188:36377
+#kafka生产者配置
+spring.kafka.producer.retries=0
+spring.kafka.producer.batch-size=4096
+spring.kafka.producer.buffer-memory=40960
+# kafka topic
+com.zcxk.kafka.single.data.topic=sc_single_data_topic_dev
+com.zcxk.kafka.multi.data.topic=sc_multi_data_topic_dev

+ 19 - 0
smart-city-dispatcher/target/classes/application-prd.properties

@@ -0,0 +1,19 @@
+server.port=8091
+
+#log
+logging.level.root=info
+logging.path=/mnt/prd/dispatcher/logs
+
+spring.jackson.time-zone=GMT+8
+spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
+spring.jackson.joda-date-time-format: yyyy-MM-dd HH:mm:ss
+
+#kafka 
+spring.kafka.bootstrap-servers=172.18.110.178:9092
+#kafka producer config
+spring.kafka.producer.retries=0
+spring.kafka.producer.batch-size=4096
+spring.kafka.producer.buffer-memory=40960
+#kafka topic
+com.zcxk.kafka.single.data.topic=sc_single_data_topic
+com.zcxk.kafka.multi.data.topic=sc_multi_data_topic

+ 15 - 0
smart-city-dispatcher/target/classes/application-sit.properties

@@ -0,0 +1,15 @@
+server.port=8091
+#log
+logging.level.root=info
+logging.path=/opt/sit/dispatcher/logs
+
+
+
+#kafka 
+spring.kafka.bootstrap-servers=193.112.139.7:9092
+#kafka producer
+spring.kafka.producer.retries=0
+spring.kafka.producer.batch-size=4096
+spring.kafka.producer.buffer-memory=40960
+com.zcxk.kafka.single.data.topic=sc_single_data_topic
+com.zcxk.kafka.multi.data.topic=sc_multi_data_topic

+ 14 - 0
smart-city-dispatcher/target/classes/application-test.properties

@@ -0,0 +1,14 @@
+server.port=8091
+
+#日志配置
+logging.level.root=info
+logging.path=/opt/test/dispatcher/logs
+#kafka配置
+spring.kafka.bootstrap-servers=114.135.61.188:909
+#kafka生产者配置
+spring.kafka.producer.retries=0
+spring.kafka.producer.batch-size=4096
+spring.kafka.producer.buffer-memory=40960
+# kafka topic
+com.zcxk.kafka.single.data.topic=sc_single_data_topic_test
+com.zcxk.kafka.multi.data.topic=sc_multi_data_topic_test

+ 13 - 0
smart-city-dispatcher/target/classes/application-uat.properties

@@ -0,0 +1,13 @@
+server.port=8081
+#log
+logging.level.root=info
+logging.path=/data/uat/dispatcher/logs
+#kafka
+spring.kafka.bootstrap-servers=193.112.139.7:9092
+#kafka producer
+spring.kafka.producer.retries=0
+spring.kafka.producer.batch-size=4096
+spring.kafka.producer.buffer-memory=40960
+#kafka topic
+com.zcxk.kafka.single.data.topic=sc_single_data_topic
+com.zcxk.kafka.multi.data.topic=sc_multi_data_topic

+ 2 - 0
smart-city-dispatcher/target/classes/application.properties

@@ -0,0 +1,2 @@
+#开发环境:dev  测试环境:sit  线上环境:prd
+spring.profiles.active=dev

二进制
smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/Application.class


二进制
smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/api/SwaggerConfig.class


二进制
smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/vo/CommonResponseVO.class


二进制
smart-city-dispatcher/target/classes/com/zcxk/smartcity/data/dispatcher/web/DataAccessaController.class


+ 23 - 0
smart-city-dispatcher/target/classes/logback-spring.xml

@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+    <springProperty scope="context" name="LOG_PATH" source="logging.path" defaultValue="/tmp" />
+    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
+    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
+    <appender name="TIME_FILE"
+              class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <encoder>
+            <pattern>${FILE_LOG_PATTERN}</pattern>
+        </encoder>
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <fileNamePattern>${LOG_PATH}/smart_city_dispatcher.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <maxHistory>365</maxHistory>
+            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>100MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+        </rollingPolicy>
+    </appender>
+    <root level="INFO">
+        <appender-ref ref="CONSOLE" />
+        <appender-ref ref="TIME_FILE" />
+    </root>
+</configuration>

+ 15 - 0
smart-city-dispatcher/target/classes/sql/DeviceDateBase.sql

@@ -0,0 +1,15 @@
+-- auto Generated on 2018-12-21
+-- DROP TABLE IF EXISTS sc_device_date_base;
+CREATE TABLE sc_device_date_base(
+	id BIGINT (20) NOT NULL AUTO_INCREMENT COMMENT 'id',
+	max VARCHAR (128) DEFAULT '' COMMENT 'max',
+	appeui VARCHAR (128) DEFAULT '' COMMENT 'appeui',
+	last_upate_time VARCHAR (128) DEFAULT '' COMMENT 'lastUpateTime',
+	data VARCHAR (128) DEFAULT '' COMMENT 'data',
+	reserver VARCHAR (512) DEFAULT '' COMMENT 'reserver',
+	data_type INT (11) DEFAULT -1 COMMENT 'dataType',
+	gateways VARCHAR (512) DEFAULT '' COMMENT 'gateways',
+	is_analyse INT (11) DEFAULT -1 COMMENT 'isAnalyse',
+	date_create TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'dateCreate',
+	PRIMARY KEY (id)
+)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '设备上报数据';

+ 16 - 16
smart-city-platform/src/main/java/com/bz/smart_city/controller/RealTimeMonitorController.java

@@ -119,22 +119,22 @@ public class RealTimeMonitorController {
      * 水务数据库改造版本此接口已废弃
      * @throws ParseException
      */
-    @Deprecated
-    @GetMapping("/realtime/device/data/{system}/{building}/{floor}/{startDate}/{endDate}/")
-    @ApiOperation(value = "查询设备实时数据,最小粒度可以查询到某个楼层所有设备数据")
-    public AjaxMessage<List<DeviceData>> queryDeviceRealtimeData(
-            @ApiParam(value = "系统", required = true) @PathVariable int system,
-            @ApiParam(value = "建筑,0表示所有", required = true, defaultValue = "0") @PathVariable Integer building,
-            @ApiParam(value = "楼层,0表示所有", required = true, defaultValue = "0") @PathVariable Integer floor,
-            @ApiParam(value = "查询日期,YYYYMMDD格式 0表示当月数据", required = true, defaultValue = "0") @PathVariable Integer startDate,
-            @ApiParam(value = "查询日期,YYYYMMDD格式 0表示当月数据", required = true, defaultValue = "0") @PathVariable Integer endDate,
-            @ApiParam(value = "测点", required = false) @RequestParam(required = false) Integer measuring,
-            @ApiParam(value = "设备id", required = false) @RequestParam(required = false) Long deviceId) throws ParseException {
-        AjaxMessage<List<DeviceData>> returnMsg = new AjaxMessage<List<DeviceData>>();
-        List<DeviceData> dataList = deviceDataDimService.queryDeviceRealtimeData(system, building, floor, startDate, endDate, measuring, deviceId);
-        returnMsg.setMsg(ResultStatus.OK, dataList);
-        return returnMsg;
-    }
+//    @Deprecated
+//    @GetMapping("/realtime/device/data/{system}/{building}/{floor}/{startDate}/{endDate}/")
+//    @ApiOperation(value = "查询设备实时数据,最小粒度可以查询到某个楼层所有设备数据")
+//    public AjaxMessage<List<DeviceData>> queryDeviceRealtimeData(
+//            @ApiParam(value = "系统", required = true) @PathVariable int system,
+//            @ApiParam(value = "建筑,0表示所有", required = true, defaultValue = "0") @PathVariable Integer building,
+//            @ApiParam(value = "楼层,0表示所有", required = true, defaultValue = "0") @PathVariable Integer floor,
+//            @ApiParam(value = "查询日期,YYYYMMDD格式 0表示当月数据", required = true, defaultValue = "0") @PathVariable Integer startDate,
+//            @ApiParam(value = "查询日期,YYYYMMDD格式 0表示当月数据", required = true, defaultValue = "0") @PathVariable Integer endDate,
+//            @ApiParam(value = "测点", required = false) @RequestParam(required = false) Integer measuring,
+//            @ApiParam(value = "设备id", required = false) @RequestParam(required = false) Long deviceId) throws ParseException {
+//        AjaxMessage<List<DeviceData>> returnMsg = new AjaxMessage<List<DeviceData>>();
+//        List<DeviceData> dataList = deviceDataDimService.queryDeviceRealtimeData(system, building, floor, startDate, endDate, measuring, deviceId);
+//        returnMsg.setMsg(ResultStatus.OK, dataList);
+//        return returnMsg;
+//    }
 
 
     /**

+ 10 - 9
smart-city-platform/src/main/java/com/bz/smart_city/controller/water/WaterMeterReadController.java

@@ -56,15 +56,16 @@ public class WaterMeterReadController {
 	private DeviceService deviceService;
 
 
-	@ResponseBody
-	@GetMapping("/manual/read/")
-	@ApiOperation(value = "手动抄表(支持补抄表、重抄)")
-	public AjaxMessage  manualRead(
-			@ApiParam(value = "日期,今天抄昨天的格式yyyyMMdd", required = true) @RequestParam(required = true) String readDate)
-	{
-		meterReadRecordService.createMeterReadRecordAsync(DateTimeUtil.parseDate(readDate, "yyyyMMdd"));
-		return new AjaxMessage<>(ResultStatus.OK);
-	}
+//	@Deprecated
+//	@ResponseBody
+//	@GetMapping("/manual/read/")
+//	@ApiOperation(value = "手动抄表(支持补抄表、重抄)")
+//	public AjaxMessage  manualRead(
+//			@ApiParam(value = "日期,今天抄昨天的格式yyyyMMdd", required = true) @RequestParam(required = true) String readDate)
+//	{
+//		meterReadRecordService.createMeterReadRecordAsync(DateTimeUtil.parseDate(readDate, "yyyyMMdd"));
+//		return new AjaxMessage<>(ResultStatus.OK);
+//	}
 
 
 

+ 9 - 2
smart-city-platform/src/main/java/com/bz/smart_city/dao/DeviceDataDimMapper.java

@@ -26,9 +26,17 @@ public interface DeviceDataDimMapper {
     @Deprecated
     List<DeviceData> queryDeviceRealtimeData(@Param("system") Integer system, @Param("building") Integer building, @Param("floor") Integer floor, @Param("startDate") Integer startDate, @Param("endDate") Integer endDate, @Param("measuring") Integer measuring, @Param("deviceId") Long deviceId);
 
-
+    @Deprecated
     List<DeviceDataDim> queryDeviceDataDim(@Param("param") DeviceDataDim deviceDataDim, @Param("limit") Integer limit);
 
+    /**
+     * 已迁移
+     * @param beginTime
+     * @param endTime
+     * @param deviceId
+     * @return
+     */
+    @Deprecated
     List<DeviceDataDim> getDeviceDataBetweenDate(@Param("beginTime") Date beginTime, @Param("endTime") Date endTime, @Param("deviceId") Long deviceId);
 
     /**
@@ -89,5 +97,4 @@ public interface DeviceDataDimMapper {
 
     @Deprecated
     List<Map<String,Object>> getDeviceDataByTime(@Param("deviceId") Long deviceId , @Param("sendTime") Date sendTime,@Param("deviceTypeId") Integer deviceTypeId);
-
 }

+ 8 - 0
smart-city-platform/src/main/java/com/bz/smart_city/dao/MeterReadRecordMapper.java

@@ -54,7 +54,15 @@ public interface MeterReadRecordMapper {
 
     // 每日跑p计算每日用水量
     MeterReadRecord getLastDayData(@Param("deviceId") long deviceId, @Param("lastDate") Integer lastDate);
+    //
+
+    // 补充数据库中每日用水量数据
+    List<Long> getAllDeviceId(@Param("startDate") Integer startDate);
 
+    List<MeterReadRecord> getMeterReadRecordByDeviceId(@Param("deviceId") Long deviceId, @Param("startDate") Integer startDate);
+
+    void batchUpdate(@Param("list") List<MeterReadRecord> list);
+    //
 
     // 每日用水测试
     List<Long> getDeviceIdOnDate(@Param("date") Integer date, @Param("limit") Integer limit);

+ 39 - 0
smart-city-platform/src/main/java/com/bz/smart_city/dto/DeviceDataQueryDTO.java

@@ -0,0 +1,39 @@
+package com.bz.smart_city.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.springframework.data.domain.Sort;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * <p></p>
+ *
+ * @Author wilian.peng
+ * @Date 2020/7/8 9:40
+ * @Version 1.0
+ */
+@Data
+public class DeviceDataQueryDTO implements Serializable {
+    @ApiModelProperty("查询开始时间")
+    Date startDate ;
+
+    @ApiModelProperty("查询结束时间")
+    Date endDate ;
+
+    @ApiModelProperty("节点编号")
+    String deviceNo;
+
+    @ApiModelProperty("设备Id")
+    Long deviceId;
+
+    @ApiModelProperty("排序")
+    Sort sort;
+
+    @ApiModelProperty("当前页")
+    Integer pageIndex;
+
+    @ApiModelProperty("每页大小")
+    Integer pageSize ;
+}

+ 61 - 0
smart-city-platform/src/main/java/com/bz/smart_city/dto/MeterReadRecordQueryDTO.java

@@ -0,0 +1,61 @@
+package com.bz.smart_city.dto;
+
+import com.bz.smart_city.entity.ProgramItem;
+import com.bz.smart_city.entity.Site;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.springframework.data.domain.Sort;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * <p></p>
+ *
+ * @Author wilian.peng
+ * @Date 2020/7/8 14:26
+ * @Version 1.0
+ */
+@ApiModel("抄表记录查询对象")
+@Data
+public class MeterReadRecordQueryDTO implements Serializable {
+    @ApiModelProperty("站点")
+    List<Site> siteIds ;
+
+    @ApiModelProperty("场景")
+    Integer channelId ;
+
+    @ApiModelProperty("设备Id")
+    Long deviceId;
+
+    @ApiModelProperty("建筑")
+    List<Integer> buildingIds;
+
+    @ApiModelProperty("采集器编码")
+    String collectorCode;
+
+    @ApiModelProperty("集中器编码")
+    String concentratorCode ;
+
+    @ApiModelProperty("设备编号,模糊匹配")
+    String deviceNo ;
+
+    @ApiModelProperty("小区")
+    Integer communityId;
+
+    @ApiModelProperty("客户")
+    Integer customerId;
+
+    @ApiModelProperty("抄表状态 1未抄,2已抄")
+    String readStatus ;
+
+    @ApiModelProperty("开始时间")
+    Integer startDate ;
+
+    @ApiModelProperty("结束时间")
+    Integer endDate ;
+
+    @ApiModelProperty("排序")
+    Sort sort;
+}

+ 6 - 8
smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/WaterMeterReadJob.java

@@ -14,11 +14,12 @@ import com.bz.smart_city.service.MeterReadRecordService;
 import lombok.extern.slf4j.Slf4j;
 
 /**
- * 水表定时抄表任务
+ * 水表定时抄表任务,已废弃由XXL-JOB替换
  * @Description  
  * @author wilian.peng
  * @date 2019年3月16日 下午6:08:29
  */
+@Deprecated
 @Slf4j
 @Service
 public class WaterMeterReadJob implements  Job,Serializable {
@@ -27,15 +28,12 @@ public class WaterMeterReadJob implements  Job,Serializable {
 	 */
 	private static final long serialVersionUID = 191737130306302304L;
 
-	@Autowired
-	MeterReadRecordService meterReadRecordService;
-
 	@Override
 	public void execute(JobExecutionContext context) throws JobExecutionException {
-		log.info("begin water meter read job!");
-		int result = meterReadRecordService.createMeterReadRecord(new Date());
-		log.info("今日抄表数量,result = "+ result);
-		log.info("end water meter read job!");
+//		log.info("begin water meter read job!");
+//		int result = meterReadRecordService.createMeterReadRecord(new Date());
+//		log.info("今日抄表数量,result = "+ result);
+//		log.info("end water meter read job!");
 	}
 
 }

+ 16 - 14
smart-city-platform/src/main/java/com/bz/smart_city/quartz/job/WaterMeterReadJobV2.java

@@ -15,6 +15,7 @@ import java.io.Serializable;
 import java.util.Date;
 
 /**
+ * 已废弃,由XXL作业代替
  * <p>新抄表定时任务</p>
  * 按表型进行抄表,不通表型抄表时间与测点字段均不相同,需要从任务的传参中获取
  * {
@@ -49,21 +50,22 @@ public class WaterMeterReadJobV2 implements Job, Serializable {
     @Autowired
     MeterReadRecordService meterReadRecordService;
 
+    @Deprecated
     @Override
     public void execute(JobExecutionContext context) throws JobExecutionException {
-        log.info("Begin Water Meter Read Job @Time = {}", JSON.toJSONString(new Date()));
-        StopWatch clock = new StopWatch();
-        clock.start(); // 计时开始
-        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
-        log.info("Print Job Data Map ,data = {}",JSON.toJSONString(jobDataMap));
-        // 表类型编码
-        String meterTypeCode = jobDataMap.getString("MeterTypeCode");
-        // 用水量测点编码
-        String meterWSVCode = jobDataMap.getString("MeterWSVCode");
-
-        int count = meterReadRecordService.waterMeterReadDataByType(new Date() ,
-                meterTypeCode,meterWSVCode);
-        clock.stop(); // 计时结束
-        log.info("End Water Meter Read Job ,Count = {},Cost = {}ms",count,clock.getTime());
+//        log.info("Begin Water Meter Read Job @Time = {}", JSON.toJSONString(new Date()));
+//        StopWatch clock = new StopWatch();
+//        clock.start(); // 计时开始
+//        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
+//        log.info("Print Job Data Map ,data = {}",JSON.toJSONString(jobDataMap));
+//        // 表类型编码
+//        String meterTypeCode = jobDataMap.getString("MeterTypeCode");
+//        // 用水量测点编码
+//        String meterWSVCode = jobDataMap.getString("MeterWSVCode");
+//
+//        int count = meterReadRecordService.waterMeterReadDataByType(new Date() ,
+//                meterTypeCode,meterWSVCode);
+//        clock.stop(); // 计时结束
+//        log.info("End Water Meter Read Job ,Count = {},Cost = {}ms",count,clock.getTime());
     }
 }

+ 3 - 0
smart-city-platform/src/main/java/com/bz/smart_city/service/DeviceDataService.java

@@ -1,4 +1,5 @@
 package com.bz.smart_city.service;
+import com.bz.smart_city.dto.DeviceDataQueryDTO;
 import com.zcxk.zoniot.smartcity.common.dto.DeviceMeasuringDataDTO;
 import com.zcxk.zoniot.smartcity.common.model.DeviceData;
 import java.util.Date;
@@ -60,4 +61,6 @@ public interface DeviceDataService {
              Integer index,
              Integer pageSize
     );
+
+    List<DeviceData> queryDeviceDataList(DeviceDataQueryDTO param);
 }

+ 15 - 32
smart-city-platform/src/main/java/com/bz/smart_city/service/MeterReadRecordService.java

@@ -1,51 +1,34 @@
 package com.bz.smart_city.service;
-
-import java.util.Date;
 import java.util.List;
-
 import com.bz.smart_city.commom.model.CommonQueryCondition;
 import com.bz.smart_city.commom.model.ListObjectWrapper;
 import com.bz.smart_city.commom.model.Pagination;
-import com.bz.smart_city.dto.ClearingDataDTO;
 import com.bz.smart_city.dto.MeterReadDataDTO;
+import com.bz.smart_city.dto.MeterReadRecordQueryDTO;
 import com.bz.smart_city.dto.WaterConsumptionDto;
 import com.bz.smart_city.dto.WaterConsumptionSummaryDto;
 import com.bz.smart_city.entity.MeterReadRate;
 import com.bz.smart_city.entity.MeterReadRecord;
-import com.bz.smart_city.entity.MeterRecordStat;
-
-import javax.servlet.http.HttpServletResponse;
 
 public interface MeterReadRecordService{
+    /**
+     * 更新抄表记录
+     * @param deviceId
+     * @param param
+     * @return
+     */
+    Long updateMeterReadRecords(Long deviceId , com.zcxk.zoniot.smartcity.common.model.MeterReadRecord param) ;
 
-    int insert(MeterReadRecord meterReadRecord);
-
-    int insertSelective(MeterReadRecord meterReadRecord);
-
-    int insertList(List<MeterReadRecord> meterReadRecords);
-
-    int updateByPrimaryKeySelective(MeterReadRecord meterReadRecord);
-    
-    
-    public int createMeterReadRecord(Date date);
-    
-    public int createMeterReadRecordAsync(Date date);
+    List<com.zcxk.zoniot.smartcity.common.model.MeterReadRecord> queryMeterReadRecord(MeterReadRecordQueryDTO param);
 
-    public int createMeterReadRecordForRollback(Date date);
-    
-    
-    public Pagination<MeterReadRecord> queryMeterReadRecord(CommonQueryCondition condition ,int pageNum ,int pageSize);
-    
-    public Pagination<MeterReadRate> queryMeterReadRate(MeterReadRate param, int pageNum,int pageSize);
     @Deprecated
-    public MeterReadRate summaryMeterReadRate(MeterReadRate param);
+    Pagination<MeterReadRecord> queryMeterReadRecord(CommonQueryCondition condition ,int pageNum ,int pageSize);
     
-    public MeterReadRate summaryMeterReadRate(CommonQueryCondition condition);
+    Pagination<MeterReadRate> queryMeterReadRate(MeterReadRate param, int pageNum,int pageSize);
 
-    @Deprecated
-    public List<MeterReadRate> analysisMeterReadRate(MeterReadRate param);
-    
-    public List<MeterReadRate> analysisMeterReadRate(CommonQueryCondition condition);
+    MeterReadRate summaryMeterReadRate(CommonQueryCondition condition);
+
+    List<MeterReadRate> analysisMeterReadRate(CommonQueryCondition condition);
 
     WaterConsumptionSummaryDto waterConsumptionSummary(CommonQueryCondition condition);
 
@@ -69,5 +52,5 @@ public interface MeterReadRecordService{
      * @param wsvCode 用水量字段标识符
      * @return
      */
-    int waterMeterReadDataByType(Date date ,String waterMeterCode ,String wsvCode);
+    // int waterMeterReadDataByType(Date date ,String waterMeterCode ,String wsvCode);
 }

+ 54 - 28
smart-city-platform/src/main/java/com/bz/smart_city/service/clearing/impl/ClearingRecordServiceImpl.java

@@ -1,6 +1,10 @@
 package com.bz.smart_city.service.clearing.impl;
 
+import com.bz.smart_city.dto.MeterReadRecordQueryDTO;
+import com.bz.smart_city.service.MeterReadRecordService;
+import com.zcxk.zoniot.smartcity.common.model.MeterReadRecord;
 import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.domain.Sort;
 import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 
@@ -8,19 +12,19 @@ import com.bz.smart_city.entity.ClearingPlan;
 import com.bz.smart_city.entity.ClearingRecord;
 import com.bz.smart_city.entity.ClearingRecordItem;
 import com.bz.smart_city.entity.Device;
-import com.bz.smart_city.entity.MeterReadRecord;
 import com.bz.smart_city.service.clearing.ClearingRecordService;
 import com.github.pagehelper.PageHelper;
 
 import lombok.extern.slf4j.Slf4j;
 
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.List;
 
 import com.bz.smart_city.commom.exception.ServiceException;
-import com.bz.smart_city.commom.model.CommonQueryCondition;
 import com.bz.smart_city.commom.model.Pagination;
 import com.bz.smart_city.commom.model.ResultStatus;
 import com.bz.smart_city.commom.util.DateTimeUtil;
@@ -28,11 +32,10 @@ import com.bz.smart_city.dao.ClearingPlanMapper;
 import com.bz.smart_city.dao.ClearingRecordItemMapper;
 import com.bz.smart_city.dao.ClearingRecordMapper;
 import com.bz.smart_city.dao.DeviceMapper;
-import com.bz.smart_city.dao.MeterReadRateMapper;
-import com.bz.smart_city.dao.MeterReadRecordMapper;
 import com.bz.smart_city.dto.ClearingRecordDTO;
 import com.bz.smart_city.dto.DeviceDto;
 import com.bz.smart_city.dto.MeterReadRecordDTO;
+
 /**
  * 结算记录服务实现类
  * @Description  
@@ -55,8 +58,11 @@ public class ClearingRecordServiceImpl implements ClearingRecordService{
     @Resource
     private DeviceMapper deviceMapper;
     
-    @Resource
-    private MeterReadRecordMapper  meterReadRecordMapper;
+    //@Resource
+    //private MeterReadRecordMapper  meterReadRecordMapper;
+
+	@Resource
+	MeterReadRecordService  meterReadRecordService;
 
     @Override
 	public int generateClearingRecord(Integer clearingPlanId,Date date) {
@@ -161,51 +167,60 @@ public class ClearingRecordServiceImpl implements ClearingRecordService{
      * @param device 设备
      * @param clearingStartDate 本次月结开始时间
      * @param lastItem 上次月结数据
-     * @param List<MeterReadRecord> 月结开始时间至月结结束时间中的抄表数据
+     * @param records 月结开始时间至月结结束时间中的抄表数据
      * @return
      */
     protected MeterReadRecordDTO getClearingStartMeterRecord(DeviceDto device,Date clearingStartDate ,ClearingRecordItem lastItem,List<MeterReadRecord> records) {
     	MeterReadRecordDTO r = new MeterReadRecordDTO();
-    	if(device.getDeviceStatus() == 5) { // 设备为未启动则直接设置为 0 
+    	if(device.getDeviceStatus() == 5) {
+			// 设备为未启动则直接设置为 0
     		r.setReadDateTime(clearingStartDate);
     		r.setReadData("0");
     	}
     	else {
-    		if(lastItem != null) { // 将上期抄表止度作为本期抄表开始起度
+    		if(lastItem != null) {
+				// 将上期抄表止度作为本期抄表开始起度
     			r.setReadDateTime(lastItem.getCurrentPeriodDate());
     			r.setReadData(lastItem.getCurrentPeriodData());
     		}
     		else { // 没有上一期数据则取距离结算开始日期最近的数据
-    			CommonQueryCondition condition = new CommonQueryCondition();
-    			condition.setDeviceId(device.getId());
-    			condition.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingStartDate, "yyyyMMdd")));
-    			List<MeterReadRecord> mrs = meterReadRecordMapper.queryDeviceMeterReadRecordWithCondtion(condition);
-    			if(mrs.size() == 0 ) { // 获取不到数据,从取距离结算结束日期最远的数据
+				MeterReadRecordQueryDTO param = new MeterReadRecordQueryDTO();
+				param.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingStartDate, "yyyyMMdd")));
+				param.setDeviceId(device.getId());
+				param.setSort(new Sort(Sort.Direction.DESC,"readDate"));
+				List<MeterReadRecord> mrs = meterReadRecordService.queryMeterReadRecord(param);
+    			if(mrs.size() == 0 ) {
+    				// 获取不到数据,从取距离结算结束日期最远的数据
     				if(records.size() == 0) {
     					r.setReadDateTime(clearingStartDate);
     		    		r.setReadData("0");
     				}
     				else {
     					MeterReadRecord mr = records.get(records.size() - 1);
-    					r.setReadDateTime(mr.getReadTime());
+    					r.setReadDateTime(localDateTimeToDate(mr.getReadTime()));
         				r.setReadData(mr.getReadData());
     				}
     			}
     			else {
     				MeterReadRecord mr = mrs.get(0);
-    				r.setReadDateTime(mr.getReadTime());
+    				r.setReadDateTime(localDateTimeToDate(mr.getReadTime()));
     				r.setReadData(mr.getReadData());
     			}
     		}
     	}
     	return r; 
     }
+
+    protected Date localDateTimeToDate(LocalDateTime localDateTime){
+		Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());
+		return date;
+	}
     /**
 	  *  获取结算结束日期的抄表数据
 	 * @param device 设备
 	 * @param clearingEndDate 本次月结结束时间
 	 * @param lastItem 上次月结数据
-	 * @param List<MeterReadRecord> 月结开始时间至月结结束时间中的抄表数据
+	 * @param records 月结开始时间至月结结束时间中的抄表数据
 	 * @return
 	 */
 	protected MeterReadRecordDTO getClearingEndMeterRecord(DeviceDto device,Date clearingEndDate ,ClearingRecordItem lastItem,List<MeterReadRecord> records) {
@@ -221,24 +236,29 @@ public class ClearingRecordServiceImpl implements ClearingRecordService{
 	    			r.setReadData(lastItem.getCurrentPeriodData());
 				}
 				else { // 无上期数据时,则取距离结算结束日期最近的数据
-					CommonQueryCondition condition = new CommonQueryCondition();
-	    			condition.setDeviceId(device.getId());
-	    			condition.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
-	    			List<MeterReadRecord> mrs = meterReadRecordMapper.queryDeviceMeterReadRecordWithCondtion(condition);
+					MeterReadRecordQueryDTO param = new MeterReadRecordQueryDTO();
+					param.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
+					param.setDeviceId(device.getId());
+					param.setSort(new Sort(Sort.Direction.DESC,"readDate"));
+					List<MeterReadRecord> mrs = meterReadRecordService.queryMeterReadRecord(param);
+//					CommonQueryCondition condition = new CommonQueryCondition();
+//	    			condition.setDeviceId(device.getId());
+//	    			condition.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
+//	    			List<MeterReadRecord> mrs = meterReadRecordMapper.queryDeviceMeterReadRecordWithCondtion(condition);
 	    			if(mrs.size() == 0 ) {
 	    				r.setReadDateTime(clearingEndDate);
 	    				r.setReadData("0");
 	    			}
 	    			else {
 	    				MeterReadRecord mr = mrs.get(0);
-	    				r.setReadDateTime(mr.getReadTime());
+	    				r.setReadDateTime(localDateTimeToDate(mr.getReadTime()));
 	    				r.setReadData(mr.getReadData());
 	    			}
 				}
 			}
 			else { // 取结算周期内距离结算结束日期最近的数据
 				MeterReadRecord mr = records.get(0);
-				r.setReadDateTime(mr.getReadTime());
+				r.setReadDateTime(localDateTimeToDate(mr.getReadTime()));
 				r.setReadData(mr.getReadData());
 			}
 		}
@@ -252,11 +272,17 @@ public class ClearingRecordServiceImpl implements ClearingRecordService{
      * @return
      */
     protected List<MeterReadRecord> queryDeviceMeterReadRecordBetweenClearingStartAndEndDate(DeviceDto device,Date clearingStartDate , Date  clearingEndDate){
-    	CommonQueryCondition condition = new CommonQueryCondition();
-		condition.setDeviceId(device.getId());
-		condition.setStartDate(Integer.parseInt(DateTimeUtil.formatDate(clearingStartDate, "yyyyMMdd")));
-		condition.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
-		List<MeterReadRecord> mrs = meterReadRecordMapper.queryDeviceMeterReadRecordWithCondtion(condition);
+		MeterReadRecordQueryDTO param = new MeterReadRecordQueryDTO();
+		param.setStartDate(Integer.parseInt(DateTimeUtil.formatDate(clearingStartDate, "yyyyMMdd")));
+		param.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
+		param.setDeviceId(device.getId());
+		param.setSort(new Sort(Sort.Direction.DESC,"readDate"));
+		List<MeterReadRecord> mrs = meterReadRecordService.queryMeterReadRecord(param);
+//    	CommonQueryCondition condition = new CommonQueryCondition();
+//		condition.setDeviceId(device.getId());
+//		condition.setStartDate(Integer.parseInt(DateTimeUtil.formatDate(clearingStartDate, "yyyyMMdd")));
+//		condition.setEndDate(Integer.parseInt(DateTimeUtil.formatDate(clearingEndDate, "yyyyMMdd")));
+//		List<MeterReadRecord> mrs = meterReadRecordMapper.queryDeviceMeterReadRecordWithCondtion(condition);
     	return mrs ;
     }
     

+ 14 - 15
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataDimServiceImpl.java

@@ -20,36 +20,35 @@ import com.bz.smart_city.service.DeviceDataDimService;
 @Service
 public class DeviceDataDimServiceImpl implements DeviceDataDimService {
 
-    @Resource
-    private DeviceDataDimMapper deviceDataDimMapper;
 
     @Override
     public int insert(DeviceDataDim deviceDataDim) {
-        return deviceDataDimMapper.insert(deviceDataDim);
+        return 0;
     }
 
     @Override
     public int insertSelective(DeviceDataDim deviceDataDim) {
-        return deviceDataDimMapper.insertSelective(deviceDataDim);
+        return 0;
     }
 
     @Override
     public int insertList(List<DeviceDataDim> deviceDataDims) {
-        return deviceDataDimMapper.insertList(deviceDataDims);
+        return 0;
     }
 
     @Override
     public List<DeviceData> queryDeviceRealtimeData(Integer system, Integer building, Integer floor, Integer startDate,Integer endDate, Integer measuring, Long deviceId) {
-        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
-        if(startDate == 0){
-            LocalDateTime startDateTime =  LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
-            startDate = Integer.valueOf(startDateTime.format(df));
-        }
-        if(endDate == 0){
-            LocalDateTime endDateTime =  LocalDateTime.now().with(LocalTime.MAX);
-            endDate = Integer.valueOf(endDateTime.format(df));
-        }
-        return deviceDataDimMapper.queryDeviceRealtimeData(system, building, floor, startDate, endDate, measuring, deviceId);
+//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
+//        if(startDate == 0){
+//            LocalDateTime startDateTime =  LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
+//            startDate = Integer.valueOf(startDateTime.format(df));
+//        }
+//        if(endDate == 0){
+//            LocalDateTime endDateTime =  LocalDateTime.now().with(LocalTime.MAX);
+//            endDate = Integer.valueOf(endDateTime.format(df));
+//        }
+//        return deviceDataDimMapper.queryDeviceRealtimeData(system, building, floor, startDate, endDate, measuring, deviceId);
+        return null;
     }
 
 

+ 25 - 20
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataPushServiceImpl.java

@@ -12,10 +12,13 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import com.bz.smart_city.dto.MeterReadData;
+import com.bz.smart_city.dao.DeviceDataDimMapper;
+import com.bz.smart_city.dto.MeterReadRecordQueryDTO;
 import com.bz.smart_city.service.DeviceDataService;
+import com.bz.smart_city.service.MeterReadRecordService;
 import com.zcxk.zoniot.smartcity.common.model.DeviceData;
 import com.zcxk.zoniot.smartcity.common.model.DeviceMeasuringData;
+import com.zcxk.zoniot.smartcity.common.model.MeterReadRecord;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.InitializingBean;
@@ -24,19 +27,15 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
 import com.alibaba.fastjson.JSON;
-import com.bz.smart_city.commom.model.CommonQueryCondition;
 import com.bz.smart_city.commom.util.CronUtil;
 import com.bz.smart_city.commom.util.DateTimeUtil;
 import com.bz.smart_city.commom.util.HttpClientUtils;
-import com.bz.smart_city.dao.DeviceDataDimMapper;
 import com.bz.smart_city.dao.DeviceDataPushConfigMapper;
 import com.bz.smart_city.dao.DeviceMapper;
-import com.bz.smart_city.dao.MeterReadRecordMapper;
 import com.bz.smart_city.dao.PushLogMapper;
 import com.bz.smart_city.dto.DeviceDto;
 import com.bz.smart_city.entity.DeviceDataDim;
 import com.bz.smart_city.entity.DeviceDataPushConfig;
-import com.bz.smart_city.entity.MeterReadRecord;
 import com.bz.smart_city.entity.PushLog;
 import com.bz.smart_city.quartz.entity.QuartzEntity;
 import com.bz.smart_city.quartz.job.DeviceDataPushJob;
@@ -65,15 +64,15 @@ public class DeviceDataPushServiceImpl implements DeviceDataPushService , Initia
 	@Value("${fj.push.url}")
 	String pushUrl ; 
 	
+	// @Autowired
+	// MeterReadRecordMapper meterReadRecordMapper;
+
 	@Autowired
-	MeterReadRecordMapper meterReadRecordMapper; 
-	
+	MeterReadRecordService meterReadRecordService ;
+
 	@Autowired
 	DeviceMapper  deviceMapper;
-	
-	@Autowired
-	DeviceDataDimMapper deviceDataDimMapper;
-	
+
 	@Autowired
 	DeviceDataPushConfigMapper  deviceDataPushConfigMapper;
 	
@@ -241,7 +240,7 @@ public class DeviceDataPushServiceImpl implements DeviceDataPushService , Initia
 		boolean isSuccess = false ; 
 		Map rspObj = JSON.parseObject(response, Map.class);
 		Integer code = MapUtils.getInteger(rspObj, "code");
-		if(code == 0 ) isSuccess = true ;
+		if(code == 0 ) {isSuccess = true ;}
 		return isSuccess; 
 	}
 	@Override
@@ -385,19 +384,25 @@ public class DeviceDataPushServiceImpl implements DeviceDataPushService , Initia
         Date endDate = calendar.getTime();
     	return endDate;
     }
-	protected List<MeterReadRecord> getMeterReadRecordByCustomerId(Integer customerId,Integer date) {
-		CommonQueryCondition condition = new CommonQueryCondition();
-		condition.setCustormerId(customerId);
-		condition.setEndDate(date);
-		condition.setStartDate(date);
-		condition.setReadStatus("2");
-		List<MeterReadRecord> result = meterReadRecordMapper.queryMeterReadRecordWithCondtion(condition);
+	protected List<MeterReadRecord> getMeterReadRecordByCustomerId(Integer customerId, Integer date) {
+//		CommonQueryCondition condition = new CommonQueryCondition();
+//		condition.setCustormerId(customerId);
+//		condition.setEndDate(date);
+//		condition.setStartDate(date);
+//		condition.setReadStatus("2");
+//		List<MeterReadRecord> result = meterReadRecordMapper.queryMeterReadRecordWithCondtion(condition);
+		MeterReadRecordQueryDTO param = new MeterReadRecordQueryDTO();
+		param.setCustomerId(customerId);
+		param.setEndDate(date);
+		param.setStartDate(date);
+		param.setReadStatus("2");
+		List<MeterReadRecord> result = meterReadRecordService.queryMeterReadRecord(param);
 		return result;
 	}
 	
 	/**
 	  * 获取消息签名
-	 * @param msg
+	 * @param
 	 * @return
 	 */
 	public static String getSign(PostData data) {

+ 28 - 0
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataServiceImpl.java

@@ -2,6 +2,7 @@ package com.bz.smart_city.service.impl;
 
 
 import com.bz.smart_city.dao.DeviceMapper;
+import com.bz.smart_city.dto.DeviceDataQueryDTO;
 import com.bz.smart_city.dto.MeterReadData;
 import com.bz.smart_city.service.DeviceDataService;
 import com.mongodb.client.result.UpdateResult;
@@ -125,6 +126,33 @@ public class DeviceDataServiceImpl implements DeviceDataService {
         List<DeviceData> deviceDataList = mongoTemplate.find(query, DeviceData.class);
         return deviceDataList;
     }
+
+    @Override
+    public List<DeviceData> queryDeviceDataList(DeviceDataQueryDTO param) {
+        Query query = buildBaseQuery(param);
+        List<DeviceData> deviceDataList = mongoTemplate.find(query, DeviceData.class);
+        return deviceDataList;
+    }
+
+    protected  Query buildBaseQuery(DeviceDataQueryDTO param){
+        Query query = new Query();
+        if(param.getStartDate() != null && param.getEndDate() != null){
+            query.addCriteria(Criteria.where("receiveTime").gte(param.getStartDate()).lte(param.getEndDate()));
+        }
+        if(param.getDeviceId() != null){
+            query.addCriteria(Criteria.where("deviceId").is(param.getDeviceId()));
+        }
+        if(param.getDeviceNo() != null){
+            query.addCriteria(Criteria.where("deviceNo").is(param.getDeviceNo()));
+        }
+        if(param.getPageIndex() != null &&param.getPageSize() != null){
+            query.with(PageRequest.of(param.getPageIndex(), param.getPageSize()));
+        }
+        if(param.getSort() != null){
+            query.with(param.getSort());
+        }
+        return query ;
+    }
     protected  Query buildQuery(String customers, String communitys, String buildings, Date beginDate, Date endDate){
         Query query = new Query();
         if(StringUtils.isNotBlank(customers)){

+ 135 - 72
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/DeviceDataTimeOutServiceImpl.java

@@ -9,6 +9,9 @@ import java.util.Map;
 
 import javax.annotation.Resource;
 
+import com.bz.smart_city.dto.DeviceDataQueryDTO;
+import com.bz.smart_city.service.DeviceDataService;
+import com.zcxk.zoniot.smartcity.common.model.DeviceData;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.InitializingBean;
@@ -16,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
+import org.springframework.data.domain.Sort;
 import org.springframework.kafka.core.KafkaTemplate;
 import org.springframework.stereotype.Service;
 
@@ -67,8 +71,6 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 	DeviceErrorMapper deviceErrorMapper;
 	@Autowired
 	DeviceMapper deviceMapper;
-	@Autowired
-	DeviceDataDimMapper deviceDataDimMapper;
 	@Resource
 	SnowflakeIdWorker idWorker;
 	@Resource
@@ -86,6 +88,9 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 	@Autowired
 	KafkaTemplate<String, Object> kafkaTemplate;
 
+	@Autowired
+	DeviceDataService  deviceDataService;
+
 	static Map<String, AlarmType> alarmTypes = new HashMap<String, AlarmType>();
 
 	@Override
@@ -97,26 +102,28 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 		Device param = new Device();
 		param.setDeviceType(deviceTypeId);
 		List<Integer> statusList = new ArrayList<Integer>();
-		statusList.add(1); // 正常
-		statusList.add(2); // 故障
+		// 正常 故障  预警
+		statusList.add(1);
+		statusList.add(2);
 		// statusList.add(3);
-		statusList.add(4); // 预警
+		statusList.add(4);
 		param.setDeviceStatusList(statusList);
 		int total = deviceMapper.countDevice(param);
 
 		int pageSize = 1000;
 
 		int totalPage = total / pageSize;
-		if (total % pageSize != 0)
+		if (total % pageSize != 0){
 			totalPage++;
+		}
 		List<DeviceError> errorList = new ArrayList<DeviceError>();
-		for (int i = 1; i <= totalPage; i++) { // 测试修改
-			int start = (i - 1) * pageSize; // 测试修改
-			List<DeviceDto> deviceList = deviceMapper.getDeviceList(param, start, pageSize); // 测试修改
+		for (int i = 1; i <= totalPage; i++) {
+			int start = (i - 1) * pageSize;
+			List<DeviceDto> deviceList = deviceMapper.getDeviceList(param, start, pageSize);
 
 			for (DeviceDto device : deviceList) {
 				// 先从缓存中获取缓存数据
-				Long deviceId = device.getId(); // 设备id
+				Long deviceId = device.getId();
 				// String deviceNo = device.getDeviceNo();
 				String deviceDataJSONStr = redisUtil.get(String.valueOf(deviceId));
 				Date date = DateTimeUtil.yesterdayLastDate();
@@ -125,80 +132,100 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 					JSONObject dataObj = (JSONObject) JSON.parse(deviceDataJSONStr);
 					// 获取上报时间测点
 					JSONObject timeData = (JSONObject) dataObj.get("TIME");
-					String timeStr = (String) timeData.get("measuringVaule"); // 格式 20181221100659
+					// 格式 20181221100659
+					String timeStr = (String) timeData.get("measuringData");
 					// 判断上报时间是否超时
 					Date cacheDate = DateTimeUtil.parseDate(timeStr, "yyyyMMddHHmmss");
 					// if ((date.getTime() - cacheDate.getTime()) > period * 3600 * 1000)
-					if (cacheDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) { // 当设备为预警状态下,再进一步判断是否通讯中断
+					// 当设备为预警状态下,再进一步判断是否通讯中断
+					if (cacheDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) {
 						DeviceError alarm = createTimeOutDerviceError(device);
 						if (alarm != null) {
 							errorList.add(alarm);
 							Device obj = new Device();
 							obj.setId(device.getId());
-							obj.setDeviceStatus(2); // 设置设备为故障状态
+							// 设置设备为故障状态
+							obj.setDeviceStatus(2);
 							deviceMapper.updateByPrimaryKeySelective(obj);
 							result++;
 						}
-					} else if (cacheDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警 //(date.getTime() - cacheDate.getTime()) > 24 * 3600 * 1000
+					}
+					// 超过24小时没有上报数据则将设备状态设置为预警 //(date.getTime() - cacheDate.getTime()) > 24 * 3600 * 1000
+					else if (cacheDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) {
 						Device obj = new Device();
 						obj.setId(device.getId());
-						obj.setDeviceStatus(4); // 设置设备为预警状态
+						// 设置设备为预警状态
+						obj.setDeviceStatus(4);
 						deviceMapper.updateByPrimaryKeySelective(obj);
 						// 预警状态下的连续天数
-						if (device.getDeviceStatus() == 2) { // 故障天数清零
+						if (device.getDeviceStatus() == 2) {
+							// 故障天数 清零
 							waterMeterErrorDaysMapper.reset(deviceId);
-						} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+						} else if (device.getDeviceStatus() == 2) {
+							// 故障连续天数+1
 							waterMeterErrorDaysMapper.addDays(deviceId);
 						}
 					}
 				} else { // 缓存中没有数据则从数据库中进行查询
-					DeviceDataDim data = getLastDeviceData(deviceId);
+					DeviceData data = getLastDeviceData(deviceId);
 					if (data != null) {
-						Date sendTime = data.getSendTime();
-						if (sendTime.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) { //(date.getTime() - sendTime.getTime()) > period * 3600 * 1000
+						Date sendTime = data.getReceiveTime();
+						//(date.getTime() - sendTime.getTime()) > period * 3600 * 1000
+						if (sendTime.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) {
 							DeviceError alarm = createTimeOutDerviceError(device);
 							if (alarm != null) {
 								errorList.add(alarm);
 								Device obj = new Device();
 								obj.setId(device.getId());
-								obj.setDeviceStatus(2); // 设置设备为故障状态
+								// 设置设备为故障状态
+								obj.setDeviceStatus(2);
 								deviceMapper.updateByPrimaryKeySelective(obj);
 								result++;
 							}
-						} else if (sendTime.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警 (date.getTime() - sendTime.getTime()) > 24 * 3600 * 1000
+						}
+						// 超过24小时没有上报数据则将设备状态设置为预警 (date.getTime() - sendTime.getTime()) > 24 * 3600 * 1000
+						else if (sendTime.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) {
 							Device obj = new Device();
 							obj.setId(device.getId());
-							obj.setDeviceStatus(4); // 设置设备为预警状态
+							// 设置设备为预警状态
+							obj.setDeviceStatus(4);
 							deviceMapper.updateByPrimaryKeySelective(obj);
 
 							// 预警状态下的连续天数
-							if (device.getDeviceStatus() == 2) { // 故障天数清零
+							if (device.getDeviceStatus() == 2) {
+								// 故障天数清零
 								waterMeterErrorDaysMapper.reset(deviceId);
-							} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+							} else if (device.getDeviceStatus() == 2) {
+								// 故障连续天数+1
 								waterMeterErrorDaysMapper.addDays(deviceId);
 							}
 						}
-					} else { // 如果没上报数据则根据设备的创建时间进行对比
-						if (deviceCreateDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) { // (date.getTime() - deviceCreateDate.getTime()) > period * 3600 * 1000
+					} else {
+						// 如果没上报数据则根据设备的创建时间进行对比
+						if (deviceCreateDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) {
 							DeviceError alarm = createTimeOutDerviceError(device);
 							if (alarm != null) {
 								errorList.add(alarm);
 								Device obj = new Device();
 								obj.setId(device.getId());
-								obj.setDeviceStatus(2); // 设置设备为故障状态
+								// 设置设备为故障状态
+								obj.setDeviceStatus(2);
 								deviceMapper.updateByPrimaryKeySelective(obj);
 								result++;
 							}
 						} else if (deviceCreateDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警 (date.getTime() - deviceCreateDate.getTime()) > 24 * 3600 * 1000
 							Device obj = new Device();
 							obj.setId(device.getId());
-							obj.setDeviceStatus(4); // 设置设备为预警状态
+							// 设置设备为预警状态
+							obj.setDeviceStatus(4);
 							deviceMapper.updateByPrimaryKeySelective(obj);
 
 							// 预警状态下的连续天数
-							if (device.getDeviceStatus() == 2) { // 故障天数清零
+							if (device.getDeviceStatus() == 2) {
+								// 故障天数清零
 								waterMeterErrorDaysMapper.reset(deviceId);
-							} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+							} else if (device.getDeviceStatus() == 2) {
+								// 故障连续天数+1
 								waterMeterErrorDaysMapper.addDays(deviceId);
 							}
 						}
@@ -215,7 +242,7 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 			}
 
 			try {
-				Thread.sleep(3000l);
+				Thread.sleep(3000L);
 			} catch (Exception e) {
 				log.error("runtime error", e);
 			}
@@ -229,7 +256,7 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 			errorList.clear();
 		}
 		log.info("DeviceDataTimeOutService createTimeOutAlarm cost ="
-				+ (new Date().getTime() - startTime.getTime()) / 1000 + " seconds");
+				+ (System.currentTimeMillis()- startTime.getTime()) / 1000 + " seconds");
 		log.info("end DeviceDataTimeOutService createTimeOutAlarm, result = " + result);
 		return result;
 	}
@@ -237,39 +264,50 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 	/**
 	 * 处理告警数据
 	 * 
-	 * @param device
-	 * @param errors
-	 * @param lastReceiveTime
+	 * @param
+	 * @param
+	 * @param
 	 */
 	protected DeviceError processAlarm(DeviceError error) {
 		DeviceError rtnError = null;
 		// 1,查询最新告警记录
 		Long deviceId = error.getDeviceId();
 		List<DeviceError> lastErrorList = getDeviceLastErrorList(deviceId);
-		if (lastErrorList == null || lastErrorList.size() == 0) { // 无最新告警记录,将告警记录直接入库
+		if (lastErrorList == null || lastErrorList.size() == 0) {
+			// 无最新告警记录,将告警记录直接入库
 			rtnError = saveNewDeviceError(error);
 		} else {
 			// 2,有最新告警记录,对比最新告警的告警类型是否同新生成告警记录的告警类型
 			boolean isSame = false;
 			DeviceError originalError = null;
 			for (DeviceError lde : lastErrorList) {
-				if (2 == lde.getHandleStatus() && lde.getAlarmTypeId() == error.getAlarmTypeId()) { // 处理状态 1.已处理;2.未处理
+				// 处理状态 1.已处理;2.未处理
+				if (2 == lde.getHandleStatus() && lde.getAlarmTypeId().equals( error.getAlarmTypeId())) {
 					isSame = true;
 					originalError = lde;
 					break;
 				}
 			}
-			if (!isSame) { // 告警类型与上次告警类型不同,则直接新增记录
+			if (!isSame) {
+				// 告警类型与上次告警类型不同,则直接新增记录
 				rtnError = saveNewDeviceError(error);
-			} else { // 告警类型与上次告警类型相同
-						// 3,查询上次告警时间至本次告警时间是否有上传数据
+			} else {
+				// 告警类型与上次告警类型相同
+				// 3,查询上次告警时间至本次告警时间是否有上传数据
 				Date lastAlarmTime = Jdk8DateUtils.getLocalDateTimeToDate(lastErrorList.get(0).getLastAlarmTime());
 				Date currentAlarmTime = Jdk8DateUtils.getLocalDateTimeToDate(error.getAlarmTime());
-				List<DeviceDataDim> receiveDatas = deviceDataDimMapper.getDeviceDataBetweenDate(lastAlarmTime,
-						currentAlarmTime, deviceId);
-				if (receiveDatas != null && receiveDatas.size() != 0) { // 有新上报数据,记录为新告警
+				DeviceDataQueryDTO param = new DeviceDataQueryDTO();
+				param.setDeviceId(deviceId);
+				param.setEndDate(currentAlarmTime);
+				param.setStartDate(lastAlarmTime);
+				List<DeviceData> receiveDatas = deviceDataService.queryDeviceDataList(param);
+//				List<DeviceDataDim> receiveDatas = deviceDataDimMapper.getDeviceDataBetweenDate(lastAlarmTime,
+//						currentAlarmTime, deviceId);
+				if (receiveDatas != null && receiveDatas.size() != 0) {
+					// 有新上报数据,记录为新告警
 					rtnError = saveNewDeviceError(error);
-				} else { // 无新上报数据,更新最后一次报警的次数与最后上报时间
+				} else {
+					// 无新上报数据,更新最后一次报警的次数与最后上报时间
 					rtnError = updateExistDeviceError(error, originalError);
 				}
 			}
@@ -304,7 +342,7 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 	/**
 	 * 查看最后一次上报的告警信息
 	 * 
-	 * @param device
+	 * @param
 	 * @return
 	 */
 	protected List<DeviceError> getDeviceLastErrorList(Long deviceId) {
@@ -378,8 +416,9 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 					target = alarmType;
 				}
 			}
-			if (target != null)
+			if(target != null){
 				alarmTypes.put(key, target);
+			}
 		}
 		return target;
 	}
@@ -393,12 +432,18 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 		return alarmTypeMapper.queryAlaramType(param);
 	}
 
-	protected DeviceDataDim getLastDeviceData(Long deviceId) {
-		DeviceDataDim result = null;
-		DeviceDataDim p = new DeviceDataDim();
-		p.setDeviceId(deviceId);
+	protected DeviceData getLastDeviceData(Long deviceId) {
+		DeviceData result = null;
+//		DeviceDataDim p = new DeviceDataDim();
+//		p.setDeviceId(deviceId);
 //		p.setDeviceNo(deviceNo);
-		List<DeviceDataDim> datas = deviceDataDimMapper.queryDeviceDataDim(p, 1);
+		DeviceDataQueryDTO param = new DeviceDataQueryDTO();
+		param.setSort(new Sort(Sort.Direction.DESC, "receiveTime"));
+		param.setDeviceId(deviceId);
+		param.setPageIndex(0);
+		param.setPageSize(1);
+		List<DeviceData> datas = deviceDataService.queryDeviceDataList(param);
+//		List<DeviceDataDim> datas = deviceDataDimMapper.queryDeviceDataDim(p, 1);
 		if (datas.size() > 0) {
 			result = datas.get(0);
 		}
@@ -442,51 +487,64 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 			JSONObject dataObj = (JSONObject) JSON.parse(deviceDataJSONStr);
 			// 获取上报时间测点
 			JSONObject timeData = (JSONObject) dataObj.get("TIME");
-			String timeStr = (String) timeData.get("measuringVaule"); // 格式 20181221100659
+			// 格式 20181221100659
+			String timeStr = (String) timeData.get("measuringVaule");
 			// 判断上报时间是否超时
 			Date cacheDate = DateTimeUtil.parseDate(timeStr, "yyyyMMddHHmmss");
-			if (cacheDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) { // 当设备为预警状态下,再进一步判断是否通讯中断
+			// 当设备为预警状态下,再进一步判断是否通讯中断
+			if (cacheDate.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) {
 				alarm = createTimeOutDerviceError(device);
 				if (alarm != null) {
 					Device obj = new Device();
 					obj.setId(device.getId());
-					obj.setDeviceStatus(2); // 设置设备为故障状态
+					// 设置设备为故障状态
+					obj.setDeviceStatus(2);
 					deviceMapper.updateByPrimaryKeySelective(obj);
 				}
-			} else if (cacheDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警
+			} else if (cacheDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) {
+				// 超过24小时没有上报数据则将设备状态设置为预警
 				Device obj = new Device();
 				obj.setId(device.getId());
-				obj.setDeviceStatus(4); // 设置设备为预警状态
+				// 设置设备为预警状态
+				obj.setDeviceStatus(4);
 				deviceMapper.updateByPrimaryKeySelective(obj);
 				// 预警状态下的连续天数
-				if (device.getDeviceStatus() == 2) { // 故障天数清零
+				if (device.getDeviceStatus() == 2) {
+					// 故障天数清零
 					waterMeterErrorDaysMapper.reset(deviceId);
-				} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+				} else if (device.getDeviceStatus() == 2) {
+					// 故障连续天数+1
 					waterMeterErrorDaysMapper.addDays(deviceId);
 				}
 			}
-		} else { // 缓存中没有数据则从数据库中进行查询
-			DeviceDataDim data = getLastDeviceData(deviceId);
+		} else {
+			// 缓存中没有数据则从数据库中进行查询
+			DeviceData  data = getLastDeviceData(deviceId);
 			if (data != null) {
-				Date sendTime = data.getSendTime();
+				Date sendTime = data.getReceiveTime();
 				if (sendTime.before(DateTimeUtil.before(date, new Double(period * 3600 * 1000).longValue()))) {
 					alarm = createTimeOutDerviceError(device);
 					if (alarm != null) {
 						Device obj = new Device();
 						obj.setId(device.getId());
-						obj.setDeviceStatus(2); // 设置设备为故障状态
+						obj.setDeviceStatus(2);
+						// 设置设备为故障状态
 						deviceMapper.updateByPrimaryKeySelective(obj);
 					}
-				} else if (sendTime.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警
+				} else if (sendTime.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) {
+					// 超过24小时没有上报数据则将设备状态设置为预警
 					Device obj = new Device();
 					obj.setId(device.getId());
-					obj.setDeviceStatus(4); // 设置设备为预警状态
+					obj.setDeviceStatus(4);
+					// 设置设备为预警状态
 					deviceMapper.updateByPrimaryKeySelective(obj);
 
 					// 预警状态下的连续天数
-					if (device.getDeviceStatus() == 2) { // 故障天数清零
+					if (device.getDeviceStatus() == 2) {
+						// 故障天数清零
 						waterMeterErrorDaysMapper.reset(deviceId);
-					} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+					} else if (device.getDeviceStatus() == 2) {
+						// 故障连续天数+1
 						waterMeterErrorDaysMapper.addDays(deviceId);
 					}
 				}
@@ -496,19 +554,24 @@ public class DeviceDataTimeOutServiceImpl implements DeviceDataTimeOutService, I
 					if (alarm != null) {
 						Device obj = new Device();
 						obj.setId(device.getId());
-						obj.setDeviceStatus(2); // 设置设备为故障状态
+						// 设置设备为故障状态
+						obj.setDeviceStatus(2);
 						deviceMapper.updateByPrimaryKeySelective(obj);
 					}
-				} else if (deviceCreateDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) { // 超过24小时没有上报数据则将设备状态设置为预警
+				} else if (deviceCreateDate.before(DateTimeUtil.before(date, new Double(24 * 3600 * 1000).longValue()))) {
+					// 超过24小时没有上报数据则将设备状态设置为预警
 					Device obj = new Device();
 					obj.setId(device.getId());
-					obj.setDeviceStatus(4); // 设置设备为预警状态
+					obj.setDeviceStatus(4);
+					// 设置设备为预警状态
 					deviceMapper.updateByPrimaryKeySelective(obj);
 
 					// 预警状态下的连续天数
-					if (device.getDeviceStatus() == 2) { // 故障天数清零
+					if (device.getDeviceStatus() == 2) {
+						// 故障天数清零
 						waterMeterErrorDaysMapper.reset(deviceId);
-					} else if (device.getDeviceStatus() == 2) { // 故障连续天数+1
+					} else if (device.getDeviceStatus() == 2) {
+						// 故障连续天数+1
 						waterMeterErrorDaysMapper.addDays(deviceId);
 					}
 				}

+ 40 - 213
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/MeterReadRecordServiceImpl.java

@@ -5,20 +5,8 @@ import com.bz.smart_city.commom.exception.ServiceException;
 import com.bz.smart_city.commom.util.*;
 import com.bz.smart_city.dto.*;
 
-import com.github.pagehelper.Page;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.data.mongodb.core.aggregation.Aggregation;
-import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
-import org.springframework.data.mongodb.core.aggregation.AggregationResults;
-import org.springframework.data.mongodb.core.aggregation.ConditionalOperators;
-import org.springframework.data.mongodb.core.mapreduce.GroupBy;
-import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
@@ -109,13 +97,10 @@ public class MeterReadRecordServiceImpl implements MeterReadRecordService{
     private StatMeterReadRateByBuildingMapper statMeterReadRateByBuildingMapper;
     
     @Resource
-    CustomerService customerService;
-	@Autowired
-	private MongoTemplate mongoTemplate;
+    CustomerService customerService; 
 
 
     @Override
-	@Deprecated
 	public Pagination<MeterReadRecord> queryMeterReadRecord(CommonQueryCondition condition, int pageNum, int pageSize) {
     	log.info("begin MeterReadRecordService queryMeterReadRecord , param = "+JSON.toJSONString(condition));	
     	List<Integer> siteList = new ArrayList<Integer>();
@@ -131,7 +116,6 @@ public class MeterReadRecordServiceImpl implements MeterReadRecordService{
 	}
 
     @Override
-	@Deprecated
     public List<MeterReadRate> analysisMeterReadRate(CommonQueryCondition condition){
     	List<MeterReadRate>  result = new ArrayList<MeterReadRate>();
     	// 1,计算查询日期
@@ -532,217 +516,60 @@ public class MeterReadRecordServiceImpl implements MeterReadRecordService{
     @Override
 	public WaterConsumptionSummaryDto waterConsumptionSummary(CommonQueryCondition condition) {
 		log.info("begin MeterReadRecordService waterConsumptionSummary, params = " + JSON.toJSONString(condition));
-		//WaterConsumptionSummaryDto result = meterReadRecordMapper.getSummary(condition);
-		/*
-		db.sc_meter_read_record.aggregate(
-		[
-		{$match:{siteId:1,status:1,readDate:20200701}},
-			{$group:{_id:{
-							"deviceId": "$deviceId",
-					},
-					lastCost:{$sum:"$lastCost"}
-
-			}},
-				{$group:{
-				_id:{},
-					total:{$sum:1},
-					lastCost:{$sum:"$lastCost"}
-
-			}},
-			{ $project : {
-					total : 1,
-					lastCost : 1 ,
-					_id:0
-		}}
-
-
-		]
-		,{ allowDiskUse: true }
-		)
-		 */
-		List<AggregationOperation> operations = new ArrayList<>();
-		operations.add(Aggregation.match(Criteria.where("status").is(1)));
-		operations.add(Aggregation.match(Criteria.where("siteId").is(condition.getSiteId())));
-		operations.add(Aggregation.match(Criteria.where("readDate").gte(condition.getStartDate()).lte(condition.getEndDate())));
-		if (condition.getCustormerId() != null ) {
-			operations.add(Aggregation.match(Criteria.where("customerId").is(condition.getCustormerId())));
-		}
-		if (condition.getProvinces() != null && condition.getProvinces().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("provinceId").in(condition.getProvinces())));
-		}
-		if (condition.getCities() != null && condition.getCities().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("cityId").in(condition.getCities())));
-		}
-		if (condition.getRegions() != null && condition.getRegions().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("regionId").in(condition.getRegions())));
-		}
-		if (condition.getCommunities() != null && condition.getCommunities().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("communityId").in(condition.getCommunities())));
-		}
-		if (condition.getBuildingIds() != null && condition.getBuildingIds().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("buildingId").in(condition.getBuildingIds())));
-		}
-		// 1,添加分组条件
-		operations.add(Aggregation.group("deviceId")
-				.sum("lastCost").as("waterConsumption"));
-
-		if (condition.getBeginRate() != null) {
-			operations.add(Aggregation.match(Criteria.where("waterConsumption").gte(condition.getBeginRate())));
-		}
-		if (condition.getEndRate() != null) {
-			operations.add(Aggregation.match(Criteria.where("waterConsumption").lte(condition.getEndRate())));
-		}
-
-		operations.add(Aggregation.group()
-				.sum("waterConsumption").as("totalWaterConsumption")
-				.count().as("totalDeviceCount"));
-		operations.add(Aggregation.project("totalWaterConsumption","totalDeviceCount").
-				andExclude("_id"));
-		Aggregation aggregation = Aggregation.newAggregation(operations);
-		AggregationResults<WaterConsumptionSummaryDto> aggregationResults = mongoTemplate.aggregate(aggregation, "sc_meter_read_record", WaterConsumptionSummaryDto.class);
-		List<WaterConsumptionSummaryDto> list = aggregationResults.getMappedResults();
-		if (list != null && list.size() > 0) {
-			return list.get(0);
-		}else {
-			WaterConsumptionSummaryDto dto = new WaterConsumptionSummaryDto();
-			dto.setTotalDeviceCount(0);
-			dto.setTotalWaterConsumption(0.0);
-			return dto;
-		}
+		WaterConsumptionSummaryDto result = meterReadRecordMapper.getSummary(condition);
+		log.info("end MeterReadRecordService waterConsumptionSummary, result = " + JSON.toJSONString(result));
+		return result;
 	}
 
 	@Override
 	public Pagination<WaterConsumptionDto> getWaterConsumptionList(CommonQueryCondition condition, Integer pageNum, Integer pageSize) {
 		log.info("begin MeterReadRecordService getWaterConsumptionList, params = " + JSON.toJSONString(condition) + ", pageNum = " + pageNum + ", pageSize = " + pageSize);
-		Pagination pagination = new Pagination<>();
-
-
-		/**
-		 db.sc_meter_read_record.aggregate(
-		 [
-		 {$match:{siteId:1,status:1,readDate:20200701}},
-		 {$group:{_id:{
-		 "deviceId": "$deviceId",
-		 },
-		 meterNo:{$last:"$meterNo"},
-		 deviceTypeName:{$last:"$deviceTypeName"},
-		 customerName:{$last:"$customerName"},
-		 communityName:{$last:"$communityName"},
-		 lastCost:{$sum:"$lastCost"}
-
-		 }},
-		 { $project : {
-		 deviceId : "$_id.deviceId" ,
-		 meterNo : 1 ,
-		 lastCost : 1 ,
-		 deviceNo : 1 ,
-		 total : {$sum:1} ,
-		 _id:0
-		 }}
-		 ,{$sort:{"lastCost":-1}}
-		 ,{$skip:0}
-		 ,{$limit:10}
-
-		 ]
-		 ,{ allowDiskUse: true }
-		 )
-		 */
-		List<AggregationOperation> operations = new ArrayList<>();
-		operations.add(Aggregation.match(Criteria.where("status").is(1)));
-		operations.add(Aggregation.match(Criteria.where("siteId").is(condition.getSiteId())));
-		operations.add(Aggregation.match(Criteria.where("readDate").gte(condition.getStartDate()).lte(condition.getEndDate())));
-		if (condition.getCustormerId() != null ) {
-			operations.add(Aggregation.match(Criteria.where("customerId").is(condition.getCustormerId())));
-		}
-		if (condition.getProvinces() != null && condition.getProvinces().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("provinceId").in(condition.getProvinces())));
-		}
-		if (condition.getCities() != null && condition.getCities().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("cityId").in(condition.getCities())));
-		}
-		if (condition.getRegions() != null && condition.getRegions().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("regionId").in(condition.getRegions())));
-		}
-		if (condition.getCommunities() != null && condition.getCommunities().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("communityId").in(condition.getCommunities())));
-		}
-		if (condition.getBuildingIds() != null && condition.getBuildingIds().size() > 0) {
-			operations.add(Aggregation.match(Criteria.where("buildingId").in(condition.getBuildingIds())));
-		}
-
-		// 1,添加分组条件
-		operations.add(Aggregation.group("deviceId")
-				.last("meterNo").as("meterNo")
-				.last("deviceTypeName").as("deviceTypeName")
-				.last("customerName").as("customerName")
-				.last("communityName").as("communityName")
-				.last("buildingName").as("buildingName")
-				.last("location").as("location")
-				.sum("lastCost").as("waterConsumption"));
-		operations.add(Aggregation.project("meterNo").
-				and("deviceTypeName").as("deviceType").
-				and("customerName").as("customer").
-				and("communityName").as("community").
-				and("buildingName").as("building").
-				and("location").as("location").
-				and("waterConsumption").as("waterConsumption").
-						andExclude("_id"));
-
-		if (condition.getBeginRate() != null) {
-			operations.add(Aggregation.match(Criteria.where("waterConsumption").gte(condition.getBeginRate())));
-		}
-		if (condition.getEndRate() != null) {
-			operations.add(Aggregation.match(Criteria.where("waterConsumption").lte(condition.getEndRate())));
-		}
-
-
-		operations.add(Aggregation.count().as("total"));
-
-
-		// 3,聚合查询所有信息
-		Aggregation aggregationTotal = Aggregation.newAggregation(operations);
-		// 4,查询结果总条数
-		AggregationResults<TotalDto> total = mongoTemplate.aggregate(aggregationTotal, "sc_meter_read_record", TotalDto.class);
-		List<TotalDto> totalList = total.getMappedResults();
-		if (totalList != null && totalList.size() > 0) {
-			pagination.setTotal(totalList.get(0).getTotal());
-		}else {
-			pagination.setTotal(0);
-		}
-		operations.remove(operations.size()-1);
-
-
-		if (condition.getSortOrder() != null) {
-			if(condition.getSortOrder().equals("ASC")){
-				operations.add(Aggregation.sort(Sort.Direction.ASC, "waterConsumption"));
-			}
-			if(condition.getSortOrder().equals("DESC")){
-				operations.add(Aggregation.sort(Sort.Direction.DESC, "waterConsumption"));
-			}
-		}
-		operations.add(Aggregation.skip(Long.valueOf((pageNum-1) * pageSize)));
-		operations.add(Aggregation.limit(pageSize));
-		Aggregation aggregation = Aggregation.newAggregation(operations);
-		AggregationResults<WaterConsumptionDto> aggregationResults = mongoTemplate.aggregate(aggregation, "sc_meter_read_record", WaterConsumptionDto.class);
-		// 5,获取结果
-		List<WaterConsumptionDto> results = aggregationResults.getMappedResults();
-		log.info("end MeterReadRecordService getWaterConsumptionList, result.size = "+results);
-
-		pagination.setList(results);
-		return pagination;
+		PageHelper.startPage(pageNum, pageSize);
+		List<WaterConsumptionDto> result = meterReadRecordMapper.getList(condition);
+		log.info("end MeterReadRecordService getWaterConsumptionList, result.size = "+result.size());
+		return new Pagination<>(result);
 	}
 
 	@Async
 	@Override
-	@Deprecated
 	public void recoverAll(Integer startDate) {
     	log.info("开始用水量恢复");
-
+		List<Long> allDeviceId = meterReadRecordMapper.getAllDeviceId(startDate);
+		for (Long deviceId : allDeviceId) {
+			log.info("开始恢复设备id : " + deviceId + " 的用水量");
+			List<MeterReadRecord> meterReadRecords = meterReadRecordMapper.getMeterReadRecordByDeviceId(deviceId, startDate);
+			int last = 0;
+			for (int i = 0; i < meterReadRecords.size(); i++) {
+				MeterReadRecord meterReadRecord = meterReadRecords.get(i);
+				if (i == 0) {
+					if (meterReadRecord.getReadData() == null || meterReadRecord.getReadData().equals("")) {
+						meterReadRecord.setLastValid("0");
+						meterReadRecord.setLastCost(BigDecimal.ZERO);
+					} else {
+						meterReadRecord.setLastValid(meterReadRecord.getReadData());
+						BigDecimal cost = BigDecimal.valueOf(Double.parseDouble(meterReadRecord.getReadData()));
+						meterReadRecord.setLastCost(cost);
+					}
+				} else {
+					MeterReadRecord lastRecord = meterReadRecords.get(last);
+					if (meterReadRecord.getReadData() == null || meterReadRecord.getReadData().equals("")) {
+						meterReadRecord.setLastValid(lastRecord.getLastValid());
+						meterReadRecord.setLastCost(BigDecimal.ZERO);
+					} else {
+						meterReadRecord.setLastValid(meterReadRecord.getReadData());
+						BigDecimal cost = BigDecimal.valueOf(Double.parseDouble(meterReadRecord.getReadData()) - Double.parseDouble(lastRecord.getLastValid()));
+						meterReadRecord.setLastCost(cost);
+					}
+					last++;
+				}
+			}
+			meterReadRecordMapper.batchUpdate(meterReadRecords);
+			log.info("结束恢复设备id : " + deviceId + " 的用水量");
+		}
 		log.info("结束用水量恢复");
 	}
 
 	@Override
-	@Deprecated
 	public int createMeterReadRecordForRollback(Date date) {
 		log.info("begin MeterReadRecordService createMeterReadRecord ,date = "+ JSON.toJSONString(date));
 		Integer result = 0;

+ 2 - 1
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/StatMeterReadRateByBuildingServiceImpl.java

@@ -47,7 +47,8 @@ public class StatMeterReadRateByBuildingServiceImpl implements StatMeterReadRate
     public Pagination<DeviceDto> queryUnReadDeviceList(CommonQueryCondition condition, int pageNum, int pageSize) {
         log.info("begin StatMeterReadRateByBuildingService queryUnReadDeviceList , condition = " + JSON.toJSONString(condition));
         PageHelper.startPage(pageNum, pageSize);
-        int period = condition.getPeriod(); // 统计周期,2,昨天,7,近7天 15,近15天
+        // 统计周期,2,昨天,7,近7天 15,近15天
+        int period = condition.getPeriod();
         List<DeviceDto> rtnList = null;
         condition.setStatDay(Integer.parseInt(DateTimeUtil.formatDate(DateTimeUtil.beforeNow(1), "yyyyMMdd")));
         if (period == 2) {

+ 19 - 19
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/ZunYiNewRegionSyncServiceImpl.java

@@ -1,23 +1,18 @@
 package com.bz.smart_city.service.impl;
 
 import com.alibaba.fastjson.JSON;
-import com.bz.smart_city.commom.model.CommonQueryCondition;
 import com.bz.smart_city.commom.util.DateTimeUtil;
-import com.bz.smart_city.dao.MeterReadRecordMapper;
 import com.bz.smart_city.dto.MessageData;
-import com.bz.smart_city.dto.WaterConsumptionDto;
-import com.bz.smart_city.entity.MeterReadRecord;
+import com.bz.smart_city.dto.MeterReadRecordQueryDTO;
+import com.bz.smart_city.service.MeterReadRecordService;
 import com.bz.smart_city.service.SyncWaterMeterDataService;
-import com.bz.smart_city.service.SyncWaterMeterInfoService;
-import lombok.Data;
+import com.zcxk.zoniot.smartcity.common.model.MeterReadRecord;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.amqp.rabbit.core.RabbitTemplate;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
-
-import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -36,8 +31,11 @@ public class ZunYiNewRegionSyncServiceImpl implements SyncWaterMeterDataService
     @Autowired
     RabbitTemplate rabbitTemplate;
 
+    // @Autowired
+    // MeterReadRecordMapper meterReadRecordMapper;
+
     @Autowired
-    MeterReadRecordMapper meterReadRecordMapper;
+    MeterReadRecordService meterReadRecordService;
 
     @Value("${spring.profiles.active}")
     String env ;
@@ -46,22 +44,24 @@ public class ZunYiNewRegionSyncServiceImpl implements SyncWaterMeterDataService
     public void syncWaterMeterData(Integer customerId) {
         // 1,查询昨日抄表数据
         int yesterday = Integer.parseInt(DateTimeUtil.formatDate(DateTimeUtil.beforeNow(1), "yyyyMMdd"));
-        CommonQueryCondition condition = new CommonQueryCondition();
-        condition.setCustormerId(customerId);
+        MeterReadRecordQueryDTO param = new MeterReadRecordQueryDTO();
+        param.setCustomerId(customerId);
         if("prd".equals(env)){
-            condition.setStartDate(yesterday);
-            condition.setEndDate(yesterday);
+            param.setStartDate(yesterday);
+            param.setEndDate(yesterday);
+            // condition.setStartDate(yesterday);
+            // condition.setEndDate(yesterday);
         }
         else{
-            condition.setStartDate(20190528);
-            condition.setEndDate(20190528);
+            param.setStartDate(20190528);
+            param.setEndDate(20190528);
         }
         // 只查已抄表数据
-        condition.setReadStatus("2");
+        param.setReadStatus("2");
         // 只传已验收上线的
-        condition.setChannelId(40);
-        log.info("begin query meter read records ,condition = {}",JSON.toJSONString(condition));
-        List<MeterReadRecord> meterReadRecords = meterReadRecordMapper.queryMeterReadRecordWithCondtion(condition);
+        param.setChannelId(40);
+        log.info("begin query meter read records ,condition = {}",JSON.toJSONString(param));
+        List<MeterReadRecord> meterReadRecords =  meterReadRecordService.queryMeterReadRecord(param);
         log.info("end query meter read records ,result size is = {}",meterReadRecords.size());
 
         // 2,构建消息

+ 9 - 11
smart-city-platform/src/main/java/com/bz/smart_city/service/impl/assistant/AcceptManagerServiceImpl.java

@@ -12,19 +12,18 @@ import com.bz.smart_city.commom.util.*;
 import com.bz.smart_city.dao.*;
 import com.bz.smart_city.dto.AcceptData;
 import com.bz.smart_city.dto.AcceptListData;
-import com.bz.smart_city.dto.DeviceDto;
 import com.bz.smart_city.dto.LoginUser;
 import com.bz.smart_city.entity.*;
 import com.bz.smart_city.entity.assistant.AcceptPlan;
 import com.bz.smart_city.service.DeviceDataService;
-import org.apache.commons.lang3.StringUtils;
+import com.bz.smart_city.service.MeterReadRecordService;
+import com.zcxk.zoniot.smartcity.common.model.MeterReadRecord;
 import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.InitializingBean;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
-import org.springframework.data.mongodb.core.MongoTemplate;
 import org.springframework.kafka.core.KafkaTemplate;
 import org.springframework.stereotype.Service;
 
@@ -77,10 +76,7 @@ public class AcceptManagerServiceImpl implements AcceptManagerService,Initializi
 
 	@Autowired
 	private BuildingMapper buildingMapper;
-	
-	@Autowired
-	private DeviceDataDimMapper deviceDataDimMapper;
-	
+
 	@Autowired
 	private MeterReadRecordMapper meterReadRecordMapper;
 	
@@ -99,13 +95,16 @@ public class AcceptManagerServiceImpl implements AcceptManagerService,Initializi
 	@Autowired
 	DeviceDataService deviceDataService ;
 
+	@Autowired
+	MeterReadRecordService  meterReadRecordService;
+
 	@Override
 	public boolean createAcceptPlan(AcceptPlanDTO dto) {
 		log.info("begin AcceptManagerService createAcceptPlan,dto ={}",JSON.toJSONString(dto));
 		boolean isOk = false ; 
 		dto.setStatus(1);
 		int i = acceptPlanMapper.insert(dto);
-		if(i != 1) isOk = true ;
+		if(i != 1){ isOk = true; }
 		log.info("end AcceptManagerService createAcceptPlan,reuslt ={}",isOk);
 		return isOk;
 	}
@@ -164,9 +163,8 @@ public class AcceptManagerServiceImpl implements AcceptManagerService,Initializi
 			deviceMapper.updateByPrimaryKeySelective(device);
 			// 3.2,更改抄表记录场景
 			MeterReadRecord mr = new MeterReadRecord();
-			mr.setDeviceId(install.getDeviceId());
-			mr.setSysId(channelId);
-			meterReadRecordMapper.updateHitoryData(mr);
+			mr.setChannelId(channelId);
+			meterReadRecordService.updateMeterReadRecords(install.getDeviceId(),mr);
 			// 3.3,更改上报数据后的场景
 			// deviceDataDimMapper.updateChannel(channelId, install.getDeviceId());
 			com.zcxk.zoniot.smartcity.common.model.DeviceData p = new com.zcxk.zoniot.smartcity.common.model.DeviceData();

+ 2 - 2
smart-city-platform/src/test/java/com/bz/smart_city/MeterReadRecordServiceTests.java

@@ -87,7 +87,7 @@ public class MeterReadRecordServiceTests {
 		}
 	}
 	
-/*	@Test
+	@Test
 	public void queryMeterReadRecordTest() {
 //		MeterReadRecord param = new MeterReadRecord();
 //		param.setBuildingId(1736);
@@ -106,7 +106,7 @@ public class MeterReadRecordServiceTests {
 		Pagination<MeterReadRecord> result = meterReadRecordService.queryMeterReadRecord(param, 1, 15);
 
 		//System.out.println(JSON.toJSONString(result));
-	}*/
+	}
 	
 	@Test
 	public void queryMeterReadRateTest() {