Explorar el Código

构建耳标模块(数据采集、数据展示、业务处理)

zhuoning hace 3 años
padre
commit
cfdbd67c29
Se han modificado 99 ficheros con 14505 adiciones y 0 borrados
  1. 146 0
      huimv-farm-eartag/pom.xml
  2. 26 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/HuimvEartagApplication.java
  3. 48 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/config/CorsConfig.java
  4. 64 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/config/RestTemplateConfig.java
  5. 137 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/config/TopicRabbitMQConfig.java
  6. 55 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceController.java
  7. 385 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceManageController.java
  8. 122 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceRegisterController.java
  9. 366 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/EartagManageController.java
  10. 80 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/TestController.java
  11. 103 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/BaseFarmEntity.java
  12. 67 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/BaseFarmServerConfigEntity.java
  13. 68 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceCountEntity.java
  14. 69 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceDetailEntity.java
  15. 80 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceTimesEntity.java
  16. 68 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagCountEntity.java
  17. 69 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagDetailEntity.java
  18. 80 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagTimesEntity.java
  19. 79 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagConfigPropertiesEntity.java
  20. 237 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDataEntity.java
  21. 104 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceDayStatusEntity.java
  22. 105 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceEartagCountEntity.java
  23. 249 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceOnlineEntity.java
  24. 273 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceRegisterEntity.java
  25. 104 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagDayStatusEntity.java
  26. 129 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagOnlineEntity.java
  27. 213 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagRegisterEntity.java
  28. 117 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEnvEntity.java
  29. 69 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagHeartbeatEntity.java
  30. 105 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagRawEntity.java
  31. 153 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagTotalStatusEntity.java
  32. 165 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartarFarmAllStatusEntity.java
  33. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/BaseFarmRepo.java
  34. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/BaseFarmServerConfigRepo.java
  35. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceCountRepo.java
  36. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceDetailRepo.java
  37. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceTimesRepo.java
  38. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagCountRepo.java
  39. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagDetailRepo.java
  40. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagTimesRepo.java
  41. 13 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagConfigPropertiesRepo.java
  42. 22 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDataRepo.java
  43. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceDayStatusRepo.java
  44. 23 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceEartagCountRepo.java
  45. 20 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceOnlineRepo.java
  46. 32 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceRegisterRepo.java
  47. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagDayStatusRepo.java
  48. 56 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagOnlineRepo.java
  49. 24 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagRegisterRepo.java
  50. 14 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEnvRepo.java
  51. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagHeartbeatRepo.java
  52. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagRawRepo.java
  53. 9 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagTotalStatusRepo.java
  54. 17 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartarFarmAllStatusRepo.java
  55. 157 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/DeviceListener.java
  56. 175 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/EartagListener.java
  57. 117 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/ManageListener.java
  58. 51 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/DeviceProducer.java
  59. 106 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/InputProducer.java
  60. 65 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/ManageProducer.java
  61. 74 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/server/EartagServer2.java
  62. 383 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/server/EartagServerHandler2.java
  63. 102 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/ICacheService.java
  64. 36 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDataService.java
  65. 71 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceManageService.java
  66. 25 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceRegisterService.java
  67. 57 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceService.java
  68. 51 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IEartagManageService.java
  69. 22 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IEartagService.java
  70. 554 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/CacheServiceImpl.java
  71. 905 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DataServiceImpl.java
  72. 957 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceManageServiceImpl.java
  73. 314 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceRegisterServiceImpl.java
  74. 863 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceServiceImpl.java
  75. 875 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/EartagManageServiceImpl.java
  76. 629 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/EartagServiceImpl.java
  77. 12 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BaseTemplete.java
  78. 109 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BizConst.java
  79. 935 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BytesUtil.java
  80. 51 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/Const.java
  81. 300 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/DateUtil.java
  82. 187 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/DateUtil2.java
  83. 516 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/HttpTemplete.java
  84. 21 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/JSONUtil.java
  85. 124 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/MathUtil.java
  86. 89 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/MathUtil2.java
  87. 31 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/RegexUtil.java
  88. 266 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/AddressUtils.java
  89. 58 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/IPMain.java
  90. 60 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/IPUtils.java
  91. 60 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/MyTest.java
  92. 139 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/EartagDataVo.java
  93. 61 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/FarmAllStatusVo.java
  94. 79 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/Result.java
  95. 41 0
      huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/ResultCode.java
  96. 107 0
      huimv-farm-eartag/src/main/resources/application-dev.yml
  97. 107 0
      huimv-farm-eartag/src/main/resources/application-prod.yml
  98. 66 0
      huimv-farm-eartag/src/main/resources/application.properties
  99. 24 0
      huimv-farm-eartag/src/main/resources/assembly.xml

+ 146 - 0
huimv-farm-eartag/pom.xml

@@ -0,0 +1,146 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>huimv-farm-datacenter</artifactId>
+        <groupId>com.huimv</groupId>
+        <version>0.0.1-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>huimv-farm-eartag</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <!-- fastjson -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.28</version>
+        </dependency>
+        <!-- JPA -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-jpa</artifactId>
+        </dependency>
+        <!-- mysql -->
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+        </dependency>
+        <!-- redis -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+        <!-- lombok -->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.16.18</version>
+            <scope>provided</scope>
+        </dependency>
+        <!--hutool-->
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <!--            <version>LATEST</version>-->
+            <version>5.6.5</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.5</version>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>3.7</version>
+        </dependency>
+
+        <!-- -->
+        <!-- 排除Tomcat容器 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <!-- 移除掉默认支持的 Tomcat -->
+            <exclusions>
+                <exclusion>
+                    <groupId>org.springframework.boot</groupId>
+                    <artifactId>spring-boot-starter-tomcat</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <!-- 添加 Undertow 容器 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-undertow</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- eartag2-common -->
+<!--        <dependency>-->
+<!--            <groupId>com.huimv</groupId>-->
+<!--            <artifactId>huimv-eartag2-common</artifactId>-->
+<!--            <version>0.0.1-SNAPSHOT</version>-->
+<!--        </dependency>-->
+
+        <!-- netty -->
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty-all</artifactId>
+            <version>4.1.45.Final</version>
+        </dependency>
+        <!--hutool-->
+<!--        <dependency>-->
+<!--            <groupId>cn.hutool</groupId>-->
+<!--            <artifactId>hutool-all</artifactId>-->
+<!--            <version>5.6.5</version>-->
+<!--        </dependency>-->
+                <!-- httpclient -->
+<!--                <dependency>-->
+<!--                    <groupId>org.apache.httpcomponents</groupId>-->
+<!--                    <artifactId>httpclient</artifactId>-->
+<!--                    <version>4.5.5</version>-->
+<!--                </dependency>-->
+<!--        <dependency>-->
+<!--            <groupId>junit</groupId>-->
+<!--            <artifactId>junit</artifactId>-->
+<!--            <scope>test</scope>-->
+<!--        </dependency>-->
+
+        <!--rabbitmq-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-amqp</artifactId>
+        </dependency>
+
+        <!-- actuator -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+
+    </dependencies>
+</project>

+ 26 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/HuimvEartagApplication.java

@@ -0,0 +1,26 @@
+package com.huimv.eartag;
+
+import com.huimv.eartag.server.EartagServer2;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.ApplicationContext;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@SpringBootApplication
+public class HuimvEartagApplication {
+    public static void main(String[] args) throws InterruptedException {
+//        SpringApplication.run(HuimvEartagApplication.class, args);
+        ApplicationContext applicationContext = SpringApplication.run(HuimvEartagApplication.class, args);
+        //EartagServer
+//        applicationContext.getBean(EartagServer.class).start();
+        //EartagServer2
+        applicationContext.getBean(EartagServer2.class).run();
+    }
+}

+ 48 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/config/CorsConfig.java

@@ -0,0 +1,48 @@
+package com.huimv.eartag.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Configuration
+public class CorsConfig implements WebMvcConfigurer {
+
+    /**
+     * 开启跨域
+     */
+    @Override
+    public void addCorsMappings(CorsRegistry registry) {
+        // 设置允许跨域的路由
+        registry.addMapping("/**")
+                // 设置允许跨域请求的域名
+                .allowedOriginPatterns("*")
+                // 是否允许证书(cookies)
+                .allowCredentials(true)
+                // 设置允许的方法
+                .allowedMethods("*")
+                // 跨域允许时间
+                .maxAge(3600);
+    }
+
+//    @Override
+//    public void addCorsMappings(CorsRegistry registry) {
+////        设置允许跨域的路径
+//        registry.addMapping("/**")
+////                设置允许跨域请求的域名
+//                .allowedOrigins("*")
+////                是否允许证书
+//                .allowCredentials(true)
+//                .allowedMethods("GET", "POST", "DELETE", "PUT","OPTIONS")
+//                .allowedHeaders("*")
+////                跨域允许时间
+//                .maxAge(3600);
+//    }
+}

+ 64 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/config/RestTemplateConfig.java

@@ -0,0 +1,64 @@
+package com.huimv.eartag.config;
+
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Configuration
+public class RestTemplateConfig {
+    @Bean
+    public RestTemplate restTemplate() {
+        return new RestTemplate(httpRequestFactory());
+    }
+
+    @Bean
+    public ClientHttpRequestFactory httpRequestFactory() {
+        return new HttpComponentsClientHttpRequestFactory(httpClient());
+    }
+
+    @Bean
+    public HttpClient httpClient() {
+        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
+                .register("http", PlainConnectionSocketFactory.getSocketFactory())
+                .register("https", SSLConnectionSocketFactory.getSocketFactory())
+                .build();
+        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
+        //最大连接数
+        poolingHttpClientConnectionManager.setMaxTotal(200);
+        //最大路由数
+        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);
+        //定义不活动的时间
+        poolingHttpClientConnectionManager.setValidateAfterInactivity(2000);
+        RequestConfig requestConfig = RequestConfig.custom()
+                //服务器返回数据的时间,超时抛出read timeout
+                .setSocketTimeout(65000)
+                //连接上服务器的时间,超时抛出connect timeout
+                .setConnectTimeout(5000)
+                //从连接池中获取的超时时间,超时未拿到连接会报错ConnectionTimeoutException:Timeout waiting for connection from pool
+                .setConnectionRequestTimeout(1000)
+                .build();
+        return HttpClientBuilder.create()
+                .setDefaultRequestConfig(requestConfig)
+                .setConnectionManager(poolingHttpClientConnectionManager)
+                .build();
+    }
+}

+ 137 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/config/TopicRabbitMQConfig.java

@@ -0,0 +1,137 @@
+package com.huimv.eartag.config;
+
+import com.huimv.eartag.utils.Const;
+import org.springframework.amqp.core.Binding;
+import org.springframework.amqp.core.BindingBuilder;
+import org.springframework.amqp.core.Queue;
+import org.springframework.amqp.core.TopicExchange;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Configuration
+public class TopicRabbitMQConfig {
+    //原始数据队列
+    @Bean
+    public Queue askDeviceQueue() {
+        return new Queue(Const.QUEUE_ASK_DEVICE);
+    }
+    @Bean
+    public Queue askEartagQueue() {
+        return new Queue(Const.QUEUE_ASK_EARTAG);
+    }
+    //心跳
+    @Bean
+    public Queue heartbeatQueue() {
+        return new Queue(Const.QUEUE_DEVICE_HEARTBEAT);
+    }
+
+    //采集器温度
+    @Bean
+    public Queue deviceTempQueue() {
+        return new Queue(Const.QUEUE_DEVICE_TEMP);
+    }
+    //耳标数据
+    @Bean
+    public Queue eartagQueue() {
+        return new Queue(Const.QUEUE_EARTAG);
+    }
+
+
+    //原始交换机
+    @Bean
+    TopicExchange askDeviceExchange() {
+        return new TopicExchange(Const.EXCHANGE_ASK_DEVICE);
+    }
+    @Bean
+    TopicExchange askEartagExchange() {
+        return new TopicExchange(Const.EXCHANGE_ASK_EARTAG);
+    }
+    //采集器设备交换机
+    TopicExchange deviceExchange() {
+        return new TopicExchange(Const.EXCHANGE_DEVICE);
+    }
+
+    //耳标交换机
+//    @Bean
+    TopicExchange eartagExchange() {
+        return new TopicExchange(Const.EXCHANGE_EARTAG);
+    }
+
+
+    //绑定关系
+    @Bean
+    Binding bindingDeviceExchangeMessage() {
+        return BindingBuilder.bind(askDeviceQueue()).to(askDeviceExchange()).with(Const.ROUTING_KEY_ASK_DEVICE);
+    }
+    @Bean
+    Binding bindingAskEartagExchangeMessage() {
+        return BindingBuilder.bind(askEartagQueue()).to(askEartagExchange()).with(Const.ROUTING_KEY_ASK_EARTAG);
+    }
+    //设备交换机、心跳队列、心跳路由键绑定
+    @Bean
+    Binding bindingHeartbeatExchangeMessage() {
+        return BindingBuilder.bind(heartbeatQueue()).to(deviceExchange()).with(Const.ROUTING_KEY_DEVICE_HEARTBEAT);
+    }
+
+    //设备交换机、设备环境温度队列、设备环境路由键绑定
+    @Bean
+    Binding bindingDeviceTempExchangeMessage() {
+        return BindingBuilder.bind(deviceTempQueue()).to(deviceExchange()).with(Const.ROUTING_KEY_DEVICE_TEMP);
+    }
+    //耳标交换机、耳标队列、耳标路由键绑定
+    @Bean
+    Binding bindingEartagExchangeMessage() {
+        return BindingBuilder.bind(eartagQueue()).to(eartagExchange()).with(Const.ROUTING_KEY_EARTAG);
+    }
+
+    // ============================= 设备绑定队列 ============================= //
+    @Bean
+    public Queue syncDeviceRegisterQueue() {
+        return new Queue(Const.QUEUE_SYNC_DEVICE_REGISTER);
+    }
+    @Bean
+    TopicExchange syncDeviceRegisterExchange() {
+        return new TopicExchange(Const.EXCHANGE_SYNC_DEVICE_REGISTER);
+    }
+    @Bean
+    Binding bindingDeviceRegisterExchangeMessage() {
+        return BindingBuilder.bind(syncDeviceRegisterQueue()).to(syncDeviceRegisterExchange()).with(Const.ROUTING_KEY_SYNC_DEVICE_REGISTER);
+    }
+
+    // =============================耳标绑定队列 ============================= //
+    @Bean
+    public Queue syncEartagRegisterQueue() {
+        return new Queue(Const.QUEUE_SYNC_EARTAG_REGISTER);
+    }
+    @Bean
+    TopicExchange syncEartagRegisterExchange() {
+        return new TopicExchange(Const.EXCHANGE_SYNC_EARTAG_REGISTER);
+    }
+    @Bean
+    Binding bindingEartagRegisterExchangeMessage() {
+        return BindingBuilder.bind(syncEartagRegisterQueue()).to(syncEartagRegisterExchange()).with(Const.ROUTING_KEY_SYNC_EARTAG_REGISTER);
+    }
+
+    // ============================= 同步设备总数-绑定队列 ============================= //
+    @Bean
+    public Queue syncDeviceTotalQueue() {
+        return new Queue(Const.QUEUE_SYNC_DEVICE_TOTAL);
+    }
+    @Bean
+    TopicExchange syncDeviceTotalExchange() {
+        return new TopicExchange(Const.EXCHANGE_SYNC_DEVICE_TOTAL);
+    }
+    @Bean
+    Binding bindingDeviceTotalExchangeMessage() {
+        return BindingBuilder.bind(syncDeviceTotalQueue()).to(syncDeviceTotalExchange()).with(Const.ROUTING_KEY_SYNC_DEVICE_TOTAL);
+    }
+
+}

+ 55 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceController.java

@@ -0,0 +1,55 @@
+package com.huimv.eartag.controller;
+
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.vo.FarmAllStatusVo;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@RestController
+@Slf4j
+@RequestMapping(value = "/deviceController")
+public class DeviceController {
+    @Autowired
+    private IDeviceService deviceService;
+
+//    @GetMapping(value = "/updateFarmAllStatus")
+//    public String updateFarmAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
+//        System.out.println("# farmId>>"+farmId);
+//        System.out.println("# todayDateText>>"+todayDateText);
+//        System.out.println("# todayDate>>"+todayDate);
+//        System.out.println("# nowTimestamp>>"+nowTimestamp);
+//        //{更新总状态}
+//        deviceService.updateEnvtempOfDeviceAllStatus(farmId, todayDateText, todayDate, nowTimestamp);
+//        return "ok";
+//    }
+
+    @PostMapping(value = "/updateFarmAllStatus")
+    public String updateFarmAllStatus(@RequestBody FarmAllStatusVo farmAllStatusVo) throws ParseException {
+        String farmId = farmAllStatusVo.getFarmId();
+        String todayDateText = farmAllStatusVo.getTodayDateText();
+        java.sql.Date todayDate = farmAllStatusVo.getTodayDate();
+        Timestamp nowTimestamp = farmAllStatusVo.getNowTimestamp();
+        System.out.println("farmId>>"+farmId);
+        System.out.println("todayDateText>>"+todayDateText);
+        System.out.println("todayDate>>"+todayDate);
+        System.out.println("nowTimestamp>>"+nowTimestamp);
+        //{更新牧场状态}
+        deviceService.updateEnvtempOfDeviceAllStatus(farmId,todayDateText,todayDate,nowTimestamp);
+        return "ok";
+    }
+}

+ 385 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceManageController.java

@@ -0,0 +1,385 @@
+package com.huimv.eartag.controller;
+
+import com.huimv.eartag.service.IDeviceManageService;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.vo.Result;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.text.ParseException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@CrossOrigin
+@RestController
+@RequestMapping(value = "/device")
+@Slf4j
+public class DeviceManageController {
+//    @Autowired
+//    private ICacheService cacheService;
+    @Autowired
+    private RabbitTemplate rabbitTemplate;
+    @Autowired
+    private IDeviceManageService deviceService;
+
+    /**
+     * @Method      : getNowAllStatus
+     * @Description : 读取最新设备和耳标总状态
+     * @Params      : []
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/5
+     * @Time        : 17:03
+     */
+    @RequestMapping(value = "/getNowAllStatus",method = RequestMethod.GET)
+    public Result getNowAllStatus(@RequestParam(value = "farmId",required = true) String farmId) throws ParseException {
+        log.info("<getNowAllStatus>输入参数 farmId>>"+farmId);
+        //
+        return deviceService.getNowAllStatus(farmId);
+    }
+
+    /**
+     * @Method      : listManyDaysAllStatus
+     * @Description : 显示N天的总状态记录
+     * @Params      : [farmId, days]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/6
+     * @Time        : 22:18
+     */
+    @RequestMapping(value = "/listManyDaysAllStatus",method = RequestMethod.GET)
+    public Result listManyDaysAllStatus(@RequestParam(value = "farmId",required = true) String farmId,@RequestParam(value = "days",required = true) Integer days) throws ParseException {
+        log.info("<listManyDaysAllStatus>输入参数 farmId>>"+farmId);
+        log.info("<listManyDaysAllStatus>输入参数 days>>"+days);
+        if(days == null){
+            //默认7天数据
+            days = 7;
+        }
+        //
+        return deviceService.listManyDaysAllStatus(farmId,days);
+    }
+
+    /**
+     * @Method      : listOnlineDevice
+     * @Description : 显示当天在线设备记录
+     * @Params      : [farmId]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 11:09
+     */
+    @RequestMapping(value = "/listOnlineDevice",method = RequestMethod.GET)
+    public Result listOnlineDevice(@RequestParam(value = "farmId",required = true) String farmId,
+                                   @RequestParam(value = "date",required = true) String date) throws ParseException {
+        log.info("<listOnlineDevice>输入参数 farmId>>"+farmId);
+        log.info("<listOnlineDevice>输入参数 date>>"+date);
+        //
+        return deviceService.listOnlineDevice(farmId,date);
+    }
+
+    /**
+     * @Method      : listOnlineDeviceByPager
+     * @Description : 分页显示N天在线记录
+     * @Params      : [farmId, deviceCode, alias, addDate, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 20:22
+     */
+    @RequestMapping(value = "/listOnlineDeviceByPager",method = RequestMethod.GET)
+    public Result listOnlineDeviceByPager(@RequestParam(value = "farmId",required = true) String farmId,
+                                          @RequestParam(value = "deviceCode",required = false) String deviceCode,
+                                          @RequestParam(value = "alias",required = false) String alias,
+                                          @RequestParam(value = "addDate",required = false) String addDate,
+                                          @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                          @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listOnlineDevice>输入参数 farmId>>"+farmId);
+        log.info("<listOnlineDevice>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listOnlineDevice>输入参数 alias>>"+alias);
+        log.info("<listOnlineDevice>输入参数 addDate>>"+addDate);
+        log.info("<listOnlineDevice>输入参数 pageNo>>"+pageNo);
+        log.info("<listOnlineDevice>输入参数 pageSize>>"+pageSize);
+        //
+        return deviceService.listOnlineDevice(farmId,deviceCode,alias,addDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : getDeviceRegisterByDeviceCode
+     * @Description : 通过设备编码查询设备注册信息
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 14:01
+     */
+    @RequestMapping(value = "/getDeviceRegisterByDeviceCode",method = RequestMethod.GET)
+    public Result getDeviceRegisterByDeviceCode(@RequestParam(value = "deviceCode",required = true) String deviceCode) throws ParseException {
+        log.info("<getDeviceRegisterByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        //
+        return deviceService.getDeviceRegisterByDeviceCode(deviceCode);
+    }
+
+    /**
+     * @Method      : listDeviceRegisterInPager
+     * @Description : 列表展示设备注册(分页)
+     * @Params      : [farmId, deviceCode, alias, startDate, endDate, activeStatus, liveStatus, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/9
+     * @Time        : 22:34
+     */
+    @RequestMapping(value = "/listDeviceRegisterInPager",method = RequestMethod.GET)
+    public Result listDeviceRegisterInPager(@RequestParam(value = "farmId",required = true) String farmId,
+                                            @RequestParam(value = "deviceCode",required = false) String deviceCode,
+                                            @RequestParam(value = "alias",required = false) String alias,
+                                            @RequestParam(value = "startDate",required = false) String startDate,
+                                            @RequestParam(value = "endDate",required = false) String endDate,
+                                            @RequestParam(value = "activeStatus",required = false) Integer activeStatus,
+                                            @RequestParam(value = "liveStatus",required = false) Integer liveStatus,
+                                            @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                            @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listDeviceRegisterInPager>输入参数 farmId>>"+farmId);
+        log.info("<listDeviceRegisterInPager>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listDeviceRegisterInPager>输入参数 alias>>"+alias);
+        log.info("<listDeviceRegisterInPager>输入参数 startDate>>"+startDate);
+        log.info("<listDeviceRegisterInPager>输入参数 endDate>>"+endDate);
+        log.info("<listDeviceRegisterInPager>输入参数 activeStatus>>"+activeStatus);
+        log.info("<listDeviceRegisterInPager>输入参数 liveStatus>>"+liveStatus);
+        log.info("<listDeviceRegisterInPager>输入参数 pageNo>>"+pageNo);
+        log.info("<listDeviceRegisterInPager>输入参数 pageSize>>"+pageSize);
+        //
+        return deviceService.listDeviceRegisterInPager(farmId,deviceCode,alias,startDate,endDate,activeStatus,liveStatus,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listManyDaysOnlineByDeviceCode
+     * @Description : F1接口-查询单个设备N天在线图表
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 14:07
+     */
+    @RequestMapping(value = "/listDeviceOnlineCountByDeviceCode",method = RequestMethod.GET)
+    public Result listDeviceOnlineCountByDeviceCode(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                    @RequestParam(value = "pastDays",required = false) Integer pastDays) throws ParseException {
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 pastDays>>"+pastDays);
+        if(pastDays == null){
+            pastDays = 7;
+        }
+        //查询单个设备N天在线记录
+        return deviceService.listDeviceOnlineCountByDeviceCode(deviceCode,pastDays);
+    }
+
+    /**
+     * @Method      : listDeviceOnlineCountByDeviceCodeInPager
+     * @Description : F2接口-查询单个设备在线记录
+     * @Params      : [deviceCode, startDate, endDate, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/18
+     * @Time        : 14:31
+     */
+    @RequestMapping(value = "/listDeviceOnlineCountByDeviceCodeInPager",method = RequestMethod.GET)
+    public Result listDeviceOnlineCountByDeviceCodeInPager(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                           @RequestParam(value = "startDate",required = false) String startDate,
+                                                           @RequestParam(value = "endDate",required = false) String endDate,
+                                                           @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                           @RequestParam(value = "pageSize",required = true) Integer pageSize ) throws ParseException {
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 startDate>>"+startDate);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 endDate>>"+endDate);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 pageNo>>"+pageNo);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 pageSize>>"+pageSize);
+        DateUtil dateUtil = new DateUtil();
+        if(startDate == null || startDate.trim().length() == 0){
+            startDate = dateUtil.getTodayDateText();
+        }
+        //endDate
+        if(endDate == null || endDate.trim().length() == 0){
+            endDate = dateUtil.getTodayDateText();
+        }
+        //查询单个设备N天在线记录(,endDate)
+        return deviceService.listDeviceOnlineCountByDeviceCodeInPager(deviceCode,startDate,endDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listDeviceOnlineStatusByDeviceCode
+     * @Description : 显示设备在线状态
+     * @Params      : [deviceCode, pastDays]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 15:44
+     */
+    @RequestMapping(value = "/listDeviceOnlineStatusByDeviceCode",method = RequestMethod.GET)
+    public Result listDeviceOnlineStatusByDeviceCode(@RequestParam(value = "deviceCode",required = true) String deviceCode,@RequestParam(value = "pastDays",required = true) Integer pastDays) throws ParseException {
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listManyDaysOnlineByDeviceCode>输入参数 pastDays>>"+pastDays);
+        if(pastDays == null){
+            pastDays = 7;
+        }
+        //查询单个设备N天在线记录
+        return deviceService.listDeviceOnlineStatusByDeviceCode(deviceCode,pastDays);
+    }
+
+    /**
+     * @Method      : listEartagOnlineCountByDeviceCode
+     * @Description : 显示设备关联耳标统计
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 18:11
+     */
+    @RequestMapping(value = "/listDeviceEartagOnlineCountByDeviceCode",method = RequestMethod.GET)
+    public Result listDeviceEartagOnlineCountByDeviceCode(@RequestParam(value = "deviceCode",required = true) String deviceCode) throws ParseException {
+        log.info("<listEartagOnlineCountByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        //查询设备关联的在线耳标统计
+        return deviceService.listDeviceEartagOnlineCountByDeviceCode(deviceCode);
+    }
+
+    /**
+     * @Method      : listDeviceEartagOnlineCountByDeviceCodeInPager
+     * @Description : 显示设备关联耳标统计(带分页)
+     * @Params      : [deviceCode, earmark, addDate, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/9
+     * @Time        : 20:06
+     */
+    @RequestMapping(value = "/listDeviceEartagOnlineCountByDeviceCodeInPager",method = RequestMethod.GET)
+    public Result listDeviceEartagOnlineCountByDeviceCodeInPager(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                                 @RequestParam(value = "earmark",required = false) String earmark,
+                                                                 @RequestParam(value = "addDate",required = false) String addDate,
+                                                                 @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                                 @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listDeviceEartagOnlineCountByDeviceCodeInPager>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listDeviceEartagOnlineCountByDeviceCodeInPager>输入参数 earmark>>"+earmark);
+        log.info("<listDeviceEartagOnlineCountByDeviceCodeInPager>输入参数 addDate>>"+addDate);
+        log.info("<listDeviceEartagOnlineCountByDeviceCodeInPager>输入参数 pageNo>>"+pageNo);
+        log.info("<listDeviceEartagOnlineCountByDeviceCodeInPager>输入参数 pageSize>>"+pageSize);
+        //
+        if(addDate == null){
+            addDate  =  new DateUtil().getTodayDateText();
+        }
+        //查询设备关联的在线耳标统计
+        return deviceService.listDeviceEartagOnlineCountByDeviceCodeInPager(deviceCode,earmark,addDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listDeviceEartagOnlineStatusByDeviceCodeAndDate
+     * @Description : 查询和设备相关的所有耳标状态
+     * @Params      : [deviceCode, earmark, addDate]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/29
+     * @Time        : 10:55
+     */
+    @RequestMapping(value = "/listDeviceEartagOnlineStatusByDeviceCodeAndDate",method = RequestMethod.GET)
+    public Result listDeviceEartagOnlineStatusByDeviceCodeAndDate(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                                  @RequestParam(value = "earmark",required = false) String earmark,
+                                                                  @RequestParam(value = "addDate",required = false) String addDate) throws ParseException {
+        log.info("<listDeviceEartagOnlineStatusByDeviceCodeAndDate>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listDeviceEartagOnlineStatusByDeviceCodeAndDate>输入参数 earmark>>"+earmark);
+        log.info("<listDeviceEartagOnlineStatusByDeviceCodeAndDate>输入参数 addDate>>"+addDate);
+        //
+        if(addDate == null || addDate.trim().length() == 0){
+            addDate  =  new DateUtil().getTodayDateText();
+        }
+        //查询设备关联的在线耳标统计
+        return deviceService.listDeviceEartagOnlineStatusByDeviceCodeAndDate(deviceCode,earmark,addDate);
+    }
+
+    /**
+     * @Method      : listDeviceEnvtempByDeviceCode
+     * @Description : 显示设备温度流水
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 21:11
+     */
+    @RequestMapping(value = "/listDeviceEnvtempByDeviceCode",method = RequestMethod.GET)
+    public Result listDeviceEnvtempByDeviceCode(@RequestParam(value = "deviceCode",required = true) String deviceCode) throws ParseException {
+        log.info("<listDeviceEnvtempByDeviceCode>输入参数 deviceCode>>"+deviceCode);
+        //查询设备环境温度
+        return deviceService.listDeviceEnvtempByDeviceCode(deviceCode);
+    }
+
+    /**
+     * @Method      : listDeviceEnvtempByDeviceCodeInPager
+     * @Description : 显示设备温度流水
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 21:11
+     */
+    @RequestMapping(value = "/listDeviceEnvtempByDeviceCodeInPager",method = RequestMethod.GET)
+    public Result listDeviceEnvtempByDeviceCodeInPager(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                       @RequestParam(value = "addDate",required = false) String addDate,
+                                                       @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                       @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 addDate>>"+addDate);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 pageNo>>"+pageNo);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 pageSize>>"+pageSize);
+        //
+        if(addDate == null || addDate.trim().length() == 0){
+            addDate  =  new DateUtil().getTodayDateText();
+        }
+        //查询设备环境温度
+        return deviceService.listDeviceEnvtempByDeviceCodeInPager(deviceCode,addDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listHeartbeatByDeviceCodeAndDateInPager
+     * @Description : 显示设备心跳数据(带分页)
+     * @Params      : [deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/9
+     * @Time        : 20:35
+     */
+    @RequestMapping(value = "/listHeartbeatByDeviceCodeAndDateInPager",method = RequestMethod.GET)
+    public Result listHeartbeatByDeviceCodeAndDateInPager(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                          @RequestParam(value = "addDate",required = false) String addDate,
+                                                          @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                          @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listHeartbeatByDeviceCodeAndDateInPager>输入参数 deviceCode>>"+deviceCode);
+        log.info("<listHeartbeatByDeviceCodeAndDateInPager>输入参数 addDate>>"+addDate);
+        log.info("<listHeartbeatByDeviceCodeAndDateInPager>输入参数 pageNo>>"+pageNo);
+        log.info("<listHeartbeatByDeviceCodeAndDateInPager>输入参数 pageSize>>"+pageSize);
+        //
+        if(addDate == null || addDate.trim().length() == 0){
+            addDate  =  new DateUtil().getTodayDateText();
+        }
+        //显示设备心跳
+        return deviceService.listHeartbeatByDeviceCodeAndDateInPager(deviceCode,addDate,pageNo,pageSize);
+    }
+}

+ 122 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/DeviceRegisterController.java

@@ -0,0 +1,122 @@
+package com.huimv.eartag.controller;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.service.IDeviceRegisterService;
+import com.huimv.eartag.vo.Result;
+import com.huimv.eartag.vo.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.text.ParseException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+//@CrossOrigin
+@RestController
+@RequestMapping(value = "/deviceRegister")
+@Slf4j
+public class DeviceRegisterController {
+    @Autowired
+    private IDeviceRegisterService deviceRegisterService;
+
+    @GetMapping("/addDevice")
+    public Result addDevice(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                            @RequestParam(value = "chipId",required = true) String chipId,
+                            @RequestParam(value = "deviceStatus",required = true) Integer deviceStatus,
+                            @RequestParam(value = "activeStatus",required = true) Integer activeStatus,
+                            @RequestParam(value = "deviceAlias",required = false) String deviceAlias,
+                            @RequestParam(value = "location",required = false) String location,
+                            @RequestParam(value = "remark",required = false) String remark,
+                            @RequestParam(value = "farmId",required = true) String farmId) throws ParseException {
+        log.info("farmId>>"+farmId);
+        log.info("chipId>>"+chipId);
+        log.info("deviceCode>>"+deviceCode);
+        log.info("deviceStatus>>"+deviceStatus);
+        log.info("activeStatus>>"+activeStatus);
+        //deviceStatus
+        if(deviceStatus == null){
+            //待机状态
+            deviceStatus = 0;
+        }
+        //activeStatus
+        if(activeStatus == null){
+            //未激活
+            activeStatus = 0;
+        }
+        //{添加设备}
+        return deviceRegisterService.addDevice(chipId,deviceCode,deviceStatus,activeStatus,deviceAlias,location,remark,farmId);
+    }
+
+
+    @PostMapping("/addDevice1")
+    public Result addDevice1(@RequestBody JSONObject json){
+        System.out.println("## json>>"+json);
+        String msg = "";
+        return new Result(ResultCode.SUCCESS,msg);
+    }
+
+    @GetMapping("/editDevice")
+    public Result editDevice(@RequestParam(value = "deviceCode",required = true) String deviceCode,
+                             @RequestParam(value = "chipId",required = true) String chipId,
+                             @RequestParam(value = "LastDeviceStatus",required = true) Integer LastDeviceStatus,
+                             @RequestParam(value = "deviceStatus",required = true) Integer deviceStatus,
+                             @RequestParam(value = "activeStatus",required = true) Integer activeStatus,
+                             @RequestParam(value = "deviceAlias",required = false) String deviceAlias,
+                             @RequestParam(value = "location",required = false) String location,
+                             @RequestParam(value = "remark",required = false) String remark,
+                             @RequestParam(value = "id",required = true) Integer id) throws ParseException {
+
+        log.info("(editDevice).deviceCode>>"+deviceCode);
+        log.info("(editDevice).chipId>>"+chipId);
+        log.info("(editDevice).LastDeviceStatus>>"+LastDeviceStatus);
+        log.info("(editDevice).deviceStatus>>"+deviceStatus);
+        log.info("(editDevice).activeStatus>>"+activeStatus);
+        log.info("(editDevice).deviceAlias>>"+deviceAlias);
+        log.info("(editDevice).location>>"+location);
+        log.info("(editDevice).remark>>"+remark);
+        log.info("(editDevice).id>>"+id);
+        //{编辑}
+        return deviceRegisterService.editDevice(chipId,deviceCode,LastDeviceStatus,deviceStatus,activeStatus,deviceAlias,location,remark,id);
+    }
+
+    @GetMapping("/removeDevice")
+    public Result removeDevice(@RequestParam(value = "ids",required = true) String ids){
+        //{移除设备}
+        return deviceRegisterService.removeDevice(ids);
+    }
+
+//    @GetMapping("/listDevice")
+    @RequestMapping(value = "/listAllDeviceInPager",method = RequestMethod.GET)
+    public Result listDevice(@RequestParam(value = "farmId",required = true) String farmId,
+                             @RequestParam(value = "deviceCode",required = true) String deviceCode,
+                             @RequestParam(value = "deviceStatus",required = false) Integer deviceStatus,
+                             @RequestParam(value = "activeStatus",required = false) Integer activeStatus,
+                             @RequestParam(value = "deviceAlias",required = false) String deviceAlias,
+                             @RequestParam(value = "location",required = false) String location,
+                             @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                             @RequestParam(value = "pageSize",required = true) Integer pageSize){
+        //
+        if(pageNo == null || pageNo.toString().length()==0 || pageSize == null || pageSize.toString().length() == 0){
+            return new Result(10010,"页码或页码尺寸不能为空.",false);
+        }
+        //{展示设备列表}
+        return deviceRegisterService.listDevice(farmId,deviceCode,deviceStatus,activeStatus,deviceAlias,location,pageNo,pageSize);
+    }
+
+    @GetMapping("/setDeviceStatus")
+    public Result setDeviceStatus(@RequestParam(value = "id",required = true) Integer id,
+                               @RequestParam(value = "deviceStatus",required = true) Integer deviceStatus) throws ParseException {
+        log.info("(setDeviceStatus).id>>"+id);
+        log.info("(setDeviceStatus).deviceStatus>>"+deviceStatus);
+        //{注销设备}
+        return deviceRegisterService.setDeviceStatus(id,deviceStatus);
+    }
+
+}

+ 366 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/EartagManageController.java

@@ -0,0 +1,366 @@
+package com.huimv.eartag.controller;
+
+import com.huimv.eartag.service.IEartagManageService;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.vo.Result;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.text.ParseException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@CrossOrigin
+@RestController
+@RequestMapping(value = "/eartag")
+@Slf4j
+public class EartagManageController {
+    @Autowired
+    private IEartagManageService eartagService;
+
+    /**
+     * @Method      : listEartagOnlineAllStatus
+     * @Description : 显示耳标前N天在线记录
+     * @Params      : [farmId, days]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/30
+     * @Time        : 20:04
+     */
+    @RequestMapping(value = "/listManyEartagOnlineStatus",method = RequestMethod.GET)
+    public Result listManyEartagOnlineStatus(@RequestParam(value = "farmId",required = true) String farmId, @RequestParam(value = "days",required = true) Integer days) throws ParseException {
+        log.info("<listManyDaysAllStatus>输入参数 farmId>>"+farmId);
+        log.info("<listManyDaysAllStatus>输入参数 days>>"+days);
+        if(days == null){
+            //默认7天数据
+            days = 7;
+        }
+        //{}
+        return eartagService.listManyEartagOnlineStatus(farmId,days);
+    }
+
+    /**
+     * @Method      : getEartagRegisterByEarmark
+     * @Description : 读取耳标注册信息,设备在线页面调用
+     * @Params      : [earmark]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 18:39
+     */
+    @RequestMapping(value = "/getEartagRegisterByEarmark",method = RequestMethod.GET)
+    public Result getEartagRegisterByEarmark(@RequestParam(value = "earmark",required = true) String earmark) throws ParseException {
+        log.info("<getEartagRegisterByEarmark> 输入参数earmark>>"+earmark);
+        //
+        return eartagService.getEartagRegisterByEarmark(earmark);
+    }
+
+    /**
+     * @Method      : getEartagFlowByEarmarkAndToday
+     * @Description :读取耳标今天所有耳标流水,设备在线页面调用
+     * @Params      : [earmark]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 18:41
+     */
+    @RequestMapping(value = "/listEartagFlowByEarmarkAndToday",method = RequestMethod.GET)
+    public Result listEartagFlowByEarmarkAndToday(@RequestParam(value = "earmark",required = true) String earmark) throws ParseException {
+        log.info("<listEartagFlowByEarmarkAndToday> 输入参数 earmark>>"+earmark);
+        //
+        return eartagService.listEartagFlowByEarmarkAndToday(earmark);
+    }
+
+    /**
+     * @Method      : listEartagFlowByEarmarkAndTodayInPager
+     * @Description :
+     * @Params      : [earmark, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 20:18
+     */
+    @RequestMapping(value = "/listEartagFlowByEarmarkAndTodayInPager",method = RequestMethod.GET)
+    public Result listEartagFlowByEarmarkAndTodayInPager(@RequestParam(value = "earmark",required = true) String earmark,
+                                                         @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                         @RequestParam(value = "pageSize",required = true) Integer pageSize,
+                                                         @RequestParam(value = "createDate",required = false) String createDate,
+                                                         @RequestParam(value = "deviceCode",required = false) String deviceCode) throws ParseException {
+        log.info("<listEartagFlowByEarmarkAndTodayInPager> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagFlowByEarmarkAndTodayInPager> 输入参数 pageNo>>"+pageNo);
+        log.info("<listEartagFlowByEarmarkAndTodayInPager> 输入参数 pageSize>>"+pageSize);
+        log.info("<listEartagFlowByEarmarkAndTodayInPager> 输入参数 createDate>>"+createDate);
+        log.info("<listEartagFlowByEarmarkAndTodayInPager> 输入参数 deviceCode>>"+deviceCode);
+        if(createDate == null || createDate.trim().length() == 0){
+            createDate = new DateUtil().getTodayDateText();
+        }
+        //
+        return eartagService.listEartagFlowByEarmarkAndTodayInPager(earmark,pageNo,pageSize,createDate,deviceCode);
+    }
+
+    /**
+     * @Method      : listEartagFlowByDeviceCodeAndEarmarkAndToday
+     * @Description : 读取设备下和该耳标今天所有耳标流水,设备在线页面调用
+     * @Params      : [earmark, deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 18:56
+     */
+    @RequestMapping(value = "/listEartagFlowByDeviceCodeAndEarmarkAndToday",method = RequestMethod.GET)
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndToday(@RequestParam(value = "earmark",required = true) String earmark,
+                                                               @RequestParam(value = "deviceCode",required = true) String deviceCode) throws ParseException {
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndToday> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndToday> 输入参数 deviceCode>"+deviceCode);
+        //
+        return eartagService.listEartagFlowByDeviceCodeAndEarmarkAndToday(earmark,deviceCode);
+    }
+
+    /**
+     * @Method      : listEartagFlowByDeviceCodeAndEarmarkAndToday
+     * @Description : 读取设备下和该耳标今天所有耳标流水,设备在线页面调用(分页)
+     * @Params      : [earmark, deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7
+     * @Time        : 18:56
+     */
+    @RequestMapping(value = "/listEartagFlowByDeviceCodeAndEarmarkAndDateInPager",method = RequestMethod.GET)
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndDateInPager(@RequestParam(value = "earmark",required = true) String earmark,
+                                                                     @RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                                     @RequestParam(value = "addDate",required = false) String addDate,
+                                                                     @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                                     @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndDateInPager> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndDateInPager> 输入参数 deviceCode>"+deviceCode);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 addDate>>"+addDate);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 pageNo>>"+pageNo);
+        log.info("<listDeviceEnvtempByDeviceCodeInPager>输入参数 pageSize>>"+pageSize);
+        //
+        if(addDate == null){
+            addDate  =  new DateUtil().getTodayDateText();
+        }
+        //
+        return eartagService.listEartagFlowByDeviceCodeAndEarmarkAndDateInPager(earmark,deviceCode,addDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager
+     * @Description : 读取设备下和该耳标今天所有耳标流水,设备在线页面调用(分页)
+     * @Params      : [earmark, deviceCode]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 20:34
+     */
+    @RequestMapping(value = "/listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager",method = RequestMethod.GET)
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager(@RequestParam(value = "earmark",required = true) String earmark,
+                                                                      @RequestParam(value = "deviceCode",required = true) String deviceCode,
+                                                                      @RequestParam(value = "createDate",required = true) String createDate,
+                                                                      @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                                                      @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager> 输入参数 deviceCode>"+deviceCode);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager> 输入参数 createDate>"+createDate);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager> 输入参数 pageNo>>"+pageNo);
+        log.info("<listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager> 输入参数 pageSize>>"+pageSize);
+        if(createDate == null || createDate.trim().length() == 0){
+            createDate = new DateUtil().getTodayDateText();
+        }
+        //
+        return eartagService.listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager(earmark,deviceCode,createDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listEartagOnlineCountByEarmarkAndDate
+     * @Description : 显示耳标在线统计
+     * @Params      : [earmark, pastDays]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 18:28
+     */
+    @RequestMapping(value = "/listEartagOnlineCountByEarmarkAndDate",method = RequestMethod.GET)
+    public Result listEartagCountByEarmarkAndDate(@RequestParam(value = "earmark",required = true) String earmark,
+                                                  @RequestParam(value = "pastDays",required = true) Integer pastDays,
+                                                  @RequestParam(value = "showMode",required = true) Integer showMode) throws ParseException {
+        log.info("<listEartagOnlineCountByEarmarkAndDate> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagOnlineCountByEarmarkAndDate> 输入参数 pastDays>"+pastDays);
+        log.info("<listEartagOnlineStatusByEarmarkAndDate> 输入参数 showMode>"+showMode);
+        if(showMode == null){
+            showMode = 1;
+        }
+        //
+        return eartagService.listEartagOnlineCountByEarmarkAndDate(earmark,pastDays,showMode);
+    }
+
+    /**
+     * @Method      : listEartagOnlineStatusByEarmarkAndDate
+     * @Description : 显示耳标在线状态
+     * @Params      : [earmark, pastDays]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8
+     * @Time        : 19:52
+     */
+    @RequestMapping(value = "/listEartagOnlineStatusByEarmarkAndDate",method = RequestMethod.GET)
+    public Result listEartagOnlineStatusByEarmarkAndDate(@RequestParam(value = "earmark",required = true) String earmark,
+                                                         @RequestParam(value = "pastDays",required = true) Integer pastDays) throws ParseException {
+        log.info("<listEartagOnlineStatusByEarmarkAndDate> 输入参数 earmark>>"+earmark);
+        log.info("<listEartagOnlineStatusByEarmarkAndDate> 输入参数 pastDays>"+pastDays);
+        //
+        return eartagService.listEartagOnlineStatusByEarmarkAndDate(earmark,pastDays);
+    }
+
+    /**
+     * @Method      : listEartagOnlineAllStatus
+     * @Description : 前N天耳标在线状态
+     * @Params      : [farmId, days]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/10
+     * @Time        : 20:43
+     */
+    @RequestMapping(value = "/listEartagOnlineAllStatus",method = RequestMethod.GET)
+    public Result listEartagOnlineAllStatus(@RequestParam(value = "farmId",required = true) String farmId,
+                                            @RequestParam(value = "days",required = true) Integer days) throws ParseException {
+        log.info("<listEartagOnlineAllStatus>输入参数 farmId>>"+farmId);
+        log.info("<listEartagOnlineAllStatus>输入参数 days>>"+days);
+        if(days == null){
+            //默认7天数据
+            days = 7;
+        }
+        //
+        return eartagService.listEartagOnlineAllStatus(farmId,days);
+    }
+
+    /**
+     * @Method      : listEartagOnlineCount
+     * @Description : 列表展示某一天的在线记录
+     * @Params      : [farmId, addDate, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/10
+     * @Time        : 21:50
+     */
+    @RequestMapping(value = "/listOnlineEartagCount",method = RequestMethod.GET)
+    public Result listEartagOnlineCount(@RequestParam(value = "farmId",required = true) String farmId,
+                                        @RequestParam(value = "addDate",required = false) String addDate,
+                                        @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                        @RequestParam(value = "pageSize",required = true) Integer pageSize,
+                                        @RequestParam(value = "showMode",required = true) Integer showMode) throws ParseException {
+        log.info("<listOnlineEartagCount>输入参数 farmId>>"+farmId);
+        log.info("<listOnlineEartagCount>输入参数 addDate>>"+addDate);
+        log.info("<listOnlineEartagCount>输入参数 pageNo>>"+pageNo);
+        log.info("<listOnlineEartagCount>输入参数 pageSize>>"+pageSize);
+        log.info("<listOnlineEartagCount>输入参数 showMode>>"+showMode);
+        if(addDate == null || addDate.trim().length() == 0){
+            addDate = new DateUtil().getTodayDateText();
+        }
+        //
+        return eartagService.listOnlineEartagCount(farmId,addDate,pageNo,pageSize,showMode);
+    }
+
+    /**
+     * @Method      : listEartagDeviceByEarmarkAndAddDate
+     * @Description : 根据耳标和日期,查询关联设备记录
+     * @Params      : [earmark, addDate]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/10
+     * @Time        : 22:33
+     */
+    @RequestMapping(value = "/listEartagDeviceByEarmarkAndAddDate",method = RequestMethod.GET)
+    public Result listEartagDeviceByEarmarkAndAddDate(@RequestParam(value = "earmark",required = true) String earmark,
+                                                      @RequestParam(value = "addDate",required = false) String addDate) throws ParseException {
+        log.info("<listEartagDeviceByEarmarkAndAddDate>输入参数 earmark>>"+earmark);
+        log.info("<listEartagDeviceByEarmarkAndAddDate>输入参数 addDate>>"+addDate);
+        if(addDate == null || addDate.trim().length() == 0){
+            addDate = new DateUtil().getTodayDateText();
+        }
+        //
+        return eartagService.listEartagDeviceByEarmarkAndAddDate(earmark,addDate);
+    }
+
+    /**
+     * @Method      : listAllEartagRegister
+     * @Description : 展示所有耳标注册列表
+     * @Params      : [farmId]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/11
+     * @Time        : 9:35
+     */
+    @RequestMapping(value = "/listAllEartagRegister",method = RequestMethod.GET)
+    public Result listAllEartagRegister(@RequestParam(value = "farmId",required = true) String farmId,
+                                        @RequestParam(value = "earmark",required = false) String earmark,
+                                        @RequestParam(value = "activeStatus",required = false) Integer activeStatus,
+                                        @RequestParam(value = "liveStatus",required = false) Integer liveStatus,
+                                        @RequestParam(value = "registerType",required = false) Integer registerType,
+                                        @RequestParam(value = "startDate",required = false) String startDate,
+                                        @RequestParam(value = "endDate",required = false) String endDate,
+                                        @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                        @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listAllEartagRegister> 输入参数 farmId>>"+farmId);
+        log.info("<listAllEartagRegister> 输入参数 earmark>>"+earmark);
+        log.info("<listAllEartagRegister> 输入参数 activeStatus>>"+activeStatus);
+        log.info("<listAllEartagRegister> 输入参数 liveStatus>>"+liveStatus);
+        log.info("<listAllEartagRegister> 输入参数 registerType>>"+registerType);
+        log.info("<listAllEartagRegister> 输入参数 startDate>>"+startDate);
+        log.info("<listAllEartagRegister> 输入参数 endDate>>"+endDate);
+        log.info("<listAllEartagRegister> 输入参数 pageNo>>"+pageNo);
+        log.info("<listAllEartagRegister> 输入参数 pageSize>>"+pageSize);
+        //
+        return eartagService.listAllEartagRegister(farmId,earmark,activeStatus,liveStatus,registerType,startDate,endDate,pageNo,pageSize);
+    }
+
+    /**
+     * @Method      : listAllEartagFlow
+     * @Description : 展示所有流水列表
+     * @Params      : [farmId, createDate, deviceCode, earmark, pageNo, pageSize]
+     * @Return      : com.huimv.eartag2.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/11
+     * @Time        : 20:29
+     */
+    @RequestMapping(value = "/listAllEartagFlow",method = RequestMethod.GET)
+    public Result listAllEartagFlow(@RequestParam(value = "farmId",required = true) String farmId,
+                                    @RequestParam(value = "createDate",required = false) String createDate,
+                                    @RequestParam(value = "deviceCode",required = false) String deviceCode,
+                                    @RequestParam(value = "earmark",required = false) String earmark,
+                                    @RequestParam(value = "pageNo",required = true) Integer pageNo,
+                                    @RequestParam(value = "pageSize",required = true) Integer pageSize) throws ParseException {
+        log.info("<listAllEartagRegister> 输入参数 farmId>>"+farmId);
+        log.info("<listAllEartagRegister> 输入参数 createDate>>"+createDate);
+        log.info("<listAllEartagRegister> 输入参数 deviceCode>>"+deviceCode);
+        log.info("<listAllEartagRegister> 输入参数 earmark>>"+earmark);
+        log.info("<listAllEartagRegister> 输入参数 pageNo>>"+pageNo);
+        log.info("<listAllEartagRegister> 输入参数 pageSize>>"+pageSize);
+        if(createDate == null || createDate.trim().length() == 0){
+            createDate = new DateUtil().getTodayDateText();
+        }
+        //{}
+        return eartagService.listAllEartagFlow(farmId,createDate,deviceCode,earmark,pageNo,pageSize);
+    }
+}

+ 80 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/controller/TestController.java

@@ -0,0 +1,80 @@
+package com.huimv.eartag.controller;
+
+import com.huimv.eartag.producer.ManageProducer;
+import com.huimv.eartag.service.IDeviceManageService;
+import com.huimv.eartag.utils.Const;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@RestController
+@RequestMapping("/test")
+public class TestController {
+    @Autowired
+    private IDeviceManageService deviceService;
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+    @Autowired
+    private ManageProducer producer;
+
+    @GetMapping("/sendMq")
+    public void sendMq(){
+        Map map = new HashMap();
+        String askText = "hm+202007239999866+4+1+247+20220407140548+0+end";
+        map.put("askText",askText);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_DEVICE, Const.ROUTING_KEY_ASK_DEVICE, map);
+        System.out.println("同步设备注册信息 >>"+map.toString());
+    }
+
+    @GetMapping("/getName")
+    public String getName(){
+        return "Hello,World.";
+    }
+
+    //
+    @PostMapping("/testRemoteProcessFarmAllStatus")
+    public void testRemoteProcessFarmAllStatus() throws ParseException {
+        deviceService.remoteProcessFarmAllStatus("101");
+    }
+
+    @PostMapping("/testSendMq")
+    public void testSendMq() throws ParseException {
+        System.out.println("2.");
+        Map map = new HashMap();
+        map.put("deviceRegister","{\"activeStatus\":0,\"chipId\":\"30\",\"createDate\":1647878400000,\"deviceAlias\":\"\",\"deviceCode\":\"30\",\"deviceStatus\":0,\"farmId\":\"101\",\"id\":52,\"location\":\"\",\"registerTime\":1647955296670,\"remark\":\"\"}");
+//        map.put("deviceRegister","123");
+
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_SYNC_DEVICE_REGISTER, Const.ROUTING_KEY_SYNC_DEVICE_REGISTER, map);
+        System.out.println("同步设备注册信息 >>"+map.toString());
+        System.out.println("2.1");
+//        return "ok";
+    }
+
+
+    @PostMapping("/testSendMq2")
+    public void testSendMq2() throws ParseException {
+        String msg = "{\"activeStatus\":0,\"chipId\":\"30\",\"createDate\":1647878400000,\"deviceAlias\":\"\",\"deviceCode\":\"30\",\"deviceStatus\":0,\"farmId\":\"101\",\"id\":52,\"location\":\"\",\"registerTime\":1647955296670,\"remark\":\"\"}";
+        producer.sendSyncDeviceRegister(msg);
+//        producer.sendSyncDeviceRegister("456");
+    }
+    //
+//    @PostMapping("/testRemoteProcessFarmAllStatus2")
+//    public void testRemoteProcessFarmAllStatus2() throws ParseException {
+//        deviceService.remoteProcessFarmAllStatus2("101");
+//    }
+}

+ 103 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/BaseFarmEntity.java

@@ -0,0 +1,103 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+
+@Entity
+@Table(name = "base_farm")
+public class BaseFarmEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    @Column(name = "farm_name")
+    private String farmName;
+
+    @Column(name = "location")
+    private String location;
+
+    @Column(name = "leader")
+    private String leader;
+
+    @Column(name = "phone")
+    private String phone;
+
+    @Column(name = "remark")
+    private String remark;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    public void setFarmName(String farmName) {
+        this.farmName = farmName;
+    }
+
+    public String getFarmName() {
+        return farmName;
+    }
+
+    public void setLocation(String location) {
+        this.location = location;
+    }
+
+    public String getLocation() {
+        return location;
+    }
+
+    public void setLeader(String leader) {
+        this.leader = leader;
+    }
+
+    public String getLeader() {
+        return leader;
+    }
+
+    public void setPhone(String phone) {
+        this.phone = phone;
+    }
+
+    public String getPhone() {
+        return phone;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    @Override
+    public String toString() {
+        return "BaseFarmEntity{" +
+                "id=" + id + '\'' +
+                "farmId=" + farmId + '\'' +
+                "farmName=" + farmName + '\'' +
+                "location=" + location + '\'' +
+                "leader=" + leader + '\'' +
+                "phone=" + phone + '\'' +
+                "remark=" + remark + '\'' +
+                '}';
+    }
+}

+ 67 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/BaseFarmServerConfigEntity.java

@@ -0,0 +1,67 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+
+@Entity
+@Table(name = "base_farm_server_config")
+public class BaseFarmServerConfigEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    @Column(name = "server_ip")
+    private String serverIp;
+
+    @Column(name = "server_port")
+    private Integer serverPort;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    public void setServerIp(String serverIp) {
+        this.serverIp = serverIp;
+    }
+
+    public String getServerIp() {
+        return serverIp;
+    }
+
+    public void setServerPort(Integer serverPort) {
+        this.serverPort = serverPort;
+    }
+
+    public Integer getServerPort() {
+        return serverPort;
+    }
+
+    @Override
+    public String toString() {
+        return "BaseFarmServerConfigEntity{" +
+                "id=" + id + '\'' +
+                "farmId=" + farmId + '\'' +
+                "serverIp=" + serverIp + '\'' +
+                "serverPort=" + serverPort + '\'' +
+                '}';
+    }
+}

+ 68 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceCountEntity.java

@@ -0,0 +1,68 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_abnormal_device_count")
+public class EartagAbnormalDeviceCountEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "farm_id", nullable = false)
+    private String farmId;
+
+    @Column(name = "device_count", nullable = false)
+    private String deviceCount;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setDeviceCount(String deviceCount) {
+        this.deviceCount = deviceCount;
+    }
+
+    public String getDeviceCount() {
+        return deviceCount;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalDeviceCountEntity{" +
+                "id=" + id + '\'' +
+                "farmId=" + farmId + '\'' +
+                "deviceCount=" + deviceCount + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 69 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceDetailEntity.java

@@ -0,0 +1,69 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_abnormal_device_detail")
+public class EartagAbnormalDeviceDetailEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code", nullable = false)
+    private String deviceCode;
+
+    @Column(name = "add_time", nullable = false)
+    private Timestamp addTime;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalDeviceDetailEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 80 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalDeviceTimesEntity.java

@@ -0,0 +1,80 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_abnormal_device_times")
+public class EartagAbnormalDeviceTimesEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code", nullable = false)
+    private String deviceCode;
+
+    @Column(name = "times", nullable = false)
+    private Integer times;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    @Column(name = "farmId", nullable = false)
+    private String farmId;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setTimes(Integer times) {
+        this.times = times;
+    }
+
+    public Integer getTimes() {
+        return times;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalDeviceTimesEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "times=" + times + '\'' +
+                "createDate=" + createDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                '}';
+    }
+}

+ 68 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagCountEntity.java

@@ -0,0 +1,68 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_abnormal_eartag_count")
+public class EartagAbnormalEartagCountEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "farm_id", nullable = false)
+    private String farmId;
+
+    @Column(name = "eartag_count", nullable = false)
+    private String eartagCount;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setEartagCount(String eartagCount) {
+        this.eartagCount = eartagCount;
+    }
+
+    public String getEartagCount() {
+        return eartagCount;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalEartagCountEntity{" +
+                "id=" + id + '\'' +
+                "farmId=" + farmId + '\'' +
+                "eartagCount=" + eartagCount + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 69 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagDetailEntity.java

@@ -0,0 +1,69 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_abnormal_eartag_detail")
+public class EartagAbnormalEartagDetailEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "earmark", nullable = false)
+    private String earmark;
+
+    @Column(name = "add_time", nullable = false)
+    private Timestamp addTime;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalEartagDetailEntity{" +
+                "id=" + id + '\'' +
+                "earmark=" + earmark + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 80 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagAbnormalEartagTimesEntity.java

@@ -0,0 +1,80 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_abnormal_eartag_times")
+public class EartagAbnormalEartagTimesEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "earmark", nullable = false)
+    private String earmark;
+
+    @Column(name = "times", nullable = false)
+    private Integer times;
+
+    @Column(name = "create_date", nullable = false)
+    private Date createDate;
+
+    @Column(name = "farmId", nullable = false)
+    private String farmId;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setTimes(Integer times) {
+        this.times = times;
+    }
+
+    public Integer getTimes() {
+        return times;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagAbnormalEartagTimesEntity{" +
+                "id=" + id + '\'' +
+                "earmark=" + earmark + '\'' +
+                "times=" + times + '\'' +
+                "createDate=" + createDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                '}';
+    }
+}

+ 79 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagConfigPropertiesEntity.java

@@ -0,0 +1,79 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+
+@Entity
+@Table(name = "eartag_config_properties")
+public class EartagConfigPropertiesEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "pro_key")
+    private String proKey;
+
+    @Column(name = "pro_val1")
+    private String proVal1;
+
+    @Column(name = "pro_sort", nullable = false)
+    private String proSort;
+
+    @Column(name = "pro_val2")
+    private String proVal2;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setProKey(String proKey) {
+        this.proKey = proKey;
+    }
+
+    public String getProKey() {
+        return proKey;
+    }
+
+    public void setProVal1(String proVal1) {
+        this.proVal1 = proVal1;
+    }
+
+    public String getProVal1() {
+        return proVal1;
+    }
+
+    public void setProSort(String proSort) {
+        this.proSort = proSort;
+    }
+
+    public String getProSort() {
+        return proSort;
+    }
+
+    public void setProVal2(String proVal2) {
+        this.proVal2 = proVal2;
+    }
+
+    public String getProVal2() {
+        return proVal2;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagConfigPropertiesEntity{" +
+                "id=" + id + '\'' +
+                "proKey=" + proKey + '\'' +
+                "proVal1=" + proVal1 + '\'' +
+                "proSort=" + proSort + '\'' +
+                "proVal2=" + proVal2 + '\'' +
+                '}';
+    }
+}

+ 237 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDataEntity.java

@@ -0,0 +1,237 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_data")
+public class EartagDataEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "cmd_header")
+    private String cmdHeader;
+
+    @Column(name = "device")
+    private String device;
+
+    @Column(name = "earmark")
+    private String earmark;
+
+    @Column(name = "bat")
+    private Integer bat;
+
+    @Column(name = "ear_temp")
+    private Integer earTemp;
+
+    @Column(name = "ear_temp1")
+    private Float earTemp1;
+
+    @Column(name = "env_temp")
+    private Integer envTemp;
+
+    @Column(name = "env_temp1")
+    private Float envTemp1;
+
+    @Column(name = "act")
+    private Integer act;
+
+    @Column(name = "act1")
+    private Integer act1;
+
+    @Column(name = "signal1")
+    private Integer signal1;
+
+    @Column(name = "ask_time")
+    private String askTime;
+
+    @Column(name = "other")
+    private String other;
+
+    @Column(name = "add_time")
+    private Timestamp addTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "ask_date")
+    private Date askDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setCmdHeader(String cmdHeader) {
+        this.cmdHeader = cmdHeader;
+    }
+
+    public String getCmdHeader() {
+        return cmdHeader;
+    }
+
+    public void setDevice(String device) {
+        this.device = device;
+    }
+
+    public String getDevice() {
+        return device;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setBat(Integer bat) {
+        this.bat = bat;
+    }
+
+    public Integer getBat() {
+        return bat;
+    }
+
+    public void setEarTemp(Integer earTemp) {
+        this.earTemp = earTemp;
+    }
+
+    public Integer getEarTemp() {
+        return earTemp;
+    }
+
+    public void setEarTemp1(Float earTemp1) {
+        this.earTemp1 = earTemp1;
+    }
+
+    public Float getEarTemp1() {
+        return earTemp1;
+    }
+
+    public void setEnvTemp(Integer envTemp) {
+        this.envTemp = envTemp;
+    }
+
+    public Integer getEnvTemp() {
+        return envTemp;
+    }
+
+    public void setEnvTemp1(Float envTemp1) {
+        this.envTemp1 = envTemp1;
+    }
+
+    public Float getEnvTemp1() {
+        return envTemp1;
+    }
+
+    public void setAct(Integer act) {
+        this.act = act;
+    }
+
+    public Integer getAct() {
+        return act;
+    }
+
+    public void setAct1(Integer act1) {
+        this.act1 = act1;
+    }
+
+    public Integer getAct1() {
+        return act1;
+    }
+
+    public void setSignal1(Integer signal1) {
+        this.signal1 = signal1;
+    }
+
+    public Integer getSignal1() {
+        return signal1;
+    }
+
+    public void setAskTime(String askTime) {
+        this.askTime = askTime;
+    }
+
+    public String getAskTime() {
+        return askTime;
+    }
+
+    public void setOther(String other) {
+        this.other = other;
+    }
+
+    public String getOther() {
+        return other;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setAskDate(Date askDate) {
+        this.askDate = askDate;
+    }
+
+    public Date getAskDate() {
+        return askDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDataEntity{" +
+                "id=" + id + '\'' +
+                "cmdHeader=" + cmdHeader + '\'' +
+                "device=" + device + '\'' +
+                "earmark=" + earmark + '\'' +
+                "bat=" + bat + '\'' +
+                "earTemp=" + earTemp + '\'' +
+                "earTemp1=" + earTemp1 + '\'' +
+                "envTemp=" + envTemp + '\'' +
+                "envTemp1=" + envTemp1 + '\'' +
+                "act=" + act + '\'' +
+                "act1=" + act1 + '\'' +
+                "signal1=" + signal1 + '\'' +
+                "askTime=" + askTime + '\'' +
+                "other=" + other + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                "askDate=" + askDate + '\'' +
+                '}';
+    }
+}

+ 104 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceDayStatusEntity.java

@@ -0,0 +1,104 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_device_day_status")
+public class EartagDeviceDayStatusEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    @Column(name = "total")
+    private Integer total;
+
+    @Column(name = "online")
+    private Integer online;
+
+    @Column(name = "offline")
+    private Integer offline;
+
+    @Column(name = "online_rate")
+    private Float onlineRate;
+
+    @Column(name = "add_date")
+    private Date addDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    public void setTotal(Integer total) {
+        this.total = total;
+    }
+
+    public Integer getTotal() {
+        return total;
+    }
+
+    public void setOnline(Integer online) {
+        this.online = online;
+    }
+
+    public Integer getOnline() {
+        return online;
+    }
+
+    public void setOffline(Integer offline) {
+        this.offline = offline;
+    }
+
+    public Integer getOffline() {
+        return offline;
+    }
+
+    public void setOnlineRate(Float onlineRate) {
+        this.onlineRate = onlineRate;
+    }
+
+    public Float getOnlineRate() {
+        return onlineRate;
+    }
+
+    public void setAddDate(Date addDate) {
+        this.addDate = addDate;
+    }
+
+    public Date getAddDate() {
+        return addDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDeviceDayStatusEntity{" +
+                "id=" + id + '\'' +
+                "farmId=" + farmId + '\'' +
+                "total=" + total + '\'' +
+                "online=" + online + '\'' +
+                "offline=" + offline + '\'' +
+                "onlineRate=" + onlineRate + '\'' +
+                "addDate=" + addDate + '\'' +
+                '}';
+    }
+}

+ 105 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceEartagCountEntity.java

@@ -0,0 +1,105 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_device_eartag_count")
+public class EartagDeviceEartagCountEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "earmark")
+    private String earmark;
+
+    @Column(name = "total")
+    private Integer total;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "update_time")
+    private Timestamp updateTime;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setTotal(Integer total) {
+        this.total = total;
+    }
+
+    public Integer getTotal() {
+        return total;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setUpdateTime(Timestamp updateTime) {
+        this.updateTime = updateTime;
+    }
+
+    public Timestamp getUpdateTime() {
+        return updateTime;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDeviceEartagCountEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "earmark=" + earmark + '\'' +
+                "total=" + total + '\'' +
+                "createDate=" + createDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                "updateTime=" + updateTime + '\'' +
+                '}';
+    }
+}

+ 249 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceOnlineEntity.java

@@ -0,0 +1,249 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_device_online")
+public class EartagDeviceOnlineEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "alias")
+    private String alias;
+
+    @Column(name = "heartbeat_total")
+    private Integer heartbeatTotal;
+
+    @Column(name = "envtemp_total")
+    private Integer envtempTotal;
+
+    @Column(name = "eartag_total")
+    private Integer eartagTotal;
+
+    @Column(name = "first_time")
+    private Timestamp firstTime;
+
+    @Column(name = "last_time")
+    private Timestamp lastTime;
+
+    @Column(name = "last_envtemp")
+    private String lastEnvtemp;
+
+    @Column(name = "last_eartag")
+    private String lastEartag;
+
+    @Column(name = "add_date")
+    private Date addDate;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "heartbeat_first_time")
+    private Timestamp heartbeatFirstTime;
+
+    @Column(name = "heartbeat_last_time")
+    private Timestamp heartbeatLastTime;
+
+    @Column(name = "envtemp_first_time")
+    private Timestamp envtempFirstTime;
+
+    @Column(name = "envtemp_last_time")
+    private Timestamp envtempLastTime;
+
+    @Column(name = "eartag_first_time")
+    private Timestamp eartagFirstTime;
+
+    @Column(name = "eartag_last_time")
+    private Timestamp eartagLastTime;
+
+    @Column(name = "live_status")
+    private Integer liveStatus;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setAlias(String alias) {
+        this.alias = alias;
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    public void setHeartbeatTotal(Integer heartbeatTotal) {
+        this.heartbeatTotal = heartbeatTotal;
+    }
+
+    public Integer getHeartbeatTotal() {
+        return heartbeatTotal;
+    }
+
+    public void setEnvtempTotal(Integer envtempTotal) {
+        this.envtempTotal = envtempTotal;
+    }
+
+    public Integer getEnvtempTotal() {
+        return envtempTotal;
+    }
+
+    public void setEartagTotal(Integer eartagTotal) {
+        this.eartagTotal = eartagTotal;
+    }
+
+    public Integer getEartagTotal() {
+        return eartagTotal;
+    }
+
+    public void setFirstTime(Timestamp firstTime) {
+        this.firstTime = firstTime;
+    }
+
+    public Timestamp getFirstTime() {
+        return firstTime;
+    }
+
+    public void setLastTime(Timestamp lastTime) {
+        this.lastTime = lastTime;
+    }
+
+    public Timestamp getLastTime() {
+        return lastTime;
+    }
+
+    public void setLastEnvtemp(String lastEnvtemp) {
+        this.lastEnvtemp = lastEnvtemp;
+    }
+
+    public String getLastEnvtemp() {
+        return lastEnvtemp;
+    }
+
+    public void setLastEartag(String lastEartag) {
+        this.lastEartag = lastEartag;
+    }
+
+    public String getLastEartag() {
+        return lastEartag;
+    }
+
+    public void setAddDate(Date addDate) {
+        this.addDate = addDate;
+    }
+
+    public Date getAddDate() {
+        return addDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setHeartbeatFirstTime(Timestamp heartbeatFirstTime) {
+        this.heartbeatFirstTime = heartbeatFirstTime;
+    }
+
+    public Timestamp getHeartbeatFirstTime() {
+        return heartbeatFirstTime;
+    }
+
+    public void setHeartbeatLastTime(Timestamp heartbeatLastTime) {
+        this.heartbeatLastTime = heartbeatLastTime;
+    }
+
+    public Timestamp getHeartbeatLastTime() {
+        return heartbeatLastTime;
+    }
+
+    public void setEnvtempFirstTime(Timestamp envtempFirstTime) {
+        this.envtempFirstTime = envtempFirstTime;
+    }
+
+    public Timestamp getEnvtempFirstTime() {
+        return envtempFirstTime;
+    }
+
+    public void setEnvtempLastTime(Timestamp envtempLastTime) {
+        this.envtempLastTime = envtempLastTime;
+    }
+
+    public Timestamp getEnvtempLastTime() {
+        return envtempLastTime;
+    }
+
+    public void setEartagFirstTime(Timestamp eartagFirstTime) {
+        this.eartagFirstTime = eartagFirstTime;
+    }
+
+    public Timestamp getEartagFirstTime() {
+        return eartagFirstTime;
+    }
+
+    public void setEartagLastTime(Timestamp eartagLastTime) {
+        this.eartagLastTime = eartagLastTime;
+    }
+
+    public Timestamp getEartagLastTime() {
+        return eartagLastTime;
+    }
+
+    public void setLiveStatus(Integer liveStatus) {
+        this.liveStatus = liveStatus;
+    }
+
+    public Integer getLiveStatus() {
+        return liveStatus;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDeviceOnlineEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "alias=" + alias + '\'' +
+                "heartbeatTotal=" + heartbeatTotal + '\'' +
+                "envtempTotal=" + envtempTotal + '\'' +
+                "eartagTotal=" + eartagTotal + '\'' +
+                "firstTime=" + firstTime + '\'' +
+                "lastTime=" + lastTime + '\'' +
+                "lastEnvtemp=" + lastEnvtemp + '\'' +
+                "lastEartag=" + lastEartag + '\'' +
+                "addDate=" + addDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                "heartbeatFirstTime=" + heartbeatFirstTime + '\'' +
+                "heartbeatLastTime=" + heartbeatLastTime + '\'' +
+                "envtempFirstTime=" + envtempFirstTime + '\'' +
+                "envtempLastTime=" + envtempLastTime + '\'' +
+                "eartagFirstTime=" + eartagFirstTime + '\'' +
+                "eartagLastTime=" + eartagLastTime + '\'' +
+                "liveStatus=" + liveStatus + '\'' +
+                '}';
+    }
+}

+ 273 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagDeviceRegisterEntity.java

@@ -0,0 +1,273 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_device_register")
+public class EartagDeviceRegisterEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "chip_id")
+    private String chipId;
+
+    @Column(name = "county_code")
+    private String countyCode;
+
+    @Column(name = "county_name")
+    private String countyName;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "farm_name")
+    private String farmName;
+
+    @Column(name = "type_f")
+    private Integer typeF;
+
+    @Column(name = "stage")
+    private Integer stage;
+
+    @Column(name = "pigpen_id")
+    private Integer pigpenId;
+
+    @Column(name = "unit_id")
+    private Integer unitId;
+
+    @Column(name = "register_time")
+    private Timestamp registerTime;
+
+    @Column(name = "last_time")
+    private Timestamp lastTime;
+
+    @Column(name = "active_status")
+    private Integer activeStatus;
+
+    @Column(name = "active_time")
+    private Timestamp activeTime;
+
+    @Column(name = "device_status", nullable = false)
+    private Integer deviceStatus;
+
+    @Column(name = "device_alias")
+    private String deviceAlias;
+
+    @Column(name = "location")
+    private String location;
+
+    @Column(name = "remark")
+    private String remark;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    @Column(name = "update_type")
+    private String updateType;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setChipId(String chipId) {
+        this.chipId = chipId;
+    }
+
+    public String getChipId() {
+        return chipId;
+    }
+
+    public void setCountyCode(String countyCode) {
+        this.countyCode = countyCode;
+    }
+
+    public String getCountyCode() {
+        return countyCode;
+    }
+
+    public void setCountyName(String countyName) {
+        this.countyName = countyName;
+    }
+
+    public String getCountyName() {
+        return countyName;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setFarmName(String farmName) {
+        this.farmName = farmName;
+    }
+
+    public String getFarmName() {
+        return farmName;
+    }
+
+    public void setTypeF(Integer typeF) {
+        this.typeF = typeF;
+    }
+
+    public Integer getTypeF() {
+        return typeF;
+    }
+
+    public void setStage(Integer stage) {
+        this.stage = stage;
+    }
+
+    public Integer getStage() {
+        return stage;
+    }
+
+    public void setPigpenId(Integer pigpenId) {
+        this.pigpenId = pigpenId;
+    }
+
+    public Integer getPigpenId() {
+        return pigpenId;
+    }
+
+    public void setUnitId(Integer unitId) {
+        this.unitId = unitId;
+    }
+
+    public Integer getUnitId() {
+        return unitId;
+    }
+
+    public void setRegisterTime(Timestamp registerTime) {
+        this.registerTime = registerTime;
+    }
+
+    public Timestamp getRegisterTime() {
+        return registerTime;
+    }
+
+    public void setLastTime(Timestamp lastTime) {
+        this.lastTime = lastTime;
+    }
+
+    public Timestamp getLastTime() {
+        return lastTime;
+    }
+
+    public void setActiveStatus(Integer activeStatus) {
+        this.activeStatus = activeStatus;
+    }
+
+    public Integer getActiveStatus() {
+        return activeStatus;
+    }
+
+    public void setActiveTime(Timestamp activeTime) {
+        this.activeTime = activeTime;
+    }
+
+    public Timestamp getActiveTime() {
+        return activeTime;
+    }
+
+    public void setDeviceStatus(Integer deviceStatus) {
+        this.deviceStatus = deviceStatus;
+    }
+
+    public Integer getDeviceStatus() {
+        return deviceStatus;
+    }
+
+    public void setDeviceAlias(String deviceAlias) {
+        this.deviceAlias = deviceAlias;
+    }
+
+    public String getDeviceAlias() {
+        return deviceAlias;
+    }
+
+    public void setLocation(String location) {
+        this.location = location;
+    }
+
+    public String getLocation() {
+        return location;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setUpdateType(String updateType) {
+        this.updateType = updateType;
+    }
+
+    public String getUpdateType() {
+        return updateType;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDeviceRegisterEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "chipId=" + chipId + '\'' +
+                "countyCode=" + countyCode + '\'' +
+                "countyName=" + countyName + '\'' +
+                "farmId=" + farmId + '\'' +
+                "farmName=" + farmName + '\'' +
+                "typeF=" + typeF + '\'' +
+                "stage=" + stage + '\'' +
+                "pigpenId=" + pigpenId + '\'' +
+                "unitId=" + unitId + '\'' +
+                "registerTime=" + registerTime + '\'' +
+                "lastTime=" + lastTime + '\'' +
+                "activeStatus=" + activeStatus + '\'' +
+                "activeTime=" + activeTime + '\'' +
+                "deviceStatus=" + deviceStatus + '\'' +
+                "deviceAlias=" + deviceAlias + '\'' +
+                "location=" + location + '\'' +
+                "remark=" + remark + '\'' +
+                "createDate=" + createDate + '\'' +
+                "updateType=" + updateType + '\'' +
+                '}';
+    }
+}

+ 104 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagDayStatusEntity.java

@@ -0,0 +1,104 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+
+@Entity
+@Table(name = "eartag_eartag_day_status")
+public class EartagEartagDayStatusEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "total")
+    private Integer total;
+
+    @Column(name = "online")
+    private Integer online;
+
+    @Column(name = "offline")
+    private Integer offline;
+
+    @Column(name = "online_rate")
+    private Float onlineRate;
+
+    @Column(name = "add_date")
+    private Date addDate;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setTotal(Integer total) {
+        this.total = total;
+    }
+
+    public Integer getTotal() {
+        return total;
+    }
+
+    public void setOnline(Integer online) {
+        this.online = online;
+    }
+
+    public Integer getOnline() {
+        return online;
+    }
+
+    public void setOffline(Integer offline) {
+        this.offline = offline;
+    }
+
+    public Integer getOffline() {
+        return offline;
+    }
+
+    public void setOnlineRate(Float onlineRate) {
+        this.onlineRate = onlineRate;
+    }
+
+    public Float getOnlineRate() {
+        return onlineRate;
+    }
+
+    public void setAddDate(Date addDate) {
+        this.addDate = addDate;
+    }
+
+    public Date getAddDate() {
+        return addDate;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagEartagDayStatusEntity{" +
+                "id=" + id + '\'' +
+                "total=" + total + '\'' +
+                "online=" + online + '\'' +
+                "offline=" + offline + '\'' +
+                "onlineRate=" + onlineRate + '\'' +
+                "addDate=" + addDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                '}';
+    }
+}

+ 129 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagOnlineEntity.java

@@ -0,0 +1,129 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_eartag_online")
+public class EartagEartagOnlineEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "earmark")
+    private String earmark;
+
+    @Column(name = "total")
+    private Integer total;
+
+    @Column(name = "first_time")
+    private Timestamp firstTime;
+
+    @Column(name = "last_time")
+    private Timestamp lastTime;
+
+    @Column(name = "env_temp")
+    private String envTemp;
+
+    @Column(name = "eartag_temp")
+    private String eartagTemp;
+
+    @Column(name = "add_date")
+    private Date addDate;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setTotal(Integer total) {
+        this.total = total;
+    }
+
+    public Integer getTotal() {
+        return total;
+    }
+
+    public void setFirstTime(Timestamp firstTime) {
+        this.firstTime = firstTime;
+    }
+
+    public Timestamp getFirstTime() {
+        return firstTime;
+    }
+
+    public void setLastTime(Timestamp lastTime) {
+        this.lastTime = lastTime;
+    }
+
+    public Timestamp getLastTime() {
+        return lastTime;
+    }
+
+    public void setEnvTemp(String envTemp) {
+        this.envTemp = envTemp;
+    }
+
+    public String getEnvTemp() {
+        return envTemp;
+    }
+
+    public void setEartagTemp(String eartagTemp) {
+        this.eartagTemp = eartagTemp;
+    }
+
+    public String getEartagTemp() {
+        return eartagTemp;
+    }
+
+    public void setAddDate(Date addDate) {
+        this.addDate = addDate;
+    }
+
+    public Date getAddDate() {
+        return addDate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagEartagOnlineEntity{" +
+                "id=" + id + '\'' +
+                "earmark=" + earmark + '\'' +
+                "total=" + total + '\'' +
+                "firstTime=" + firstTime + '\'' +
+                "lastTime=" + lastTime + '\'' +
+                "envTemp=" + envTemp + '\'' +
+                "eartagTemp=" + eartagTemp + '\'' +
+                "addDate=" + addDate + '\'' +
+                "farmId=" + farmId + '\'' +
+                '}';
+    }
+}

+ 213 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEartagRegisterEntity.java

@@ -0,0 +1,213 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_eartag_register")
+public class EartagEartagRegisterEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "earmark")
+    private String earmark;
+
+    @Column(name = "first_time")
+    private Timestamp firstTime;
+
+    @Column(name = "last_time")
+    private Timestamp lastTime;
+
+    @Column(name = "first_device")
+    private String firstDevice;
+
+    @Column(name = "belong_device")
+    private String belongDevice;
+
+    @Column(name = "last_device")
+    private String lastDevice;
+
+    @Column(name = "register_time")
+    private Timestamp registerTime;
+
+    @Column(name = "register_type")
+    private Integer registerType;
+
+    @Column(name = "remark")
+    private String remark;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "active_status")
+    private Integer activeStatus;
+
+    @Column(name = "active_time")
+    private Timestamp activeTime;
+
+    @Column(name = "live_status")
+    private Integer liveStatus;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    @Column(name = "bat")
+    private Integer bat;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setFirstTime(Timestamp firstTime) {
+        this.firstTime = firstTime;
+    }
+
+    public Timestamp getFirstTime() {
+        return firstTime;
+    }
+
+    public void setLastTime(Timestamp lastTime) {
+        this.lastTime = lastTime;
+    }
+
+    public Timestamp getLastTime() {
+        return lastTime;
+    }
+
+    public void setFirstDevice(String firstDevice) {
+        this.firstDevice = firstDevice;
+    }
+
+    public String getFirstDevice() {
+        return firstDevice;
+    }
+
+    public void setBelongDevice(String belongDevice) {
+        this.belongDevice = belongDevice;
+    }
+
+    public String getBelongDevice() {
+        return belongDevice;
+    }
+
+    public void setLastDevice(String lastDevice) {
+        this.lastDevice = lastDevice;
+    }
+
+    public String getLastDevice() {
+        return lastDevice;
+    }
+
+    public void setRegisterTime(Timestamp registerTime) {
+        this.registerTime = registerTime;
+    }
+
+    public Timestamp getRegisterTime() {
+        return registerTime;
+    }
+
+    public void setRegisterType(Integer registerType) {
+        this.registerType = registerType;
+    }
+
+    public Integer getRegisterType() {
+        return registerType;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setActiveStatus(Integer activeStatus) {
+        this.activeStatus = activeStatus;
+    }
+
+    public Integer getActiveStatus() {
+        return activeStatus;
+    }
+
+    public void setActiveTime(Timestamp activeTime) {
+        this.activeTime = activeTime;
+    }
+
+    public Timestamp getActiveTime() {
+        return activeTime;
+    }
+
+    public void setLiveStatus(Integer liveStatus) {
+        this.liveStatus = liveStatus;
+    }
+
+    public Integer getLiveStatus() {
+        return liveStatus;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setBat(Integer bat) {
+        this.bat = bat;
+    }
+
+    public Integer getBat() {
+        return bat;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagEartagRegisterEntity{" +
+                "id=" + id + '\'' +
+                "earmark=" + earmark + '\'' +
+                "firstTime=" + firstTime + '\'' +
+                "lastTime=" + lastTime + '\'' +
+                "firstDevice=" + firstDevice + '\'' +
+                "belongDevice=" + belongDevice + '\'' +
+                "lastDevice=" + lastDevice + '\'' +
+                "registerTime=" + registerTime + '\'' +
+                "registerType=" + registerType + '\'' +
+                "remark=" + remark + '\'' +
+                "farmId=" + farmId + '\'' +
+                "activeStatus=" + activeStatus + '\'' +
+                "activeTime=" + activeTime + '\'' +
+                "liveStatus=" + liveStatus + '\'' +
+                "createDate=" + createDate + '\'' +
+                "bat=" + bat + '\'' +
+                '}';
+    }
+}

+ 117 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagEnvEntity.java

@@ -0,0 +1,117 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_env")
+public class EartagEnvEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "temp1")
+    private Integer temp1;
+
+    @Column(name = "temp2")
+    private Float temp2;
+
+    @Column(name = "ask_time")
+    private Timestamp askTime;
+
+    @Column(name = "add_time")
+    private Timestamp addTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    @Column(name = "ask_date")
+    private Date askDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setTemp1(Integer temp1) {
+        this.temp1 = temp1;
+    }
+
+    public Integer getTemp1() {
+        return temp1;
+    }
+
+    public void setTemp2(Float temp2) {
+        this.temp2 = temp2;
+    }
+
+    public Float getTemp2() {
+        return temp2;
+    }
+
+    public void setAskTime(Timestamp askTime) {
+        this.askTime = askTime;
+    }
+
+    public Timestamp getAskTime() {
+        return askTime;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    public void setAskDate(Date askDate) {
+        this.askDate = askDate;
+    }
+
+    public Date getAskDate() {
+        return askDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagEnvEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "temp1=" + temp1 + '\'' +
+                "temp2=" + temp2 + '\'' +
+                "askTime=" + askTime + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                "askDate=" + askDate + '\'' +
+                '}';
+    }
+}

+ 69 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagHeartbeatEntity.java

@@ -0,0 +1,69 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_heartbeat")
+public class EartagHeartbeatEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "add_time")
+    private Timestamp addTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagHeartbeatEntity{" +
+                "id=" + id + '\'' +
+                "deviceCode=" + deviceCode + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 105 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagRawEntity.java

@@ -0,0 +1,105 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_raw")
+public class EartagRawEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "cmd_header")
+    private String cmdHeader;
+
+    @Column(name = "cmd")
+    private String cmd;
+
+    @Column(name = "device")
+    private String device;
+
+    @Column(name = "ask")
+    private String ask;
+
+    @Column(name = "add_time")
+    private Timestamp addTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setCmdHeader(String cmdHeader) {
+        this.cmdHeader = cmdHeader;
+    }
+
+    public String getCmdHeader() {
+        return cmdHeader;
+    }
+
+    public void setCmd(String cmd) {
+        this.cmd = cmd;
+    }
+
+    public String getCmd() {
+        return cmd;
+    }
+
+    public void setDevice(String device) {
+        this.device = device;
+    }
+
+    public String getDevice() {
+        return device;
+    }
+
+    public void setAsk(String ask) {
+        this.ask = ask;
+    }
+
+    public String getAsk() {
+        return ask;
+    }
+
+    public void setAddTime(Timestamp addTime) {
+        this.addTime = addTime;
+    }
+
+    public Timestamp getAddTime() {
+        return addTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagRawEntity{" +
+                "id=" + id + '\'' +
+                "cmdHeader=" + cmdHeader + '\'' +
+                "cmd=" + cmd + '\'' +
+                "device=" + device + '\'' +
+                "ask=" + ask + '\'' +
+                "addTime=" + addTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 153 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartagTotalStatusEntity.java

@@ -0,0 +1,153 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartag_total_status")
+public class EartagTotalStatusEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_total")
+    private Integer deviceTotal;
+
+    @Column(name = "device_online")
+    private Integer deviceOnline;
+
+    @Column(name = "device_offline")
+    private Integer deviceOffline;
+
+    @Column(name = "device_rate")
+    private Float deviceRate;
+
+    @Column(name = "device_cancel")
+    private Integer deviceCancel;
+
+    @Column(name = "eartag_total")
+    private Integer eartagTotal;
+
+    @Column(name = "eartag_online")
+    private Integer eartagOnline;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    @Column(name = "update_time")
+    private Timestamp updateTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceTotal(Integer deviceTotal) {
+        this.deviceTotal = deviceTotal;
+    }
+
+    public Integer getDeviceTotal() {
+        return deviceTotal;
+    }
+
+    public void setDeviceOnline(Integer deviceOnline) {
+        this.deviceOnline = deviceOnline;
+    }
+
+    public Integer getDeviceOnline() {
+        return deviceOnline;
+    }
+
+    public void setDeviceOffline(Integer deviceOffline) {
+        this.deviceOffline = deviceOffline;
+    }
+
+    public Integer getDeviceOffline() {
+        return deviceOffline;
+    }
+
+    public void setDeviceRate(Float deviceRate) {
+        this.deviceRate = deviceRate;
+    }
+
+    public Float getDeviceRate() {
+        return deviceRate;
+    }
+
+    public void setDeviceCancel(Integer deviceCancel) {
+        this.deviceCancel = deviceCancel;
+    }
+
+    public Integer getDeviceCancel() {
+        return deviceCancel;
+    }
+
+    public void setEartagTotal(Integer eartagTotal) {
+        this.eartagTotal = eartagTotal;
+    }
+
+    public Integer getEartagTotal() {
+        return eartagTotal;
+    }
+
+    public void setEartagOnline(Integer eartagOnline) {
+        this.eartagOnline = eartagOnline;
+    }
+
+    public Integer getEartagOnline() {
+        return eartagOnline;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    public void setUpdateTime(Timestamp updateTime) {
+        this.updateTime = updateTime;
+    }
+
+    public Timestamp getUpdateTime() {
+        return updateTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagTotalStatusEntity{" +
+                "id=" + id + '\'' +
+                "deviceTotal=" + deviceTotal + '\'' +
+                "deviceOnline=" + deviceOnline + '\'' +
+                "deviceOffline=" + deviceOffline + '\'' +
+                "deviceRate=" + deviceRate + '\'' +
+                "deviceCancel=" + deviceCancel + '\'' +
+                "eartagTotal=" + eartagTotal + '\'' +
+                "eartagOnline=" + eartagOnline + '\'' +
+                "farmId=" + farmId + '\'' +
+                "updateTime=" + updateTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 165 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/entity/EartarFarmAllStatusEntity.java

@@ -0,0 +1,165 @@
+package com.huimv.eartag.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Date;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "eartar_farm_all_status")
+public class EartarFarmAllStatusEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_total")
+    private Integer deviceTotal;
+
+    @Column(name = "device_online")
+    private Integer deviceOnline;
+
+    @Column(name = "device_offline")
+    private Integer deviceOffline;
+
+    @Column(name = "device_rate")
+    private Float deviceRate;
+
+    @Column(name = "device_cancel")
+    private Integer deviceCancel;
+
+    @Column(name = "eartag_total")
+    private Integer eartagTotal;
+
+    @Column(name = "eartag_online")
+    private Integer eartagOnline;
+
+    @Column(name = "eartag_rate")
+    private Float eartagRate;
+
+    @Column(name = "farm_id")
+    private String farmId;
+
+    @Column(name = "update_time")
+    private Timestamp updateTime;
+
+    @Column(name = "create_date")
+    private Date createDate;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceTotal(Integer deviceTotal) {
+        this.deviceTotal = deviceTotal;
+    }
+
+    public Integer getDeviceTotal() {
+        return deviceTotal;
+    }
+
+    public void setDeviceOnline(Integer deviceOnline) {
+        this.deviceOnline = deviceOnline;
+    }
+
+    public Integer getDeviceOnline() {
+        return deviceOnline;
+    }
+
+    public void setDeviceOffline(Integer deviceOffline) {
+        this.deviceOffline = deviceOffline;
+    }
+
+    public Integer getDeviceOffline() {
+        return deviceOffline;
+    }
+
+    public void setDeviceRate(Float deviceRate) {
+        this.deviceRate = deviceRate;
+    }
+
+    public Float getDeviceRate() {
+        return deviceRate;
+    }
+
+    public void setDeviceCancel(Integer deviceCancel) {
+        this.deviceCancel = deviceCancel;
+    }
+
+    public Integer getDeviceCancel() {
+        return deviceCancel;
+    }
+
+    public void setEartagTotal(Integer eartagTotal) {
+        this.eartagTotal = eartagTotal;
+    }
+
+    public Integer getEartagTotal() {
+        return eartagTotal;
+    }
+
+    public void setEartagOnline(Integer eartagOnline) {
+        this.eartagOnline = eartagOnline;
+    }
+
+    public Integer getEartagOnline() {
+        return eartagOnline;
+    }
+
+    public void setEartagRate(Float eartagRate) {
+        this.eartagRate = eartagRate;
+    }
+
+    public Float getEartagRate() {
+        return eartagRate;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setUpdateTime(Timestamp updateTime) {
+        this.updateTime = updateTime;
+    }
+
+    public Timestamp getUpdateTime() {
+        return updateTime;
+    }
+
+    public void setCreateDate(Date createDate) {
+        this.createDate = createDate;
+    }
+
+    public Date getCreateDate() {
+        return createDate;
+    }
+
+    @Override
+    public String toString() {
+        return "EartarFarmAllStatusEntity{" +
+                "id=" + id + '\'' +
+                "deviceTotal=" + deviceTotal + '\'' +
+                "deviceOnline=" + deviceOnline + '\'' +
+                "deviceOffline=" + deviceOffline + '\'' +
+                "deviceRate=" + deviceRate + '\'' +
+                "deviceCancel=" + deviceCancel + '\'' +
+                "eartagTotal=" + eartagTotal + '\'' +
+                "eartagOnline=" + eartagOnline + '\'' +
+                "eartagRate=" + eartagRate + '\'' +
+                "farmId=" + farmId + '\'' +
+                "updateTime=" + updateTime + '\'' +
+                "createDate=" + createDate + '\'' +
+                '}';
+    }
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/BaseFarmRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.BaseFarmEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface BaseFarmRepo extends JpaRepository<BaseFarmEntity, Integer>, JpaSpecificationExecutor<BaseFarmEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/BaseFarmServerConfigRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.BaseFarmServerConfigEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface BaseFarmServerConfigRepo extends JpaRepository<BaseFarmServerConfigEntity, Integer>, JpaSpecificationExecutor<BaseFarmServerConfigEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceCountRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalDeviceCountEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalDeviceCountRepo extends JpaRepository<EartagAbnormalDeviceCountEntity, Void>, JpaSpecificationExecutor<EartagAbnormalDeviceCountEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceDetailRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalDeviceDetailEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalDeviceDetailRepo extends JpaRepository<EartagAbnormalDeviceDetailEntity, Void>, JpaSpecificationExecutor<EartagAbnormalDeviceDetailEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalDeviceTimesRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalDeviceTimesEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalDeviceTimesRepo extends JpaRepository<EartagAbnormalDeviceTimesEntity, Void>, JpaSpecificationExecutor<EartagAbnormalDeviceTimesEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagCountRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalEartagCountEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalEartagCountRepo extends JpaRepository<EartagAbnormalEartagCountEntity, Void>, JpaSpecificationExecutor<EartagAbnormalEartagCountEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagDetailRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalEartagDetailEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalEartagDetailRepo extends JpaRepository<EartagAbnormalEartagDetailEntity, Void>, JpaSpecificationExecutor<EartagAbnormalEartagDetailEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagAbnormalEartagTimesRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagAbnormalEartagTimesEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagAbnormalEartagTimesRepo extends JpaRepository<EartagAbnormalEartagTimesEntity, Void>, JpaSpecificationExecutor<EartagAbnormalEartagTimesEntity> {
+
+}

+ 13 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagConfigPropertiesRepo.java

@@ -0,0 +1,13 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagConfigPropertiesEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+public interface EartagConfigPropertiesRepo extends JpaRepository<EartagConfigPropertiesEntity, Integer>, JpaSpecificationExecutor<EartagConfigPropertiesEntity> {
+
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_config_properties WHERE farm_id=?1 AND farm_id=?2")
+    EartagConfigPropertiesEntity getThresholdVal(String farmId, String sort);
+}

+ 22 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDataRepo.java

@@ -0,0 +1,22 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagDataEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagDataRepo extends JpaRepository<EartagDataEntity, Integer>, JpaSpecificationExecutor<EartagDataEntity> {
+    //--查询最新到耳标记录
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_data WHERE device=?1 ORDER BY id DESC LIMIT 1")
+    EartagDataEntity getLastEartagData(String deviceCode);
+
+    //
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_data WHERE device=?1 AND earmark=?2 AND DATE_FORMAT(add_time,'%Y-%m-%d')=DATE_FORMAT(?3,'%Y-%m-%d') ORDER BY id DESC")
+    List<EartagDataEntity> getEartagFlowByDeviceCodeAndEarmarkAndToday(String deviceCode, String earmark, String todayDateText);
+
+    //
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_data WHERE earmark=?1 AND DATE_FORMAT(add_time,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') ORDER BY id DESC")
+    List<EartagDataEntity> getEartagFlowByEarmarkAndToday(String earmark, String todayDateText);
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceDayStatusRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagDeviceDayStatusEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagDeviceDayStatusRepo extends JpaRepository<EartagDeviceDayStatusEntity, Integer>, JpaSpecificationExecutor<EartagDeviceDayStatusEntity> {
+
+}

+ 23 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceEartagCountRepo.java

@@ -0,0 +1,23 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagDeviceEartagCountEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagDeviceEartagCountRepo extends JpaRepository<EartagDeviceEartagCountEntity, Integer>, JpaSpecificationExecutor<EartagDeviceEartagCountEntity> {
+
+    //
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_eartag_count WHERE device_code=?1 AND DATE_FORMAT(create_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d')")
+    List<EartagDeviceEartagCountEntity> getOnlineEartagByDeviceCode(String deviceCode, String todayDateText);
+
+    //
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_eartag_count WHERE earmark=?1 AND DATE_FORMAT(create_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d')")
+    List<EartagDeviceEartagCountEntity> getOnlineEartagDeviceByEarmarkAndAddDate(String earmark, String addDate);
+
+    //
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_eartag_count WHERE earmark=?1 AND device_code=?2 AND DATE_FORMAT(create_date,'%Y-%m-%d')=DATE_FORMAT(?3,'%Y-%m-%d')")
+    List<EartagDeviceEartagCountEntity> getEartagDeviceCount(String earmark, String deviceCode, String todayDateText);
+}

+ 20 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceOnlineRepo.java

@@ -0,0 +1,20 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagDeviceOnlineEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagDeviceOnlineRepo extends JpaRepository<EartagDeviceOnlineEntity, Integer>, JpaSpecificationExecutor<EartagDeviceOnlineEntity> {
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_online WHERE device_code=?1 AND DATE_FORMAT(add_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') limit 1")
+    EartagDeviceOnlineEntity getDeviceOnline(String deviceCode, String todayText);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_online WHERE farm_id=?1 AND DATE_FORMAT(add_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') ORDER BY add_date DESC")
+    List<EartagDeviceOnlineEntity> getDeviceOnlineByFarmIdAndCreateDate(String farmId, String todayDate);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_online WHERE device_code=?1 AND add_date BETWEEN DATE_FORMAT(?2,'%Y-%m-%d') AND DATE_FORMAT(?3,'%Y-%m-%d') ORDER BY add_date ASC")
+    List<EartagDeviceOnlineEntity> getDeviceOnlineByDeviceCode(String deviceCode, String pastDate, String todayDate);
+}

+ 32 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagDeviceRegisterRepo.java

@@ -0,0 +1,32 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagDeviceRegisterEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagDeviceRegisterRepo extends JpaRepository<EartagDeviceRegisterEntity, Integer>, JpaSpecificationExecutor<EartagDeviceRegisterEntity> {
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_register WHERE device_code=?1 LIMIT 1")
+    EartagDeviceRegisterEntity getDeviceRegister(String deviceCode);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_register WHERE id=?1")
+    EartagDeviceRegisterEntity getDeviceRegisterByRowId(String id);
+
+//    @Query(nativeQuery = true,value = "SELECT COUNT(*) total FROM eartag_device_register WHERE farm_id=?1 AND (device_status=0 OR device_status=1 OR device_status=2)")
+    @Query(nativeQuery = true,value = "SELECT COUNT(*) total FROM eartag_device_register WHERE farm_id=?1 AND device_status IN(0,1,2)")
+    List<Object[]> getDeviceCountByFarmId(String farmId);
+
+    @Query(nativeQuery = true,value = "SELECT COUNT(*) total FROM eartag_device_register WHERE farm_id=?1 AND device_status=?2")
+    List<Object[]> getDeviceCountByFarmIdAndLiveStatus(String farmId, Integer liveStatus);
+
+    @Query(nativeQuery = true,value = "SELECT device_code FROM eartag_device_register WHERE device_status=1")
+    List<Object[]> getDeviceCodeFromDeviceRegister();
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_register WHERE id=?1")
+    EartagDeviceRegisterEntity getDeviceRegisterById(Integer id);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_device_register WHERE chip_id=?1")
+    EartagDeviceRegisterEntity getByChipId(String chipId);
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagDayStatusRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagEartagDayStatusEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagEartagDayStatusRepo extends JpaRepository<EartagEartagDayStatusEntity, Integer>, JpaSpecificationExecutor<EartagEartagDayStatusEntity> {
+
+}

+ 56 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagOnlineRepo.java

@@ -0,0 +1,56 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagEartagOnlineEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagEartagOnlineRepo extends JpaRepository<EartagEartagOnlineEntity, Integer>, JpaSpecificationExecutor<EartagEartagOnlineEntity> {
+
+    /**
+     * @Method      : getOneByEarmarkAndFarmId
+     * @Description : 
+     * @Params      : [earmark, todayDateText, farmId]
+     * @Return      : com.huimv.eartag2.common.dao.entity.EartagEartagOnlineEntity
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/2       
+     * @Time        : 16:09
+     */
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_online WHERE earmark=?1 AND DATE_FORMAT(add_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') AND farm_id=?3")
+    EartagEartagOnlineEntity getOneByEarmarkAndFarmId(String earmark, String todayDateText, String farmId);
+
+    /**
+     * @Method      : getEartagOnlineByEarmarkAndDate
+     * @Description : 
+     * @Params      : [earmark, startDateText, todayDateText]
+     * @Return      : java.util.List<com.huimv.eartag2.common.dao.entity.EartagEartagOnlineEntity>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/8       
+     * @Time        : 18:43
+     */
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_online WHERE earmark=?1 AND add_date BETWEEN DATE_FORMAT(?2,'%Y-%m-%d') AND DATE_FORMAT(?3,'%Y-%m-%d') ORDER BY add_date ASC")
+    List<EartagEartagOnlineEntity> getEartagOnlineByEarmarkAndDate(String earmark, String startDateText, String todayDateText);
+
+    /**
+     * @Method      : getEartagOnlineByFarmIdAndDate
+     * @Description : 
+     * @Params      : [farmId, addDate]
+     * @Return      : java.util.List<com.huimv.eartag2.common.dao.entity.EartagEartagOnlineEntity>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/10       
+     * @Time        : 21:58
+     */
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_online WHERE farm_id=?1 AND DATE_FORMAT(add_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') ORDER BY add_date ASC")
+    List<EartagEartagOnlineEntity> getEartagOnlineByFarmIdAndDate(String farmId, String addDate);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_online WHERE earmark=?1 AND add_date BETWEEN DATE_FORMAT(?2,'%Y-%m-%d') AND DATE_FORMAT(?3,'%Y-%m-%d') ORDER BY add_date DESC")
+    List<EartagEartagOnlineEntity> getEartagOnlineRecordsByEarmarkAndDate(String earmark, String startDateText, String todayDateText);
+
+//    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_online WHERE farm_id=?1 AND add_date = DATE_FORMAT(,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') ORDER BY add_date ASC")
+//    List<EartagEartagOnlineEntity> getEartagOnlineByEarmarkAndStartDateAndEndDate(String earmark, String todayDateText, String startDateText);
+}

+ 24 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEartagRegisterRepo.java

@@ -0,0 +1,24 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagEartagRegisterEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagEartagRegisterRepo extends JpaRepository<EartagEartagRegisterEntity, Integer>, JpaSpecificationExecutor<EartagEartagRegisterEntity> {
+
+    @Query(nativeQuery = true,value = "SELECT COUNT(*) total FROM eartag_eartag_register WHERE farm_id=?1 AND live_status=1")
+    List<Object[]> getEartagCountByFarmId(String farmId);
+
+    @Query(nativeQuery = true,value = "SELECT COUNT(*) total FROM eartag_eartag_register WHERE farm_id=?1 AND live_status=?2")
+    List<Object[]> getEartagCountByFarmId(String farmId, Integer liveStatus);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_register WHERE farm_id=?2 AND earmark=?1")
+    EartagEartagRegisterEntity getOneByEarmark(String earmark, String farmId);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_eartag_register WHERE earmark=?1 LIMIT 1")
+    EartagEartagRegisterEntity getEartagByEarmark(String earmark);
+
+}

+ 14 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagEnvRepo.java

@@ -0,0 +1,14 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagEnvEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartagEnvRepo extends JpaRepository<EartagEnvEntity, Integer>, JpaSpecificationExecutor<EartagEnvEntity> {
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartag_env WHERE device_code=?1 AND DATE_FORMAT(add_time,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d') limit 1")
+    List<EartagEnvEntity> getDeviceEnvtempByDeviceCode(String deviceCode, String todayDateText);
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagHeartbeatRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagHeartbeatEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagHeartbeatRepo extends JpaRepository<EartagHeartbeatEntity, Integer>, JpaSpecificationExecutor<EartagHeartbeatEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagRawRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagRawEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagRawRepo extends JpaRepository<EartagRawEntity, Integer>, JpaSpecificationExecutor<EartagRawEntity> {
+
+}

+ 9 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartagTotalStatusRepo.java

@@ -0,0 +1,9 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartagTotalStatusEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+public interface EartagTotalStatusRepo extends JpaRepository<EartagTotalStatusEntity, Integer>, JpaSpecificationExecutor<EartagTotalStatusEntity> {
+
+}

+ 17 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/dao/repo/EartarFarmAllStatusRepo.java

@@ -0,0 +1,17 @@
+package com.huimv.eartag.dao.repo;
+
+import com.huimv.eartag.dao.entity.EartarFarmAllStatusEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.List;
+
+public interface EartarFarmAllStatusRepo extends JpaRepository<EartarFarmAllStatusEntity, Integer>, JpaSpecificationExecutor<EartarFarmAllStatusEntity> {
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartar_farm_all_status WHERE farm_id=?1 AND DATE_FORMAT(create_date,'%Y-%m-%d')=DATE_FORMAT(?2,'%Y-%m-%d')")
+    EartarFarmAllStatusEntity getOneByFarmIdAndCreateDate(String farmId, String todayDateText);
+
+    @Query(nativeQuery = true,value = "SELECT * FROM eartar_farm_all_status WHERE farm_id=?1 AND create_date BETWEEN DATE_FORMAT(?2,'%Y-%m-%d') AND DATE_FORMAT(?3,'%Y-%m-%d') ORDER BY create_date ASC")
+    List<EartarFarmAllStatusEntity> getOneByFarmIdAndCreateDateAndPastDate(String farmId, String pastDate, String todayDate);
+}

+ 157 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/DeviceListener.java

@@ -0,0 +1,157 @@
+package com.huimv.eartag.listener;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.producer.DeviceProducer;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.service.IEartagService;
+import com.huimv.eartag.utils.Const;
+import com.huimv.eartag.utils.MathUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.annotation.RabbitHandler;
+import org.springframework.amqp.rabbit.annotation.RabbitListener;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.math.BigDecimal;
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+@Slf4j
+public class DeviceListener {
+    @Autowired
+    private IDeviceService deviceService;
+    @Autowired
+    private IEartagService eartagService;
+    @Autowired
+    private DeviceProducer processProducer;
+
+    /**
+     * @Method : processRawdata
+     * @Description :
+     * @Params : [RawMap]
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/3/12
+     * @Time : 17:28
+     */
+    @RabbitListener(queues = Const.QUEUE_ASK_DEVICE)
+    @RabbitHandler
+    public void processRawdata(Map RawMap) throws ParseException {
+        System.out.println("<<<<<<<<<<<<<<< RawMap>>" + RawMap.toString());
+        String askText = RawMap.get("askText").toString();
+        //本模块主要执行保存以下4类数据:(其他注册数据,在线数据,状态数据等都是由其他模块工程执行处理-process2模块工程)
+        //--保存原始流水数据(原始流水表)
+        //--保存设备心跳流水数据(设备心跳流水表)
+        //--保存设备环境流水数据(设备温度流水表)
+        //--保存耳标流水数据(耳标流水表)
+
+        //处理请求报文//
+        Map askMap = handleAskText(askText);
+        System.out.println("## askMap>>" + askMap.toString());
+        String type = askMap.get("type").toString();
+        JSONObject dataJo = (JSONObject) askMap.get("data");
+        if (type.trim().equalsIgnoreCase("device-heartbeat")) {
+            //--(1)处理心跳数据
+            //{处理设备心跳数据}
+            deviceService.handleDeviceHeartbeat(dataJo);
+        } else if (type.trim().equalsIgnoreCase("device-temp")) {
+            //--(2)处理环境数据
+            //{处理设备环境温度数据}
+            deviceService.handleDeviceEnvtemp(dataJo);
+        }
+    }
+
+    /**
+     * @Method : handleAskText
+     * @Description :
+     * @Params : [askText]
+     * @Return : java.util.Map
+     * @Author : ZhuoNing
+     * @Date : 2022/3/12
+     * @Time : 17:27
+     */
+    private Map handleAskText(String askText) {
+        Map outMap = new HashMap();
+        JSONObject dataJo = new JSONObject();
+        String type = "";
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            String device = dataArray[1];
+            String cmd = dataArray[2];
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+                dataJo.put("device", device);
+                type = "device-heartbeat";
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+                dataJo.put("device", dataArray[1]);
+                dataJo.put("temp", dataArray[4]);
+                dataJo.put("askTime", dataArray[5]);
+                type = "device-temp";
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+            }
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+//            String device = dataArray[1];
+            //-- 耳标数据 --//
+            //计算耳标温度
+            Double earTemp = 0D;
+            String other = dataArray[9];
+            if (other != null && other.trim().length() > 0) {
+                String[] otherArray = other.split("#");
+                String resi = otherArray[2];
+                int resiInt = Integer.parseInt(resi);
+                if (resiInt != 0) {
+                    Double temp = MathUtil.ln(resiInt);
+                    earTemp = new BigDecimal(temp).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
+                }
+            }
+            //计算运动量//
+            Integer act1Int = eartagService.countAct(dataArray[1], dataArray[6]);
+            //命令头
+            dataJo.put("cmdHeader", dataArray[0]);
+            //采集器id
+            dataJo.put("device", dataArray[1]);
+            //耳标号
+            dataJo.put("earmark", dataArray[2]);
+            //电池电量
+            dataJo.put("bat", dataArray[3]);
+            //耳标温度
+            dataJo.put("earTemp", dataArray[4]);
+            dataJo.put("earTemp1", earTemp);
+            //环境温度
+            dataJo.put("envTemp", dataArray[5]);
+            //运动量
+            dataJo.put("act", dataArray[6]);
+            dataJo.put("act1", act1Int);
+            //信号强度
+            dataJo.put("signal", dataArray[7]);
+            //采集时间
+            dataJo.put("askTime", dataArray[8]);
+            //预留字段
+            dataJo.put("other", dataArray[9]);
+            type = "eartag";
+        }
+        outMap.put("type", type);
+        outMap.put("data", dataJo);
+        return outMap;
+    }
+}

+ 175 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/EartagListener.java

@@ -0,0 +1,175 @@
+package com.huimv.eartag.listener;
+
+import com.alibaba.fastjson.JSONObject;
+
+import com.huimv.eartag.utils.Const;
+import com.huimv.eartag.utils.MathUtil;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.service.IEartagService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.annotation.RabbitHandler;
+import org.springframework.amqp.rabbit.annotation.RabbitListener;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.math.BigDecimal;
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+@Slf4j
+public class EartagListener {
+    @Autowired
+    private IDeviceService deviceService;
+    @Autowired
+    private IEartagService eartagService;
+
+    /**
+     * @Method      : processRawdata
+     * @Description :
+     * @Params      : [RawMap]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/12
+     * @Time        : 17:53
+     */
+    @RabbitListener(queues = Const.QUEUE_ASK_EARTAG)
+    @RabbitHandler
+    public void processRawdata(Map RawMap) throws ParseException {
+        System.out.println("<<<<<<<<<<<<<<< RawMap>>"+RawMap.toString());
+        String askText = RawMap.get("askText").toString();
+        System.out.println("<<<<<<<<<<<<<<<<<<<<<<< 处理耳标 <<<<<<<<<<<<<<<<<<<<<<<");
+        //本模块主要执行保存以下4类数据:(其他注册数据,在线数据,状态数据等都是由其他模块工程执行处理-process2模块工程)
+        //--保存原始流水数据(原始流水表)
+        //--保存设备心跳流水数据(设备心跳流水表)
+        //--保存设备环境流水数据(设备温度流水表)
+        //--保存耳标流水数据(耳标流水表)
+
+        //{处理请求报文}
+        Map askMap = handleAskText(askText);
+        String type = askMap.get("type").toString();
+        JSONObject dataJo = (JSONObject) askMap.get("data");
+        System.out.println("## dataJo>>"+dataJo);
+        //
+        String earmark = dataJo.getString("earmark");
+        System.out.println("earmark>>"+earmark);
+        //测试代码(属于测试耳标才能进行测试)
+        if(checkTestRange(earmark)){
+            if(type.trim().equalsIgnoreCase("eartag")){
+                //{处理耳标数据}
+                eartagService.handleEartag(dataJo);
+            }
+        }else{
+            System.out.println("## 已过滤非测试耳标");
+        }
+//        //正式代码
+//        if(type.trim().equalsIgnoreCase("eartag")){
+//            System.out.println("askText>>"+askText);
+//            //{处理耳标数据}
+//            eartagService.handleEartag(dataJo);
+//        }
+    }
+
+    private boolean checkTestRange(String earmark) {
+        Long c = Long.parseLong(earmark);
+        Long a = 122083123610001L;
+        Long b = 122083123610100L;
+        return (c>=a && c<b) || (c>a && c<=b);
+    }
+
+    /**
+     * @Method      : handleAskText
+     * @Description : 处理请求
+     * @Params      : [askText]
+     * @Return      : java.util.Map
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/2/9
+     * @Time        : 13:38
+     */
+    private Map handleAskText(String askText) {
+        Map outMap = new HashMap();
+        JSONObject dataJo = new JSONObject();
+        String type = "";
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            String device = dataArray[1];
+            String cmd = dataArray[2];
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+                dataJo.put("device", device);
+                type = "device-heartbeat";
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+                dataJo.put("device", dataArray[1]);
+                dataJo.put("temp", dataArray[4]);
+                dataJo.put("askTime", dataArray[5]);
+                type = "device-temp";
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+            }
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+//            String device = dataArray[1];
+            //-- 耳标数据 --//
+            //计算耳标温度
+            Double earTemp = 0D;
+            String other = dataArray[9];
+            if (other != null && other.trim().length() > 0) {
+                String[] otherArray = other.split("#");
+                String resi = otherArray[2];
+                int resiInt = Integer.parseInt(resi);
+                if(resiInt != 0){
+                    Double temp = MathUtil.ln(resiInt);
+                    earTemp = new BigDecimal(temp).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
+                }
+            }
+            //计算运动量//
+            Integer act1Int = eartagService.countEartagAct(dataArray[2], dataArray[6]);
+            //命令头
+            dataJo.put("cmdHeader", dataArray[0]);
+            //采集器id
+            dataJo.put("device", dataArray[1]);
+            //耳标号
+            dataJo.put("earmark", dataArray[2]);
+            //电池电量
+            dataJo.put("bat", dataArray[3]);
+            //耳标温度
+            dataJo.put("earTemp", dataArray[4]);
+            dataJo.put("earTemp1", earTemp);
+            //环境温度
+            dataJo.put("envTemp", dataArray[5]);
+            dataJo.put("envTemp1", MathUtil.countEnvtemp(dataArray[5],2));
+            //运动量
+            dataJo.put("act", dataArray[6]);
+            dataJo.put("act1", act1Int);
+            //信号强度
+            dataJo.put("signal", dataArray[7]);
+            //采集时间
+            dataJo.put("askTime", dataArray[8]);
+            //预留字段
+            dataJo.put("other", dataArray[9]);
+            type = "eartag";
+        }
+        outMap.put("type",type);
+        outMap.put("data",dataJo);
+        return outMap;
+    }
+}

+ 117 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/listener/ManageListener.java

@@ -0,0 +1,117 @@
+package com.huimv.eartag.listener;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.utils.Const;
+import com.huimv.eartag.utils.DateUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.annotation.RabbitHandler;
+import org.springframework.amqp.rabbit.annotation.RabbitListener;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.text.ParseException;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+@Slf4j
+public class ManageListener {
+    @Autowired
+    private IDeviceService deviceService;
+    /**
+     * @Method      : processSyncDeviceRegister
+     * @Description : 监听处理同步设备注册信息队列
+     * @Params      : [map]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/22
+     * @Time        : 16:03
+     */
+    @RabbitListener(queues = Const.QUEUE_SYNC_DEVICE_REGISTER)
+    @RabbitHandler
+    public void processSyncDeviceRegister(Map map) throws ParseException {
+        System.out.println("device queue>>");
+        JSONObject deviceRegisterJo = JSONObject.parseObject(map.get("deviceRegister").toString()) ;
+        System.out.println("deviceRegisterJo>>"+deviceRegisterJo.toJSONString());
+        DateUtil dateUtil = new DateUtil();
+        String todayDateText = dateUtil.getTodayDateText();
+
+//        System.out.println("同步设备注册信息>>"+deviceRegisterJo);
+        //{计算有效设备总数并存储到缓存}
+        deviceService.countEffectiveDeviceTotal(deviceRegisterJo);
+        System.out.println("4.");
+
+        //{计算设备和耳标总状态}
+        deviceService.countFarmAllStatus(deviceRegisterJo);
+        System.out.println("5.");
+
+        //{}
+        deviceService.unCancelDeviceOnlineLiveStatus(deviceRegisterJo,todayDateText);
+        System.out.println("6.");
+    }
+
+    /**
+     * @Method      : processSyncEartagRegister
+     * @Description : 监听处理-同步耳标数据
+     * @Params      : [map]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/25       
+     * @Time        : 10:14
+     */
+//    @RabbitListener(queues = Const.QUEUE_SYNC_EARTAG_REGISTER)
+//    @RabbitHandler
+//    public void processSyncEartagRegister(Map map) throws ParseException {
+//        System.out.println("eartag queue>>");
+//        JSONObject deviceRegisterJo = JSONObject.parseObject(map.get("eartagRegister").toString()) ;
+//        System.out.println("deviceRegisterJo>>"+deviceRegisterJo.toJSONString());
+//
+////        System.out.println("同步设备注册信息>>"+deviceRegisterJo);
+//        //{计算有效耳标总数并存储到缓存}
+////        deviceService.countEffectiveDeviceTotal(deviceRegisterJo);
+//        System.out.println("4.");
+//
+//        //{计算设备和耳标总状态}
+////        deviceService.countFarmAllStatus(deviceRegisterJo);
+//        System.out.println("5.");
+//    }
+
+
+    /**
+     * @Method      : processSyncDeviceTotal
+     * @Description : 同步设备总数
+     * @Params      : [map]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/4/1       
+     * @Time        : 11:34
+     */
+    @RabbitListener(queues = Const.QUEUE_SYNC_DEVICE_TOTAL)
+    @RabbitHandler
+    public void processSyncDeviceTotal(Map map) throws ParseException {
+//        System.out.println("device_total queue>>"+map.toString());
+        DateUtil dateUtil = new DateUtil();
+        String todayDateText = dateUtil.getTodayDateText();
+        //{重新计算有效设备总数并存储到缓存}
+        deviceService.countEffectiveDeviceTotal(map);
+
+        //{更新总状态}
+        deviceService.cancelFarmAllStatus(map);
+
+        //{}
+        deviceService.cancelDeviceOnlineLiveStatus(map,todayDateText);
+
+        System.out.println("重新计算有效设备总数并存储到缓存完成.");
+    }
+}

+ 51 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/DeviceProducer.java

@@ -0,0 +1,51 @@
+package com.huimv.eartag.producer;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.utils.Const;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class DeviceProducer {
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+
+    //处理心跳数据
+    public String sendHeartbeat(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("heartbeat",dataJo.toString());
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_DEVICE, Const.ROUTING_KEY_DEVICE_HEARTBEAT, map);
+        System.out.println("处理心跳 >>"+dataJo);
+        return "ok";
+    }
+
+    //处理环境温度数据
+    public String sendDeviceTemp(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("deviceTemp",dataJo);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_DEVICE, Const.ROUTING_KEY_DEVICE_TEMP, map);
+        System.out.println("处理环境温度 >>"+dataJo);
+        return "ok";
+    }
+
+    //处理耳标数据
+    public String sendEartag(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("eartag",dataJo);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_EARTAG, Const.ROUTING_KEY_EARTAG, map);
+        System.out.println("处理耳标数据 >>"+dataJo);
+        return "ok";
+    }
+}

+ 106 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/InputProducer.java

@@ -0,0 +1,106 @@
+package com.huimv.eartag.producer;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.utils.Const;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+@Slf4j
+public class InputProducer {
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+
+    /**
+     * @Method      : saveRawdata
+     * @Description : 保存原始数据到rabbitmq
+     * @Params      : [askText]
+     * @Return      : java.lang.String
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/2/8
+     * @Time        : 17:39
+     */
+    public String sendClientAsk(String askText){
+        Map map = new HashMap();
+//        System.out.println("000000000000000000 >>"+askText);
+        map.put("askText",askText);
+//        System.out.println("111111111111111111>>"+map.toString());
+//        rabbitTemplate.convertAndSend("askExchange", "topic.askText.key", map);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK, Const.ROUTING_KEY_ASK, map);
+//        System.out.println("保存原始数据到rabbitMQ>>"+map.toString());
+        return "ok";
+    }
+
+    //处理心跳数据
+    public String sendHeartbeat(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("heartbeat",dataJo.toString());
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_DEVICE, Const.ROUTING_KEY_DEVICE_HEARTBEAT, map);
+        System.out.println("处理心跳 >>"+dataJo);
+        return "ok";
+    }
+
+    //处理环境温度数据
+    public String sendDeviceTemp(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("deviceTemp",dataJo);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_DEVICE, Const.ROUTING_KEY_DEVICE_TEMP, map);
+        System.out.println("处理环境温度 >>"+dataJo);
+        return "ok";
+    }
+
+    //处理耳标数据
+    public String sendEartag(JSONObject dataJo) {
+        Map map = new HashMap();
+        map.put("eartag",dataJo);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_EARTAG, Const.ROUTING_KEY_EARTAG, map);
+        System.out.println("处理耳标数据 >>"+dataJo);
+        return "ok";
+    }
+    
+    /**
+     * @Method      : sendClientAsk2
+     * @Description : 发送耳标数据队列和设备数据队列
+     * @Params      : [askText]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/12       
+     * @Time        : 18:30
+     */
+    public String sendClientAsk2(String askText) {
+        askText = askText.replaceAll("\r","").replaceAll("\n","");
+        Map map = new HashMap();
+        map.put("askText",askText);
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //发送到设备处理消息队列
+            rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_DEVICE, Const.ROUTING_KEY_ASK_DEVICE, map);
+            System.out.println("## >> 发送设备处理 ...");
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            if(dataArray[2].trim().equalsIgnoreCase("ffffffffffffffff") || dataArray[2].trim().equalsIgnoreCase("0000000000000000")){
+                log.error("舍弃掉未配置耳标号的耳标,"+askText+"");
+            }else{
+                //发送到耳标处理消息队列
+                rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_EARTAG, Const.ROUTING_KEY_ASK_EARTAG, map);
+                System.out.println("## >> 发送耳标处理 ...");
+            }
+        }
+        return "ok";
+    }
+}

+ 65 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/producer/ManageProducer.java

@@ -0,0 +1,65 @@
+package com.huimv.eartag.producer;
+
+import com.huimv.eartag.utils.Const;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class ManageProducer {
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+
+    /**
+     * @Method      : sendSyncDeviceRegister
+     * @Description : 处理同步设备注册相关信息
+     * @Params      : [deviceRegister]
+     * @Return      : java.lang.String
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/4/1
+     * @Time        : 15:19
+     */
+    public String sendSyncDeviceRegister(String deviceRegister) {
+        Map map = new HashMap();
+        map.put("deviceRegister",deviceRegister);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_SYNC_DEVICE_REGISTER, Const.ROUTING_KEY_SYNC_DEVICE_REGISTER, map);
+        System.out.println("同步设备注册信息 >>"+map.toString());
+        return "ok";
+    }
+
+    /**
+     * @Method      : sendSyncDeviceTotal
+     * @Description : 发送同步设备总数
+     * @Params      : [farmId]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/4/1       
+     * @Time        : 15:19
+     */
+    public void sendSyncDeviceTotal(String farmId, String deviceCode) {
+//        System.out.println("设置取消状态 2.");
+        Map map = new HashMap();
+        map.put("farmId",farmId);
+        map.put("deviceCode",deviceCode);
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_SYNC_DEVICE_TOTAL, Const.ROUTING_KEY_SYNC_DEVICE_TOTAL, map);
+        System.out.println("设置取消状态 3.同步设备总数信息 >>"+map.toString());
+    }
+
+    //更新设备别名
+    public void sendUpdateDeviceAlias(String deviceRegisterText) {
+        
+    }
+}

+ 74 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/server/EartagServer2.java

@@ -0,0 +1,74 @@
+package com.huimv.eartag.server;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class EartagServer2 {
+    @Autowired
+    private EartagServerHandler2 serverHandler;
+    //监听端口
+    private int port = 8012;
+    //创建构造方法
+    public EartagServer2(){
+    }
+
+    public static void main(String[] args) throws InterruptedException {
+        new EartagServer2().run();
+    }
+/**
+ *
+ * 功能描述: 启动方法前台多个服务  处理多个线程
+ *
+ * @param:
+ * @return:
+ * @auther: LiGang
+ * @date: 2019/3/26 11:31
+ */
+    /**
+     * 启动流程
+     */
+    public void run() throws InterruptedException {
+        //配置服务端线程组
+        EventLoopGroup bossGroup=new NioEventLoopGroup();
+        EventLoopGroup workGroup=new NioEventLoopGroup();
+
+        try{
+            //引导整个server的启动
+            ServerBootstrap serverBootstrap = new ServerBootstrap();
+            serverBootstrap.group(bossGroup,workGroup)
+                    .channel(NioServerSocketChannel.class)    //指定处理的连接类型
+                    .childHandler(new ChannelInitializer<SocketChannel>() {
+                        @Override
+                        protected void initChannel(SocketChannel socketChannel) throws Exception {
+                            socketChannel.pipeline().addLast(serverHandler);
+                        }
+                    });
+            System.out.println("# 耳标及采集器设备数据接收服务器已经启动。#");
+            System.out.println("# 准备接收数据:");
+            //绑定端口,同步等待成功
+            ChannelFuture cf = serverBootstrap.bind(port).sync();
+            // 等待服务端监听端口关闭
+            cf.channel().closeFuture().sync();
+        }finally {
+            //优雅的退出
+            bossGroup.shutdownGracefully();
+            workGroup.shutdownGracefully();
+        }
+    }
+}

+ 383 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/server/EartagServerHandler2.java

@@ -0,0 +1,383 @@
+package com.huimv.eartag.server;
+
+import com.alibaba.fastjson.JSONArray;
+import com.huimv.eartag.service.IDataService;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.utils.DateUtil2;
+import com.huimv.eartag.utils.RegexUtil;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.util.CharsetUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@ChannelHandler.Sharable
+@Component
+@Slf4j
+public class EartagServerHandler2 extends ChannelInboundHandlerAdapter {
+    @Autowired
+    private IDataService dataService;
+    @Autowired
+    private DateUtil2 dateUtil;
+    @Autowired
+    private RegexUtil regexUtil;
+    @Autowired
+    private IDeviceService deviceService;
+    @Value("${data.input.flow}")
+    private Integer dataInputFlow;
+    @Value("${data.test.input}")
+    private Integer dataTestInput;
+    private StringBuilder askTextSb = null;
+    private int num = 0;
+
+    //
+    public void appendClientAsk(String text){
+        if(this.askTextSb == null){
+            askTextSb = new StringBuilder();
+        }
+        askTextSb.append(text);
+    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        ByteBuf data = (ByteBuf) msg;
+        String clientAskText = data.toString(CharsetUtil.UTF_8);
+//        System.out.println((++num)+"次, 客户端消息clientAskText>>"+clientAskText);
+        //保存实例内的客户端请求
+        appendClientAsk(clientAskText);
+    }
+
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+//        ctx.writeAndFlush("111");
+//        System.out.println("EchoServerHandle channelReadComplete");
+        if(askTextSb.toString().indexOf("end") != -1){
+//            System.out.println("askTextSb.内容()>>"+askTextSb.toString());
+//            System.out.println("askTextSb.内容长度>>"+askTextSb.length());
+//            System.out.println("输入完成.");
+            // 处理客户端消息
+            handleClientEartagMessage(askTextSb.toString(),ctx);
+            //清空重置;
+            askTextSb.delete(0,askTextSb.length());
+            num = 0;
+//            System.out.println("清空sb实例. 长度>>"+askTextSb.length());
+        }
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+//        System.out.println("cause.getMessage()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+cause.getMessage());
+        if(cause.getMessage().indexOf("Connection reset") != -1){
+            log.info("相关采集器设备正在重启:"+cause.toString());
+        }
+//        cause.printStackTrace();
+        ctx.close();
+    }
+
+    /**
+     * @Method      : handleClientMessage
+     * @Description : 处理请求小心
+     * @Params      : [clientAskText, ctx]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/28       
+     * @Time        : 17:36
+     */
+    private void handleClientEartagMessage(String clientAskText, ChannelHandlerContext ctx) throws ParseException {
+//        System.out.println("## clientAskText>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "+clientAskText);
+        clientAskText = clientAskText.replaceAll("\r","").replaceAll("\n","");
+        System.out.println("### 服务端接收数据 >>" + clientAskText);
+        /////////////////////////////////////////////////////////////
+        //TEST-saveRawData()
+        if(dataTestInput == 1){
+            deviceService.saveRawData(clientAskText);
+        }
+        /////////////////////////////////////////////////////////////
+
+        //{}
+        int countPlus = regexUtil.countPlus(clientAskText);
+        if (countPlus < 4) {
+            System.out.println("当前数据为不完整数据,故丢弃.>>" + clientAskText);
+        } else {
+            //--处理客户端请求数据
+            //{拆分粘包数据}
+            JSONArray askJa = getPerData(clientAskText);
+//            System.out.println("askJa.size()="+askJa.size());
+            for (int a = 0; a < askJa.size(); a++) {
+                String askText = askJa.getString(a);
+//                System.out.println((a+1)+",askText"+askText);
+                /////////////////////////////////////////////////////////////
+                //TEST-saveRawData()
+//                deviceService.saveRawData(askText);
+                /////////////////////////////////////////////////////////////
+                if (dataInputFlow == 1) {
+                    //{处理请求内容}
+                    handleAskText(askText, ctx);
+                } else {
+                    //{处理请求内容2}
+                    handleAskText2(askText, ctx);
+                }
+            }
+        }
+    }
+
+    /**
+     * @Method : handleAskText2
+     * @Description :
+     * @Params : [askText, ctx]
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/3/23
+     * @Time : 18:08
+     */
+    private void handleAskText2(String askText, ChannelHandlerContext ctx) throws ParseException {
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        //芯片id/设备编码
+        String idCode = dataArray[1];
+        String cmd = dataArray[2];
+        Map map = new HashMap();
+        map.put("askText", askText);
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+                System.out.println("==>命令0");
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                System.out.println("==>命令1请求 askText>>" + askText.trim());
+                //处理获取设备编码命令
+                //{读取设备编码}
+                String deviceCode = dataService.getDeviceCodeByChipId(idCode);
+                log.info("获取设备编码结果,芯片id>>" + idCode + " ,deviceCode>>" + deviceCode);
+                if (deviceCode != null) {
+                    String answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                    log.info(">>命令1设备编码-应答数据>>" + answer);
+                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+                } else {
+                    log.error("检测到未注册的采集器设备,已舍弃请求.");
+                }
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                System.out.println("==>命令2请求 askText>>" + askText);
+                if (dataService.isEffectiveDevice(idCode)) {
+                    //处理服务器时间命令
+                    String answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                    log.info(">>命令2服务器时间-应答数据>>" + answer);
+                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+                }else {
+                    System.out.println("##获取服务器时间-无效设备编码 idCode=" + idCode);
+                }
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                System.out.println("==>命令3请求 askText>>" + askText);
+                //处理心跳包命令
+                //{设备心跳应答}
+                if (dataService.isEffectiveDevice(idCode)) {
+                    String answer = "hm+3+6+end";
+                    log.info(">>命令3心跳包-应答数据>>" + answer);
+                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+
+                    //{发送到设备处理消息队列}
+                    dataService.sendDeviceMQ(map);
+                    log.info(">>发送设备心跳数据消息到MQ."+map);
+                } else {
+                    System.out.println("##心跳包-无效设备编码(" + idCode+"),请求拒绝。");
+                }
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                System.out.println("==>命令4请求 askText>>" + askText);
+                //处理设备环境温度命令
+                //{设备环境温度应答}
+                if (dataService.isEffectiveDevice(idCode)) {
+                    String answer = "hm+4+7+end";
+                    log.info(">>命令4环境温度-应答数据>>" + answer);
+                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+
+                    //{发送到设备处理消息队列}
+                    dataService.sendDeviceMQ(map);
+                    log.info(">>发送设备环境温度数据消息到MQ."+map);
+                } else {
+                    System.out.println("##环境温度-无效设备编码(" + idCode+"),请求拒绝。");
+                }
+            } else {
+                System.out.println("==>未知命令");
+                log.error(">>当前数据为非法数据>>" + askText);
+            }
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            System.out.println("==>耳标命令请求 askText>>"+askText);
+            //耳标应答数据(不需要应答)
+            if (checkValidEarmark(cmd)) {
+                log.error(">>舍弃掉未配置耳标号的耳标," + askText + "");
+            } else {
+                //{检查设备是否在处于工作状态或待机状态}
+//                if (dataService.isWorkStatusDevice(idCode)) {
+                if (dataService.isEffectiveDevice(idCode)) {
+                    //{发送到耳标处理消息队列}
+                    dataService.sendEartagMQ(map);
+                    log.info(">>发送耳标数据消息到MQ."+map);
+                }else{
+                    System.out.println("无效设备编码 idCode="+idCode);
+                }
+            }
+        } else {
+            System.out.println("==>未知命令");
+            log.error("##当前请求数据为非法数据>>" + askText);
+        }
+    }
+
+    //检查无效耳标
+    public boolean checkValidEarmark(String earmark) {
+        if (earmark.trim().equalsIgnoreCase("ffffffffffffffff") || earmark.trim().equalsIgnoreCase("0000000000000000")) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * @Method : handleAskText
+     * @Description : 处理请求内容
+     * @Params : [askText, ctx]
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/3/23
+     * @Time : 17:36
+     */
+    private void handleAskText(String askText, ChannelHandlerContext ctx) throws ParseException {
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        //芯片id/设备编码
+        String idCode = dataArray[1];
+        String cmd = dataArray[2];
+        //{先判断是否已经注册,未注册的非法设备都过滤掉}
+        boolean validStatus = dataService.isValidDevice(cmdHeader, idCode, cmd);
+        System.out.println("## validStatus>>" + validStatus);
+        if (validStatus) {
+            System.out.println("-->1");
+            //{处理应答}
+            String answer = dataService.getDeviceAnswer(cmdHeader, cmd, idCode);
+            System.out.println("-->2");
+            if (answer != null) {
+                System.out.println("-->2.1");
+                log.info("###应答响应>>" + answer + "\n");
+                ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+                System.out.println("-->2.2");
+            } else {
+                System.out.println("-->2.3");
+                log.info("###应答数据>>" + answer + ",不需要应答。\n");
+            }
+            System.out.println("-->3");
+            //{发送消息异步处理}
+            dataService.sendBizMQ(cmdHeader, cmd, askText);
+            System.out.println("-->4");
+        }
+    }
+
+    //    @Override
+//    public void channelRead_old2(ChannelHandlerContext ctx, Object msg) throws Exception {
+//        ByteBuf data = (ByteBuf) msg;
+//        String clientAskText = data.toString(CharsetUtil.UTF_8);
+////        clientAskText = clientAskText.replaceAll("\r","").replaceAll("\n","");
+//        System.out.println("### 服务端接收数据 >>" + clientAskText);
+//        //TEST-saveRawData()
+////        deviceService.saveRawData(clientAskText);
+//        //{}
+//        int countPlus = regexUtil.countPlus(clientAskText);
+//        if (countPlus < 4) {
+//            System.out.println("当前数据为不完整数据,故丢弃.>>" + clientAskText);
+//        } else {
+//            //--处理客户端请求数据
+////            System.out.println("000拆分粘包之前数据 clientAskText>>"+clientAskText);
+//            //{拆分粘包数据}
+//            JSONArray askJa = getPerData(clientAskText);
+//            for (int a = 0; a < askJa.size(); a++) {
+//                //先判断是否再所有牧场的集合当中,未登记都过滤掉;
+////                cacheService.isValidDevice(deviceCode);
+//
+//                //{处理客户端请求数据}
+//                String answer = dataService.handleClientAsk(askJa.getString(a));
+//                System.out.println("## 返回应答>>" + answer);
+//                if (answer != null) {
+//                    log.info("###应答响应>>" + answer + "\n");
+//                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+//                } else {
+//                    log.info("###应答数据>>" + answer + ",不需要应答。\n");
+//                }
+//            }
+//        }
+//    }
+
+    //    @Override
+//    public void channelRead_old1(ChannelHandlerContext ctx, Object msg) throws Exception {
+//        ByteBuf data = (ByteBuf) msg;
+//        String clientAskText = data.toString(CharsetUtil.UTF_8);
+//        System.out.println("### 服务端接收数据 >>" + clientAskText);
+//        if (clientAskText.length() <= 18) {
+//            System.out.println("当前数据为不完整数据,故丢弃.>>" + clientAskText);
+//        } else {
+//            //--处理客户端请求数据
+////            String answer = eartagDataService.handleClientAsk(clientAskText, ctx);
+//////            String answer = eartagDataService.handleClientAsk(clientAsk, ctx);
+////            if (answer != null) {
+////                log.info("###应答响应>>" + answer + "\n");
+////                ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+////            } else {
+////                log.info("###应答数据>>" + answer + ",不需要应答。\n");
+////            }
+////            System.out.println("000拆分粘包之前数据 clientAskText>>"+clientAskText);
+////            --拆分粘包数据
+//            JSONArray askJa = getPerData(clientAskText);
+//            for (int a = 0; a < askJa.size(); a++) {
+//                //--处理客户端请求数据
+//                String answer = dataService.handleClientAsk(askJa.getString(a), ctx);
+////            String answer = eartagDataService.handleClientAsk(clientAsk, ctx);
+//                if (answer != null) {
+//                    log.info("###应答响应>>" + answer + "\n");
+//                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
+//                } else {
+//                    log.info("###应答数据>>" + answer + ",不需要应答。\n");
+//                }
+//            }
+//        }
+//    }
+
+    //拆分粘包数据
+    public JSONArray getPerData(String text) {
+        String key = "end";
+        Pattern pattern = Pattern.compile(key);
+        Matcher matcher = pattern.matcher(text);
+        int count = 0;
+        while (matcher.find()) {
+            count++;
+        }
+        JSONArray dataJa = new JSONArray();
+        if (count == 1) {
+            dataJa.add(text);
+        } else {
+            for (int a = 0; a < count; a++) {
+                int p1 = text.indexOf("end");
+                dataJa.add(text.substring(0, p1 + 3));
+                text = text.substring(p1 + 3, text.length());
+            }
+        }
+        return dataJa;
+    }
+
+}

+ 102 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/ICacheService.java

@@ -0,0 +1,102 @@
+package com.huimv.eartag.service;
+
+import com.huimv.eartag.dao.entity.*;
+
+import java.text.ParseException;
+import java.util.List;
+import java.util.Map;
+
+public interface ICacheService {
+    //{}
+    Object getDeviceCodeByChipId(String chipId);
+
+    //
+    boolean checkEffectiveDeviceSet(String idCode);
+
+    //# 读根据设备编码读取牧场id
+    Object getFarmIdByDeviceCode(String deviceCode);
+
+    void putDeviceRegister(String deviceCode, EartagDeviceRegisterEntity deviceRegisterEntity);
+
+//    void putDeviceRegister(String deviceCode, EartagDeviceRegisterEntity deviceRegisterEntity);
+
+    void putEartagFlowToCache(String earmark, EartagDataEntity dataEntity);
+
+    void putEartagRegister(String earmark, EartagEartagRegisterEntity eartagRegisterEntity);
+
+    void putEartagTotal(Integer total, String farmId);
+
+    Object getHashProperty(String hashKey, String fieldName);
+
+    void putDeviceInOnline(String deviceCode, EartagDeviceOnlineEntity eartagDeviceOnlineEntity);
+
+    void putEartagOnlineCount(String earmark, EartagEartagOnlineEntity eartagOnlineEntity);
+
+    void countEartagDeviceOnlineTimes(String earmark, String deviceCode, int total, EartagDeviceEartagCountEntity deviceEartagCountEntity);
+
+    Map<Object, Object> getHashEntries(String hashKey);
+
+    void putHashKeyProperty(String hashKey, String fieldName, Object value);
+
+    boolean isExistEartagOnlineSet(String farmId, String earmark, String todayDateText);
+
+    void putEartagDeviceOnlineCount(String earmark, String deviceCode, String todayDateText, EartagDeviceEartagCountEntity deviceEartagCountEntity);
+
+    Integer getDeviceTotal(String farmId);
+
+    void putDeviceTotal(Integer total, String farmId);
+
+    Integer getDeviceOnlineSum(String farmId, String todayDateText);
+
+    Integer getDeviceCancel(String farmId);
+
+    void putDeviceCancel(Integer total, String farmId);
+
+    void flashAllStatusCache(String farmId, EartarFarmAllStatusEntity farmAllStatusEntity);
+
+    Integer getEartagTotal(String farmId);
+
+    Integer getEartagOnlineTotalFromCache(String farmId, String todayDateText);
+
+    void putEartagToOnlineInSet(String farmId, String earmark, String todayDateText) throws ParseException;
+
+    Object getEartagLastAct(String earmark);
+
+    void putEartagAct(String earmark, String nowAct);
+
+    boolean isExistDeviceOnlineSet(String farmId, String deviceCode, String todayDateText);
+
+    void putDeviceToOnlineSet(String farmId, String deviceCode, String todayDateText);
+
+    Object getEnvTempThresholdVal(String farmId);
+
+    void deleteDeviceToOnlineSet(String farmId, String deviceCode, String todayDateText);
+
+    Map getFarmAllStatusByFarmId(String farmId);
+
+    void putFarmAllStatusCache(String farmId, EartarFarmAllStatusEntity farmAllStatusEntity);
+
+    int getDeviceOnlineTotal(String farmId, String todayDateText);
+
+    int getEartagOnlineTotal(String farmId, String todayDateText);
+
+    void putDeviceTotal_(Integer effectiveDeviceTotal, String farmId);
+
+    void putAllDeviceSet(String deviceCode);
+
+    void putChipIdToCache(String chipId, String deviceCode);
+
+    void deleteDeviceRegister(String deviceCode);
+
+    void deleteDeviceCodeSetCache(String deviceCode);
+
+    void deleteOnlineDeviceSet(String farmId, String deviceCode, String todayDateText);
+
+    void deleteChipIdHashCache(String chipId);
+
+    int isExistAllDeviceSet();
+
+    boolean isExistDeviceCode(String deviceCode);
+
+    void putAllDeviceSet(List list);
+}

+ 36 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDataService.java

@@ -0,0 +1,36 @@
+package com.huimv.eartag.service;
+
+import java.text.ParseException;
+import java.util.Map;
+
+public interface IDataService {
+    //
+    String handleClientAsk(String receiveData) throws ParseException;
+
+    //解析客户端请求
+    Map parseDeviceAsk(String askText) throws ParseException;
+
+    //判断设备有效性
+    boolean isValidDevice(String cmdHeader, String idCode, String cmd);
+
+    //获取设备应答
+    String getDeviceAnswer(String cmdHeader, String cmd, String idCode) throws ParseException;
+
+    //发送消息
+    void sendBizMQ(String cmdHeader, String cmd, String askText);
+
+    //发送设备消息
+    void sendEartagMQ(Map map);
+
+    //
+    String getDeviceCodeByChipId(String idCode);
+
+    //发送耳标消息
+    void sendDeviceMQ(Map map);
+
+    //判断是否是工作状态的设备
+    boolean isWorkStatusDevice(String idCode);
+
+    //检查是否是有效设备
+    boolean isEffectiveDevice(String idCode);
+}

+ 71 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceManageService.java

@@ -0,0 +1,71 @@
+package com.huimv.eartag.service;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.vo.Result;
+
+import java.text.ParseException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public interface IDeviceManageService {
+    //
+    Result getNowAllStatus(String farmId) throws ParseException;
+
+    //显示前N天记录
+    Result listManyDaysAllStatus(String farmId, Integer days) throws ParseException;
+
+    //显示在线设备
+    Result listOnlineDevice(String farmId, String date) throws ParseException;
+
+    //
+    Result getDeviceRegisterByDeviceCode(String deviceCode) throws ParseException;
+
+    //查询单个设备N天在线记录
+    Result listDeviceOnlineCountByDeviceCode(String deviceCode, Integer pastDays) throws ParseException;
+
+    //查询设备在线状态
+    Result listDeviceOnlineStatusByDeviceCode(String deviceCode, Integer pastDays) throws ParseException;
+
+    //查询设备关联的在线耳标统计
+    Result listDeviceEartagOnlineCountByDeviceCode(String deviceCode) throws ParseException;
+
+    void remoteProcessFarmAllStatus(String farmId) throws ParseException;
+
+    void remoteProcessFarmAllStatus2(String farmId) throws ParseException;
+
+    //查询在线设备
+    Result listOnlineDevice(String farmId, String deviceCode, String alias, String addDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //查询设备环境温度
+    Result listDeviceEnvtempByDeviceCode(String deviceCode) throws ParseException;
+
+    //用分页方式
+    Result listDeviceEartagOnlineCountByDeviceCodeInPager(String deviceCode, String earmark, String addDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //显示设备心跳
+    Result listHeartbeatByDeviceCodeAndDateInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //分页查询设备温度
+    Result listDeviceEnvtempByDeviceCodeInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //分页查询列表
+    Result listDeviceRegisterInPager(String farmId, String deviceCode, String alias, String startDate, String endDate, Integer activeStatus, Integer liveStatus, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //单个耳标指定
+    Result listDeviceOnlineCountByDeviceCodeInPager(String deviceCode, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //同步设备注册信息
+    void countEffectiveDeviceTotal(JSONObject deviceRegister);
+
+    //计算总状态信息
+    void countFarmAllStatus(JSONObject deviceRegisterJo) throws ParseException;
+
+    //
+    Result listDeviceEartagOnlineStatusByDeviceCodeAndDate(String deviceCode, String earmark, String addDate);
+}

+ 25 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceRegisterService.java

@@ -0,0 +1,25 @@
+package com.huimv.eartag.service;
+
+import com.huimv.eartag.vo.Result;
+
+import java.text.ParseException;
+
+public interface IDeviceRegisterService {
+    //添加设备
+    Result addDevice(String chipId, String deviceCode, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, String remark, String farmId) throws ParseException;
+
+    //编辑设备
+    Result editDevice(String chipId, String deviceCode, Integer lastDeviceStatus, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, String remark, Integer id) throws ParseException;
+
+    //移除设备
+    Result removeDevice(String ids);
+
+    //展示设备注册列表
+    Result listDevice(String farmId, String deviceCode, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, Integer pageNo, Integer pageSize);
+
+    //批量删除
+    Result removeBatchDevice(String ids);
+
+    //注销设备
+    Result setDeviceStatus(Integer id, Integer deviceStatus) throws ParseException;
+}

+ 57 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IDeviceService.java

@@ -0,0 +1,57 @@
+package com.huimv.eartag.service;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public interface IDeviceService {
+    //处理采集器设备信息
+    void handleDeviceInfo();
+
+    //保存原始数据
+    void saveRawData(String askText) throws ParseException;
+
+    //{根据芯片id读取设备编码}
+    String getDeviceCodeByChipId(String chipId);
+
+    String getFarmIdByDeviceCode(String deviceCode);
+
+    //计算设备总数
+    int getDeviceTotalByFarmIdFromDeviceRegister(String farmId);
+
+
+    //计算注销设备数量
+    int getDeviceCancelTotalFromDeviceRegister(String farmId);
+
+    //计算处于不同生存状态的设备数量
+    Integer getDeviceSum(String farmId, Integer liveStatus);
+
+    //更新设备环境信息
+    void updateEnvtempOfDeviceAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException;
+
+    void handleDeviceHeartbeat(JSONObject dataJo) throws ParseException;
+
+    void handleDeviceEnvtemp(JSONObject dataJo) throws ParseException;
+
+    void countEffectiveDeviceTotal(JSONObject deviceRegisterJo);
+
+    void countEffectiveDeviceTotal(Map inMap);
+
+    void countFarmAllStatus(JSONObject deviceRegisterJo) throws ParseException;
+
+    void unCancelDeviceOnlineLiveStatus(JSONObject deviceRegisterJo, String todayDateText);
+
+    void cancelFarmAllStatus(Map map) throws ParseException;
+
+    void cancelDeviceOnlineLiveStatus(Map map, String todayDateText);
+}

+ 51 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IEartagManageService.java

@@ -0,0 +1,51 @@
+package com.huimv.eartag.service;
+
+import com.huimv.eartag.vo.Result;
+
+import java.text.ParseException;
+
+public interface IEartagManageService {
+    //
+    Result getEartagRegisterByEarmark(String earmark) throws ParseException;
+
+    //根据耳标号读取今天所有流水
+    Result listEartagFlowByEarmarkAndToday(String earmark) throws ParseException;
+
+    Result listEartagFlowByDeviceCodeAndEarmarkAndToday(String earmark, String deviceCode) throws ParseException;
+
+    //显示耳标在线统计
+    Result listEartagOnlineCountByEarmarkAndDate(String earmark, Integer pastDays, Integer showMode) throws ParseException;
+
+    //显示耳标在线统计
+    Result listEartagOnlineStatusByEarmarkAndDate(String earmark, Integer pastDays) throws ParseException;
+
+    //带分页查询耳标流水
+    Result listEartagFlowByEarmarkAndTodayInPager(String earmark, Integer pageNo, Integer pageSize, String createDate, String deviceCode) throws ParseException;
+
+    //带分页查询耳标流水
+    Result listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager(String earmark, String deviceCode, String createDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //带分页查询耳标流水
+    Result listEartagFlowByDeviceCodeAndEarmarkAndDateInPager(String earmark, String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //前N天的耳标在线状态
+    Result listEartagOnlineAllStatus(String farmId, Integer days) throws ParseException;
+
+    //展示在线耳标列表
+    Result listOnlineEartagCount(String farmId, String addDate, Integer pageNo, Integer pageSize, Integer showMode) throws ParseException;
+
+    //获取该耳边前N天历史记录
+//    Result getEartagOnlineCountByEarmark(String earmark, Integer days) throws ParseException;
+
+    //通过耳标号和日期获取耳标关联设备信息
+    Result listEartagDeviceByEarmarkAndAddDate(String earmark, String addDate);
+
+    //分页展示所有耳标注册列表
+    Result listAllEartagRegister(String farmId, String earmark, Integer activeStatus, Integer liveStatus, Integer registerType, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //分页展示所有耳标流水列表
+    Result listAllEartagFlow(String farmId, String createDate, String deviceCode, String earmark, Integer pageNo, Integer pageSize) throws ParseException;
+
+    //
+    Result listManyEartagOnlineStatus(String farmId, Integer days) throws ParseException;
+}

+ 22 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/IEartagService.java

@@ -0,0 +1,22 @@
+package com.huimv.eartag.service;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.text.ParseException;
+
+public interface IEartagService {
+    //处理耳标信息
+    void handleEartagInfo();
+
+    Integer countAct(String deviceCode, String nowAct);
+
+    Integer getEartagRegTotalByFarmId(String farmId);
+
+    //计算运动量
+    Integer countEartagAct(String earmark, String nowAct);
+
+    //
+    void handleEartag(JSONObject dataJo) throws ParseException;
+
+//    Integer getEartagOnelineTotal(String farmId, String todayDateText);
+}

+ 554 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/CacheServiceImpl.java

@@ -0,0 +1,554 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.*;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.service.ICacheService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class CacheServiceImpl implements ICacheService {
+    @Autowired
+    private RedisTemplate redisTemplate;
+    @Value("${redis.expire.eartag_online_set}")
+    private Integer eartagOnlineSetExpire;
+
+    @Override
+    public Object getDeviceCodeByChipId(String chipId) {
+        String  hashKey = BizConst.CHIP_DEVICE_PREFIX;
+        return redisTemplate.opsForHash().get(hashKey,chipId);
+    }
+
+    @Override
+    public boolean checkEffectiveDeviceSet(String idCode) {
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+        return redisTemplate.opsForSet().isMember(setKey,idCode);
+    }
+
+    //# 读根据设备编码读取牧场id
+    @Override
+    public Object getFarmIdByDeviceCode(String deviceCode) {
+        Object farmIdObj = redisTemplate.opsForHash().get(BizConst.DEVICE_REGISTER_PREFIX + deviceCode,"farmId");
+        return farmIdObj;
+    }
+
+    @Override
+    public void putDeviceRegister(String deviceCode, EartagDeviceRegisterEntity deviceRegisterEntity) {
+        //--更新redis中注册表数据
+        String deviceRegHashKey = BizConst.DEVICE_REGISTER_PREFIX + deviceCode;
+        //将Entity转为Map
+        Map registerMap = RegisterEntityToMap(deviceRegisterEntity);
+        redisTemplate.opsForHash().putAll(deviceRegHashKey, registerMap);
+    }
+
+    /**
+     * @Method : RegisterEntityToMap
+     * @Description :
+     * @Params : [deviceRegisterEntity]
+     * @Return : java.util.Map
+     * @Author : ZhuoNing
+     * @Date : 2022/2/21
+     * @Time : 14:03
+     */
+    private Map RegisterEntityToMap(EartagDeviceRegisterEntity deviceRegisterEntity) {
+        Map map = new HashMap();
+        map.put("Id", deviceRegisterEntity.getId());
+        map.put("deviceCode", deviceRegisterEntity.getDeviceCode());
+        map.put("farmId", deviceRegisterEntity.getFarmId());
+        map.put("farmName", deviceRegisterEntity.getFarmName());
+        map.put("typeF", deviceRegisterEntity.getTypeF());
+        map.put("stage", deviceRegisterEntity.getStage());
+        map.put("pigpenId", deviceRegisterEntity.getPigpenId());
+        map.put("unitId", deviceRegisterEntity.getUnitId());
+        map.put("registerTime", deviceRegisterEntity.getRegisterTime());
+        map.put("lastTime", deviceRegisterEntity.getLastTime());
+        map.put("activeStatus", deviceRegisterEntity.getActiveStatus());
+        map.put("activeTime", deviceRegisterEntity.getActiveTime());
+        map.put("deviceStatus", deviceRegisterEntity.getDeviceStatus());
+        map.put("deviceAlias", deviceRegisterEntity.getDeviceAlias());
+        map.put("location", deviceRegisterEntity.getLocation());
+        map.put("remark", deviceRegisterEntity.getRemark());
+        return map;
+    }
+
+    @Override
+    public void putEartagFlowToCache(String earmark, EartagDataEntity dataEntity) {
+        Map<String, String> map = new HashMap<>();
+        map.put("cmdHeader", dataEntity.getCmdHeader());
+        map.put("device", dataEntity.getDevice());
+        map.put("earmark", dataEntity.getEarmark());
+        map.put("bat", dataEntity.getBat().toString());
+        map.put("earTemp", dataEntity.getEarTemp().toString());
+        map.put("earTemp1", dataEntity.getEarTemp1().toString());
+        map.put("envTemp", dataEntity.getEnvTemp().toString());
+        map.put("envTemp1", dataEntity.getEnvTemp1().toString());
+        map.put("act", dataEntity.getAct().toString());
+        map.put("act1", dataEntity.getAct1().toString());
+        map.put("signal1", dataEntity.getSignal1().toString());
+        map.put("askTime", dataEntity.getAskTime());
+        map.put("other", dataEntity.getOther());
+        map.put("addTime", dataEntity.getAddTime().toString());
+        //为hash结构设置多个键值对(hmset)
+        redisTemplate.opsForHash().putAll(BizConst.EARTAG_FLOW_PREFIX+earmark, map);
+    }
+
+    @Override
+    public void putEartagRegister(String earmark, EartagEartagRegisterEntity eartagRegisterEntity) {
+        Map map = new HashMap();
+//        map.put("id", eartagRegisterEntity.getId());
+        map.put("earmark",eartagRegisterEntity.getEarmark());
+        map.put("firstTime",eartagRegisterEntity.getFirstTime());
+        map.put("lastTime",eartagRegisterEntity.getLastTime());
+        map.put("firstDevice",eartagRegisterEntity.getFirstDevice());
+        map.put("belongDevice",eartagRegisterEntity.getBelongDevice());
+        map.put("lastDevice",eartagRegisterEntity.getLastDevice());
+        map.put("registerTime",eartagRegisterEntity.getRegisterTime());
+        map.put("registerType",eartagRegisterEntity.getRegisterType());
+        map.put("remark",eartagRegisterEntity.getRemark());
+        map.put("farmId",eartagRegisterEntity.getFarmId());
+        map.put("activeStatus",eartagRegisterEntity.getActiveStatus());
+        map.put("activeTime",eartagRegisterEntity.getActiveTime());
+        map.put("liveStatus",eartagRegisterEntity.getLiveStatus());
+        //更新缓存
+        String earmarkOnlineKey = BizConst.EARTAG_REGISTER_PREFIX + earmark;
+        redisTemplate.opsForHash().putAll(earmarkOnlineKey, map);
+    }
+
+    @Override
+    public void putEartagTotal(Integer total, String farmId) {
+        String valueKey = BizConst.FARM_EARTAG_TOTAL_PREFIX+farmId;
+        redisTemplate.opsForValue().set(valueKey,total);
+    }
+
+    @Override
+    public Object getHashProperty(String hashKey, String fieldName) {
+        Object obj = redisTemplate.opsForHash().get(hashKey, fieldName);
+        return obj;
+    }
+
+    /**
+     * @Method      : putDeviceInOnline
+     * @Description : 将数据库中的在线数据更新对应的缓存数据中
+     * @Params      : [deviceOnlineHashKey, eartagDeviceOnlineEntity]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/1
+     * @Time        : 16:07
+     */
+    @Override
+    public void putDeviceInOnline(String deviceCode, EartagDeviceOnlineEntity eartagDeviceOnlineEntity) {
+        Map map = new HashMap();
+//        map.put("id", eartagDeviceOnlineEntity.getId());
+        map.put("deviceCode", eartagDeviceOnlineEntity.getDeviceCode());
+        map.put("alias", eartagDeviceOnlineEntity.getAlias());
+        map.put("heartbeatTotal", eartagDeviceOnlineEntity.getHeartbeatTotal());
+        map.put("envtempTotal", eartagDeviceOnlineEntity.getEnvtempTotal());
+        map.put("eartagTotal", eartagDeviceOnlineEntity.getEartagTotal());
+        map.put("firstTime", eartagDeviceOnlineEntity.getFirstTime());
+        map.put("lastTime", eartagDeviceOnlineEntity.getLastTime());
+        map.put("lastEnvtemp", eartagDeviceOnlineEntity.getLastEnvtemp());
+        map.put("lastEartag", eartagDeviceOnlineEntity.getLastEartag());
+        map.put("addDate", eartagDeviceOnlineEntity.getAddDate());
+        map.put("farmId", eartagDeviceOnlineEntity.getFarmId());
+        //更新缓存
+        String deviceOnlineKey = BizConst.DEVICE_ONLINE_PREFIX + deviceCode;
+        redisTemplate.opsForHash().putAll(deviceOnlineKey, map);
+//        Map onlineMap = fromOnlineEntityToMap(newDeviceOnlineEntity);
+//        redisTemplate.opsForHash().putAll(deviceOnlineHashKey, onlineMap);
+    }
+
+    /**
+     * @Method      : putEartagOnlineCount
+     * @Description :
+     * @Params      : [earmark, eartagOnlineEntity]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/3
+     * @Time        : 15:29
+     */
+    @Override
+    public void putEartagOnlineCount(String earmark, EartagEartagOnlineEntity eartagOnlineEntity) {
+        Map map = new HashMap();
+//        map.put("id", eartagRegisterEntity.getId());
+        map.put("earmark",eartagOnlineEntity.getEarmark());
+        map.put("total",eartagOnlineEntity.getTotal());
+        map.put("firstTime",eartagOnlineEntity.getFirstTime());
+        map.put("lastTime",eartagOnlineEntity.getLastTime());
+        map.put("envTemp",eartagOnlineEntity.getEnvTemp());
+        map.put("eartagTemp",eartagOnlineEntity.getEartagTemp());
+        map.put("addDate",eartagOnlineEntity.getAddDate());
+        map.put("farmId",eartagOnlineEntity.getFarmId());
+        //更新缓存
+        String earmarkOnlineKey = BizConst.EARTAG_ONLINE_PREFIX + earmark;
+        redisTemplate.opsForHash().putAll(earmarkOnlineKey, map);
+    }
+
+    @Override
+    public void countEartagDeviceOnlineTimes(String earmark, String deviceCode, int total, EartagDeviceEartagCountEntity deviceEartagCountEntity) {
+        String hashKey = BizConst.ONLINE_EARMARK_DEVICE_PREFIX+earmark+":"+deviceCode;
+//        redisTemplate.opsForHash().increment(hashKey,"total",1);  // Error
+
+//        Integer total = (Integer) getHashKeyProperty(hashKey, "total");
+//        putHashKeyProperty(hashKey,"total",++total);
+        Map map = getHashEntries(hashKey);
+        if(map.size()>0){
+            putHashKeyProperty(hashKey,"total",total);
+        }else{
+            Map newMap = JSON.parseObject(JSONObject.toJSONString(deviceEartagCountEntity),Map.class);
+            redisTemplate.opsForHash().putAll(hashKey,newMap);
+        }
+    }
+
+    @Override
+    public Map<Object, Object> getHashEntries(String hashKey) {
+//        String hashKey = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
+        Map<Object, Object> entriesMap = redisTemplate.opsForHash().entries(hashKey);
+        return entriesMap;
+    }
+
+    @Override
+    public void putHashKeyProperty(String hashKey, String fieldName, Object value){
+        redisTemplate.opsForHash().put(hashKey,fieldName,value);
+    }
+
+    @Override
+    public boolean isExistEartagOnlineSet(String farmId, String earmark, String todayDateText) {
+//        redisTemplate.opsForSet().add(BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+"_"+todayDateText, earmark);
+        String setKey = BizConst.SET_FARM_EARMARK_ONLINE_PREFIX + farmId+":"+todayDateText;
+//        System.out.println("## eartag.setKey .isExistEartagOnlineSet >>"+setKey+",earmark>>"+earmark);
+        return redisTemplate.opsForSet().isMember(setKey, earmark);
+    }
+
+    @Override
+    public void putEartagDeviceOnlineCount(String earmark, String deviceCode, String todayDateText, EartagDeviceEartagCountEntity deviceEartagCountEntity){
+        //将实体类对象转成Map对象
+        Map map = JSON.parseObject(JSONObject.toJSONString(deviceEartagCountEntity),Map.class);
+//        Map map2 = (Map)JSONObject.parse(JSONObject.toJSONString(deviceEartagCountEntity));
+//        Map map3 = (Map)JSON.parse(JSONObject.toJSONString(deviceEartagCountEntity));
+//        Map map4 = (Map)JSON.parseObject(JSONObject.toJSONString(deviceEartagCountEntity));
+//        Map<String, Object> map = JSON.parseObject(JSONObject.toJSONString(deviceEartagCountEntity), new TypeReference<Map<String, Object>>(){} );
+
+        //        String hashKey = BizConst.ONLINE_EARMARK_DEVICE_PREFIX+earmark+":"+deviceCode+":"+todayDateText;
+        String hashKey = BizConst.ONLINE_EARMARK_DEVICE_PREFIX+earmark+":"+deviceCode;
+        redisTemplate.opsForHash().putAll(hashKey,map);
+    }
+
+    @Override
+    public Integer getDeviceTotal(String farmId) {
+        String valueKey = BizConst.FARM_DEVICE_TOTAL_PREFIX+farmId;
+//        String value = (String) redisTemplate.opsForValue().get(valueKey);
+//        System.out.println("## value>>"+value);
+//        redisTemplate.opsForValue().set(valueKey,"50");
+        Object obj = redisTemplate.opsForValue().get(valueKey);
+        if(obj == null){
+            return null;
+        }else{
+            return Integer.parseInt(String.valueOf(obj));
+        }
+    }
+
+    @Override
+    public void putDeviceTotal(Integer total, String farmId) {
+        String valueKey = BizConst.FARM_DEVICE_TOTAL_PREFIX+farmId;
+        redisTemplate.opsForValue().set(valueKey,total);
+    }
+
+    @Override
+    public Integer getDeviceOnlineSum(String farmId, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+":"+todayDateText;
+        Set<String> resultSet = redisTemplate.opsForSet().members(setKey);
+        return resultSet.size();
+    }
+
+    @Override
+    public Integer getDeviceCancel(String farmId) {
+        String valueKey = BizConst.FARM_DEVICE_CANCEL_PREFIX+farmId;
+//        String value = (String) redisTemplate.opsForValue().get(valueKey);
+        Object obj = redisTemplate.opsForValue().get(valueKey);
+        if(obj == null){
+            return null;
+        }else{
+            return Integer.parseInt(String.valueOf(obj));
+        }
+    }
+
+    @Override
+    public void putDeviceCancel(Integer total, String farmId) {
+        String valueKey = BizConst.FARM_DEVICE_CANCEL_PREFIX+farmId;
+        redisTemplate.opsForValue().set(valueKey,total);
+    }
+
+    @Override
+    public void flashAllStatusCache(String farmId, EartarFarmAllStatusEntity farmAllStatusEntity) {
+        Map allStatusMap = new HashMap();
+//        allStatusMap.put("id",farmAllStatusEntity.getId());
+        allStatusMap.put("deviceTotal",farmAllStatusEntity.getDeviceTotal());
+        allStatusMap.put("deviceOnline",farmAllStatusEntity.getDeviceOnline());
+        allStatusMap.put("deviceOffline",farmAllStatusEntity.getDeviceOffline());
+        allStatusMap.put("deviceRate",farmAllStatusEntity.getDeviceRate());
+        allStatusMap.put("deviceCancel",farmAllStatusEntity.getDeviceCancel());
+        allStatusMap.put("eartagTotal",farmAllStatusEntity.getEartagTotal());
+        allStatusMap.put("eartagOnline",farmAllStatusEntity.getEartagOnline());
+        allStatusMap.put("farmId",farmId);
+//        allStatusMap.put("updateTime",duObj.formatDateTime(duObj.getTodayText()));
+//        allStatusMap.put("createDate",duObj.getTodayDate());
+        allStatusMap.put("updateTime",farmAllStatusEntity.getUpdateTime());
+        allStatusMap.put("createDate",farmAllStatusEntity.getCreateDate());
+
+        redisTemplate.opsForHash().putAll(BizConst.FARM_ALL_STATUS_PREFIX+farmId, allStatusMap);
+    }
+
+    @Override
+    public Integer getEartagTotal(String farmId) {
+        String valueKey = BizConst.FARM_EARTAG_TOTAL_PREFIX+farmId;
+        Object obj = redisTemplate.opsForValue().get(valueKey);
+        if(obj != null){
+            return Integer.parseInt(String.valueOf(obj));
+        }else{
+            return null;
+        }
+    }
+
+    /**
+     * @Method      : getEartagOnlineTotalFromCache
+     * @Description : 返回集合缓存的数量;
+     * @Params      : [farmId, todayDateText]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/3
+     * @Time        : 10:55
+     */
+    @Override
+    public Integer getEartagOnlineTotalFromCache(String farmId, String todayDateText) {
+        String setKey = BizConst.SET_FARM_EARMARK_ONLINE_PREFIX + farmId+":"+todayDateText;
+        return redisTemplate.opsForSet().members(setKey).size();
+    }
+
+    @Override
+    public void putEartagToOnlineInSet(String farmId, String earmark, String todayDateText) throws ParseException {
+        String setKey = BizConst.SET_FARM_EARMARK_ONLINE_PREFIX + farmId+":"+todayDateText;
+//        System.out.println("## eartag.setKey .putEartagToOnlineInSet>>"+setKey+",earmark>>"+earmark);
+        redisTemplate.opsForSet().add(setKey, earmark);
+        //设置25小时过期
+        redisTemplate.expire(setKey,eartagOnlineSetExpire , TimeUnit.HOURS);
+//        Set<String> resultSet = redisTemplate.opsForSet().members(setKey);
+//        System.out.println("## "+setKey+">>"+resultSet.size()+" >>"+resultSet);
+    }
+
+    @Override
+    public Object getEartagLastAct(String earmark) {
+        String valuekey = BizConst.EARTAG_LAST_ACT_PREFIX+earmark;
+        return redisTemplate.opsForValue().get(valuekey);
+    }
+
+    @Override
+    public void putEartagAct(String earmark, String nowAct) {
+        String valuekey = BizConst.EARTAG_LAST_ACT_PREFIX+earmark;
+        redisTemplate.opsForValue().set(valuekey,nowAct);
+    }
+
+    @Override
+    public boolean isExistDeviceOnlineSet(String farmId, String deviceCode, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+":"+todayDateText;
+        return redisTemplate.opsForSet().isMember(setKey, deviceCode);
+    }
+
+    /**
+     * @Method      : putDeviceCode
+     * @Description : 将新的设备编号加入到缓存当中;
+     * @Params      : [farmId, deviceCode]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/1
+     * @Time        : 13:42
+     */
+    @Override
+    public void putDeviceToOnlineSet(String farmId, String deviceCode, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+":"+todayDateText;
+        redisTemplate.opsForSet().add(setKey, deviceCode);
+        redisTemplate.expire(setKey,eartagOnlineSetExpire , TimeUnit.HOURS);
+    }
+
+    @Override
+    public Object getEnvTempThresholdVal(String farmId) {
+        String key = BizConst.HASH_ENV_TEMP_TV_PREFIX+farmId;
+        String hashKey = "envTemp";
+        return redisTemplate.opsForHash().get(key,hashKey);
+    }
+
+    @Override
+    public void deleteDeviceToOnlineSet(String farmId, String deviceCode, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+":"+todayDateText;
+//        redisTemplate.opsForSet().add(setKey, deviceCode);
+//        redisTemplate.expire(setKey,eartagOnlineSetExpire , TimeUnit.HOURS);
+        redisTemplate.opsForSet().remove(setKey,deviceCode);
+    }
+
+    @Override
+    public Map getFarmAllStatusByFarmId(String farmId) {
+        String hashKey = BizConst.FARM_ALL_STATUS_PREFIX+farmId;
+        return redisTemplate.opsForHash().entries(hashKey);
+    }
+
+    @Override
+    public void putFarmAllStatusCache(String farmId, EartarFarmAllStatusEntity farmAllStatusEntity) {
+//        Map allStatusMap = new HashMap();
+////        allStatusMap.put("id",farmAllStatusEntity.getId());
+//        allStatusMap.put("deviceTotal",farmAllStatusEntity.getDeviceTotal());
+//        allStatusMap.put("deviceOnline",farmAllStatusEntity.getDeviceOnline());
+//        allStatusMap.put("deviceOffline",farmAllStatusEntity.getDeviceOffline());
+//        allStatusMap.put("deviceRate",farmAllStatusEntity.getDeviceRate());
+//        allStatusMap.put("deviceCancel",farmAllStatusEntity.getDeviceCancel());
+//        allStatusMap.put("eartagTotal",farmAllStatusEntity.getEartagTotal());
+//        allStatusMap.put("eartagOnline",farmAllStatusEntity.getEartagOnline());
+//        allStatusMap.put("farmId",farmId);
+////        allStatusMap.put("updateTime",duObj.formatDateTime(duObj.getTodayText()));
+////        allStatusMap.put("createDate",duObj.getTodayDate());
+//        allStatusMap.put("updateTime",farmAllStatusEntity.getUpdateTime());
+//        allStatusMap.put("createDate",farmAllStatusEntity.getCreateDate());
+        Map allStatusMap = JSON.parseObject(JSONObject.toJSONString(farmAllStatusEntity),Map.class);
+        redisTemplate.opsForHash().putAll(BizConst.FARM_ALL_STATUS_PREFIX+farmId, allStatusMap);
+    }
+
+    @Override
+    public int getDeviceOnlineTotal(String farmId, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX+farmId+"_"+todayDateText;
+        Set<String> resultSet = redisTemplate.opsForSet().members(setKey);
+        return resultSet.size();
+    }
+
+    @Override
+    public int getEartagOnlineTotal(String farmId, String todayDateText) {
+        String setKey = BizConst.SET_FARM_EARMARK_ONLINE_PREFIX+farmId+"_"+todayDateText;
+        Set<String> resultSet = redisTemplate.opsForSet().members(setKey);
+        return resultSet.size();
+    }
+
+    @Override
+    public void putDeviceTotal_(Integer effectiveDeviceTotal, String farmId) {
+        String valueKey = BizConst.FARM_DEVICE_TOTAL_PREFIX+farmId;
+        redisTemplate.opsForValue().set(valueKey,effectiveDeviceTotal);
+        // TEST
+//        Object obj = redisTemplate.opsForValue().get(valueKey);
+//        System.out.println("TEST value>>"+obj.toString());
+    }
+
+    @Override
+    public void putAllDeviceSet(String deviceCode){
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+        redisTemplate.opsForSet().add(setKey,deviceCode);
+    }
+
+    @Override
+    public void putChipIdToCache(String chipId, String deviceCode) {
+        System.out.println("## <putChipIdToCache> chipId>>"+chipId);
+        System.out.println("## <putChipIdToCache> deviceCode>>"+deviceCode);
+
+        String key = BizConst.CHIP_DEVICE_PREFIX;
+        String hashKey = chipId;
+        //
+        redisTemplate.opsForHash().put(key,hashKey,deviceCode);
+//        redisTemplate.expire(key,chipIdExpire , TimeUnit.HOURS);
+    }
+
+    @Override
+    public void deleteDeviceRegister(String deviceCode) {
+        String key = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
+//        System.out.println(">> <deleteDeviceRegister> key>>"+key);
+        Object obj = redisTemplate.opsForHash().entries(key);
+        if(obj == null){
+            log.error("##Error 该key["+key+"]的缓存不存在.");
+        }else{
+            redisTemplate.delete(key);
+//            System.out.println(">> end <deleteDeviceRegister> key>>"+key);
+        }
+    }
+
+    @Override
+    public void deleteDeviceCodeSetCache(String deviceCode) {
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+//        System.out.println(">> <deleteDeviceCodeSetCache> setKey "+setKey);
+//        redisTemplate.opsForSet().add(setKey,deviceCode);
+        redisTemplate.opsForSet().remove(setKey, deviceCode);
+//        System.out.println(">> end <deleteDeviceCodeSetCache> setKey "+setKey);
+    }
+
+    @Override
+    public void deleteOnlineDeviceSet(String farmId, String deviceCode, String todayDateText) {
+        String setKey = BizConst.SET_FARM_DEVICE_ONLINE_PREFIX + farmId+":"+todayDateText;
+        redisTemplate.opsForSet().remove(setKey,deviceCode);
+    }
+
+    @Override
+    public void deleteChipIdHashCache(String chipId) {
+        String key = BizConst.CHIP_DEVICE_PREFIX;
+        String hashKey = chipId;
+//        System.out.println(">> <deleteChipIdHashCache> key>>"+key+",hashKey>>"+hashKey);
+        Object obj = redisTemplate.opsForHash().get(key, hashKey);
+//        System.out.println(">> obj>>"+obj);
+        if(obj == null){
+            log.error("##Error 该key>>"+key+",hashKey>>"+hashKey+"的缓存不存在.");
+        }else{
+            redisTemplate.opsForHash().delete(key,hashKey);
+        }
+
+//        Object obj = redisTemplate.opsForHash().entries(key);
+//        System.out.println(">> obj>>"+obj);
+//        if(obj == null){
+//            log.error("##Error 该key["+key+"]的缓存不存在.");
+//        }else{
+//            redisTemplate.delete(key);
+//        }
+        System.out.println(">> end <deleteChipIdHashCache> key "+key);
+    }
+
+    @Override
+    public int isExistAllDeviceSet() {
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+        Set<String> resultSet = redisTemplate.opsForSet().members(setKey);
+        return resultSet.size();
+    }
+
+    @Override
+    public boolean isExistDeviceCode(String deviceCode) {
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+//        log.info("## setKey>>"+setKey+", deviceCode>>"+deviceCode);
+        return redisTemplate.opsForSet().isMember(setKey, deviceCode);
+    }
+
+    @Override
+    public void putAllDeviceSet(List list) {
+        String setKey = BizConst.SET_ALL_DEVICE_PREFIX;
+        for(int a=0;a<list.size();a++){
+            redisTemplate.opsForSet().add(setKey,list.get(a).toString());
+        }
+        //验证
+//        Set<String> resultSet = redisTemplate.opsForSet().members("setKey");
+//        System.out.println("# resultSet.toString()>>"+resultSet.toString());
+    }
+}

+ 905 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DataServiceImpl.java

@@ -0,0 +1,905 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.EartagDataEntity;
+import com.huimv.eartag.dao.entity.EartagEnvEntity;
+import com.huimv.eartag.dao.entity.EartagHeartbeatEntity;
+import com.huimv.eartag.dao.entity.EartagRawEntity;
+import com.huimv.eartag.dao.repo.EartagDataRepo;
+import com.huimv.eartag.dao.repo.EartagEnvRepo;
+import com.huimv.eartag.dao.repo.EartagHeartbeatRepo;
+import com.huimv.eartag.dao.repo.EartagRawRepo;
+import com.huimv.eartag.utils.Const;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.producer.InputProducer;
+import com.huimv.eartag.service.ICacheService;
+import com.huimv.eartag.service.IDataService;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.service.IEartagService;
+import com.huimv.eartag.utils.DateUtil2;
+import com.huimv.eartag.utils.RegexUtil;
+import io.netty.channel.ChannelHandlerContext;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class DataServiceImpl implements IDataService {
+    @Autowired
+    private DateUtil2 dateUtil;
+    @Autowired
+    private RedisTemplate redisTemplate;
+    @Autowired
+    private EartagRawRepo rawRepo;
+    @Autowired
+    private EartagHeartbeatRepo heartbeatRepo;
+    @Autowired
+    private EartagEnvRepo envRepo;
+    @Autowired
+    private EartagDataRepo eartagDataRepo;
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+    @Autowired
+    private IDeviceService deviceService;
+    @Autowired
+    private IEartagService eartagService;
+    @Autowired
+    private InputProducer producer;
+    @Autowired
+    private RegexUtil regexUtil;
+    @Autowired
+    private ICacheService cacheService;
+
+    //处理接收数据
+    @Override
+    public String handleClientAsk(String askText) throws ParseException {
+//        System.out.println("000拆分粘包之后数据>>"+askText);
+        //--对接收的上报数据解析
+        String answer = parseAskText2(askText);
+
+        //--将原始数据保存到rabbitMQ(重构之后代码)
+        producer.sendClientAsk2(askText);
+
+        return answer;
+    }
+
+    @Override
+    public Map parseDeviceAsk(String askText) throws ParseException {
+        Map resultMap = new HashMap();
+        log.info("#开始解析Ask请求数据>>" + askText.trim().replace("\n", ""));
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        String answer = null;
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            //芯片id/设备编码
+            String idCode = dataArray[1];
+            String cmd = dataArray[2];
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+//                answer = null;
+                resultMap.put("clientType", "device");
+                resultMap.put("answerStatus", false);
+                resultMap.put("answerText", null);
+                resultMap.put("mqStatus", false);
+                resultMap.put("askText", askText);
+                return resultMap;
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+                //{读取设备编码}
+                String deviceCode = getDeviceCodeByChipId(idCode);
+                if (deviceCode == null) {
+                    log.error("异常:该芯片ID[" + idCode + "]未获取到设备编码,该设备为非法未注册设备.");
+                    resultMap.put("validStatus",false);
+                }else {
+                    answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                    log.info("##获取设备编码-应答数据>>" + answer);
+//                resultMap.put("chipId", idCode);
+//                resultMap.put("deviceCode", deviceCode);
+                    resultMap.put("validStatus",true);
+                    resultMap.put("clientType", "device");
+                    resultMap.put("answerStatus", true);
+                    resultMap.put("answerText", answer);
+                    resultMap.put("mqStatus", false);
+                    resultMap.put("askText", askText);
+                }
+                return resultMap;
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+//                answer = "hm+2+0+"+dateUtil.getNowText()+"+4+end";
+                answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                log.info("##获取服务器时间-应答数据>>" + answer);
+                resultMap.put("validStatus",true);
+                resultMap.put("clientType", "device");
+                resultMap.put("answerStatus", true);
+                resultMap.put("answerText", answer);
+                resultMap.put("mqStatus", false);
+                resultMap.put("askText", askText);
+                return resultMap;
+
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+//                heartbeatMap = new HashMap();
+//                answer = "hm+3+0+6+end";
+                answer = "hm+3+6+end";
+                log.info("##心跳包-应答数据>>" + answer);
+                resultMap.put("validStatus",true);
+                resultMap.put("clientType", "device");
+                resultMap.put("answerStatus", true);
+                resultMap.put("answerText", answer);
+                resultMap.put("mqStatus", true);
+                resultMap.put("askText", askText);
+                return resultMap;
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+//                answer = "hm+4+0+7+end";
+                answer = "hm+4+7+end";
+                log.info("##环境温度-应答数据>>" + answer);
+                resultMap.put("validStatus",true);
+                resultMap.put("clientType", "device");
+                resultMap.put("answerStatus", true);
+                resultMap.put("answerText", answer);
+                resultMap.put("mqStatus", true);
+                resultMap.put("askText", askText);
+                return resultMap;
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+                resultMap.put("validStatus",false);
+                resultMap.put("clientType", "device");
+                resultMap.put("answerStatus", false);
+                resultMap.put("answerText", null);
+                resultMap.put("mqStatus", false);
+                return resultMap;
+            }
+//            return answer;
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            //耳标应答数据(不需要应答)
+            answer = null;
+            resultMap.put("validStatus",true);
+            resultMap.put("clientType", "eartag");
+            resultMap.put("answerStatus", false);
+            resultMap.put("answerText", null);
+            resultMap.put("mqStatus", true);
+            resultMap.put("askText", askText);
+            return resultMap;
+        } else {
+            log.error("##当前请求数据为非法数据>>" + askText);
+            resultMap.put("validStatus",false);
+            resultMap.put("clientType", "不清楚设备类型");
+            resultMap.put("answerStatus", false);
+            resultMap.put("answerText", null);
+            resultMap.put("mqStatus", false);
+            return resultMap;
+        }
+    }
+
+    @Override
+    public boolean isValidDevice(String cmdHeader, String idCode, String cmd) {
+        if (cmdHeader.trim().equalsIgnoreCase("hm") && cmd.trim().equalsIgnoreCase("1")) {
+            //{读取设备编码}
+            String deviceCode = getDeviceCodeByChipId(idCode);
+            log.info("芯片id>>"+idCode+", 设备编码>>"+deviceCode);
+            if(deviceCode == null){
+                return false;
+            }else{
+                return true;
+            }
+        }else{
+            return true;
+        }
+    }
+
+    @Override
+    public String getDeviceAnswer(String cmdHeader, String cmd, String idCode) throws ParseException {
+        String answer = null;
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //获取目标服务器的通信地址和端口号(不需要处理)
+                answer = null;
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //{读取设备编码}
+                String deviceCode = getDeviceCodeByChipId(idCode);
+                answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                log.info("##获取设备编码-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+                answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                log.info("##获取服务器时间-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+                answer = "hm+3+6+end";
+                log.info("##心跳包-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+                answer = "hm+4+7+end";
+                log.info("##环境温度-应答数据>>" + answer);
+            } else {
+                log.error("##当前数据为非法数据>>");
+            }
+            return answer;
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            //耳标应答数据(不需要应答)
+           return null;
+        } else {
+            log.error("##当前请求数据为非法数据>>");
+            return null;
+        }
+    }
+
+    /**
+     * @Method      : sendBizMQ
+     * @Description : 注意:askText中第三位cmd对于耳标数据而言是耳标号,对于设备而言是命令。
+     * @Params      : [cmdHeader, cmd, askText]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/23       
+     * @Time        : 17:20
+     */
+    @Override
+    public void sendBizMQ(String cmdHeader, String cmd, String askText) {
+        askText = askText.replaceAll("\r","").replaceAll("\n","");
+        Map map = new HashMap();
+        map.put("askText",askText);
+        System.out.println("-->3.1");
+        if (cmdHeader.trim().equalsIgnoreCase("hm") && (cmd.trim().equalsIgnoreCase("3") || cmd.trim().equalsIgnoreCase("4"))) {
+            System.out.println("-->3.2");
+            //发送到设备处理消息队列
+            rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_DEVICE, Const.ROUTING_KEY_ASK_DEVICE, map);
+            System.out.println("## --> 发送设备处理模块.");
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            System.out.println("-->3.3");
+            //{发送消息}
+            if(cmd.trim().equalsIgnoreCase("ffffffffffffffff") || cmd.trim().equalsIgnoreCase("0000000000000000")){
+                log.error("舍弃掉未配置耳标号的耳标,"+askText+"");
+            }else{
+                System.out.println("-->3.4");
+                //{检查设备是否在处于工作状态或待机状态}
+                if(isWorkStatusDevice(cmdHeader)){
+                    //发送到耳标处理消息队列
+                    rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_EARTAG, Const.ROUTING_KEY_ASK_EARTAG, map);
+                    System.out.println("## --> 发送耳标处理模块.");
+                }
+            }
+        }
+        System.out.println("-->3.5");
+    }
+
+    @Override
+    public void sendEartagMQ(Map map) {
+        //发送到耳标处理消息队列
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_EARTAG, Const.ROUTING_KEY_ASK_EARTAG, map);
+    }
+
+
+    public String handleClientAsk_1(String askText) throws ParseException {
+//        System.out.println("000拆分粘包之后数据>>"+askText);
+        //--对接收的上报数据解析
+        String answer = parseAskText2(askText);
+
+        //--将原始数据保存到rabbitMQ(重构之后代码)
+        producer.sendClientAsk2(askText);
+
+        return answer;
+    }
+
+    //--处理客户端请求
+    public String handleClientAsk_old(String askText, ChannelHandlerContext ctx) throws ParseException {
+        //原始数据
+        Map rawMap = new HashMap();
+        //心跳数据
+        Map heartbeatMap = new HashMap();
+        //温度数据
+        Map envtempMap = new HashMap();
+        //耳标数据
+        JSONObject eartagJo = new JSONObject();
+        //--对接收的上报数据解析
+        String answer = parseAskText(askText, rawMap, heartbeatMap, envtempMap, eartagJo);
+        //--保存数据
+        save(rawMap, heartbeatMap, envtempMap, eartagJo);
+        //--处理分支流程
+//        handleBranch();
+        //--处理采集器信息
+        deviceService.handleDeviceInfo();
+        //--处理耳标信息
+        eartagService.handleEartagInfo();
+        return answer;
+    }
+
+    /**
+     * @Method : handleBranch
+     * @Description : 处理分支流程
+     * @Params : []
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/1/24
+     * @Time : 11:35
+     */
+    private void handleBranch() {
+        //--处理注册表数据
+        handleRegister();
+        //--处理在线记录数据
+        handleOnline();
+        //--处理状态数据
+        handleAllState();
+    }
+
+    /**
+     * @Method : handleAllState
+     * @Description : 处理状态数据
+     * @Params : []
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/1/24
+     * @Time : 14:26
+     */
+    private void handleAllState() {
+
+    }
+
+    /**
+     * @Method : handleOnline
+     * @Description : 处理在线记录数据
+     * @Params : []
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/1/24
+     * @Time : 14:26
+     */
+    private void handleOnline() {
+
+    }
+
+    /**
+     * @Method : handleRegister
+     * @Description : 处理注册表数据
+     * @Params : []
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/1/24
+     * @Time : 14:26
+     */
+    private void handleRegister() {
+        Map map = new HashMap();
+
+        //将消息携带绑定键值:topic.device.register 发送到交换机TestDirectExchange
+        rabbitTemplate.convertAndSend("deviceTopicExchange", "topic.device.register", map);
+    }
+
+    /**
+     * @Method : save
+     * @Description : 保存数据
+     * @Params : [rawMap, heartbeatMap, envtempMap, eartagJo]
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/1/24
+     * @Time : 11:35
+     */
+    private void save(Map rawMap, Map heartbeatMap, Map envtempMap, JSONObject eartagJo) throws ParseException {
+        //--保存原始数据
+        saveRawData(rawMap);
+        //心跳
+        if (heartbeatMap.size() > 0) {
+            //--保存心跳流水数据
+            saveHeartBeat(heartbeatMap);
+        }
+        //采集器温度
+        if (envtempMap.size() > 0) {
+            //--保存采集器温度流水数据
+            saveEnvTempData(envtempMap);
+        }
+        //耳标
+        if (eartagJo.size() > 0) {
+            //--保存耳标流水数据
+            saveEartagData(eartagJo);
+        }
+    }
+
+    /**
+     * 保存心跳数据
+     */
+    private void saveHeartBeat(Map heartbeatMap) {
+        String deviceCode = heartbeatMap.get("device").toString();
+        EartagHeartbeatEntity addHeartbeatEntity = new EartagHeartbeatEntity();
+        addHeartbeatEntity.setDeviceCode(deviceCode);
+        addHeartbeatEntity.setAddTime(new Timestamp(new Date().getTime()));
+        heartbeatRepo.saveAndFlush(addHeartbeatEntity);
+    }
+
+    /**
+     * 保存采集器温度数据
+     */
+    private void saveEnvTempData(Map tempMap) throws ParseException {
+        EartagEnvEntity envEntity = new EartagEnvEntity();
+        envEntity.setDeviceCode(tempMap.get("device").toString());
+        envEntity.setTemp1(Integer.parseInt(tempMap.get("temp").toString()));
+        envEntity.setTemp2(0F);
+        envEntity.setAddTime(new Timestamp(new Date().getTime()));
+        envRepo.saveAndFlush(envEntity);
+    }
+
+    /**
+     * 保存耳标数据
+     */
+    private void saveEartagData(JSONObject eartagJo) {
+        EartagDataEntity dataEntity = new EartagDataEntity();
+        dataEntity.setCmdHeader(eartagJo.getString("cmdHeader"));
+        dataEntity.setDevice(eartagJo.getString("device"));
+        dataEntity.setEarmark(eartagJo.getString("earmark"));
+        dataEntity.setBat(Integer.parseInt(eartagJo.getString("bat")));
+        dataEntity.setEarTemp(Integer.parseInt(eartagJo.getString("earTemp")));
+        dataEntity.setEarTemp1(eartagJo.getFloat("earTemp1"));
+        dataEntity.setEnvTemp(Integer.parseInt(eartagJo.getString("envTemp")));
+        dataEntity.setEnvTemp1(eartagJo.getFloat("envTemp1"));
+        dataEntity.setAct(Integer.parseInt(eartagJo.getString("act")));
+        dataEntity.setAct1(Integer.parseInt(eartagJo.getString("act1")));
+        dataEntity.setSignal1(Integer.parseInt(eartagJo.getString("signal")));
+        dataEntity.setAskTime(getAskTime(eartagJo.getString("askTime")));
+        dataEntity.setOther(eartagJo.getString("other"));
+        dataEntity.setAddTime(new Timestamp(new Date().getTime()));
+        eartagDataRepo.saveAndFlush(dataEntity);
+
+        //最新的耳标数据覆盖老数据
+        Map<String, String> map = new HashMap<>();
+        map.put("cmdHeader", dataEntity.getCmdHeader());
+        map.put("device", dataEntity.getDevice());
+        map.put("earmark", dataEntity.getEarmark());
+        map.put("bat", dataEntity.getBat().toString());
+        map.put("earTemp", dataEntity.getEarTemp().toString());
+        map.put("earTemp1", dataEntity.getEarTemp1().toString());
+        map.put("envTemp", dataEntity.getEnvTemp().toString());
+        map.put("envTemp1", dataEntity.getEnvTemp1().toString());
+        map.put("act", dataEntity.getAct().toString());
+        map.put("act1", dataEntity.getAct1().toString());
+        map.put("signal1", dataEntity.getSignal1().toString());
+        map.put("askTime", dataEntity.getAskTime());
+        map.put("other", dataEntity.getOther());
+        map.put("addTime", dataEntity.getAddTime().toString());
+        //为hash结构设置多个键值对(hmset)
+        redisTemplate.opsForHash().putAll(dataEntity.getDevice(), map);
+    }
+
+    //
+    public String getAskTime(String askTime) {
+        String newAskTime = askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) + " " + askTime.substring(8, 10) + ":" + askTime.substring(10, 12) + ":" + askTime.substring(12, 14);
+        return newAskTime;
+    }
+
+    /**
+     * 保存原始数据
+     */
+    private void saveRawData(Map rawMap) {
+        //类型、设备、命令、数据内容、日期
+        EartagRawEntity addRawEntity = new EartagRawEntity();
+        addRawEntity.setCmdHeader(rawMap.get("cmdHeader").toString());
+        addRawEntity.setDevice(rawMap.get("device").toString());
+        addRawEntity.setCmd(rawMap.get("cmd").toString());
+        addRawEntity.setAsk(rawMap.get("ask").toString());
+        addRawEntity.setAddTime(new Timestamp(new Date().getTime()));
+        rawRepo.saveAndFlush(addRawEntity);
+    }
+
+    //处理耳标数据
+    private void handleEartag(Map dataMap) {
+        log.info("耳标数据>>" + dataMap.toString());
+    }
+
+    /* 根本设备id获取设备编码 */
+    @Override
+    public String getDeviceCodeByChipId(String chipId) {
+//        ValueOperations ops = redisTemplate.opsForValue();
+//        ops.set("deviceCode", "202007239999869");
+//        String deviceCode = (String) ops.get("deviceCode");
+//        System.out.println("redis->deviceCode>>" + deviceCode);
+
+//        String deviceCode = "";
+//        if (chipId.trim().equalsIgnoreCase("a848fad42b8a")) {
+//            deviceCode = "202007239999866";
+//        } else if (chipId.trim().equalsIgnoreCase("a848fad3fefb")) {
+//            deviceCode = "202007239999873";
+//        } else {
+//            deviceCode = "202007239999869";
+//        }
+
+        //{根据芯片id读取设备编码}
+        String deviceCode = deviceService.getDeviceCodeByChipId(chipId);
+//        System.out.println("chipId>>" + chipId + " ,deviceCode>>" + deviceCode);
+        return deviceCode;
+    }
+
+    @Override
+    public void sendDeviceMQ(Map map) {
+        //发送到耳标处理消息队列
+        rabbitTemplate.convertAndSend(Const.EXCHANGE_ASK_DEVICE, Const.ROUTING_KEY_ASK_DEVICE, map);
+    }
+
+    @Override
+    public boolean isWorkStatusDevice(String idCode) {
+        String key = BizConst.DEVICE_REGISTER_PREFIX+idCode;
+        String hashKey = "deviceStatus";
+        Object deviceStatusObj = redisTemplate.opsForHash().get(key,hashKey);
+        System.out.println("## deviceStatusObj>>"+deviceStatusObj);
+        if(deviceStatusObj == null){
+            return false;
+        }else{
+            String deviceStatus = deviceStatusObj.toString();
+            if(deviceStatus.trim().equalsIgnoreCase("0") || deviceStatus.trim().equalsIgnoreCase("1")){
+                return true;
+            }else{
+                return false;
+            }
+        }
+    }
+
+    @Override
+    public boolean isEffectiveDevice(String idCode) {
+        //{检查有效设备集合}
+        return cacheService.checkEffectiveDeviceSet(idCode);
+    }
+
+    /**
+     * 解析接收数据
+     */
+    private String parseAskText2(String askText) throws ParseException {
+        log.info("#开始解析Ask请求数据>>" + askText.trim().replace("\n", ""));
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        String answer = null;
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            //芯片id/设备编码
+            String idCode = dataArray[1];
+            String cmd = dataArray[2];
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+                answer = null;
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+                //{读取设备编码}
+                String deviceCode = getDeviceCodeByChipId(idCode);
+                answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                log.info("##获取设备编码-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+//                answer = "hm+2+0+"+dateUtil.getNowText()+"+4+end";
+                answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                log.info("##获取服务器时间-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+//                heartbeatMap = new HashMap();
+//                answer = "hm+3+0+6+end";
+                answer = "hm+3+6+end";
+                log.info("##心跳包-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+//                answer = "hm+4+0+7+end";
+                answer = "hm+4+7+end";
+                log.info("##环境温度-应答数据>>" + answer);
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+            }
+            return answer;
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            //耳标应答数据(不需要应答)
+            answer = null;
+        } else {
+            log.error("##当前请求数据为非法数据>>" + askText);
+        }
+        return answer;
+    }
+
+    //old
+    private String parseAskText(String askText, Map rawMap, Map heartbeatMap, Map envTempMap, JSONObject eartagJo) throws ParseException {
+        log.info("#开始解析Ask请求数据>>" + askText.trim().replace("\n", ""));
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        String answer = null;
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            String device = dataArray[1];
+            String cmd = dataArray[2];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", cmd);
+            rawMap.put("ask", askText);
+            //耳标数据
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //不需要处理
+                answer = null;
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+                /* 读取设备编码 */
+                String deviceCode = getDeviceCodeByChipId(device);
+                answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                log.info("##获取设备编码-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+                //应答数据
+//                answer = "hm+2+0+"+dateUtil.getNowText()+"+4+end";
+                answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                log.info("##获取服务器时间-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+//                heartbeatMap = new HashMap();
+                heartbeatMap.put("device", device);
+//                answer = "hm+3+0+6+end";
+                answer = "hm+3+6+end";
+                log.info("##心跳包-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+                envTempMap.put("device", dataArray[1]);
+                envTempMap.put("temp", dataArray[4]);
+                envTempMap.put("askTime", dataArray[5]);
+                //应答数据
+//                answer = "hm+4+0+7+end";
+                answer = "hm+4+7+end";
+                log.info("##环境温度-应答数据>>" + answer);
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+            }
+            return answer;
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            //应答数据
+            answer = null;
+            //采集器原始数据
+            String device = dataArray[1];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", "");
+            rawMap.put("ask", askText);
+            rawMap.put("addTime", dateUtil.getTodayMissionText());
+            //-- 耳标数据 --//
+            //计算耳标温度
+            Double earTemp = 0D;
+            String other = dataArray[9];
+            if (other != null && other.trim().length() > 0) {
+                String[] otherArray = other.split("#");
+                String resi = otherArray[2];
+                Double temp = ln(Integer.parseInt(resi));
+                earTemp = new BigDecimal(temp).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
+            }
+            //--计算运动量
+            Integer act1Int = countAct(dataArray[1], dataArray[6]);
+            //命令头
+            eartagJo.put("cmdHeader", dataArray[0]);
+            //采集器id
+            eartagJo.put("device", dataArray[1]);
+            //耳标号
+            eartagJo.put("earmark", dataArray[2]);
+            //电池电量
+            eartagJo.put("bat", dataArray[3]);
+            //耳标温度
+            eartagJo.put("earTemp", dataArray[4]);
+            eartagJo.put("earTemp1", earTemp);
+            //环境温度
+            eartagJo.put("envTemp", dataArray[5]);
+            //运动量
+            eartagJo.put("act", dataArray[6]);
+            eartagJo.put("act1", act1Int);
+            //信号强度
+            eartagJo.put("signal", dataArray[7]);
+            //采集时间
+            eartagJo.put("askTime", dataArray[8]);
+            //预留字段
+            eartagJo.put("other", dataArray[9]);
+        } else {
+            log.error("##当前请求数据为非法数据>>" + askText);
+            //采集器原始数据
+            String device = dataArray[1];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", "");
+            rawMap.put("ask", askText);
+//            rawMap.put("addTime",dateUtil.getTodayMissionText());
+        }
+        return answer;
+    }
+
+    /**
+     * @Method : countAct
+     * @Description : 计算act数值
+     * @Params : [deviceCode, nowAct0]
+     * @Return : java.lang.Integer
+     * @Author : ZhuoNing
+     * @Date : 2022/1/18
+     * @Time : 15:25
+     */
+    private Integer countAct(String deviceCode, String nowAct) {
+        //读取hash
+        Object actObj = redisTemplate.opsForHash().get(deviceCode, "act");
+        if (actObj == null) {
+            //--初始化最新的redis记录
+            initRedisObj(deviceCode);
+            Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
+            if (lastAct == null) {
+                log.error("#--- redis数据库有问题,请检查redis是否能正常连接 ---# ");
+                return 0;
+            }
+        }
+        Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
+        Integer act1 = Integer.parseInt(nowAct) - Integer.parseInt(lastAct.toString());
+//        redisTemplate.opsForHash().put(deviceCode, "act1", act1);
+        return act1;
+    }
+
+    /**
+     * 初始化redis最新记录
+     */
+    private void initRedisObj(String deviceCode) {
+        System.out.println("deviceCode>>" + deviceCode);
+        //
+//        Optional optional = eartagDataRepo.getLastEartagData(deviceCode);
+        EartagDataEntity lastEartagDataEntity = eartagDataRepo.getLastEartagData(deviceCode);
+        if (lastEartagDataEntity != null) {
+//            EartagDataEntity lastEartagDataEntity = (EartagDataEntity) optional.get();
+            System.out.println("## lastEartagDataEntity.toString>>" + lastEartagDataEntity.toString());
+            //--从数据库读取最新记录并覆盖redis
+            Map<String, String> map = new HashMap<>();
+            map.put("cmdHeader", lastEartagDataEntity.getCmdHeader());
+            map.put("device", lastEartagDataEntity.getDevice());
+            map.put("earmark", lastEartagDataEntity.getEarmark());
+            map.put("bat", lastEartagDataEntity.getBat().toString());
+            map.put("earTemp", lastEartagDataEntity.getEarTemp().toString());
+            map.put("earTemp1", lastEartagDataEntity.getEarTemp1().toString());
+            map.put("envTemp", lastEartagDataEntity.getEnvTemp().toString());
+            map.put("envTemp1", lastEartagDataEntity.getEnvTemp1().toString());
+            map.put("act", lastEartagDataEntity.getAct().toString());
+            map.put("act1", lastEartagDataEntity.getAct1().toString());
+            map.put("signal1", lastEartagDataEntity.getSignal1().toString());
+            map.put("askTime", lastEartagDataEntity.getAskTime());
+            map.put("other", lastEartagDataEntity.getOther());
+            map.put("addTime", lastEartagDataEntity.getAddTime().toString());
+            //为hash结构设置多个键值对(hmset)
+            redisTemplate.opsForHash().putAll(deviceCode, map);
+        }
+    }
+
+    public static double A = 0.00335396319311466;
+    public static double B = 0.000256376549039663;
+    public static double C = 0.00000248933580817244;
+    public static double D = 0.0000000753805242068686;
+    public static double E = -0.0000000204758173596178;
+
+    //保留一位小数
+    public static double changeDouble(Double dou) {
+        NumberFormat nf = new DecimalFormat("0.0 ");
+        dou = Double.parseDouble(nf.format(dou));
+        return dou;
+    }
+
+    public static double ln(int rv) {
+        int R_REF = 10000;
+        double ln = Math.log((double) rv / R_REF);
+        //保留一位小数
+        return changeDouble(1 / (A + B * ln + C * Math.pow(ln, 2) + D * Math.pow(ln, 3) + E * Math.pow(ln, 4)) - 273.15) + 0.001;
+    }
+
+    //暂存老代码
+    private String parseAskText_0(String askText, Map rawMap, Map heartbeatMap, Map envTempMap, Map eartagMap) throws ParseException {
+        log.info("#开始解析Ask请求数据>>" + askText.trim().replace("\n", ""));
+        String[] dataArray = askText.split("\\+");
+        String cmdHeader = dataArray[0];
+        String answer = null;
+        heartbeatMap = null;
+        envTempMap = null;
+        eartagMap = null;
+        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
+            //采集器原始数据
+            String device = dataArray[1];
+            String cmd = dataArray[2];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", cmd);
+            rawMap.put("ask", askText);
+//            rawMap.put("addTime",dateUtil.getTodayMissionText());
+            //耳标数据
+            eartagMap = null;
+            //采集器应答数据
+            if (cmd.trim().equalsIgnoreCase("0")) {
+                //需要不处理,默认cmdHeader = null
+                answer = null;
+            } else if (cmd.trim().equalsIgnoreCase("1")) {
+                //获取设备编码
+                /* 读取设备编码 */
+                String deviceCode = getDeviceCodeByChipId(device);
+                answer = "hm+1+0+" + deviceCode + "+123+8+end";
+                log.info("##获取设备编码-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("2")) {
+                //获取服务器时间命令
+                //应答数据
+//                answer = "hm+2+0+"+dateUtil.getNowText()+"+4+end";
+                answer = "hm+2+" + dateUtil.getNowText() + "+4+end";
+                log.info("##获取服务器时间-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("3")) {
+                //心跳包命令
+                heartbeatMap = new HashMap();
+                heartbeatMap.put("device", device);
+//                answer = "hm+3+0+6+end";
+                answer = "hm+3+6+end";
+                log.info("##心跳包-应答数据>>" + answer);
+            } else if (cmd.trim().equalsIgnoreCase("4")) {
+                //环境温度-设备、数值、上传时间
+                envTempMap = new HashMap();
+                envTempMap.put("device", dataArray[1]);
+                envTempMap.put("temp", dataArray[4]);
+                envTempMap.put("askTime", dataArray[5]);
+                System.out.println("envTempMap.toString()>>" + envTempMap.toString());
+                //应答数据
+//                answer = "hm+4+0+7+end";
+                answer = "hm+4+7+end";
+                log.info("##环境温度-应答数据>>" + answer);
+            } else {
+                log.error("##当前数据为非法数据>>" + askText);
+            }
+            return answer;
+        } else if (cmdHeader.trim().equalsIgnoreCase("zj")) {
+            //应答数据
+            answer = null;
+            //采集器原始数据
+            String device = dataArray[1];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", "");
+            rawMap.put("ask", askText);
+            rawMap.put("addTime", dateUtil.getTodayMissionText());
+            //耳标数据
+            eartagMap = new HashMap();
+            //命令头
+            eartagMap.put("cmdHeader", dataArray[0]);
+            //采集器id
+            eartagMap.put("device", dataArray[1]);
+            //耳标号
+            eartagMap.put("earmark", dataArray[2]);
+            //电池电量
+            eartagMap.put("bat", dataArray[3]);
+            //耳标温度
+            eartagMap.put("earTemp", dataArray[4]);
+            //环境温度
+            eartagMap.put("envTemp", dataArray[5]);
+            //运动量
+            eartagMap.put("act", dataArray[6]);
+            //信号强度
+            eartagMap.put("signal", dataArray[7]);
+            //采集时间
+            eartagMap.put("askTime", dataArray[8]);
+            //预留字段
+            eartagMap.put("other", dataArray[9]);
+            System.out.println("11111111111111111 >>" + eartagMap.toString());
+        } else {
+            log.error("##当前请求数据为非法数据>>" + askText);
+            //采集器原始数据
+            String device = dataArray[1];
+            rawMap.put("cmdHeader", cmdHeader);
+            rawMap.put("device", device);
+            rawMap.put("cmd", "");
+            rawMap.put("ask", askText);
+//            rawMap.put("addTime",dateUtil.getTodayMissionText());
+        }
+        return answer;
+    }
+
+}

+ 957 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceManageServiceImpl.java

@@ -0,0 +1,957 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.*;
+import com.huimv.eartag.dao.repo.*;
+import com.huimv.eartag.service.ICacheService;
+import com.huimv.eartag.service.IDeviceManageService;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.utils.JSONUtil;
+import com.huimv.eartag.utils.MathUtil;
+import com.huimv.eartag.vo.FarmAllStatusVo;
+import com.huimv.eartag.vo.Result;
+import com.huimv.eartag.vo.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import javax.persistence.criteria.Order;
+import javax.persistence.criteria.Predicate;
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class DeviceManageServiceImpl implements IDeviceManageService {
+    @Value("${device.online.access_mode}")
+    private String deviceOnlineAccessMode;
+    @Value("${service.farmAllStatus.host}")
+    private String serviceFarmAllStatusHost;
+    @Value("${service.farmAllStatus.ip}")
+    private String serviceFarmAllStatusIp;
+    @Value("${service.farmAllStatus.url}")
+    private String serviceFarmAllStatusUrl;
+    @Autowired
+    private ICacheService cacheService;
+    @Autowired
+    private EartarFarmAllStatusRepo farmAllStatusRepo;
+    @Autowired
+    private EartagDeviceRegisterRepo deviceRegisterRepo;
+    @Autowired
+    private EartagEartagRegisterRepo eartagRegisterRepo;
+    @Autowired
+    private EartagDeviceOnlineRepo deviceOnlineRepo;
+    @Autowired
+    private EartagEartagOnlineRepo eartagOnlineRepo;
+    @Autowired
+    private EartagDeviceEartagCountRepo deviceEartagCountRepo;
+    @Autowired
+    private EartagEnvRepo eartagEnvRepo;
+    @Autowired
+    private EartagHeartbeatRepo heartbeatRepo;
+
+
+    /**
+     * @Method : listDeviceEnvtempByDeviceCode
+     * @Description :
+     * @Params : [deviceCode]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 20:55
+     */
+    @Override
+    public Result listDeviceEnvtempByDeviceCode(String deviceCode) throws ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        //
+        List<EartagEnvEntity> eartagEnvEntityList = eartagEnvRepo.getDeviceEnvtempByDeviceCode(deviceCode, todayDateText);
+        if (eartagEnvEntityList.size() == 0) {
+            return new Result(BizConst.CODE_ENVTEMP_FLOW_NO_EXIST, BizConst.MSG_ENVTEMP_FLOW_NO_EXIST, false);
+        } else {
+            JSONArray dataJa = new JSONArray();
+            for (EartagEnvEntity eartagEnvEntity : eartagEnvEntityList) {
+                JSONObject eartagEnvJo = JSONUtil.convertEntityToJSONObject(eartagEnvEntity);
+                eartagEnvJo.put("addTime", du.formatDatetimeText(eartagEnvJo.getDate("addTime")));
+                dataJa.add(eartagEnvJo);
+            }
+            return new Result(ResultCode.SUCCESS, dataJa);
+        }
+    }
+
+    /**
+     * @Method : listDeviceEartagOnlineCountByDeviceCodeInPager
+     * @Description : 显示设备关联耳标统计(带分页)
+     * @Params : [deviceCode, earmark, addDate, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/9
+     * @Time : 20:08
+     */
+    @Override
+    public Result listDeviceEartagOnlineCountByDeviceCodeInPager(String deviceCode, String earmark, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagDeviceEartagCountEntity> sf = (Specification<EartagDeviceEartagCountEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        return new Result(ResultCode.SUCCESS, deviceEartagCountRepo.findAll(sf, pageable));
+    }
+
+    @Override
+    public Result listHeartbeatByDeviceCodeAndDateInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        System.out.println("## addDate>>" + addDate);
+        //
+        Specification<EartagHeartbeatEntity> sf = (Specification<EartagHeartbeatEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagHeartbeatEntity> pageHeartbeatEntity = heartbeatRepo.findAll(sf, pageable);
+        DateUtil dateUtil = new DateUtil();
+        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageHeartbeatEntity));
+        JSONArray contentJa = pageJo.getJSONArray("content");
+        for(int a=0;a<contentJa.size();a++){
+            JSONObject contentJo = contentJa.getJSONObject(a);
+            contentJo.put("addTime",dateUtil.formatDatetimeText(contentJo.getDate("addTime")));
+        }
+        return new Result(ResultCode.SUCCESS, pageJo);
+    }
+
+    /**
+     * @Method : listDeviceEnvtempByDeviceCodeInPager
+     * @Description : 分页查询设备温度
+     * @Params : [deviceCode, addDate, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/9
+     * @Time : 21:27
+     */
+    @Override
+    public Result listDeviceEnvtempByDeviceCodeInPager(String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagEnvEntity> sf = (Specification<EartagEnvEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagEnvEntity> pageEnvEntity = eartagEnvRepo.findAll(sf, pageable);
+        DateUtil dateUtil = new DateUtil();
+        String pageStr = JSONObject.toJSONString(pageEnvEntity);
+        JSONObject pageJo = JSONObject.parseObject(pageStr);
+        JSONArray contentJa = pageJo.getJSONArray("content");
+        for(int a=0;a<contentJa.size();a++){
+            JSONObject contentJo = contentJa.getJSONObject(a);
+            contentJo.put("addTime",dateUtil.formatDatetimeText(contentJo.getDate("addTime")));
+        }
+        return new Result(ResultCode.SUCCESS, pageJo);
+    }
+
+    /**
+     * @Method : listDeviceRegisterInPager
+     * @Description : 列表查询分页信息(分页)
+     * @Params : [farmId, deviceCode, alias, startDate, endDate, activeStatus, liveStatus, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/9
+     * @Time : 22:28
+     */
+    @Override
+    public Result listDeviceRegisterInPager(String farmId, String deviceCode, String alias, String startDate, String endDate, Integer activeStatus, Integer liveStatus, Integer pageNo, Integer pageSize) throws ParseException {
+//        System.out.println("# farmId>>"+farmId);
+//        System.out.println("# deviceCode>>"+deviceCode);
+//        System.out.println("# alias>>"+alias);
+//        System.out.println("# startDate>>"+startDate);
+//        System.out.println("# endDate>>"+endDate);
+//        System.out.println("# activeStatus>>"+activeStatus);
+//        System.out.println("# liveStatus>>"+liveStatus);
+//        System.out.println("# pageNo>>"+pageNo);
+//        System.out.println("# pageSize>>"+pageSize);
+        //
+        Specification<EartagDeviceRegisterEntity> sf = (Specification<EartagDeviceRegisterEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //farmId
+            if (null != farmId && farmId.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //alias
+            if (null != alias && alias.trim().length() > 0) {
+                predList.add(criteriaBuilder.like(root.get("deviceAlias").as(String.class), alias));
+            }
+            //startDate
+            if (null != startDate && startDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(startDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //endDate
+            if (null != endDate && endDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(endDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //activeStatus
+            if (null != activeStatus) {
+                predList.add(criteriaBuilder.equal(root.get("activeStatus").as(Integer.class), activeStatus));
+            }
+            //liveStatus
+            if (null != liveStatus) {
+                predList.add(criteriaBuilder.equal(root.get("deviceStatus").as(Integer.class), liveStatus));
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        DateUtil dateUtil = new DateUtil();
+        //{}
+        Page<EartagDeviceRegisterEntity> pageDeviceRegister = deviceRegisterRepo.findAll(sf, pageable);
+        //////////////////////////////////////////////////////////////////////////////////
+//        JSONObject outDataJo = new JSONObject();
+//        outDataJo.put("pageable", pageDeviceRegister.getPageable());
+//        outDataJo.put("last", pageDeviceRegister.isLast());
+//        outDataJo.put("totalElements", pageDeviceRegister.getTotalElements());
+//        outDataJo.put("totalPages", pageDeviceRegister.getTotalPages());
+//        outDataJo.put("number", pageDeviceRegister.getNumber());
+//        outDataJo.put("size", pageDeviceRegister.getSize());
+//        outDataJo.put("sort", pageDeviceRegister.getSort());
+//        outDataJo.put("numberOfElements", pageDeviceRegister.getNumberOfElements());
+//        outDataJo.put("first", pageDeviceRegister.isFirst());
+//        outDataJo.put("empty", pageDeviceRegister.isEmpty());
+//
+//        List<EartagDeviceRegisterEntity> deviceRegisterEntityList = pageDeviceRegister.getContent();
+////        System.out.println("## deviceRegisterEntityList.size>>"+deviceRegisterEntityList.size());
+//        JSONArray outJa = new JSONArray();
+//        outDataJo.put("content", outJa);
+//        for (EartagDeviceRegisterEntity deviceRegisterEntity : deviceRegisterEntityList) {
+//            JSONObject outJo = new JSONObject();
+//            outJa.add(outJo);
+//            outJo.put("id", deviceRegisterEntity.getId());
+//            outJo.put("deviceCode", deviceRegisterEntity.getDeviceCode());
+//            outJo.put("countyCode", deviceRegisterEntity.getCountyCode());
+//            outJo.put("countyName", deviceRegisterEntity.getCountyName());
+//            outJo.put("farmId", deviceRegisterEntity.getFarmId());
+//            outJo.put("farmName", deviceRegisterEntity.getFarmName());
+//            outJo.put("typeF", deviceRegisterEntity.getTypeF());
+//            outJo.put("stage", deviceRegisterEntity.getStage());
+//            outJo.put("pigpenId", deviceRegisterEntity.getPigpenId());
+//            outJo.put("unitId", deviceRegisterEntity.getUnitId());
+////            outJo.put("registerTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getRegisterTime()));
+////            outJo.put("lastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getLastTime()));
+//            outJo.put("activeStatus", deviceRegisterEntity.getActiveStatus());
+////            outJo.put("activeTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getActiveTime()));
+//            outJo.put("deviceStatus", deviceRegisterEntity.getDeviceStatus());
+//            outJo.put("deviceAlias", deviceRegisterEntity.getDeviceAlias());
+//            outJo.put("location", deviceRegisterEntity.getLocation());
+//            outJo.put("remark", deviceRegisterEntity.getRemark());
+//            outJo.put("createDate", deviceRegisterEntity.getCreateDate());
+//            outJo.put("updateType", deviceRegisterEntity.getUpdateType());
+//        }
+        ///////////////////////////////////////////////////////////////////////
+        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageDeviceRegister));
+        JSONArray contentJa = pageJo.getJSONArray("content");
+        for(int a=0;a<contentJa.size();a++){
+            JSONObject contentJo = contentJa.getJSONObject(a);
+            contentJo.put("registerTime",dateUtil.formatDatetimeText(contentJo.getDate("registerTime")));
+            contentJo.put("lastTime",dateUtil.formatDatetimeText(contentJo.getDate("lastTime")));
+            contentJo.put("activeTime",dateUtil.formatDatetimeText(contentJo.getDate("activeTime")));
+        }
+        return new Result(ResultCode.SUCCESS, pageJo);
+    }
+
+    @Override
+    public Result listDeviceOnlineCountByDeviceCodeInPager(String deviceCode, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagDeviceOnlineEntity> sf = (Specification<EartagDeviceOnlineEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            List<Predicate> predList = new ArrayList<>();
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //startDate
+            if (null != startDate && startDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(startDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //endDate
+            if (null != endDate && endDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("addDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(endDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        DateUtil dateUtil = new DateUtil();
+        //{}
+        Page<EartagDeviceOnlineEntity> pageDeviceOnline = deviceOnlineRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        List<EartagDeviceOnlineEntity> deviceRegisterEntityList = pageDeviceOnline.getContent();
+//        System.out.println("## deviceRegisterEntityList.size>>"+deviceRegisterEntityList.size());
+        for (EartagDeviceOnlineEntity deviceRegisterEntity : deviceRegisterEntityList) {
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", deviceRegisterEntity.getId());
+            outJo.put("deviceCode", deviceRegisterEntity.getDeviceCode());
+            outJo.put("alias", deviceRegisterEntity.getAlias());
+            outJo.put("heartbeatTotal", deviceRegisterEntity.getHeartbeatTotal());
+            outJo.put("envtempTotal", deviceRegisterEntity.getEnvtempTotal());
+            outJo.put("eartagTotal", deviceRegisterEntity.getEartagTotal());
+            outJo.put("lastEnvtemp", deviceRegisterEntity.getLastEnvtemp());
+            outJo.put("lastEartag", deviceRegisterEntity.getLastEartag());
+            outJo.put("heartbeatFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getHeartbeatFirstTime()));
+            outJo.put("heartbeatLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getHeartbeatLastTime()));
+            outJo.put("envtempFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEnvtempFirstTime()));
+            outJo.put("envtempLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEnvtempLastTime()));
+            outJo.put("eartagFirstTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEartagFirstTime()));
+            outJo.put("eartagLastTime", dateUtil.formatDatetimeText(deviceRegisterEntity.getEartagLastTime()));
+            outJo.put("addDate", deviceRegisterEntity.getAddDate());
+            outJo.put("farmId", deviceRegisterEntity.getFarmId());
+        }
+        outDataJo.put("pageable", pageDeviceOnline.getPageable());
+        outDataJo.put("last", pageDeviceOnline.isLast());
+        outDataJo.put("totalElements", pageDeviceOnline.getTotalElements());
+        outDataJo.put("totalPages", pageDeviceOnline.getTotalPages());
+        outDataJo.put("number", pageDeviceOnline.getNumber());
+        outDataJo.put("size", pageDeviceOnline.getSize());
+        outDataJo.put("sort", pageDeviceOnline.getSort());
+        outDataJo.put("numberOfElements", pageDeviceOnline.getNumberOfElements());
+        outDataJo.put("first", pageDeviceOnline.isFirst());
+        outDataJo.put("empty", pageDeviceOnline.isEmpty());
+        return new Result(ResultCode.SUCCESS, outDataJo);
+    }
+
+    @Override
+    public void countEffectiveDeviceTotal (JSONObject deviceRegisterJo) {
+        String farmId = deviceRegisterJo.getString("farmId");
+        //{}
+        Integer effectiveDeviceTotal = getEffectiveDeviceSum(farmId);
+        System.out.println("## effectiveDeviceTotal>>"+effectiveDeviceTotal);
+        //{设置设备总数}
+        cacheService.putDeviceTotal_(effectiveDeviceTotal,farmId);
+    }
+
+    @Override
+    public void countFarmAllStatus(JSONObject deviceRegisterJo) throws ParseException {
+        String farmId = deviceRegisterJo.getString("farmId");
+        //{}
+        remoteProcessFarmAllStatus(farmId);
+    }
+
+    @Override
+    public Result listDeviceEartagOnlineStatusByDeviceCodeAndDate(String deviceCode, String earmark, String addDate) {
+        //
+        Specification<EartagDeviceEartagCountEntity> sf = (Specification<EartagDeviceEartagCountEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("total")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.findAll(sf);
+        JSONArray dataJa = new JSONArray();
+        for(EartagDeviceEartagCountEntity deviceEartagCountEntity:deviceEartagCountEntityList){
+            JSONObject eartagJo = new JSONObject();
+            dataJa.add(eartagJo);
+            String earmark1 = deviceEartagCountEntity.getEarmark();
+//            eartagJo.put("earmark",earmark1.substring(9,earmark1.length()));
+            eartagJo.put("earmark",earmark1);
+            eartagJo.put("value",deviceEartagCountEntity.getTotal());
+        }
+        return new Result(ResultCode.SUCCESS, dataJa);
+    }
+
+    @Override
+    public void remoteProcessFarmAllStatus(String farmId) throws ParseException {
+        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+
+        RestTemplate restTemplate = new RestTemplate();
+
+        String url = "http://" + serviceFarmAllStatusHost + ":" + serviceFarmAllStatusIp + serviceFarmAllStatusUrl;
+        System.out.println("## url>>"+url);
+
+        FarmAllStatusVo farmAllStatusVo = new FarmAllStatusVo();
+        farmAllStatusVo.setFarmId(farmId);
+        farmAllStatusVo.setTodayDateText(todayDateText);
+        farmAllStatusVo.setTodayDate(todayDate);
+        farmAllStatusVo.setNowTimestamp(nowTimestamp);
+        //{}
+        String result = restTemplate.postForObject(url,farmAllStatusVo,String.class);
+        System.out.println("result>>"+result);
+    }
+
+    @Override
+    public void remoteProcessFarmAllStatus2(String farmId) throws ParseException {
+        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+
+        RestTemplate restTemplate = new RestTemplate();
+        String host = "192.168.1.30";
+        String port = "8092";
+        String service = "/deviceController/updateFarmAllStatus";
+        String url = "http://" + host + ":" + port + service+"?farmId="+farmId+"&todayDateText="+todayDateText+"&todayDate="+todayDate+"&nowTimestamp="+nowTimestamp;
+        System.out.println("## url>>"+url);
+        //{}
+        String result = restTemplate.getForObject(url,String.class);
+        System.out.println("result>>"+result);
+    }
+
+    public Integer getEffectiveDeviceSum(String farmId){
+        List<Object[]> deviceRegisterList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
+        Object[] deviceRegObj = (Object[]) deviceRegisterList.get(0);
+        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+deviceRegObj[0].toString());
+        //设备总数
+        return Integer.parseInt(deviceRegObj[0].toString());
+    }
+    /**
+     * @Method : listOnlineDevice
+     * @Description :
+     * @Params : [farmId, deviceCode, alias, addDate, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 20:55
+     */
+    @Override
+    public Result listOnlineDevice(String farmId, String deviceCode, String alias, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        String todayDate = dateUtil.getTodayDateText();
+        //* 这里提供2种方式:1、从数据库读取 2、从缓存中取数(后期优化),但是同时提供2种方式都可用,防止缓存方式失效 */
+//        System.out.println("deviceOnlineAccessMode>>" + deviceOnlineAccessMode);
+        if (deviceOnlineAccessMode.trim().equalsIgnoreCase("mysql")) {
+            //
+            return listDeviceOnlineFromMySQL(farmId, addDate, deviceCode, alias, pageNo, pageSize);
+        } else {
+            //
+            return listDeviceOnlineFromCache(farmId, todayDate);
+        }
+    }
+
+    //分页查询
+    private Result listDeviceOnlineFromMySQL(String farmId, String addDate, String deviceCode, String alias, Integer pageNo, Integer pageSize) throws ParseException {
+//        //
+//        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByFarmIdAndCreateDate(farmId,addDate);
+//        if(deviceOnlineEntityList.size()==0){
+//            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST,BizConst.MSG_DEVICE_ONLINE_NO_EXIST,false);
+//        }else{
+//            return new Result(ResultCode.SUCCESS,JSONObject.toJSONString(deviceOnlineEntityList));
+//        }
+        Integer liveStatus = 1;
+        DateUtil dateUtil = new DateUtil();
+        //
+        Specification<EartagDeviceOnlineEntity> sf = (Specification<EartagDeviceOnlineEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //
+            if (null != farmId && farmId.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("addDate").as(Date.class), new Date(dateUtil.parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //
+            if (null != alias && alias.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("alias").as(String.class), alias));
+            }
+            predList.add(criteriaBuilder.equal(root.get("liveStatus").as(Integer.class), liveStatus));
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+//            orders.add(criteriaBuilder.desc(root.get("id")));
+            orders.add(criteriaBuilder.desc(root.get("lastTime")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagDeviceOnlineEntity> pageDeviceOnlineEntity = deviceOnlineRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        outDataJo.put("pageable",pageDeviceOnlineEntity.getPageable());
+        outDataJo.put("last",pageDeviceOnlineEntity.isLast());
+        outDataJo.put("totalElements",pageDeviceOnlineEntity.getTotalElements());
+        outDataJo.put("totalPages",pageDeviceOnlineEntity.getTotalPages());
+        outDataJo.put("number",pageDeviceOnlineEntity.getNumber());
+        outDataJo.put("size",pageDeviceOnlineEntity.getSize());
+        outDataJo.put("sort",pageDeviceOnlineEntity.getSort());
+        outDataJo.put("numberOfElements",pageDeviceOnlineEntity.getNumberOfElements());
+        outDataJo.put("first",pageDeviceOnlineEntity.isFirst());
+        outDataJo.put("empty",pageDeviceOnlineEntity.isEmpty());
+
+        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = pageDeviceOnlineEntity.getContent();
+        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>deviceOnlineEntityList.size>>"+deviceOnlineEntityList.size());
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content",outJa);
+        for(EartagDeviceOnlineEntity deviceOnlineEntity:deviceOnlineEntityList){
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id",deviceOnlineEntity.getId());
+            outJo.put("deviceCode",deviceOnlineEntity.getDeviceCode());
+            outJo.put("alias",deviceOnlineEntity.getAlias());
+            outJo.put("heartbeatTotal",deviceOnlineEntity.getHeartbeatTotal());
+            outJo.put("envtempTotal",deviceOnlineEntity.getEnvtempTotal());
+            outJo.put("eartagTotal",deviceOnlineEntity.getEartagTotal());
+            outJo.put("firstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getFirstTime()));
+            outJo.put("lastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getLastTime()));
+            outJo.put("lastEnvtemp",deviceOnlineEntity.getLastEnvtemp());
+            outJo.put("lastEartag",deviceOnlineEntity.getLastEartag());
+            outJo.put("addDate",deviceOnlineEntity.getAddDate());
+            outJo.put("farmId",deviceOnlineEntity.getFarmId());
+            outJo.put("heartbeatFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getHeartbeatFirstTime()));
+            outJo.put("heartbeatLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getHeartbeatLastTime()));
+            outJo.put("envtempFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEnvtempFirstTime()));
+            outJo.put("envtempLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEnvtempLastTime()));
+            outJo.put("eartagFirstTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEartagFirstTime()));
+            outJo.put("eartagLastTime",dateUtil.formatDatetimeText(deviceOnlineEntity.getEartagLastTime()));
+        }
+        return new Result(ResultCode.SUCCESS, outDataJo);
+    }
+
+    /**
+     * @Method : listDeviceEartagOnlineCountByDeviceCode
+     * @Description :
+     * @Params : [deviceCode]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 17:13
+     */
+    @Override
+    public Result listDeviceEartagOnlineCountByDeviceCode(String deviceCode) throws ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        //
+        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getOnlineEartagByDeviceCode(deviceCode, todayDateText);
+        if (deviceEartagCountEntityList.size() == 0) {
+            return new Result(BizConst.CODE_DEVICE_EARTAG_COUNT_NO_EXIST, BizConst.MSG_DEVICE_EARTAG_COUNT_NO_EXIST, false);
+        } else {
+            return new Result(ResultCode.SUCCESS, JSON.toJSON(deviceEartagCountEntityList));
+        }
+    }
+
+    /**
+     * @Method : listDeviceOnlineStatusByDeviceCode
+     * @Description : 列表在线设备关联在线耳标统计
+     * @Params : [deviceCode, pastDays]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 17:13
+     */
+    @Override
+    public Result listDeviceOnlineStatusByDeviceCode(String deviceCode, Integer pastDays) throws ParseException {
+        DateUtil du = new DateUtil();
+        DateUtil dateUtil = new DateUtil();
+        String pastDate = dateUtil.getPastDate(pastDays);
+        String todayDate = dateUtil.getTodayDateText();
+        //
+        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByDeviceCode(deviceCode, pastDate, todayDate);
+        if (deviceOnlineEntityList.size() > 0) {
+            List<String> pastDateList = du.getPastIntervalsASC(pastDays);
+            JSONArray dataJa = new JSONArray();
+            for (String pastDayDate : pastDateList) {
+                JSONObject newJo = new JSONObject();
+                dataJa.add(newJo);
+                newJo.put("time", pastDayDate);
+                boolean ieFound = false;
+                for (EartagDeviceOnlineEntity deviceOnlineEntity : deviceOnlineEntityList) {
+                    int compareTo = du.parseDate(pastDayDate).compareTo(deviceOnlineEntity.getAddDate());
+                    if (compareTo == 0) {
+                        newJo.put("value", 1);
+                        ieFound = true;
+                        break;
+                    }
+                }
+                if (!ieFound) {
+                    newJo.put("value", 0);
+                }
+            }
+            return new Result(ResultCode.SUCCESS, dataJa);
+        } else {
+            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : listDeviceOnlineByDeviceCode
+     * @Description : 查询单个设备N天在线记录
+     * @Params : [deviceCode]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 14:08
+     */
+    @Override
+    public Result listDeviceOnlineCountByDeviceCode(String deviceCode, Integer pastDays) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        String pastDate = dateUtil.getPastDate(pastDays);
+        String todayDate = dateUtil.getTodayDateText();
+        System.out.println("# deviceCode>>"+deviceCode);
+        System.out.println("# pastDate>>"+pastDate);
+        System.out.println("# todayDate>>"+todayDate);
+        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByDeviceCode(deviceCode, pastDate, todayDate);
+        System.out.println("deviceOnlineEntityList.size>>"+deviceOnlineEntityList.size());
+        if (deviceOnlineEntityList.size() > 0) {
+            JSONArray dataJa = new JSONArray();
+            for (EartagDeviceOnlineEntity deviceOnlineEntity : deviceOnlineEntityList) {
+                JSONObject newJo = new JSONObject();
+                dataJa.add(newJo);
+                newJo.put("time", dateUtil.formatDateText(deviceOnlineEntity.getAddDate()));
+                newJo.put("value1", deviceOnlineEntity.getHeartbeatTotal());
+                newJo.put("value2", deviceOnlineEntity.getEnvtempTotal());
+                newJo.put("value3", deviceOnlineEntity.getEartagTotal());
+            }
+            return new Result(ResultCode.SUCCESS, dataJa);
+        } else {
+            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : getDeviceRegisterByDeviceCode
+     * @Description : 通过设备编号显示设备注册信息
+     * @Params : [deviceCode]
+     * @Return : void
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 13:55
+     */
+    @Override
+    public Result getDeviceRegisterByDeviceCode(String deviceCode) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        //
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
+        if (deviceRegisterEntity == null) {
+            log.error(BizConst.MSG_DEVICE_REGISTER_NO_EXIST);
+            return new Result(BizConst.CODE_DEVICE_REGISTER_NO_EXIST, BizConst.MSG_DEVICE_REGISTER_NO_EXIST, false);
+        } else {
+            JSONObject resultJo = (JSONObject) JSON.toJSON(deviceRegisterEntity);
+            resultJo.put("activeTime", dateUtil.formatDatetimeText(resultJo.getDate("activeTime")));
+            resultJo.put("registerTime", dateUtil.formatDatetimeText(resultJo.getDate("registerTime")));
+            resultJo.put("lastTime", dateUtil.formatDatetimeText(resultJo.getDate("lastTime")));
+            return new Result(ResultCode.SUCCESS, resultJo);
+        }
+    }
+
+    /**
+     * @Method : listOnlineDevice
+     * @Description : 显示在线设备记录
+     * @Params : [farmId]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 13:21
+     */
+    @Override
+    public Result listOnlineDevice(String farmId, String date) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        if (date == null) {
+            date = dateUtil.getTodayDateText();
+        }
+        //* 这里提供2种方式:1、从数据库读取 2、从缓存中取数(后期优化),但是同时提供2种方式都可用,防止缓存方式失效 */
+        System.out.println("deviceOnlineAccessMode>>" + deviceOnlineAccessMode);
+        if (deviceOnlineAccessMode.trim().equalsIgnoreCase("mysql")) {
+            //
+            return listDeviceOnlineFromMySQL(farmId, date);
+        } else {
+            //
+            return listDeviceOnlineFromCache(farmId, date);
+        }
+    }
+
+
+    //从缓存读取在线记录(后期优化)
+    private Result listDeviceOnlineFromCache(String farmId, String todayDate) {
+
+
+
+        return null;
+    }
+
+    //从数据库读取在线记录
+    private Result listDeviceOnlineFromMySQL(String farmId, String todayDate) throws ParseException {
+        DateUtil du = new DateUtil();
+        //
+        List<EartagDeviceOnlineEntity> deviceOnlineEntityList = deviceOnlineRepo.getDeviceOnlineByFarmIdAndCreateDate(farmId, todayDate);
+        if (deviceOnlineEntityList.size() == 0) {
+            return new Result(BizConst.CODE_DEVICE_ONLINE_NO_EXIST, BizConst.MSG_DEVICE_ONLINE_NO_EXIST, false);
+        } else {
+//            for(EartagDeviceOnlineEntity deviceOnlineEntity:deviceOnlineEntityList){
+//                deviceOnlineEntity.setHeartbeatFirstTime(du.formatDatetimeText());
+//            }
+            JSONArray resultJa = (JSONArray) JSON.toJSON(deviceOnlineEntityList);
+            for (int a = 0; a < resultJa.size(); a++) {
+                JSONObject resultJo = resultJa.getJSONObject(a);
+                resultJo.put("envtempFirstTime", du.formatDateText(resultJo.getTimestamp("envtempFirstTime")));
+                resultJo.put("envtempLastTime", du.formatDateText(resultJo.getTimestamp("envtempLastTime")));
+            }
+            return new Result(ResultCode.SUCCESS, resultJa);
+        }
+    }
+
+    /**
+     * @Method      : processReturnResult
+     * @Description : 处理返回结果
+     * @Params      : [resultJo]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/30
+     * @Time        : 18:31
+     */
+    public void processReturnResult(JSONObject resultJo) throws ParseException {
+        MathUtil mathUtil = new MathUtil();
+        DateUtil dateUtil = new DateUtil();
+        resultJo.put("deviceRate",mathUtil.countRate(resultJo.getFloat("deviceRate"),1)+"%");
+        resultJo.put("eartagRate",mathUtil.countRate(resultJo.getIntValue("eartagOnline"),resultJo.getIntValue("eartagTotal"),1)+"%");
+        resultJo.put("updateTime", dateUtil.formatDatetimeText(resultJo.getDate("updateTime")));
+//        resultJo.put("deviceTotal",resultJo.getString("deviceTotal")+"个");
+//        resultJo.put("deviceOnline",resultJo.getString("deviceOnline")+"个");
+//        resultJo.put("deviceOffline",resultJo.getString("deviceOffline")+"个");
+//        resultJo.put("eartagTotal",resultJo.getString("eartagTotal")+"枚");
+//        resultJo.put("eartagOnline",resultJo.getString("eartagOnline")+"枚");
+    }
+
+    @Override
+    public Result getNowAllStatus(String farmId) throws ParseException {
+        //#读取设备和耳标总状态缓存;
+        //      总状态缓存存在:从缓存读取数据返回;
+        //      总状态缓存不存在:从数据库读取记录:
+        //              {
+        //              数据库记录存在:读取记录返回,并初始化缓存;
+        //              数据库记录不存在:则构建数据库记录,并初始化缓存,返回结果;
+        //              }
+
+        //{从总状态缓存钟读取缓存数据}
+        DateUtil dateUtil = new DateUtil();
+        Map farmAllStatusMap = cacheService.getFarmAllStatusByFarmId(farmId);
+        if (farmAllStatusMap.size() > 0) {
+            log.info("返回缓存数据.");
+            JSONObject resultJo = (JSONObject) JSON.toJSON(farmAllStatusMap);
+            //{处理返回结果}
+            processReturnResult(resultJo);
+//            return new Result(ResultCode.SUCCESS, JSON.toJSON(farmAllStatusMap));
+            return new Result(ResultCode.SUCCESS, resultJo);
+        } else {
+            //#从数据库读取总状态表
+            String todayDateText = dateUtil.getTodayDateText();
+            Date todayDate = dateUtil.getTodayMySQLDate();
+            Timestamp timestamp = dateUtil.getTimestamp();
+            EartarFarmAllStatusEntity farmAllStatusEntity = farmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId, todayDateText);
+            if (farmAllStatusEntity != null) {
+                //#初始化总状态缓存
+                cacheService.putFarmAllStatusCache(farmId, farmAllStatusEntity);
+                JSONObject resultJo = (JSONObject) JSON.toJSON(farmAllStatusEntity);
+                //{处理返回结果}
+                processReturnResult(resultJo);
+//                return new Result(ResultCode.SUCCESS, JSON.toJSON(farmAllStatusEntity));
+                return new Result(ResultCode.SUCCESS, resultJo);
+            } else {
+                //*构建总状态数据 */
+                int deviceTotal = getDeviceCancelTotalFromDeviceRegister(farmId);
+                int eartagTotal = getEartagRegTotalByFarmId(farmId);
+                int deviceOnlineTotal = cacheService.getDeviceOnlineTotal(farmId, todayDateText);
+                int eartagOnlineTotal = cacheService.getEartagOnlineTotal(farmId, todayDateText);
+                int deviceOffline = deviceTotal - deviceOnlineTotal;
+                BigDecimal deviceRateBd = new BigDecimal(deviceOnlineTotal).divide(new BigDecimal(deviceTotal), 1, BigDecimal.ROUND_HALF_UP);
+                BigDecimal eartagRateBd = new BigDecimal(eartagOnlineTotal).divide(new BigDecimal(eartagTotal), 1, BigDecimal.ROUND_HALF_UP);
+
+                EartarFarmAllStatusEntity newFarmAllStatusEntity = new EartarFarmAllStatusEntity();
+                newFarmAllStatusEntity.setDeviceTotal(deviceTotal);
+                newFarmAllStatusEntity.setDeviceOnline(deviceOnlineTotal);
+                newFarmAllStatusEntity.setDeviceOffline(deviceOffline);
+                newFarmAllStatusEntity.setDeviceRate(Float.parseFloat(deviceRateBd.toString()));
+                newFarmAllStatusEntity.setEartagTotal(eartagTotal);
+                newFarmAllStatusEntity.setEartagOnline(eartagOnlineTotal);
+                newFarmAllStatusEntity.setEartagRate(Float.parseFloat(eartagRateBd.toString()));
+                newFarmAllStatusEntity.setFarmId(farmId);
+                newFarmAllStatusEntity.setUpdateTime(timestamp);
+                newFarmAllStatusEntity.setCreateDate(todayDate);
+                farmAllStatusRepo.saveAndFlush(newFarmAllStatusEntity);
+                //*初始化总状态缓存*/
+                cacheService.putFarmAllStatusCache(farmId, newFarmAllStatusEntity);
+//                return new Result(ResultCode.SUCCESS, JSON.toJSON(newFarmAllStatusEntity));
+                JSONObject resultJo = (JSONObject) JSON.toJSON(newFarmAllStatusEntity);
+                //{处理返回结果}
+                processReturnResult(resultJo);
+                return new Result(ResultCode.SUCCESS, resultJo);
+            }
+        }
+
+    }
+
+    @Override
+    public Result listManyDaysAllStatus(String farmId, Integer days) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        String pastDate = dateUtil.getPastDate(days);
+        String todayDate = dateUtil.getTodayDateText();
+        List<EartarFarmAllStatusEntity> FarmAllStatusEntityList = farmAllStatusRepo.getOneByFarmIdAndCreateDateAndPastDate(farmId, pastDate, todayDate);
+        JSONArray dataJa = new JSONArray();
+        for (EartarFarmAllStatusEntity farmAllStatusEntity : FarmAllStatusEntityList) {
+            JSONObject newJo = new JSONObject();
+            dataJa.add(newJo);
+            newJo.put("time", dateUtil.formatDateText(farmAllStatusEntity.getCreateDate()));
+            newJo.put("value", farmAllStatusEntity.getDeviceOnline());
+//            newJo.put("total", farmAllStatusEntity.getDeviceTotal());
+//            newJo.put("rate", farmAllStatusEntity.getDeviceRate());
+//            newJo.put("offline", farmAllStatusEntity.getDeviceOffline());
+        }
+        return new Result(ResultCode.SUCCESS, dataJa);
+    }
+
+    //计算注册设备数量
+    private int getDeviceCancelTotalFromDeviceRegister(String farmId) {
+        List<Object[]> deviceRegList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
+        Object[] deviceRegObj = (Object[]) deviceRegList.get(0);
+        //设备总数
+        return Integer.parseInt(deviceRegObj[0].toString());
+    }
+
+    //计算注册耳标数量
+    public Integer getEartagRegTotalByFarmId(String farmId) {
+        int eartagTotal = 0;
+        List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId);
+        Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
+        //处于工作状态的耳标总数
+        return Integer.parseInt(eartagRegObj[0].toString());
+    }
+}

+ 314 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceRegisterServiceImpl.java

@@ -0,0 +1,314 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.EartagDeviceRegisterEntity;
+import com.huimv.eartag.dao.repo.EartagDeviceRegisterRepo;
+import com.huimv.eartag.service.ICacheService;
+import com.huimv.eartag.service.IDeviceRegisterService;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.vo.Result;
+import com.huimv.eartag.vo.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+
+import javax.persistence.criteria.Order;
+import javax.persistence.criteria.Predicate;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class DeviceRegisterServiceImpl implements IDeviceRegisterService {
+    @Autowired
+    private EartagDeviceRegisterRepo deviceRegisterRepo;
+    @Autowired
+    private ICacheService cacheService;
+    @Autowired
+    private com.huimv.eartag.producer.ManageProducer producer;
+
+    @Override
+    public Result addDevice(String chipId, String deviceCode, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, String remark, String farmId) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        Date todayDate = dateUtil.getTodayDate();
+        Timestamp nowTimestamp = dateUtil.getTimestamp();
+        //判断是否存在相同的设备编码
+        if(isExistSameDevice(deviceCode)){
+            return new Result(BizConst.CODE_DEVICE_CODE_EXIST,BizConst.MSG_DEVICE_CODE_EXIST,false);
+        }
+        //
+        EartagDeviceRegisterEntity deviceRegisterEntity = new EartagDeviceRegisterEntity();
+        deviceRegisterEntity.setChipId(chipId.trim());
+        deviceRegisterEntity.setDeviceCode(deviceCode.trim());
+        deviceRegisterEntity.setFarmId(farmId.trim());
+        deviceRegisterEntity.setRegisterTime(nowTimestamp);
+        deviceRegisterEntity.setActiveStatus(activeStatus);
+        deviceRegisterEntity.setDeviceStatus(deviceStatus);
+        deviceRegisterEntity.setDeviceAlias(deviceAlias.trim());
+        deviceRegisterEntity.setLocation(location.trim());
+        deviceRegisterEntity.setRemark(remark.trim());
+        deviceRegisterEntity.setCreateDate(new java.sql.Date(todayDate.getTime()));
+        deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
+
+        //{设置工作状态}
+        setDeviceWorkStatus(deviceRegisterEntity);
+        return new Result(ResultCode.SUCCESS);
+    }
+
+    @Override
+    public Result editDevice(String chipId, String deviceCode, Integer lastDeviceStatus, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, String remark, Integer id) throws ParseException {
+        if(deviceStatus == 2){
+            activeStatus = 2;
+        }
+        //
+//        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getById(id);
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
+//        deviceRegisterEntity.setChipId(chipId);
+//        deviceRegisterEntity.setDeviceCode(deviceCode);
+        deviceRegisterEntity.setDeviceStatus(deviceStatus);
+        deviceRegisterEntity.setActiveStatus(activeStatus);
+        deviceRegisterEntity.setDeviceAlias(deviceAlias);
+        deviceRegisterEntity.setLocation(location);
+        deviceRegisterEntity.setRemark(remark);
+        deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
+        //设置注销状态
+        if((lastDeviceStatus == 0 || lastDeviceStatus == 1) && deviceStatus == 2){
+            //{设置注销状态}
+            setDeviceCancelStatus(deviceRegisterEntity);
+        }
+        //设置工作状态
+        if(lastDeviceStatus == 2 && (deviceStatus == 1 || deviceStatus == 0)){
+            //{设置工作状态}
+            setDeviceWorkStatus(deviceRegisterEntity);
+        }
+        //发送更名操作
+        producer.sendUpdateDeviceAlias(JSONObject.toJSONString(deviceRegisterEntity));
+        return new Result(ResultCode.SUCCESS);
+    }
+
+//    @Override
+//    public Result removeDevice(String ids) {
+//        String[] idsArray = ids.split(",");
+//        List<Integer> idList = new ArrayList();
+////        for(int a=0;a<idsArray.length;a++){
+////            idList.add(Integer.parseInt(idsArray[a]));
+////        }
+////        deviceRegisterRepo.removeDevice(idList);
+////        List<EartagDeviceRegisterEntity> deviceRegisterEntityList = deviceRegisterRepo.getDeviceRegisterByIds(idList);
+////        deviceRegisterRepo.deleteAll(deviceRegisterEntityList);
+////        deviceRegisterRepo.removeDevice();
+//
+////        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(ids);
+//        return new Result(ResultCode.SUCCESS);
+//    }
+
+    @Override
+    public Result listDevice(String farmId, String deviceCode, Integer deviceStatus, Integer activeStatus, String deviceAlias, String location, Integer pageNo, Integer pageSize) {
+        //
+        Specification<EartagDeviceRegisterEntity> sf = (Specification<EartagDeviceRegisterEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //farmId
+            if (null != farmId && farmId.trim().length()>0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length()>0) {
+                predList.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), deviceCode));
+            }
+            //createDate
+//            if (null != createDate && createDate.trim().length()>0) {
+//                try {
+//                    predList.add(criteriaBuilder.equal(root.get("createDate").as(java.sql.Date.class), new java.sql.Date(new DateUtil().parseDateTextToLong(createDate))));
+//                } catch (ParseException e) {
+//                    e.printStackTrace();
+//                }
+//            }
+            //deviceStatus
+            if (null != deviceStatus) {
+                predList.add(criteriaBuilder.equal(root.get("deviceStatus").as(Integer.class), deviceStatus));
+            }
+            //activeStatus
+            if (null != activeStatus) {
+                predList.add(criteriaBuilder.equal(root.get("activeStatus").as(Integer.class), activeStatus));
+            }
+            //location
+            if (null != location && location.trim().length()>0) {
+                predList.add(criteriaBuilder.like(root.get("location").as(String.class), location));
+            }
+            //deviceAlias
+            if (null != deviceAlias && deviceAlias.trim().length()>0) {
+                predList.add(criteriaBuilder.like(root.get("deviceAlias").as(String.class), deviceAlias));
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagDeviceRegisterEntity> entityPage = deviceRegisterRepo.findAll(sf, pageable);
+        return new Result(ResultCode.SUCCESS, entityPage);
+    }
+
+    @Override
+    public Result removeBatchDevice(String ids) {
+        String id = "1";
+        Integer id2 = 1;
+
+        deviceRegisterRepo.getById(id2);
+
+        return null;
+    }
+
+    @Override
+    public Result setDeviceStatus(Integer id, Integer deviceStatus) throws ParseException {
+//        System.out.println("## <setDeviceStatus> id="+id);
+//        System.out.println("## <setDeviceStatus> deviceStatus="+deviceStatus);
+        //
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getById(id);
+        if(deviceRegisterEntity == null){
+            log.error(BizConst.MSG_DEVICE_REGISTER_NO_EXIST);
+            return new Result(BizConst.CODE_DEVICE_REGISTER_NO_EXIST,BizConst.MSG_DEVICE_REGISTER_NO_EXIST,false);
+        }
+        deviceRegisterEntity.setDeviceStatus(deviceStatus);
+        deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
+        String deviceCode = deviceRegisterEntity.getDeviceCode();
+        //操作缓存
+        if(deviceStatus==1){
+            //{设置工作状态}
+            setDeviceWorkStatus(deviceRegisterEntity);
+        }else if(deviceStatus==2){
+            //{设置注销状态}
+            setDeviceCancelStatus(deviceRegisterEntity);
+        }
+        return new Result(ResultCode.SUCCESS);
+    }
+
+    /**
+     * @Method      : setDeviceWorkStatus
+     * @Description : 设置工作状态
+     * @Params      : [deviceRegisterEntity]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/4/1       
+     * @Time        : 10:43
+     */
+    private void setDeviceWorkStatus(EartagDeviceRegisterEntity deviceRegisterEntity) throws ParseException {
+        String deviceCode = deviceRegisterEntity.getDeviceCode();
+        String chipId = deviceRegisterEntity.getChipId();
+//        String farmId = deviceRegisterEntity.getFarmId();
+//        DateUtil dateUtil = new DateUtil();
+        //设置设备注册信息缓存
+        cacheService.putDeviceRegister(deviceCode,deviceRegisterEntity);
+        //{将该设备编号加入到集合Set当中}
+        cacheService.putAllDeviceSet(deviceCode);
+        //{将芯片ID和设备编码加入缓存}
+        cacheService.putChipIdToCache(chipId,deviceCode);
+        //{将该设备编码加入到在线设备集合当中}
+//        cacheService.putOnlineDeviceSet(farmId,deviceCode,dateUtil.getTodayDateText());
+
+        //{将最新设备数量加入到缓存}--MQ异步处理
+//        Integer deviceStatus = 1;
+//        cacheService.putDeviceTotal_(getDeviceSum(deviceRegisterEntity.getFarmId(),deviceStatus),deviceRegisterEntity.getFarmId());
+
+        //{MQ异步处理-设备注册信息}
+        producer.sendSyncDeviceRegister(JSONObject.toJSONString(deviceRegisterEntity));
+    }
+
+    public Integer getDeviceSum(String farmId, Integer liveStatus){
+        //# 计算处于工作状态的设备总数(设备注册表)
+        List<Object[]> deviceRegList = deviceRegisterRepo.getDeviceCountByFarmIdAndLiveStatus(farmId,liveStatus);
+        Object[] deviceRegObj = (Object[]) deviceRegList.get(0);
+        //设备总数
+        return Integer.parseInt(deviceRegObj[0].toString());
+    }
+
+    //设置注销状态
+    private void setDeviceCancelStatus(EartagDeviceRegisterEntity deviceRegisterEntity) throws ParseException {
+        //
+        DateUtil dateUtil = new DateUtil();
+        String todayDateText = dateUtil.getTodayDateText();
+        String deviceCode = deviceRegisterEntity.getDeviceCode();
+        String chipId = deviceRegisterEntity.getChipId();
+        String farmId = deviceRegisterEntity.getFarmId();
+        //删除设备注册消息
+        cacheService.deleteDeviceRegister(deviceCode);
+        //{从集合Set当中删除设备编号}
+        cacheService.deleteDeviceCodeSetCache(deviceCode);
+        //{从在线设备集合中删除该设备编码}
+        cacheService.deleteOnlineDeviceSet(farmId,deviceCode,todayDateText);
+        if(chipId != null){
+            //{删除芯片ID缓存}
+            cacheService.deleteChipIdHashCache(chipId);
+        }
+        //发送MQ,处理更新在线设备数
+        producer.sendSyncDeviceTotal(farmId,deviceCode);
+    }
+
+    @Override
+    public Result removeDevice(String ids) {
+        String[] idArray = ids.split(",");
+        List deviceCodeList = new ArrayList();
+        for(int a=0;a<idArray.length;a++){
+            EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getById(Integer.parseInt(idArray[a]));
+            if(deviceRegisterEntity == null){
+                //暂不确定这里怎么写
+                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+            }else{
+                if(deviceRegisterEntity.getDeviceStatus()==2){
+                    deviceRegisterRepo.delete(deviceRegisterEntity);
+                }else{
+                    deviceCodeList.add(deviceRegisterEntity.getDeviceCode());
+                }
+            }
+        }
+        if(deviceCodeList.size()==0){
+            return new Result(ResultCode.SUCCESS);
+        }else{
+            return new Result(BizConst.CODE_DEVICE_STATUS_EXIST,"这些设备["+deviceCodeList.toString()+"]要先注销再删除.",false);
+        }
+
+    }
+
+    //
+    private Boolean isExistSameDevice(String deviceCode) {
+        int allDeviceSetSize = cacheService.isExistAllDeviceSet();
+        if(allDeviceSetSize == 0){
+            //{初始化集合}
+            initAllDeviceSet();
+        }
+        boolean isExist = cacheService.isExistDeviceCode(deviceCode);
+        return isExist;
+    }
+
+    private void initAllDeviceSet() {
+        List<Object[]> objectList = deviceRegisterRepo.getDeviceCodeFromDeviceRegister();
+        List list = new ArrayList();
+        for(int a=0;a<objectList.size();a++){
+            Object[] object = (Object[]) objectList.get(a);
+            list.add(object[0]);
+        }
+        System.out.println("list.toString()>>"+list.toString());
+        cacheService.putAllDeviceSet(list);
+    }
+}

+ 863 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/DeviceServiceImpl.java

@@ -0,0 +1,863 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.*;
+import com.huimv.eartag.dao.repo.*;
+import com.huimv.eartag.service.IEartagService;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.service.ICacheService;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.utils.MathUtil;
+import lombok.extern.slf4j.Slf4j;
+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.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class DeviceServiceImpl implements IDeviceService {
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+    @Autowired
+    private EartagRawRepo eartagRawRepo;
+    @Autowired
+    private EartagDeviceRegisterRepo deviceRegisterRepo;
+    @Autowired
+    private ICacheService cacheService;
+    @Autowired
+    private EartagDeviceOnlineRepo deviceOnlineRepo;
+    @Autowired
+    private EartarFarmAllStatusRepo eartagFarmAllStatusRepo;
+    @Autowired
+    private EartarFarmAllStatusRepo farmAllStatusRepo;
+//    @Autowired
+//    private IEartagService eartagService;
+    @Autowired
+    private EartagDeviceOnlineRepo eartagDeviceOnlineRepo;
+    @Autowired
+    private EartagEartagRegisterRepo eartagRegisterRepo;
+    @Autowired
+    private EartagConfigPropertiesRepo configPropertiesRepo;
+    @Value("${service.farmAllStatus.host}")
+    private String serviceFarmAllStatusHost;
+    @Value("${service.farmAllStatus.ip}")
+    private String serviceFarmAllStatusIp;
+    @Value("${service.farmAllStatus.url}")
+    private String serviceFarmAllStatusUrl;
+    @Autowired
+    private EartagHeartbeatRepo heartbeatRepo;
+    @Autowired
+    private EartagEnvRepo envRepo;
+
+    //处理采集器设备信息
+    @Override
+    public void handleDeviceInfo() {
+        //--处理注册表数据
+        handleEartagRegister();
+        //--处理在线记录数据
+        handleEartagOnline();
+        //--处理状态数据
+        handleEartagAllState();
+    }
+
+    @Override
+    public void saveRawData(String askText) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        EartagRawEntity eartagRawEntity = new EartagRawEntity();
+        eartagRawEntity.setAsk(askText);
+        eartagRawEntity.setAddTime(dateUtil.getTimestamp());
+        eartagRawEntity.setCreateDate(new Date(dateUtil.getTodayDate().getTime()));
+        eartagRawRepo.saveAndFlush(eartagRawEntity);
+    }
+
+    @Override
+    public String getDeviceCodeByChipId(String chipId) {
+        //{}
+        Object deviceCodeObj = cacheService.getDeviceCodeByChipId(chipId);
+        if(deviceCodeObj != null){
+            return (String)deviceCodeObj;
+        }else{
+            return null;
+            //{从数据库读取设备编码返回}
+//            return getDeviceCodeByChipIdFromMySQL(chipId);
+        }
+    }
+
+    @Override
+    public String getFarmIdByDeviceCode(String deviceCode) {
+        //
+        String farmId = (String)cacheService.getFarmIdByDeviceCode(deviceCode);
+        if(farmId != null && farmId.trim().length()>0){
+            return farmId;
+        }else{
+            EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
+            //{将设备注册信息保存到缓存中}
+            cacheService.putDeviceRegister(deviceCode,deviceRegisterEntity);
+            return deviceRegisterEntity.getFarmId();
+        }
+    }
+
+
+    //从数据库读取deviceCode
+    private String getDeviceCodeByChipIdFromMySQL(String chipId) {
+        //{}
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getByChipId(chipId);
+        if(deviceRegisterEntity == null){
+            log.error("该芯片id不存在.");
+            return null;
+        }else{
+            return deviceRegisterEntity.getDeviceCode();
+        }
+    }
+
+    //计算设备总数
+    @Override
+    public int getDeviceTotalByFarmIdFromDeviceRegister(String farmId){
+        //从缓存钟读取设备总数
+        Integer deviceTotal = cacheService.getDeviceTotal(farmId);
+        if(deviceTotal != null) {
+            return deviceTotal;
+        }else{
+            List<Object[]> deviceRegList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
+            Object[] deviceRegObj = (Object[]) deviceRegList.get(0);
+            Integer total = Integer.parseInt(deviceRegObj[0].toString());
+            //设置缓存
+            cacheService.putDeviceTotal(total,farmId);
+            //设备总数
+            return total;
+        }
+    }
+
+    //计算注销设备数量
+    @Override
+    public int getDeviceCancelTotalFromDeviceRegister(String farmId) {
+        //从缓存钟读取设备总数
+        Integer deviceCancel = cacheService.getDeviceCancel(farmId);
+        if(deviceCancel != null) {
+            return deviceCancel;
+        }else {
+            //注销状态
+            Integer liveStatus = 2;
+            List<Object[]> deviceCancelList = deviceRegisterRepo.getDeviceCountByFarmIdAndLiveStatus(farmId,liveStatus);
+            Object[] deviceRegObj = (Object[]) deviceCancelList.get(0);
+            Integer total = Integer.parseInt(deviceRegObj[0].toString());
+            //设置注销缓存
+            cacheService.putDeviceCancel(total,farmId);
+            //设备总数
+            return total;
+        }
+    }
+
+    //计算处于不同生存状态的设备数量
+    @Override
+    public Integer getDeviceSum(String farmId, Integer liveStatus){
+        //# 计算处于工作状态的设备总数(设备注册表)
+        List<Object[]> deviceRegList = deviceRegisterRepo.getDeviceCountByFarmIdAndLiveStatus(farmId,liveStatus);
+        Object[] deviceRegObj = (Object[]) deviceRegList.get(0);
+        //设备总数
+        return Integer.parseInt(deviceRegObj[0].toString());
+    }
+
+    //更新设备环境信息
+    @Override
+    public void updateEnvtempOfDeviceAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
+        System.out.println("## farmId>>"+farmId);
+        //{获取处于工作状态的设备数量}
+        Integer deviceTotal = getDeviceTotalByFarmIdFromDeviceRegister(farmId);
+        System.out.println("## 1.deviceTotal>>"+deviceTotal);
+        if(deviceTotal == 0){
+            log.error("出错:设备总数(deviceTotal)不能为0.");
+        }
+        //设备在线数量
+        Integer deviceOnlineSum = cacheService.getDeviceOnlineSum(farmId,todayDateText);
+        System.out.println("## 2.设备当前在线数量(deviceOnlineSum)="+deviceOnlineSum);
+        deviceOnlineSum++;
+        System.out.println("## 3.设备当前在线数量(deviceOnlineSum) 2="+deviceOnlineSum);
+        //设备离线数量
+        Integer deviceOfflineSum = 0;
+        if(deviceTotal > deviceOnlineSum){
+            deviceOfflineSum = deviceTotal - deviceOnlineSum;
+        }
+        System.out.println("## 4.deviceOfflineSum>>"+deviceOfflineSum);
+        //设备在线率
+        BigDecimal deviceRateBd= new BigDecimal(deviceOnlineSum).divide(new BigDecimal(deviceTotal),1,BigDecimal.ROUND_HALF_UP);
+        Float deviceOnlineRate = Float.parseFloat(deviceRateBd.toString());
+        System.out.println("## 5.deviceOnlineRate>>"+deviceOnlineRate);
+        //{获取注销设备数量}
+        Integer deviceCancelSum = getDeviceCancelTotalFromDeviceRegister(farmId);
+        Integer eartagOnlineSum = 0;
+        Float eartagOnlineRate = 0F;
+        //耳标总数量
+//        Integer eartagTotal = eartagService.getEartagRegTotalByFarmId(farmId);
+        Integer eartagTotal = getEartagRegTotalByFarmId(farmId);
+        if(eartagTotal != 0){
+            //耳标在线数量
+//            eartagOnlineSum = eartagService.getEartagOnelineTotal(farmId,todayDateText);
+            eartagOnlineSum = getEartagOnelineTotal(farmId,todayDateText);
+            //耳标在线率
+            BigDecimal eartagRateBd= new BigDecimal(eartagOnlineSum).divide(new BigDecimal(eartagTotal),1,BigDecimal.ROUND_HALF_UP);
+            eartagOnlineRate = Float.parseFloat(eartagRateBd.toString());
+        }
+        //
+        EartarFarmAllStatusEntity farmAllStatusEntity = eartagFarmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId,todayDateText);
+        if(farmAllStatusEntity == null){
+            //{新建设备状态记录并更新缓存cache}
+            createNewFarmAllStatus(farmId,todayDate,nowTimestamp,deviceTotal,deviceOnlineSum,deviceOfflineSum,deviceCancelSum,deviceOnlineRate,eartagTotal,eartagOnlineSum,eartagOnlineRate);
+        }else{
+            //计算设备状态并更新缓存cache(在线数+1,离线数-1,计算设备在线率)
+            farmAllStatusEntity.setDeviceTotal(deviceTotal);
+            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
+            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
+            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
+            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
+            farmAllStatusEntity.setEartagTotal(eartagTotal);
+            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
+            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
+            farmAllStatusEntity.setUpdateTime(nowTimestamp);
+            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
+            System.out.println("## 更新的内容="+farmAllStatusEntity);
+            //# 同步更新牧场总状态缓存相关字段 #
+            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
+        }
+    }
+
+    //读取耳标注册数据
+//    @Override
+    public Integer getEartagRegTotalByFarmId(String farmId){
+        //从缓存读取耳标总数
+        Integer eartagTotal = cacheService.getEartagTotal(farmId);
+        if(eartagTotal != null){
+            return eartagTotal;
+        }else{
+//            List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId);
+//            Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
+//            Integer total = Integer.parseInt(eartagRegObj[0].toString());
+            ///
+            Integer liveStatus = 1;
+            //{读取处于工作状态的耳标总数}
+            Integer total = getEartagSum(farmId,liveStatus);
+            //设置耳标总数缓存
+            cacheService.putEartagTotal(total,farmId);
+            //处于工作状态的耳标总数
+            return total;
+        }
+    }
+
+    //计算处于不同生存状态的耳标数量
+    private Integer getEartagSum(String farmId,Integer liveStatus){
+        List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId,liveStatus);
+        Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
+        //处于工作状态的耳标总数
+        return Integer.parseInt(eartagRegObj[0].toString());
+    }
+
+//    @Override
+    public Integer getEartagOnelineTotal(String farmId, String todayDateText) {
+        return cacheService.getEartagOnlineTotalFromCache(farmId,todayDateText);
+    }
+
+    //# 创建总状态记录 #
+    private void createNewFarmAllStatus(String farmId, java.sql.Date todayDate, Timestamp nowTimestamp, Integer deviceTotal, Integer deviceOnlineSum, Integer deviceOfflineSum, Integer deviceCancelSum, Float deviceOnlineRate, Integer eartagTotal, Integer eartagOnlineSum, Float eartagOnlineRate) {
+        Integer liveStatus = 1;
+        if(getDeviceSum(farmId,liveStatus) == 0){
+            log.error("该牧场没有任何处于工作状态的采集器设备.");
+        }else{
+            //# 计算耳标总数(耳标注册表)
+            EartarFarmAllStatusEntity farmAllStatusEntity = new EartarFarmAllStatusEntity();
+            farmAllStatusEntity.setDeviceTotal(deviceTotal);
+            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
+            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
+            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
+            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
+            farmAllStatusEntity.setEartagTotal(eartagTotal);
+            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
+            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
+            farmAllStatusEntity.setFarmId(farmId);
+            farmAllStatusEntity.setUpdateTime(nowTimestamp);
+            farmAllStatusEntity.setCreateDate(todayDate);
+            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
+            //设置总状态缓存
+            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
+        }
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    /**
+     * @Method      : handleDeviceHeartbeat
+     * @Description : 处理设备心跳数据
+     * @Params      : [dataJo]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/12
+     * @Time        : 19:16
+     */
+    @Override
+    public void handleDeviceHeartbeat(JSONObject dataJo) throws ParseException {
+        System.out.println("心跳数据 dataJo>>"+dataJo);
+        //逻辑处理:
+        //1、保存设备心跳流水数据;
+        //2、更新设备注册表(活动状态、活动更新时间,更新类型)
+        //3、更新在线统计表(心跳数,心跳最早上传时间,最后一次上传时间)
+        //4、更新总状态表表
+        //Step1:更新设备注册表[设置活动状态为1,设置活动状态更新时间]
+        //Step2:更新在线统计[心跳数+1,心跳第一次上传时间,心跳最后一次时间],预先判断该数据是否存在,如果不存在要先添加记录,如果存在就修改数据
+
+        System.out.println("dataJo>"+dataJo);
+        String deviceCode = dataJo.getString("device");
+        //{获取牧场id}
+        String farmId = getFarmIdByDeviceCode(deviceCode);
+        if(farmId != null){
+            String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+            java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+            Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+            //1、{保存设备心跳记录}
+            saveDeviceHeartbeat(dataJo,todayDate);
+
+            String updateType="设备心跳";
+            //2、{更新设备注册表}
+            updateDeviceRegister(farmId, deviceCode,nowTimestamp,updateType);
+
+            //3、{更新在线统计表}
+            updateDeviceOnlineCountWithHeartbeat(farmId, deviceCode,todayDateText,nowTimestamp,todayDate);
+
+            //判断该设备编号是否存在缓存在线集合当中;
+            Boolean isExist = cacheService.isExistDeviceOnlineSet(farmId, deviceCode, todayDateText);
+            System.out.println("心跳处理 isExist>>"+isExist);
+            if (!isExist) {
+                //4、{更新总状态表}
+                updateEnvtempOfDeviceAllStatus(farmId, todayDateText,todayDate,nowTimestamp);
+
+                //# 将新设备编号加入在线缓存 #
+                cacheService.putDeviceToOnlineSet(farmId, deviceCode,todayDateText);
+            }
+        }else{
+            log.error("出错:该请求的FarmId为空.请检查该设备编码["+deviceCode+"]是否存在FarmId.");
+        }
+        System.out.println("## END 心跳数据。 "+new com.huimv.eartag.utils.DateUtil().getTodayMissionText());
+    }
+
+    //更新在线状态
+    public void updateDeviceOnlineCountWithHeartbeat(String farmId, String deviceCode, String todayDateText, Timestamp nowTimestamp, java.sql.Date todayDate) throws ParseException {
+        String hashKey = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
+        //计算设备别名
+        String alias = (String)cacheService.getHashProperty(hashKey,"deviceAlias");
+        //读取在线日期
+        EartagDeviceOnlineEntity eartagDeviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode, todayDateText);
+        if (eartagDeviceOnlineEntity == null) {
+            Integer heartbeatTotal = 1;
+            Integer envtempTotal = 0;
+            Timestamp heartbeatFirstTime = nowTimestamp;
+            Timestamp heartbeatLastTime = nowTimestamp;
+            Timestamp envtempFirstTime = null;
+            Timestamp envtempLastTime = null;
+            Timestamp firstTime = nowTimestamp;
+            Timestamp lastTime = nowTimestamp;
+            Integer liveStatus = 1;
+            //{计算耳标总数}
+//            Integer eartagTotal = eartagService.getEartagRegTotalByFarmId(farmId);
+            Integer eartagTotal = 0;
+            //{新建设备在线统计并创建缓存}
+            newDeviceOnline(deviceCode,alias,heartbeatTotal,envtempTotal,eartagTotal,todayDate,farmId,heartbeatFirstTime,heartbeatLastTime,envtempFirstTime,envtempLastTime,firstTime,lastTime,liveStatus);
+        }else{
+            eartagDeviceOnlineEntity.setAlias(alias);
+            int heartbeatTotal = eartagDeviceOnlineEntity.getHeartbeatTotal();
+            eartagDeviceOnlineEntity.setHeartbeatTotal(++heartbeatTotal);
+            if(eartagDeviceOnlineEntity.getHeartbeatFirstTime() == null){
+                eartagDeviceOnlineEntity.setHeartbeatFirstTime(nowTimestamp);
+            }
+            eartagDeviceOnlineEntity.setHeartbeatLastTime(nowTimestamp);
+            if(eartagDeviceOnlineEntity.getFirstTime() == null){
+                eartagDeviceOnlineEntity.setFirstTime(nowTimestamp);
+            }
+            eartagDeviceOnlineEntity.setLastTime(nowTimestamp);
+            eartagDeviceOnlineRepo.saveAndFlush(eartagDeviceOnlineEntity);
+            //更新设备在线缓存数据
+            cacheService.putDeviceInOnline(deviceCode,eartagDeviceOnlineEntity);
+        }
+    }
+
+    /**
+     * @Method      : newDeviceOnline
+     * @Description : 通过心跳创建在线统计记录
+     * @Params      : [deviceCode, alias, heartbeatTotal, envtempTotal, eartagTotal, todayDate, farmId, heartbeatFirstTime, heartbeatLastTime, envtempFirstTime, envtempLastTime]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/14
+     * @Time        : 21:23
+     */
+    private void newDeviceOnline(String deviceCode, String alias, Integer heartbeatTotal, Integer envtempTotal, Integer eartagTotal, java.sql.Date todayDate, String farmId, Timestamp heartbeatFirstTime, Timestamp heartbeatLastTime, Timestamp envtempFirstTime, Timestamp envtempLastTime, Timestamp firstTime, Timestamp lastTime, Integer liveStatus) {
+        EartagDeviceOnlineEntity newEartagDeviceOnlineEntity = new EartagDeviceOnlineEntity();
+        newEartagDeviceOnlineEntity.setDeviceCode(deviceCode);
+        newEartagDeviceOnlineEntity.setAlias(alias);
+        newEartagDeviceOnlineEntity.setHeartbeatTotal(heartbeatTotal);;
+        newEartagDeviceOnlineEntity.setEnvtempTotal(envtempTotal);
+        newEartagDeviceOnlineEntity.setEartagTotal(eartagTotal);
+        newEartagDeviceOnlineEntity.setAddDate(todayDate);
+        newEartagDeviceOnlineEntity.setFarmId(farmId);
+        newEartagDeviceOnlineEntity.setHeartbeatFirstTime(heartbeatFirstTime);
+        newEartagDeviceOnlineEntity.setHeartbeatLastTime(heartbeatLastTime);
+        newEartagDeviceOnlineEntity.setEnvtempFirstTime(envtempFirstTime);
+        newEartagDeviceOnlineEntity.setEnvtempLastTime(envtempLastTime);
+        newEartagDeviceOnlineEntity.setFirstTime(firstTime);
+        newEartagDeviceOnlineEntity.setLastTime(lastTime);
+        newEartagDeviceOnlineEntity.setLiveStatus(liveStatus);
+        eartagDeviceOnlineRepo.saveAndFlush(newEartagDeviceOnlineEntity);
+        //将新建的设备在线数据更新到设备在线缓存
+        cacheService.putDeviceInOnline(deviceCode,newEartagDeviceOnlineEntity);
+    }
+
+    //更新设备注册表
+    private void updateDeviceRegister(String farmId, String deviceCode, Timestamp nowTimestamp,String updateType) {
+        //--更新mysql
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
+        if (deviceRegisterEntity != null) {
+            //设备注册数据存在
+            deviceRegisterEntity.setDeviceStatus(1);
+            deviceRegisterEntity.setActiveStatus(1);
+            deviceRegisterEntity.setActiveTime(nowTimestamp);
+            deviceRegisterEntity.setUpdateType(updateType);
+            deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
+            //更新缓存中设备注册信息
+            cacheService.putDeviceRegister(deviceCode,deviceRegisterEntity);
+        }else{
+            //设备注册数据不存在
+            //新建设备注册记录
+            newDeviceRegister(farmId,deviceCode,nowTimestamp,updateType);
+        }
+    }
+
+    //新建设备注册记录
+    public void newDeviceRegister(String farmId,String deviceCode,Timestamp nowTimestamp,String updateType){
+        EartagDeviceRegisterEntity newDeviceRegisterEntity = new EartagDeviceRegisterEntity();
+        newDeviceRegisterEntity.setDeviceCode(deviceCode);
+        newDeviceRegisterEntity.setFarmId(farmId);
+        newDeviceRegisterEntity.setRegisterTime(nowTimestamp);
+        newDeviceRegisterEntity.setActiveStatus(1);
+        newDeviceRegisterEntity.setActiveTime(nowTimestamp);
+        newDeviceRegisterEntity.setDeviceStatus(1);
+        newDeviceRegisterEntity.setUpdateType(updateType);
+        deviceRegisterRepo.saveAndFlush(newDeviceRegisterEntity);
+        //更新缓存中设备注册信息
+        cacheService.putDeviceRegister(deviceCode,newDeviceRegisterEntity);
+    }
+
+    /**
+     * @Method      : saveDeviceHeartbeat
+     * @Description : 保存设备心跳数据
+     * @Params      : [dataJo]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/2/15
+     * @Time        : 14:39
+     */
+//    @Override
+    public void saveDeviceHeartbeat(JSONObject dataJo, java.sql.Date todayDate) {
+        String deviceCode = dataJo.getString("device");
+        EartagHeartbeatEntity addHeartbeatEntity = new EartagHeartbeatEntity();
+        addHeartbeatEntity.setDeviceCode(deviceCode);
+        addHeartbeatEntity.setAddTime(new Timestamp(new java.util.Date().getTime()));
+        addHeartbeatEntity.setCreateDate(todayDate);
+        heartbeatRepo.saveAndFlush(addHeartbeatEntity);
+    }
+
+    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    /**
+     * @Method      : handleDeviceEnvtemp
+     * @Description : 处理设备环境温度数据
+     * @Params      : [dataJo]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/12
+     * @Time        : 19:16
+     */
+    @Override
+    public void handleDeviceEnvtemp(JSONObject dataJo) throws ParseException {
+        System.out.println("环境数据 dataJo>>"+dataJo);
+        //逻辑处理:
+        //1、保存环境温度流水数据;
+        //2、更新设备注册表(活动状态、活动更新时间,更新类型)
+        //3、更新在线统计表(环境温度计数,环境温度最早上传时间,最新环境温度,环境温度最后一次上传时间)
+        //4、更新总状态表
+        String deviceCode = dataJo.getString("device");
+        //{通过设备编码取货牧场id}
+        String farmId = getFarmIdByDeviceCode(deviceCode);
+        if(farmId != null){
+            String temp = dataJo.getString("temp");
+            String envtemp = com.huimv.eartag.utils.MathUtil.countEnvtemp(temp,2).toString();
+            String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+            java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+            Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+
+            //1.保存环境温度流水
+            saveDeviceTemp(dataJo,todayDate,nowTimestamp);
+
+            String updateType = "环境温度";
+            //2.{更新设备注册表}
+            updateDeviceRegister(farmId, deviceCode,nowTimestamp,updateType);
+
+            //3.{更新在线统计表}
+            updateDeviceOnlineWithEnvtemp(farmId, deviceCode,envtemp,todayDate,nowTimestamp);
+
+            //{检查异常温度}
+            checkAbnormalEnvTemp(farmId,envtemp);
+
+            //判断该设备编号是否存在牧场缓存在线集合当中;
+            Boolean isExist = cacheService.isExistDeviceOnlineSet(farmId, deviceCode,todayDateText);
+            System.out.println("## 环境温度 isExist>>"+isExist);
+            if (!isExist) {
+                //4.{更新总状态表}
+                updateEnvtempOfDeviceAllStatus(farmId, todayDateText,todayDate,nowTimestamp);
+
+                //{将新设备编号加入在线缓存}
+                cacheService.putDeviceToOnlineSet(farmId, deviceCode, todayDateText);
+            }
+        }else{
+            log.error("出错:该请求的FarmId为空.请检查该设备编码["+deviceCode+"]是否存在FarmId.");
+        }
+        System.out.println("## END 环境数据。"+new com.huimv.eartag.utils.DateUtil().getTodayMissionText());
+    }
+
+    /**
+     * @Method      : checkAbnormalEnvTemp
+     * @Description : 检查异常环境温度
+     * @Params      : [farmId, envtemp]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/4/6
+     * @Time        : 19:14
+     */
+    private void checkAbnormalEnvTemp(String farmId, String envtemp) {
+        //{}
+        Object envTempTvObj = cacheService.getEnvTempThresholdVal(farmId);
+        String envTempTv = "";
+        if(envTempTvObj != null){
+            envTempTv = envTempTvObj.toString();
+            String[] envTempArray = envTempTv.split("-");
+            if(envTempArray.length==1){
+                String lowTemp = envTempArray[0];
+
+            }else  if(envTempArray.length==2){
+                String lowTemp = envTempArray[0];
+                if(lowTemp == null || lowTemp.trim().length() ==0){
+
+                }
+                String highTemp = envTempArray[1];
+
+            }
+
+
+            //===============================================================================
+        }else{
+            String sort = "";
+            //从数据库读取阈值
+            EartagConfigPropertiesEntity configPropertiesEntity = configPropertiesRepo.getThresholdVal(farmId,sort);
+            if(configPropertiesEntity != null){
+                String lowTemp = configPropertiesEntity.getProVal1();
+                String highTemp = configPropertiesEntity.getProVal2();
+
+
+                //===============================================================================
+            }else{
+                log.error(farmId+"牧场的环境温度高低温阈值为空.请检查,否则不能进行设备的高低温异常统计.");
+            }
+        }
+    }
+
+    /**
+     * @Method      : updateDeviceOnlineWithEnvtemp
+     * @Description : 更新在线统计
+     * @Params      :
+     * @Return      :
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/14
+     * @Time        : 14:27
+     */
+    private void updateDeviceOnlineWithEnvtemp(String farmId, String deviceCode,String envtemp,java.sql.Date todayDate,Timestamp nowTimestamp) throws ParseException {
+        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+        String hashKey = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
+        //计算设备别名
+        String alias = (String)cacheService.getHashProperty(hashKey,"deviceAlias");
+        //读取在线日期
+        EartagDeviceOnlineEntity eartagDeviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode, todayDateText);
+        if (eartagDeviceOnlineEntity == null) {
+            Integer heartbeatTotal = 0;
+            Integer envtempTotal = 1;
+            Timestamp heartbeatFirstTime = null;
+            Timestamp heartbeatLastTime = null;
+            Timestamp envtempFirstTime = nowTimestamp;
+            Timestamp envtempLastTime = nowTimestamp;
+            Timestamp firstTime = nowTimestamp;
+            Timestamp lastTime = nowTimestamp;
+            //{计算耳标总数}
+//            Integer eartagTotal = eartagService.getEartagRegTotalByFarmId(farmId);
+            Integer eartagTotal = 0;
+            Integer liveStatus = 1;
+            //{新建设备在线统计并创建缓存}
+            newDeviceOnline(deviceCode,alias,heartbeatTotal,envtempTotal,eartagTotal,envtemp,todayDate,farmId,heartbeatFirstTime,heartbeatLastTime,envtempFirstTime,envtempLastTime,firstTime,lastTime,liveStatus);
+        }else{
+            eartagDeviceOnlineEntity.setAlias(alias);
+            int envtempTotal = eartagDeviceOnlineEntity.getEnvtempTotal();
+            eartagDeviceOnlineEntity.setEnvtempTotal(++envtempTotal);
+            eartagDeviceOnlineEntity.setLastEnvtemp(envtemp);
+            if(eartagDeviceOnlineEntity.getEnvtempFirstTime() == null){
+                eartagDeviceOnlineEntity.setEnvtempFirstTime(nowTimestamp);
+            }
+            eartagDeviceOnlineEntity.setEnvtempLastTime(nowTimestamp);
+            if(eartagDeviceOnlineEntity.getFirstTime() == null){
+                eartagDeviceOnlineEntity.setFirstTime(nowTimestamp);
+            }
+            eartagDeviceOnlineEntity.setLastTime(nowTimestamp);
+            eartagDeviceOnlineRepo.saveAndFlush(eartagDeviceOnlineEntity);
+            //更新设备在线缓存数据
+            cacheService.putDeviceInOnline(deviceCode,eartagDeviceOnlineEntity);
+        }
+    }
+
+    /**
+     * @Method      : newDeviceOnline
+     * @Description : 创建设备在线
+     * @Params      : [farmId, deviceCode]
+     * @Return      : void
+     *newDeviceOnline(deviceCode,alias,heartbeatTotal,envtempTotal,temp,todayDate,farmId,heartbeatFirstTime,heartbeatLastTime,nowTimestamp);
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/14
+     * @Time        : 14:27
+     */
+    private void newDeviceOnline(String deviceCode, String alias, Integer heartbeatTotal, Integer envtempTotal, Integer eartagTotal, String temp, java.sql.Date todayDate, String farmId, Timestamp heartbeatFirstTime, Timestamp heartbeatLastTime, Timestamp envtempFirstTime, Timestamp envtempLastTime, Timestamp firstTime, Timestamp lastTime, Integer liveStatus) {
+        EartagDeviceOnlineEntity newEartagDeviceOnlineEntity = new EartagDeviceOnlineEntity();
+        newEartagDeviceOnlineEntity.setDeviceCode(deviceCode);
+        newEartagDeviceOnlineEntity.setAlias(alias);
+        newEartagDeviceOnlineEntity.setHeartbeatTotal(heartbeatTotal);;
+        newEartagDeviceOnlineEntity.setEnvtempTotal(envtempTotal);
+        newEartagDeviceOnlineEntity.setEartagTotal(eartagTotal);
+        newEartagDeviceOnlineEntity.setLastEnvtemp(temp);
+        newEartagDeviceOnlineEntity.setAddDate(todayDate);
+        newEartagDeviceOnlineEntity.setFarmId(farmId);
+        newEartagDeviceOnlineEntity.setHeartbeatFirstTime(heartbeatFirstTime);
+        newEartagDeviceOnlineEntity.setHeartbeatLastTime(heartbeatLastTime);
+        newEartagDeviceOnlineEntity.setEnvtempFirstTime(envtempFirstTime);
+        newEartagDeviceOnlineEntity.setEnvtempLastTime(envtempLastTime);
+        newEartagDeviceOnlineEntity.setFirstTime(firstTime);
+        newEartagDeviceOnlineEntity.setLastTime(lastTime);
+        newEartagDeviceOnlineEntity.setLiveStatus(liveStatus);
+        eartagDeviceOnlineRepo.saveAndFlush(newEartagDeviceOnlineEntity);
+        //将新建的设备在线数据更新到设备在线缓存
+        cacheService.putDeviceInOnline(deviceCode,newEartagDeviceOnlineEntity);
+    }
+
+//    @Override
+    public void saveDeviceTemp(JSONObject dataJo, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+//        MathUtil mathUtil = new MathUtil();
+        String device = dataJo.getString("device");
+        String askTime = dateUtil.rebuildDateTime(dataJo.getString("askTime"));
+        String temp = dataJo.getString("temp");
+        EartagEnvEntity envEntity = new EartagEnvEntity();
+        envEntity.setDeviceCode(device);
+        envEntity.setTemp1(Integer.parseInt(temp));
+        envEntity.setTemp2(Float.parseFloat(MathUtil.countEnvtemp(temp,2)));
+        envEntity.setAddTime(nowTimestamp);
+        envEntity.setAskTime(new Timestamp(dateUtil.parseDateTime(askTime).getTime()));
+        envEntity.setCreateDate(todayDate);
+        envEntity.setAskDate(new java.sql.Date(dateUtil.parseDate(dateUtil.getAskDate(dataJo.getString("askTime"))).getTime()));
+        envRepo.saveAndFlush(envEntity);
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
+    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    @Override
+    public void countEffectiveDeviceTotal(JSONObject deviceRegisterJo) {
+        String farmId = deviceRegisterJo.getString("farmId");
+        //{}
+        Integer effectiveDeviceTotal = getEffectiveDeviceSum(farmId);
+        System.out.println("## effectiveDeviceTotal >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+effectiveDeviceTotal);
+        //{设置设备总数}
+        cacheService.putDeviceTotal(effectiveDeviceTotal,farmId);
+    }
+
+    @Override
+    public void countEffectiveDeviceTotal(Map inMap) {
+        String farmId = inMap.get("farmId").toString();
+        //{}
+        Integer effectiveDeviceTotal = getEffectiveDeviceSum(farmId);
+        System.out.println("##<注销设备> effectiveDeviceTotal>>"+effectiveDeviceTotal);
+        //{设置设备总数}
+        cacheService.putDeviceTotal(effectiveDeviceTotal,farmId);
+    }
+
+    //读取有效的设备数量
+    public Integer getEffectiveDeviceSum(String farmId){
+        List<Object[]> deviceRegisterList = deviceRegisterRepo.getDeviceCountByFarmId(farmId);
+        Object[] deviceRegObj = (Object[]) deviceRegisterList.get(0);
+        //设备总数
+        return Integer.parseInt(deviceRegObj[0].toString());
+    }
+
+    @Override
+    public void countFarmAllStatus(JSONObject deviceRegisterJo) throws ParseException {
+        String farmId = deviceRegisterJo.getString("farmId");
+        //{}
+//        remoteProcessFarmAllStatus(farmId);
+        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+        //{更新牧场总状态}
+        updateEnvtempOfDeviceAllStatus(farmId,todayDateText,todayDate,nowTimestamp);
+    }
+
+    @Override
+    public void unCancelDeviceOnlineLiveStatus(JSONObject deviceRegisterJo, String todayDateText) {
+        String deviceCode = deviceRegisterJo.getString("deviceCode");
+        String farmId = deviceRegisterJo.getString("farmId");
+        System.out.println("## <unCancelDeviceOnlineLiveStatus> deviceCode="+deviceCode);
+        System.out.println("## <unCancelDeviceOnlineLiveStatus> todayDateText="+todayDateText);
+        EartagDeviceOnlineEntity deviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode,todayDateText);
+        if(deviceOnlineEntity == null){
+            log.error("该设备当天在线记录不存在.");
+            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+        }else{
+            Integer liveStatus = 1;
+            deviceOnlineEntity.setLiveStatus(liveStatus);
+            eartagDeviceOnlineRepo.saveAndFlush(deviceOnlineEntity);
+            //更新缓存(从缓存里将该设备从set里取出,同时将该数据表对应的缓存更新)
+            cacheService.putDeviceInOnline(deviceCode,deviceOnlineEntity);
+            //从在线集合种删除设备编码
+            cacheService.putDeviceToOnlineSet(farmId,deviceCode,todayDateText);
+        }
+    }
+
+    @Override
+    public void cancelFarmAllStatus(Map map) throws ParseException {
+        String farmId = map.get("farmId").toString();
+        String todayDateText = new com.huimv.eartag.utils.DateUtil().getTodayDateText();
+        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+        //{取消牧场总状态}
+        cancelEnvtempOfDeviceAllStatus(farmId,todayDateText,todayDate,nowTimestamp);
+    }
+
+    public void cancelEnvtempOfDeviceAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
+//        System.out.println("## farmId>>"+farmId);
+        //{获取处于工作状态的设备数量}
+        Integer deviceTotal = getDeviceTotalByFarmIdFromDeviceRegister(farmId);
+        System.out.println("## A.deviceTotal>>"+deviceTotal);
+        if(deviceTotal == 0){
+            log.error("出错:设备总数(deviceTotal)不能为0.");
+        }
+        //设备在线数量
+        Integer deviceOnlineSum = cacheService.getDeviceOnlineSum(farmId,todayDateText);
+        System.out.println("# B.设备当前在线数量(deviceOnlineSum)="+deviceOnlineSum);
+//        deviceOnlineSum--;
+//        System.out.println("# 设备当前在线数量(deviceOnlineSum) 2="+deviceOnlineSum);
+        //设备离线数量
+        Integer deviceOfflineSum = 0;
+        if(deviceTotal > deviceOnlineSum){
+            deviceOfflineSum = deviceTotal - deviceOnlineSum;
+        }
+        System.out.println("## C.deviceOnlineSum>>"+deviceOnlineSum);
+        System.out.println("## D.deviceOfflineSum>>"+deviceOfflineSum);
+        //设备在线率
+        BigDecimal deviceRateBd= new BigDecimal(deviceOnlineSum).divide(new BigDecimal(deviceTotal),1,BigDecimal.ROUND_HALF_UP);
+        Float deviceOnlineRate = Float.parseFloat(deviceRateBd.toString());
+        System.out.println("## E.deviceOnlineRate>>"+deviceOnlineRate);
+        //{获取注销设备数量}
+        Integer deviceCancelSum = getDeviceCancelTotalFromDeviceRegister(farmId);
+        Integer eartagOnlineSum = 0;
+        Float eartagOnlineRate = 0F;
+        //耳标总数量
+        Integer eartagTotal = getEartagRegTotalByFarmId(farmId);
+        if(eartagTotal != 0){
+            //耳标在线数量
+            eartagOnlineSum = getEartagOnelineTotal(farmId,todayDateText);
+            //耳标在线率
+            BigDecimal eartagRateBd= new BigDecimal(eartagOnlineSum).divide(new BigDecimal(eartagTotal),1,BigDecimal.ROUND_HALF_UP);
+            eartagOnlineRate = Float.parseFloat(eartagRateBd.toString());
+        }
+        //
+        EartarFarmAllStatusEntity farmAllStatusEntity = eartagFarmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId,todayDateText);
+        if(farmAllStatusEntity == null){
+            //{新建设备状态记录并更新缓存cache}
+            createNewFarmAllStatus(farmId,todayDate,nowTimestamp,deviceTotal,deviceOnlineSum,deviceOfflineSum,deviceCancelSum,deviceOnlineRate,eartagTotal,eartagOnlineSum,eartagOnlineRate);
+        }else{
+            //计算设备状态并更新缓存cache(在线数+1,离线数-1,计算设备在线率)
+            farmAllStatusEntity.setDeviceTotal(deviceTotal);
+            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
+            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
+            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
+            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
+            farmAllStatusEntity.setEartagTotal(eartagTotal);
+            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
+            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
+            farmAllStatusEntity.setUpdateTime(nowTimestamp);
+            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
+            System.out.println("## 更新的内容="+farmAllStatusEntity);
+            //# 同步更新牧场总状态缓存相关字段 #
+            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
+        }
+    }
+
+    @Override
+    public void cancelDeviceOnlineLiveStatus(Map map, String todayDateText) {
+        String deviceCode = map.get("deviceCode").toString();
+        String farmId = map.get("farmId").toString();
+        System.out.println("## <cancelDeviceOnlineLiveStatus> todayDateText="+todayDateText);
+        System.out.println("## <cancelDeviceOnlineLiveStatus> deviceCode="+deviceCode);
+        EartagDeviceOnlineEntity deviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode,todayDateText);
+        System.out.println("## <cancelDeviceOnlineLiveStatus> deviceOnlineEntity="+deviceOnlineEntity);
+        if(deviceOnlineEntity == null){
+            log.error("该设备当天在线记录不存在.");
+            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+        }else{
+            Integer liveStatus = 0;
+            deviceOnlineEntity.setLiveStatus(liveStatus);
+            eartagDeviceOnlineRepo.saveAndFlush(deviceOnlineEntity);
+            //更新缓存(从缓存里将该设备从set里取出,同时将该数据表对应的缓存更新)
+            cacheService.putDeviceInOnline(deviceCode,deviceOnlineEntity);
+            //从在线集合种删除设备编码
+            cacheService.deleteDeviceToOnlineSet(farmId,deviceCode,todayDateText);
+        }
+    }
+
+    //--处理状态数据
+    private void handleEartagAllState() {
+
+    }
+
+    //--处理在线记录数据
+    private void handleEartagOnline() {
+
+    }
+
+    //--处理注册表数据
+    private void handleEartagRegister() {
+
+    }
+}

+ 875 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/EartagManageServiceImpl.java

@@ -0,0 +1,875 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.*;
+import com.huimv.eartag.dao.repo.*;
+import com.huimv.eartag.service.IEartagManageService;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.utils.JSONUtil;
+import com.huimv.eartag.vo.Result;
+import com.huimv.eartag.vo.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+
+import javax.persistence.criteria.Order;
+import javax.persistence.criteria.Predicate;
+import java.sql.Date;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class EartagManageServiceImpl implements IEartagManageService {
+    @Autowired
+    private EartagEartagRegisterRepo eartagRegisterRepo;
+    @Autowired
+    private EartagDataRepo eartagDataRepo;
+    @Autowired
+    private EartagEartagOnlineRepo eartagOnlineRepo;
+    @Autowired
+    private EartarFarmAllStatusRepo farmAllStatusRepo;
+    @Autowired
+    private EartagDeviceEartagCountRepo deviceEartagCountRepo;
+
+    /**
+     * @Method : listAllEartagFlow
+     * @Description : 分页展示所有流水列表
+     * @Params : [farmId, createDate, deviceCode, earmark, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/11
+     * @Time : 11:30
+     */
+    @Override
+    public Result listAllEartagFlow(String farmId, String createDate, String deviceCode, String earmark, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //farmId
+            if (null != farmId && farmId.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //earmark
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //createDate
+            if (null != createDate && createDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+//        Page<EartagDataEntity> eartagDataEntityPage = eartagDataRepo.findAll(sf, pageable);
+//        return new Result(ResultCode.SUCCESS, eartagDataEntityPage);
+        Page<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        outDataJo.put("pageable", pageEartagData.getPageable());
+        outDataJo.put("last", pageEartagData.isLast());
+        outDataJo.put("totalElements", pageEartagData.getTotalElements());
+        outDataJo.put("totalPages", pageEartagData.getTotalPages());
+        outDataJo.put("number", pageEartagData.getNumber());
+        outDataJo.put("size", pageEartagData.getSize());
+        outDataJo.put("sort", pageEartagData.getSort());
+        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
+        outDataJo.put("first", pageEartagData.isFirst());
+        outDataJo.put("empty", pageEartagData.isEmpty());
+
+        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        DateUtil dateUtil = new DateUtil();
+        for (EartagDataEntity eartagDataEntity : dataEntityList) {
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", eartagDataEntity.getId());
+            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
+            outJo.put("device", eartagDataEntity.getDevice());
+            outJo.put("earmark", eartagDataEntity.getEarmark());
+            outJo.put("bat", eartagDataEntity.getBat());
+            outJo.put("earTemp", eartagDataEntity.getEarTemp());
+            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
+            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
+            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
+            outJo.put("act", eartagDataEntity.getAct());
+            outJo.put("act1", eartagDataEntity.getAct1());
+            outJo.put("signal1", eartagDataEntity.getSignal1());
+            outJo.put("askTime", eartagDataEntity.getAskTime());
+            outJo.put("other", eartagDataEntity.getOther());
+            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
+            outJo.put("createDate", eartagDataEntity.getCreateDate());
+            outJo.put("farmId", eartagDataEntity.getFarmId());
+        }
+        return new Result(ResultCode.SUCCESS, outDataJo);
+    }
+
+    @Override
+    public Result listManyEartagOnlineStatus(String farmId, Integer days) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        String pastDate = dateUtil.getPastDate(days);
+        String todayDate = dateUtil.getTodayDateText();
+        List<EartarFarmAllStatusEntity> FarmAllStatusEntityList = farmAllStatusRepo.getOneByFarmIdAndCreateDateAndPastDate(farmId, pastDate, todayDate);
+        JSONArray dataJa = new JSONArray();
+        for (EartarFarmAllStatusEntity farmAllStatusEntity : FarmAllStatusEntityList) {
+            JSONObject newJo = new JSONObject();
+            dataJa.add(newJo);
+            newJo.put("time", dateUtil.formatDateText(farmAllStatusEntity.getCreateDate()));
+            newJo.put("value", farmAllStatusEntity.getEartagOnline());
+//            newJo.put("total", farmAllStatusEntity.getDeviceTotal());
+//            newJo.put("rate", farmAllStatusEntity.getDeviceRate());
+//            newJo.put("offline", farmAllStatusEntity.getDeviceOffline());
+        }
+        return new Result(ResultCode.SUCCESS, dataJa);
+    }
+
+    @Override
+    public Result listAllEartagRegister(String farmId, String earmark, Integer activeStatus, Integer liveStatus, Integer registerType, String startDate, String endDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagEartagRegisterEntity> sf = (Specification<EartagEartagRegisterEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //farmId
+            if (null != farmId && farmId.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //earmark
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //activeStatus
+            if (null != activeStatus) {
+                predList.add(criteriaBuilder.equal(root.get("activeStatus").as(Integer.class), activeStatus));
+            }
+            //liveStatus
+            if (null != liveStatus) {
+                predList.add(criteriaBuilder.equal(root.get("liveStatus").as(Integer.class), liveStatus));
+            }
+            //registerType
+            if (null != registerType) {
+                predList.add(criteriaBuilder.equal(root.get("registerType").as(Integer.class), registerType));
+            }
+            //startDate
+            if (null != startDate && startDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(startDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //endDate
+            if (null != endDate && endDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(endDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+//            //activeStatus
+//            if (null != activeStatus) {
+//                predList.add(criteriaBuilder.equal(root.get("activeStatus").as(Integer.class), activeStatus));
+//            }
+//            //liveStatus
+//            if (null != liveStatus) {
+//                predList.add(criteriaBuilder.equal(root.get("deviceStatus").as(Integer.class), liveStatus));
+//            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagEartagRegisterEntity> eartagRegisterPage = eartagRegisterRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+
+
+        List<EartagEartagRegisterEntity> eartagRegisterEntityList = eartagRegisterPage.getContent();
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        DateUtil dateUtil = new DateUtil();
+        for (EartagEartagRegisterEntity eartagRegisterEntity : eartagRegisterEntityList) {
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", eartagRegisterEntity.getId());
+            outJo.put("earmark", eartagRegisterEntity.getEarmark());
+            outJo.put("firstTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getFirstTime()));
+            outJo.put("lastTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getLastTime()));
+            outJo.put("firstDevice", eartagRegisterEntity.getFirstDevice());
+            outJo.put("belongDevice", eartagRegisterEntity.getBelongDevice());
+            outJo.put("lastDevice", eartagRegisterEntity.getLastDevice());
+            outJo.put("registerTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getRegisterTime()));
+            outJo.put("registerType", eartagRegisterEntity.getRegisterType());
+            outJo.put("remark", eartagRegisterEntity.getRemark());
+            outJo.put("farmId", eartagRegisterEntity.getFarmId());
+            outJo.put("activeStatus", eartagRegisterEntity.getActiveStatus());
+            outJo.put("activeTime", dateUtil.formatDatetimeText(eartagRegisterEntity.getActiveTime()));
+            outJo.put("liveStatus", eartagRegisterEntity.getLiveStatus());
+            outJo.put("createDate", eartagRegisterEntity.getCreateDate());
+        }
+        outDataJo.put("pageable", eartagRegisterPage.getPageable());
+        outDataJo.put("last", eartagRegisterPage.isLast());
+        outDataJo.put("totalElements", eartagRegisterPage.getTotalElements());
+        outDataJo.put("totalPages", eartagRegisterPage.getTotalPages());
+        outDataJo.put("number", eartagRegisterPage.getNumber());
+        outDataJo.put("size", eartagRegisterPage.getSize());
+        outDataJo.put("sort", eartagRegisterPage.getSort());
+        outDataJo.put("numberOfElements", eartagRegisterPage.getNumberOfElements());
+        outDataJo.put("first", eartagRegisterPage.isFirst());
+        outDataJo.put("empty", eartagRegisterPage.isEmpty());
+//        System.out.println("## eartagRegisterPage>>"+eartagRegisterPage);
+//        List<EartagEartagRegisterEntity> eartagRegisterEntityList = eartagRegisterPage.getContent();
+//        System.out.println("## eartagRegisterEntityList.size()>>"+eartagRegisterEntityList.size());
+//        JSONArray dataJa = new JSONArray();
+//        for(EartagEartagRegisterEntity eartagRegisterEntity:eartagRegisterEntityList){
+//            JSONObject dataJo = JSONUtil.convertEntityToJSONObject(eartagRegisterEntity);
+//            dataJa.add(dataJo);
+//            dataJo.put("firstTime",du.formatDatetimeText(eartagRegisterEntity.getFirstTime()));
+//            dataJo.put("lastTime",du.formatDatetimeText(eartagRegisterEntity.getLastTime()));
+//            dataJo.put("registerTime",du.formatDatetimeText(eartagRegisterEntity.getRegisterTime()));
+//            dataJo.put("activeTime",du.formatDatetimeText(eartagRegisterEntity.getActiveTime()));
+//            dataJo.put("createDate",du.formatDateText(eartagRegisterEntity.getCreateDate()));
+//        }
+//    for(EartagEartagRegisterEntity eartagRegisterEntity:eartagRegisterEntityList){
+//        eartagRegisterEntity.setFirstTime(new Timestamp(du.parseDateTime(eartagRegisterEntity.getFirstTime().toString()).getTime()));
+//        System.out.println("getFirstTime 33>>"+du.parseDateTime(eartagRegisterEntity.getFirstTime().toString()));
+//    }
+        return new Result(ResultCode.SUCCESS, outDataJo);
+    }
+
+    /**
+     * @Method : getEartagDeviceByEarmarkAndAddDate
+     * @Description :
+     * @Params : [earmark, addDate]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/10
+     * @Time : 22:39
+     */
+    @Override
+    public Result listEartagDeviceByEarmarkAndAddDate(String earmark, String addDate) {
+        //
+        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getOnlineEartagDeviceByEarmarkAndAddDate(earmark, addDate);
+        if (deviceEartagCountEntityList != null) {
+            return new Result(ResultCode.SUCCESS, JSON.toJSON(deviceEartagCountEntityList));
+        } else {
+            return new Result(BizConst.CODE_DEVICE_EARTAG_COUNT_NO_EXIST, BizConst.MSG_DEVICE_EARTAG_COUNT_NO_EXIST, false);
+        }
+    }
+
+
+    /**
+     * @Method : listOnlineEartagCount
+     * @Description :
+     * @Params : [farmId, addDate, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/10
+     * @Time : 21:52
+     */
+    @Override
+    public Result listOnlineEartagCount(String farmId, String addDate, Integer pageNo, Integer pageSize, Integer showMode) throws ParseException {
+        if (showMode == 1) {
+            //
+            return listEartagOnlineInRecords(farmId, addDate, pageNo, pageSize);
+        } else {
+            //
+            return getEartagOnlineInChart(farmId, addDate);
+        }
+
+    }
+
+    /**
+     * @Method : getEartagOnlineInChart
+     * @Description :
+     * @Params : [farmId, addDate]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/10
+     * @Time : 22:03
+     */
+    private Result getEartagOnlineInChart(String farmId, String addDate) throws ParseException {
+        //
+        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByFarmIdAndDate(farmId, addDate);
+        if (eartagOnlineEntityList.size() > 0) {
+            JSONArray dataJa = new JSONArray();
+            for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+                JSONObject newJo = new JSONObject();
+                newJo.put("time", eartagOnlineEntity.getEarmark());
+                newJo.put("value", eartagOnlineEntity.getTotal());
+                dataJa.add(newJo);
+            }
+            return new Result(ResultCode.SUCCESS, dataJa);
+        } else {
+            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : listEartagOnlineInRecords
+     * @Description :
+     * @Params : [farmId, addDate, pageNo, pageSize, showMode]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/10
+     * @Time : 21:54
+     */
+    private Result listEartagOnlineInRecords(String farmId, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        System.out.println("# addDate>>" + addDate);
+        System.out.println("# farmId>>" + farmId);
+        System.out.println("# pageNo>>" + pageNo);
+        System.out.println("# pageSize>>" + pageSize);
+        //
+        Specification<EartagEartagOnlineEntity> sf = (Specification<EartagEartagOnlineEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            if (null != farmId && farmId.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("farmId").as(String.class), farmId));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("addDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagEartagOnlineEntity> pageEartagOnline = eartagOnlineRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        outDataJo.put("pageable", pageEartagOnline.getPageable());
+        outDataJo.put("last", pageEartagOnline.isLast());
+        outDataJo.put("totalElements", pageEartagOnline.getTotalElements());
+        outDataJo.put("totalPages", pageEartagOnline.getTotalPages());
+        outDataJo.put("number", pageEartagOnline.getNumber());
+        outDataJo.put("size", pageEartagOnline.getSize());
+        outDataJo.put("sort", pageEartagOnline.getSort());
+        outDataJo.put("numberOfElements", pageEartagOnline.getNumberOfElements());
+        outDataJo.put("first", pageEartagOnline.isFirst());
+        outDataJo.put("empty", pageEartagOnline.isEmpty());
+
+        List<EartagEartagOnlineEntity> eartagOnlineEntityList = pageEartagOnline.getContent();
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        DateUtil dateUtil = new DateUtil();
+        for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", eartagOnlineEntity.getId());
+            outJo.put("earmark", eartagOnlineEntity.getEarmark());
+            outJo.put("total", eartagOnlineEntity.getTotal());
+            outJo.put("firstTime", dateUtil.formatDatetimeText(eartagOnlineEntity.getFirstTime()));
+            outJo.put("lastTime", dateUtil.formatDatetimeText(eartagOnlineEntity.getLastTime()));
+            outJo.put("envTemp", eartagOnlineEntity.getEnvTemp());
+            outJo.put("eartagTemp", eartagOnlineEntity.getEartagTemp());
+            outJo.put("addDate", eartagOnlineEntity.getAddDate());
+            outJo.put("farmId", eartagOnlineEntity.getFarmId());
+        }
+
+        return new Result(ResultCode.SUCCESS, outDataJo);
+    }
+
+    /**
+     * @Method : listEartagOnlineAllStatus
+     * @Description :
+     * @Params : [farmId, days]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/10
+     * @Time : 20:52
+     */
+    @Override
+    public Result listEartagOnlineAllStatus(String farmId, Integer days) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        String pastDate = dateUtil.getPastDate(days);
+        String todayDate = dateUtil.getTodayDateText();
+        List<EartarFarmAllStatusEntity> FarmAllStatusEntityList = farmAllStatusRepo.getOneByFarmIdAndCreateDateAndPastDate(farmId, pastDate, todayDate);
+        JSONArray dataJa = new JSONArray();
+        for (EartarFarmAllStatusEntity farmAllStatusEntity : FarmAllStatusEntityList) {
+            JSONObject newJo = new JSONObject();
+            dataJa.add(newJo);
+            newJo.put("time", dateUtil.formatDateText(farmAllStatusEntity.getCreateDate()));
+            newJo.put("value", farmAllStatusEntity.getEartagOnline());
+//            newJo.put("total", farmAllStatusEntity.getEartagTotal());
+        }
+        return new Result(ResultCode.SUCCESS, dataJa);
+    }
+
+    /**
+     * @Method : listEartagOnlineStatusByEarmarkAndDate
+     * @Description : 显示耳标在线统计
+     * @Params : [earmark, pastDays]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 18:30
+     */
+    @Override
+    public Result listEartagOnlineStatusByEarmarkAndDate(String earmark, Integer pastDays) throws ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        String startDateText = du.getPastDate(pastDays);
+        log.info("<listEartagOnlineStatusByEarmarkAndDate> startDateText>>" + startDateText);
+        log.info("<listEartagOnlineStatusByEarmarkAndDate> todayDateText>>" + todayDateText);
+        //读取耳标在线统计记录
+        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
+        if (eartagOnlineEntityList.size() > 0) {
+            JSONArray dataJa = new JSONArray();
+            List<String> pastDateList = du.getPastIntervalsASC(pastDays);
+            for (String pastDayDate : pastDateList) {
+                JSONObject newJo = new JSONObject();
+                dataJa.add(newJo);
+                newJo.put("time", pastDayDate);
+                boolean ieFound = false;
+                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+                    int compareTo = du.parseDate(pastDayDate).compareTo(eartagOnlineEntity.getAddDate());
+                    if (compareTo == 0) {
+                        newJo.put("value", 1);
+                        ieFound = true;
+                        break;
+                    }
+                }
+                if (!ieFound) {
+                    newJo.put("value", 0);
+                }
+            }
+//            for(EartagEartagOnlineEntity eartagOnlineEntity:eartagOnlineEntityList){
+//                JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
+//                eartagOnlineJo.put("firstTime",du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
+//                eartagOnlineJo.put("lastTime",du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
+//                eartagOnlineJo.put("addDate",du.formatDateText(eartagOnlineJo.getDate("addDate")));
+//                dataJa.add(eartagOnlineJo);
+//            }
+            return new Result(ResultCode.SUCCESS, dataJa);
+        } else {
+            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : getEartagRegisterByEarmarkInPager
+     * @Description : 分页查询耳标流水
+     * @Params : [earmark, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 20:19
+     */
+    @Override
+    public Result listEartagFlowByEarmarkAndTodayInPager(String earmark, Integer pageNo, Integer pageSize, String createDate, String deviceCode) throws ParseException {
+        System.out.println("earmark>>" + earmark);
+        System.out.println("pageNo>>" + pageNo);
+        System.out.println("pageSize>>" + pageSize);
+        System.out.println("createDate>>" + createDate);
+        System.out.println("deviceCode>>" + deviceCode);
+        //
+        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //earmark
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //createDate
+            if (null != createDate && createDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        outDataJo.put("pageable", pageEartagData.getPageable());
+        outDataJo.put("last", pageEartagData.isLast());
+        outDataJo.put("totalElements", pageEartagData.getTotalElements());
+        outDataJo.put("totalPages", pageEartagData.getTotalPages());
+        outDataJo.put("number", pageEartagData.getNumber());
+        outDataJo.put("size", pageEartagData.getSize());
+        outDataJo.put("sort", pageEartagData.getSort());
+        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
+        outDataJo.put("first", pageEartagData.isFirst());
+        outDataJo.put("empty", pageEartagData.isEmpty());
+        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
+        System.out.println("## dataEntityList.size>>" + dataEntityList.size());
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        DateUtil dateUtil = new DateUtil();
+        for (EartagDataEntity eartagDataEntity : dataEntityList) {
+//            System.out.println(">>"+deviceRegisterEntity.toString());
+//            Map map = JSON.parseObject(JSONObject.toJSONString(deviceRegisterEntity),Map.class);
+//            System.out.println("map>>"+map.toString());
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", eartagDataEntity.getId());
+            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
+            outJo.put("device", eartagDataEntity.getDevice());
+            outJo.put("earmark", eartagDataEntity.getEarmark());
+            outJo.put("bat", eartagDataEntity.getBat());
+            outJo.put("earTemp", eartagDataEntity.getEarTemp());
+            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
+            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
+            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
+            outJo.put("act", eartagDataEntity.getAct());
+            outJo.put("act1", eartagDataEntity.getAct1());
+            outJo.put("signal1", eartagDataEntity.getSignal1());
+            outJo.put("askTime", eartagDataEntity.getAskTime());
+            outJo.put("other", eartagDataEntity.getOther());
+            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
+            outJo.put("createDate", eartagDataEntity.getCreateDate());
+            outJo.put("farmId", eartagDataEntity.getFarmId());
+        }
+
+        return new Result(ResultCode.SUCCESS, outDataJo);
+//        return new Result(ResultCode.SUCCESS, pageEartagData);
+    }
+
+    /**
+     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager
+     * @Description :
+     * @Params : [earmark, deviceCode, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 20:37
+     */
+    @Override
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndTodayInPager(String earmark, String deviceCode, String createDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //earmark
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //deviceCode
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
+            }
+            //createDate
+            if (null != createDate && createDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(createDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagDataEntity> pageEartagData = eartagDataRepo.findAll(sf, pageable);
+        JSONObject outDataJo = new JSONObject();
+        outDataJo.put("pageable", pageEartagData.getPageable());
+        outDataJo.put("last", pageEartagData.isLast());
+        outDataJo.put("totalElements", pageEartagData.getTotalElements());
+        outDataJo.put("totalPages", pageEartagData.getTotalPages());
+        outDataJo.put("number", pageEartagData.getNumber());
+        outDataJo.put("size", pageEartagData.getSize());
+        outDataJo.put("sort", pageEartagData.getSort());
+        outDataJo.put("numberOfElements", pageEartagData.getNumberOfElements());
+        outDataJo.put("first", pageEartagData.isFirst());
+        outDataJo.put("empty", pageEartagData.isEmpty());
+
+        List<EartagDataEntity> dataEntityList = pageEartagData.getContent();
+        JSONArray outJa = new JSONArray();
+        outDataJo.put("content", outJa);
+        DateUtil dateUtil = new DateUtil();
+        for (EartagDataEntity eartagDataEntity : dataEntityList) {
+            JSONObject outJo = new JSONObject();
+            outJa.add(outJo);
+            outJo.put("id", eartagDataEntity.getId());
+            outJo.put("cmdHeader", eartagDataEntity.getCmdHeader());
+            outJo.put("device", eartagDataEntity.getDevice());
+            outJo.put("earmark", eartagDataEntity.getEarmark());
+            outJo.put("bat", eartagDataEntity.getBat());
+            outJo.put("earTemp", eartagDataEntity.getEarTemp());
+            outJo.put("earTemp1", eartagDataEntity.getEarTemp1());
+            outJo.put("envTemp", eartagDataEntity.getEnvTemp());
+            outJo.put("envTemp1", eartagDataEntity.getEnvTemp1());
+            outJo.put("act", eartagDataEntity.getAct());
+            outJo.put("act1", eartagDataEntity.getAct1());
+            outJo.put("signal1", eartagDataEntity.getSignal1());
+            outJo.put("askTime", eartagDataEntity.getAskTime());
+            outJo.put("other", eartagDataEntity.getOther());
+            outJo.put("addTime", dateUtil.formatDatetimeText(eartagDataEntity.getAddTime()));
+            outJo.put("createDate", eartagDataEntity.getCreateDate());
+            outJo.put("farmId", eartagDataEntity.getFarmId());
+        }
+        return new Result(ResultCode.SUCCESS, outDataJo);
+//        return new Result(ResultCode.SUCCESS, pageEartagData);
+    }
+
+    /**
+     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndDateInPager
+     * @Description :
+     * @Params : [earmark, deviceCode, addDate, pageNo, pageSize]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/9
+     * @Time : 22:14
+     */
+    @Override
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndDateInPager(String earmark, String deviceCode, String addDate, Integer pageNo, Integer pageSize) throws ParseException {
+        //
+        Specification<EartagDataEntity> sf = (Specification<EartagDataEntity>) (root, criteriaQuery, criteriaBuilder) -> {
+            //
+            List<Predicate> predList = new ArrayList<>();
+            //earmark
+            if (null != earmark && earmark.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("earmark").as(String.class), earmark));
+            }
+            //
+            if (null != deviceCode && deviceCode.trim().length() > 0) {
+                predList.add(criteriaBuilder.equal(root.get("device").as(String.class), deviceCode));
+            }
+            //
+            if (null != addDate && addDate.trim().length() > 0) {
+                try {
+                    predList.add(criteriaBuilder.equal(root.get("createDate").as(Date.class), new Date(new DateUtil().parseDateTextToLong(addDate))));
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                }
+            }
+            Predicate[] pred = new Predicate[predList.size()];
+            Predicate and = criteriaBuilder.and(predList.toArray(pred));
+            criteriaQuery.where(and);
+            //
+            List<Order> orders = new ArrayList<>();
+            orders.add(criteriaBuilder.desc(root.get("id")));
+            return criteriaQuery.orderBy(orders).getRestriction();
+        };
+        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
+        Page<EartagDataEntity> pageEnvEntity = eartagDataRepo.findAll(sf, pageable);
+        DateUtil dateUtil = new DateUtil();
+        JSONObject pageJo = JSONObject.parseObject(JSONObject.toJSONString(pageEnvEntity));
+        JSONArray contentJa = pageJo.getJSONArray("content");
+        for (int a = 0; a < contentJa.size(); a++) {
+            JSONObject contentJo = contentJa.getJSONObject(a);
+            contentJo.put("addTime", dateUtil.formatDatetimeText(contentJo.getDate("addTime")));
+        }
+        return new Result(ResultCode.SUCCESS, pageJo);
+    }
+
+    /**
+     * @Method : listEartagOnlineCountByEarmarkAndDate
+     * @Description : 显示耳标在线统计
+     * @Params : [earmark, pastDays]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/8
+     * @Time : 18:30
+     */
+    @Override
+    public Result listEartagOnlineCountByEarmarkAndDate(String earmark, Integer pastDays, Integer showMode) throws ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        String startDateText = du.getPastDate(pastDays);
+        log.info("<listEartagOnlineCountByEarmarkAndDate> startDateText>>" + startDateText);
+        log.info("<listEartagOnlineCountByEarmarkAndDate> todayDateText>>" + todayDateText);
+        //读取耳标在线统计记录
+        if (showMode == 1) {
+            List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineRecordsByEarmarkAndDate(earmark, startDateText, todayDateText);
+            if (eartagOnlineEntityList.size() > 0) {
+                //返回在线记录
+                JSONArray dataJa = new JSONArray();
+                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
+                    eartagOnlineJo.put("firstTime", du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
+                    eartagOnlineJo.put("lastTime", du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
+                    eartagOnlineJo.put("addDate", du.formatDateText(eartagOnlineJo.getDate("addDate")));
+                    dataJa.add(eartagOnlineJo);
+                }
+                return new Result(ResultCode.SUCCESS, dataJa);
+            } else {
+                return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
+            }
+        } else {
+            List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
+            if (eartagOnlineEntityList.size() > 0) {
+                //返回在线图表
+                JSONArray dataJa = new JSONArray();
+                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+//                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
+                    JSONObject newJo = new JSONObject();
+                    newJo.put("time", du.formatDateText(eartagOnlineEntity.getAddDate()));
+                    newJo.put("value", eartagOnlineEntity.getTotal());
+                    dataJa.add(newJo);
+                }
+                return new Result(ResultCode.SUCCESS, dataJa);
+            } else {
+                return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
+            }
+        }
+    }
+
+    public Result listEartagOnlineCountByEarmarkAndDate_old1(String earmark, Integer pastDays, Integer showMode) throws
+            ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        String startDateText = du.getPastDate(pastDays);
+        log.info("<listEartagOnlineCountByEarmarkAndDate> startDateText>>" + startDateText);
+        log.info("<listEartagOnlineCountByEarmarkAndDate> todayDateText>>" + todayDateText);
+        //读取耳标在线统计记录
+        List<EartagEartagOnlineEntity> eartagOnlineEntityList = eartagOnlineRepo.getEartagOnlineByEarmarkAndDate(earmark, startDateText, todayDateText);
+        if (eartagOnlineEntityList.size() > 0) {
+            if (showMode == 1) {
+                //返回在线记录
+                JSONArray dataJa = new JSONArray();
+                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
+                    eartagOnlineJo.put("firstTime", du.formatDatetimeText(eartagOnlineJo.getDate("firstTime")));
+                    eartagOnlineJo.put("lastTime", du.formatDatetimeText(eartagOnlineJo.getDate("lastTime")));
+                    eartagOnlineJo.put("addDate", du.formatDateText(eartagOnlineJo.getDate("addDate")));
+                    dataJa.add(eartagOnlineJo);
+                }
+                return new Result(ResultCode.SUCCESS, dataJa);
+            } else {
+                //返回在线图表
+                JSONArray dataJa = new JSONArray();
+                for (EartagEartagOnlineEntity eartagOnlineEntity : eartagOnlineEntityList) {
+//                    JSONObject eartagOnlineJo = JSONUtil.convertEntityToJSONObject(eartagOnlineEntity);
+                    JSONObject newJo = new JSONObject();
+                    newJo.put("time", du.formatDateText(eartagOnlineEntity.getAddDate()));
+                    newJo.put("value", eartagOnlineEntity.getTotal());
+                    dataJa.add(newJo);
+                }
+                return new Result(ResultCode.SUCCESS, dataJa);
+            }
+        } else {
+            return new Result(BizConst.CODE_EARTAG_ONLINE_NO_EXIST, BizConst.MSG_EARTAG_ONLINE_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : listEartagFlowByDeviceCodeAndEarmarkAndToday
+     * @Description : 根据设备编码、耳标号和当天日期读取耳标流水数据
+     * @Params : [earmark, deviceCode]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 18:46
+     */
+    @Override
+    public Result listEartagFlowByDeviceCodeAndEarmarkAndToday(String earmark, String deviceCode) throws
+            ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        //
+        List<EartagDataEntity> eartagDataEntityList = eartagDataRepo.getEartagFlowByDeviceCodeAndEarmarkAndToday(deviceCode, earmark, todayDateText);
+        if (eartagDataEntityList.size() > 0) {
+            return new Result(ResultCode.SUCCESS, JSON.toJSON(eartagDataEntityList));
+        } else {
+            return new Result(BizConst.CODE_EARTAG_FLOW_NO_EXIST, BizConst.MSG_EARTAG_FLOW_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : listEartagFlowByEarmarkAndToday
+     * @Description : 根据耳标号读取今天所有流水
+     * @Params : [earmark]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 18:41
+     */
+    @Override
+    public Result listEartagFlowByEarmarkAndToday(String earmark) throws ParseException {
+        DateUtil du = new DateUtil();
+        String todayDateText = du.getTodayDateText();
+        //
+        List<EartagDataEntity> eartagDataEntityList = eartagDataRepo.getEartagFlowByEarmarkAndToday(earmark, todayDateText);
+        if (eartagDataEntityList.size() > 0) {
+            return new Result(ResultCode.SUCCESS, JSON.toJSON(eartagDataEntityList));
+        } else {
+            return new Result(BizConst.CODE_EARTAG_FLOW_NO_EXIST, BizConst.MSG_EARTAG_FLOW_NO_EXIST, false);
+        }
+    }
+
+    /**
+     * @Method : getEartagRegisterByEarmark
+     * @Description :
+     * @Params : [earmark]
+     * @Return : com.huimv.eartag2.common.utils.Result
+     * @Author : ZhuoNing
+     * @Date : 2022/3/7
+     * @Time : 18:41
+     */
+    @Override
+    public Result getEartagRegisterByEarmark(String earmark) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        //
+        EartagEartagRegisterEntity eartagRegisterEntity = eartagRegisterRepo.getEartagByEarmark(earmark);
+        if (eartagRegisterEntity != null) {
+            Map map = JSON.parseObject(JSONObject.toJSONString(eartagRegisterEntity), Map.class);
+//            map.put("lastTime",dateUtil.formatDatetimeText(new Date(dateUtil.parseDateTime(map.get("lastTime").toString()).getTime())));
+            map.put("firstTime", dateUtil.formatLongToDate(Long.parseLong(map.get("firstTime").toString())));
+            map.put("lastTime", dateUtil.formatLongToDate(Long.parseLong(map.get("lastTime").toString())));
+            map.put("activeTime", dateUtil.formatLongToDate(Long.parseLong(map.get("activeTime").toString())));
+            map.put("registerTime", dateUtil.formatLongToDate(Long.parseLong(map.get("registerTime").toString())));
+            return new Result(ResultCode.SUCCESS, map);
+        } else {
+            return new Result(BizConst.CODE_EARTAG_REGISTER_NO_EXIST, BizConst.MSG_EARTAG_REGISTER_NO_EXIST, false);
+        }
+    }
+}

+ 629 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/service/impl/EartagServiceImpl.java

@@ -0,0 +1,629 @@
+package com.huimv.eartag.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.eartag.dao.entity.*;
+import com.huimv.eartag.dao.repo.*;
+import com.huimv.eartag.utils.BizConst;
+import com.huimv.eartag.utils.DateUtil;
+import com.huimv.eartag.service.ICacheService;
+import com.huimv.eartag.service.IDeviceService;
+import com.huimv.eartag.service.IEartagService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class EartagServiceImpl implements IEartagService {
+    @Autowired
+    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法
+    @Autowired
+    private RedisTemplate redisTemplate;
+    @Autowired
+    private EartagDataRepo eartagDataRepo;
+    @Autowired
+    private IDeviceService deviceService;
+    @Autowired
+    private ICacheService cacheService;
+    @Autowired
+    private EartagEartagRegisterRepo eartagRegisterRepo;
+    @Autowired
+    private EartagEartagOnlineRepo eartagOnlineRepo;
+    @Autowired
+    private EartarFarmAllStatusRepo farmAllStatusRepo;
+    @Autowired
+    private EartarFarmAllStatusRepo eartagFarmAllStatusRepo;
+    @Autowired
+    private EartagDeviceEartagCountRepo deviceEartagCountRepo;
+    @Autowired
+    private EartagDeviceRegisterRepo deviceRegisterRepo;
+    @Autowired
+    private EartagDeviceOnlineRepo eartagDeviceOnlineRepo;
+
+    //处理耳标信息
+    @Override
+    public void handleEartagInfo() {
+        //--处理注册表数据
+        handleDeviceRegister();
+        //--处理在线记录数据
+        handleDeviceOnline();
+        //--处理状态数据
+        handleDeviceAllState();
+    }
+
+    //--处理状态数据
+    private void handleDeviceAllState() {
+
+    }
+
+    //--处理在线记录数据
+    private void handleDeviceOnline() {
+
+    }
+
+    //--处理注册表数据
+    private void handleDeviceRegister() {
+
+    }
+
+    /**
+     * @Method : countAct
+     * @Description : 计算act数值
+     * @Params : [deviceCode, nowAct0]
+     * @Return : java.lang.Integer
+     * @Author : ZhuoNing
+     * @Date : 2022/1/18
+     * @Time : 15:25
+     */
+    @Override
+    public Integer countAct(String deviceCode, String nowAct) {
+        //读取hash
+        Object actObj = redisTemplate.opsForHash().get(deviceCode, "act");
+        if (actObj == null) {
+            //--初始化最新的redis记录
+            initRedisObj(deviceCode);
+            Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
+            if (lastAct == null) {
+                log.error("#--- redis数据库有问题,请检查redis是否能正常连接 ---# ");
+                return 0;
+            }
+        }
+        Object lastAct = redisTemplate.opsForHash().get(deviceCode, "act");
+        Integer act1 = Integer.parseInt(nowAct) - Integer.parseInt(lastAct.toString());
+//        redisTemplate.opsForHash().put(deviceCode, "act1", act1);
+        return act1;
+    }
+
+    /**
+     * 初始化redis最新记录
+     */
+    private void initRedisObj(String deviceCode) {
+        EartagDataEntity lastEartagDataEntity = eartagDataRepo.getLastEartagData(deviceCode);
+        if (lastEartagDataEntity != null) {
+            System.out.println("## lastEartagDataEntity.toString>>" + lastEartagDataEntity.toString());
+            //--从数据库读取最新记录并覆盖redis
+            Map<String, String> map = new HashMap<>();
+            map.put("cmdHeader", lastEartagDataEntity.getCmdHeader());
+            map.put("device", lastEartagDataEntity.getDevice());
+            map.put("earmark", lastEartagDataEntity.getEarmark());
+            map.put("bat", lastEartagDataEntity.getBat().toString());
+            map.put("earTemp", lastEartagDataEntity.getEarTemp().toString());
+            map.put("earTemp1", lastEartagDataEntity.getEarTemp1().toString());
+            map.put("envTemp", lastEartagDataEntity.getEnvTemp().toString());
+            map.put("envTemp1", lastEartagDataEntity.getEnvTemp1().toString());
+            map.put("act", lastEartagDataEntity.getAct().toString());
+            map.put("act1", lastEartagDataEntity.getAct1().toString());
+            map.put("signal1", lastEartagDataEntity.getSignal1().toString());
+            map.put("askTime", lastEartagDataEntity.getAskTime());
+            map.put("other", lastEartagDataEntity.getOther());
+            map.put("addTime", lastEartagDataEntity.getAddTime().toString());
+            //为hash结构设置多个键值对(hmset)
+            redisTemplate.opsForHash().putAll(deviceCode, map);
+        }
+    }
+
+    @Override
+    public void handleEartag(JSONObject dataJo) throws ParseException {
+        //设备编码
+        String deviceCode = dataJo.getString("device");
+        //耳标号
+        String earmark = dataJo.getString("earmark");
+        //电量
+        String bat = dataJo.getString("bat");
+        String todayDateText = new DateUtil().getTodayDateText();
+        java.sql.Date todayDate = new java.sql.Date(new java.util.Date().getTime());
+        Timestamp nowTimestamp = new Timestamp(new java.util.Date().getTime());
+        //--设备在线统计表
+        //--设备状态每日统计表
+        //--设备和耳标总状态表
+        //获取牧场id
+        String farmId = deviceService.getFarmIdByDeviceCode(deviceCode);
+        if(farmId != null) {
+            //{保存耳标流水}
+            saveEartagFlow(dataJo, nowTimestamp, todayDate, farmId);
+
+            //{更新设备注册信息}
+            updateDeviceRegister(deviceCode, nowTimestamp, todayDate, farmId);
+
+            //{更新耳标注册信息}
+            updateEartagRegister(earmark, deviceCode,bat, nowTimestamp, todayDate, farmId);
+
+            //{更新设备在线统计}
+            updateDeviceOnline(earmark, deviceCode, todayDateText,nowTimestamp, todayDate, dataJo,farmId);
+
+            //{更新耳标在线统计}
+            updateEartagOnline(earmark, deviceCode, todayDateText, todayDate, nowTimestamp, dataJo, farmId);
+
+            //{更新耳标设备在线关联统计}
+            updateEartagDeviceOnlineCount(earmark, deviceCode, todayDateText, todayDate,nowTimestamp, farmId);
+
+            //判断该设备编号是否存在牧场缓存在线集合当中;
+            if (!cacheService.isExistEartagOnlineSet(farmId, earmark, todayDateText)) {
+                //更新总状态数据
+                updateEartagPropertyOfAllStatus(farmId, todayDateText, todayDate, nowTimestamp);
+                //将耳标号加入到耳标在线集合当中
+                cacheService.putEartagToOnlineInSet(farmId, earmark, todayDateText);
+            }
+            System.out.println("## END 耳标数据。 "+new DateUtil().getTodayMissionText());
+        }else{
+            log.error("出错:该请求的FarmId为空.请检查该设备编码["+deviceCode+"]是否存在FarmId.");
+        }
+    }
+
+    /**
+     * @Author      : ZhuoNing
+     * @Date        : 2022/2/9
+     * @Time        : 14:33
+     * @param eartagJo
+     * @param nowTimestamp
+     * @param todayDate
+     * @param farmId
+     */
+    public void saveEartagFlow(JSONObject eartagJo, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) throws ParseException {
+        DateUtil dateUtil = new DateUtil();
+        EartagDataEntity dataEntity = new EartagDataEntity();
+        dataEntity.setCmdHeader(eartagJo.getString("cmdHeader"));
+        dataEntity.setDevice(eartagJo.getString("device"));
+        dataEntity.setEarmark(eartagJo.getString("earmark"));
+        dataEntity.setBat(Integer.parseInt(eartagJo.getString("bat")));
+        dataEntity.setEarTemp(Integer.parseInt(eartagJo.getString("earTemp")));
+        dataEntity.setEarTemp1(eartagJo.getFloat("earTemp1"));
+        dataEntity.setEnvTemp(Integer.parseInt(eartagJo.getString("envTemp")));
+        dataEntity.setEnvTemp1(eartagJo.getFloat("envTemp1"));
+        dataEntity.setAct(Integer.parseInt(eartagJo.getString("act")));
+        dataEntity.setAct1(Integer.parseInt(eartagJo.getString("act1")));
+        dataEntity.setSignal1(Integer.parseInt(eartagJo.getString("signal")));
+        dataEntity.setAskTime(getAskTime(eartagJo.getString("askTime")));
+        dataEntity.setOther(eartagJo.getString("other"));
+        dataEntity.setAddTime(nowTimestamp);
+        dataEntity.setCreateDate(todayDate);
+        dataEntity.setFarmId(farmId);
+        dataEntity.setAskDate(new java.sql.Date(dateUtil.parseDate(getAskDate(eartagJo.getString("askTime"))).getTime()));
+        eartagDataRepo.saveAndFlush(dataEntity);
+
+        //最新的耳标数据覆盖老数据
+        cacheService.putEartagFlowToCache(dataEntity.getEarmark(),dataEntity);
+    }
+
+    //
+    public String getAskTime(String askTime) {
+        String newAskTime = askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) + " " + askTime.substring(8, 10) + ":" + askTime.substring(10, 12) + ":" + askTime.substring(12, 14);
+        return newAskTime;
+    }
+
+    public String getAskDate(String askTime) {
+        return askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) ;
+    }
+
+    /**
+     * @Method      : updateDeviceRegister
+     * @Description : 更新设备注册状态信息
+     * @Params      : [deviceCode, nowTimestamp, todayDate, farmId]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/22
+     * @Time        : 14:06
+     */
+    private void updateDeviceRegister(String deviceCode, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) {
+        EartagDeviceRegisterEntity deviceRegisterEntity = deviceRegisterRepo.getDeviceRegister(deviceCode);
+        if(deviceRegisterEntity == null){
+            log.error("(updateDeviceRegister).deviceRegisterEntity=null <-- deviceCode>>"+deviceCode);
+        }
+        deviceRegisterEntity.setLastTime(nowTimestamp);
+        deviceRegisterEntity.setActiveStatus(1);
+        deviceRegisterEntity.setActiveTime(nowTimestamp);
+        deviceRegisterEntity.setUpdateType("耳标");
+        deviceRegisterEntity.setDeviceStatus(1);
+        deviceRegisterRepo.saveAndFlush(deviceRegisterEntity);
+    }
+
+    //更新耳标注册数据
+    public void updateEartagRegister(String earmark, String deviceCode, String bat, Timestamp nowTimestamp, java.sql.Date todayDate, String farmId) {
+        //# 判断耳标注册表是否存在;
+        //      如果不存在就注册耳标;
+        //      如果存在就更新活动状态(active_status)和活动状态更新时间(active_time)
+        Integer registerType = 1;
+        Integer activeStatus = 1;
+        Integer liveStatus = 1;        //
+        EartagEartagRegisterEntity eartagRegisterEntity = eartagRegisterRepo.getOneByEarmark(earmark,farmId);
+        if(eartagRegisterEntity == null){
+            //{新建耳标注册信息}
+            newEartagRegister(earmark,nowTimestamp,deviceCode,registerType,activeStatus,liveStatus,bat,todayDate,farmId);
+        }else{
+            eartagRegisterEntity.setLastTime(nowTimestamp);
+            eartagRegisterEntity.setLastDevice(deviceCode);
+            eartagRegisterEntity.setActiveStatus(activeStatus);
+            eartagRegisterEntity.setActiveTime(nowTimestamp);
+            eartagRegisterEntity.setBat(Integer.parseInt(bat));
+            eartagRegisterRepo.saveAndFlush(eartagRegisterEntity);
+            //更新耳标注册消息缓存
+            cacheService.putEartagRegister(earmark,eartagRegisterEntity);
+        }
+    }
+
+    //新建耳标注册信息
+    private void newEartagRegister(String earmark, Timestamp nowTimestamp, String deviceCode, Integer registerType, Integer activeStatus, Integer liveStatus, String bat, java.sql.Date todayDate, String farmId) {
+        //#创建耳标注册记录#
+        EartagEartagRegisterEntity newEartagRegisterEntity = new EartagEartagRegisterEntity();
+        newEartagRegisterEntity.setEarmark(earmark);
+        newEartagRegisterEntity.setFirstTime(nowTimestamp);
+        newEartagRegisterEntity.setLastTime(nowTimestamp);
+        newEartagRegisterEntity.setFirstDevice(deviceCode);
+        newEartagRegisterEntity.setBelongDevice(deviceCode);
+        newEartagRegisterEntity.setLastDevice(deviceCode);
+        newEartagRegisterEntity.setRegisterTime(nowTimestamp);
+        newEartagRegisterEntity.setRegisterType(registerType);
+        newEartagRegisterEntity.setFarmId(farmId);
+        newEartagRegisterEntity.setActiveStatus(activeStatus);
+        newEartagRegisterEntity.setActiveTime(nowTimestamp);
+        newEartagRegisterEntity.setLiveStatus(liveStatus);
+        newEartagRegisterEntity.setCreateDate(todayDate);
+        newEartagRegisterEntity.setBat(Integer.parseInt(bat));
+        eartagRegisterRepo.saveAndFlush(newEartagRegisterEntity);
+        //{更新耳标注册消息缓存}
+        cacheService.putEartagRegister(earmark,newEartagRegisterEntity);
+        //{更新耳标数量}
+        cacheService.putEartagTotal(getEartagSum(farmId,liveStatus),farmId);
+    }
+
+    //计算处于不同生存状态的耳标数量
+    private Integer getEartagSum(String farmId,Integer liveStatus){
+        List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId,liveStatus);
+        Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
+        //处于工作状态的耳标总数
+        return Integer.parseInt(eartagRegObj[0].toString());
+    }
+
+    /**
+     * @Method      : updateDeviceOnline
+     * @Description : 更新设备在线统计
+     * @Params      : [earmark, deviceCode, nowTimestamp, todayDate, farmId]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/29
+     * @Time        : 9:13
+     */
+    private void updateDeviceOnline(String earmark, String deviceCode, String todayDateText, Timestamp nowTimestamp, java.sql.Date todayDate, JSONObject dataJo, String farmId) {
+        // 查询在线统计;
+        // 不存在,则新建设备在线统计
+        //存在,则直接更新耳标数量;
+        String hashKey = BizConst.DEVICE_REGISTER_PREFIX+deviceCode;
+        //计算设备别名
+        String alias = (String)cacheService.getHashProperty(hashKey,"deviceAlias");
+        String earTemp1 =  dataJo.getString("earTemp1");
+        String envTemp1 = dataJo.getString("envTemp1");
+
+        //读取在线日期
+        EartagDeviceOnlineEntity eartagDeviceOnlineEntity = eartagDeviceOnlineRepo.getDeviceOnline(deviceCode, todayDateText);
+        if (eartagDeviceOnlineEntity == null) {
+            Integer heartbeatTotal = 0;
+            Integer envtempTotal = 0;
+            Timestamp heartbeatFirstTime = null;
+            Timestamp heartbeatLastTime = null;
+            Timestamp envtempFirstTime = null;
+            Timestamp envtempLastTime = null;
+            Timestamp firstTime = nowTimestamp;
+            Timestamp lastTime = nowTimestamp;
+            Timestamp eartagFirstTime = nowTimestamp;
+            Timestamp eartagLastTime = nowTimestamp;
+            Integer eartagTotal = 1;
+            Integer liveStatus = 1;
+            //{新建设备在线统计并创建缓存}
+            newDeviceOnline(deviceCode,alias,heartbeatTotal,envtempTotal,eartagTotal,todayDate,farmId,heartbeatFirstTime,heartbeatLastTime,envtempFirstTime,envtempLastTime,firstTime,lastTime,eartagFirstTime,eartagLastTime,earTemp1,envTemp1,liveStatus);
+        }else{
+
+            eartagDeviceOnlineEntity.setAlias(alias);
+            int eartagTotal = eartagDeviceOnlineEntity.getEartagTotal();
+            eartagDeviceOnlineEntity.setEartagTotal(++eartagTotal);
+            eartagDeviceOnlineEntity.setEartagFirstTime(nowTimestamp);
+            eartagDeviceOnlineEntity.setEartagLastTime(nowTimestamp);
+            eartagDeviceOnlineEntity.setLastEartag(earTemp1);
+            eartagDeviceOnlineEntity.setLastEnvtemp(envTemp1);
+            if(eartagDeviceOnlineEntity.getFirstTime() == null){
+                eartagDeviceOnlineEntity.setFirstTime(nowTimestamp);
+            }
+            eartagDeviceOnlineEntity.setLastTime(nowTimestamp);
+            eartagDeviceOnlineRepo.saveAndFlush(eartagDeviceOnlineEntity);
+            //更新设备在线缓存数据
+            cacheService.putDeviceInOnline(deviceCode,eartagDeviceOnlineEntity);
+        }
+    }
+
+    /**
+     * @Method      : newDeviceOnline
+     * @Description : 新建设备在线
+     * @Params      : [deviceCode, alias, heartbeatTotal, envtempTotal, eartagTotal, todayDate, farmId, heartbeatFirstTime, heartbeatLastTime, envtempFirstTime, envtempLastTime, firstTime, lastTime, eartagFirstTime, eartagLastTime]
+     * @Return      : void
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/29
+     * @Time        : 9:44
+     */
+    private void newDeviceOnline(String deviceCode, String alias, Integer heartbeatTotal, Integer envtempTotal, Integer eartagTotal, java.sql.Date todayDate, String farmId, Timestamp heartbeatFirstTime, Timestamp heartbeatLastTime, Timestamp envtempFirstTime, Timestamp envtempLastTime, Timestamp firstTime, Timestamp lastTime, Timestamp eartagFirstTime, Timestamp eartagLastTime, String earTemp1, String envTemp1, Integer liveStatus) {
+        EartagDeviceOnlineEntity newEartagDeviceOnlineEntity = new EartagDeviceOnlineEntity();
+        newEartagDeviceOnlineEntity.setDeviceCode(deviceCode);
+        newEartagDeviceOnlineEntity.setAlias(alias);
+        newEartagDeviceOnlineEntity.setHeartbeatTotal(heartbeatTotal);;
+        newEartagDeviceOnlineEntity.setEnvtempTotal(envtempTotal);
+        newEartagDeviceOnlineEntity.setEartagTotal(eartagTotal);
+        newEartagDeviceOnlineEntity.setFirstTime(firstTime);
+        newEartagDeviceOnlineEntity.setLastTime(lastTime);
+        newEartagDeviceOnlineEntity.setLastEnvtemp(envTemp1);
+        newEartagDeviceOnlineEntity.setLastEartag(earTemp1);
+        newEartagDeviceOnlineEntity.setAddDate(todayDate);
+        newEartagDeviceOnlineEntity.setFarmId(farmId);
+        newEartagDeviceOnlineEntity.setHeartbeatFirstTime(heartbeatFirstTime);
+        newEartagDeviceOnlineEntity.setHeartbeatLastTime(heartbeatLastTime);
+        newEartagDeviceOnlineEntity.setEnvtempFirstTime(envtempFirstTime);
+        newEartagDeviceOnlineEntity.setEnvtempLastTime(envtempLastTime);
+        newEartagDeviceOnlineEntity.setEartagFirstTime(eartagFirstTime);
+        newEartagDeviceOnlineEntity.setEartagLastTime(eartagLastTime);
+        newEartagDeviceOnlineEntity.setLiveStatus(liveStatus);
+        eartagDeviceOnlineRepo.saveAndFlush(newEartagDeviceOnlineEntity);
+        //将新建的设备在线数据更新到设备在线缓存
+        cacheService.putDeviceInOnline(deviceCode,newEartagDeviceOnlineEntity);
+    }
+
+    //更新耳标在线数据
+    public void updateEartagOnline(String earmark, String deviceCode, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, JSONObject eartagJo, String farmId) {
+        //# 判断耳标在线统计数据是否存在
+        //      存在,则更新上传记录数、最后上传时间、环境温度,耳根温度,并将上面数据更新到缓存数据中;
+        //      不存在,则创建耳标在线记录,并更新到缓存数据中;
+        String envTemp = eartagJo.getString("envTemp1");
+        String earTemp = eartagJo.getString("earTemp1");
+        EartagEartagOnlineEntity eartagOnlineEntity = eartagOnlineRepo.getOneByEarmarkAndFarmId(earmark,todayDateText,farmId);
+        if(eartagOnlineEntity == null){
+            int total = 1;
+            //{新建耳标在线记录}
+            newEartagOnline(earmark,total,nowTimestamp,earTemp,envTemp,todayDate,farmId);
+        }else{
+            int total = eartagOnlineEntity.getTotal();
+            eartagOnlineEntity.setTotal(++total);
+            eartagOnlineEntity.setLastTime(nowTimestamp);
+            eartagOnlineEntity.setEnvTemp(envTemp);
+            eartagOnlineEntity.setEartagTemp(earTemp);
+            eartagOnlineRepo.saveAndFlush(eartagOnlineEntity);
+            //更新耳标在线统计
+            cacheService.putEartagOnlineCount(earmark,eartagOnlineEntity);
+        }
+    }
+
+    //新建耳标在线记录
+    private void newEartagOnline(String earmark, int total, Timestamp nowTimestamp, String earTemp, String envTemp, java.sql.Date todayDate, String farmId) {
+        EartagEartagOnlineEntity newEartagOnlineEntity = new EartagEartagOnlineEntity();
+        newEartagOnlineEntity.setEarmark(earmark);
+        newEartagOnlineEntity.setTotal(total);
+        newEartagOnlineEntity.setFirstTime(nowTimestamp);
+        newEartagOnlineEntity.setLastTime(nowTimestamp);
+        newEartagOnlineEntity.setEnvTemp(envTemp);
+        newEartagOnlineEntity.setEartagTemp(earTemp);
+        newEartagOnlineEntity.setAddDate(todayDate);
+        newEartagOnlineEntity.setFarmId(farmId);
+        eartagOnlineRepo.saveAndFlush(newEartagOnlineEntity);
+        //更新耳标在线统计
+        cacheService.putEartagOnlineCount(earmark,newEartagOnlineEntity);
+    }
+
+    //更新耳标设备在线次数
+    private void updateEartagDeviceOnlineCount(String earmark, String deviceCode, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, String farmId) {
+        //从缓存读取耳标关联数据
+//        Map timesMap = cacheService.getEartagDeviceOnlineCountEntries(earmark,deviceCode,todayDateText);
+//        System.out.println("###################### timesMap>>"+timesMap);
+//        if(timesMap.size()==0){
+//            System.out.println("==0");
+//        }else{
+//            System.out.println("!=0");
+//        }
+        //{读取耳标设备关联统计}
+        List<EartagDeviceEartagCountEntity> deviceEartagCountEntityList = deviceEartagCountRepo.getEartagDeviceCount(earmark,deviceCode,todayDateText);
+        if(deviceEartagCountEntityList.size()==0){
+            Integer count = 1;
+            //{新建耳标设备关联统计}
+            newEartagDeviceCount(earmark,deviceCode,count,todayDateText,todayDate,nowTimestamp,farmId);
+        }else{
+            //更新次数
+            EartagDeviceEartagCountEntity deviceEartagCountEntity = deviceEartagCountEntityList.get(0);
+            int total = deviceEartagCountEntity.getTotal();
+            ++total;
+            deviceEartagCountEntity.setTotal(total);
+            deviceEartagCountEntity.setUpdateTime(nowTimestamp);
+            deviceEartagCountRepo.saveAndFlush(deviceEartagCountEntity);
+            //缓存里计数+1
+            cacheService.countEartagDeviceOnlineTimes(earmark,deviceCode,total,deviceEartagCountEntity);
+        }
+    }
+
+    //新建耳标设备关联统计记录
+    private void newEartagDeviceCount(String earmark, String deviceCode, Integer count, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp, String farmId) {
+        EartagDeviceEartagCountEntity newDeviceEartagCountEntity = new EartagDeviceEartagCountEntity();
+        newDeviceEartagCountEntity.setDeviceCode(deviceCode);
+        newDeviceEartagCountEntity.setEarmark(earmark);
+        newDeviceEartagCountEntity.setTotal(count);
+        newDeviceEartagCountEntity.setCreateDate(todayDate);
+        newDeviceEartagCountEntity.setFarmId(farmId);
+        newDeviceEartagCountEntity.setUpdateTime(nowTimestamp);
+        deviceEartagCountRepo.saveAndFlush(newDeviceEartagCountEntity);
+        //将数据保存到缓存中
+        cacheService.putEartagDeviceOnlineCount(earmark,deviceCode,todayDateText,newDeviceEartagCountEntity);
+    }
+
+    //更新设备环境信息
+    public void updateEartagPropertyOfAllStatus(String farmId, String todayDateText, java.sql.Date todayDate, Timestamp nowTimestamp) throws ParseException {
+        //{获取处于工作状态的设备数量}
+        Integer deviceTotal = deviceService.getDeviceTotalByFarmIdFromDeviceRegister(farmId);
+        //设备在线数量
+        Integer deviceOnlineSum = cacheService.getDeviceOnlineSum(farmId,todayDateText);
+        //设备离线数量
+        Integer deviceOfflineSum = 0;
+        if(deviceTotal > deviceOnlineSum){
+            deviceOfflineSum = deviceTotal - deviceOnlineSum;
+        }
+        //设备在线率
+        BigDecimal deviceRateBd= new BigDecimal(deviceOnlineSum).divide(new BigDecimal(deviceTotal),1,BigDecimal.ROUND_HALF_UP);
+        Float deviceOnlineRate = Float.parseFloat(deviceRateBd.toString());
+        //{获取注销设备数量}
+        Integer deviceCancelSum = deviceService.getDeviceCancelTotalFromDeviceRegister(farmId);
+        //耳标总数量 eartagService.
+        Integer eartagTotal = getEartagRegTotalByFarmId(farmId);
+        System.out.println("## eartagTotal>>"+eartagTotal);
+        Integer eartagOnlineSum = 0;
+        Float eartagOnlineRate = 0F;
+        if(eartagTotal != 0){
+            //耳标在线数量 eartagService.
+            eartagOnlineSum = getEartagOnelineTotal(farmId,todayDateText);
+            eartagOnlineSum++;
+            //耳标在线率
+            BigDecimal eartagRateBd= new BigDecimal(eartagOnlineSum).divide(new BigDecimal(eartagTotal),1,BigDecimal.ROUND_HALF_UP);
+            eartagOnlineRate = Float.parseFloat(eartagRateBd.toString());
+        }
+        //
+        EartarFarmAllStatusEntity farmAllStatusEntity = eartagFarmAllStatusRepo.getOneByFarmIdAndCreateDate(farmId,todayDateText);
+        if(farmAllStatusEntity == null){
+            //{新建设备状态记录并更新缓存cache}
+            newFarmAllStatus(farmId,todayDate,nowTimestamp,deviceTotal,deviceOnlineSum,deviceOfflineSum,deviceCancelSum,deviceOnlineRate,eartagTotal,eartagOnlineSum,eartagOnlineRate);
+        }else{
+            //计算设备状态并更新缓存cache(在线数+1,离线数-1,计算设备在线率)
+            farmAllStatusEntity.setDeviceTotal(deviceTotal);
+            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
+            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
+            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
+            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
+            farmAllStatusEntity.setEartagTotal(eartagTotal);
+            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
+            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
+            farmAllStatusEntity.setUpdateTime(nowTimestamp);
+            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
+            //{同步更新牧场总状态缓存相关字段}
+            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
+        }
+    }
+
+    //# 新建总状态记录 #
+    private void newFarmAllStatus(String farmId, java.sql.Date todayDate, Timestamp nowTimestamp, Integer deviceTotal, Integer deviceOnlineSum, Integer deviceOfflineSum, Integer deviceCancelSum, Float deviceOnlineRate, Integer eartagTotal, Integer eartagOnlineSum, Float eartagOnlineRate) {
+        Integer liveStatus = 1;
+        if(deviceService.getDeviceSum(farmId,liveStatus) == 0){
+            log.error("该牧场没有任何处于工作状态的采集器设备.");
+        }else{
+            //# 计算耳标总数(耳标注册表)
+            EartarFarmAllStatusEntity farmAllStatusEntity = new EartarFarmAllStatusEntity();
+            farmAllStatusEntity.setDeviceTotal(deviceTotal);
+            farmAllStatusEntity.setDeviceOnline(deviceOnlineSum);
+            farmAllStatusEntity.setDeviceOffline(deviceOfflineSum);
+            farmAllStatusEntity.setDeviceRate(deviceOnlineRate);
+            farmAllStatusEntity.setDeviceCancel(deviceCancelSum);
+            farmAllStatusEntity.setEartagTotal(eartagTotal);
+            farmAllStatusEntity.setEartagOnline(eartagOnlineSum);
+            farmAllStatusEntity.setEartagRate(eartagOnlineRate);
+            farmAllStatusEntity.setFarmId(farmId);
+            farmAllStatusEntity.setUpdateTime(nowTimestamp);
+            farmAllStatusEntity.setCreateDate(todayDate);
+            eartagFarmAllStatusRepo.saveAndFlush(farmAllStatusEntity);
+            //设置总状态缓存
+            cacheService.flashAllStatusCache(farmId,farmAllStatusEntity);
+        }
+    }
+
+    @Override
+    public Integer getEartagRegTotalByFarmId(String farmId){
+        //从缓存读取耳标总数
+        Integer eartagTotal = cacheService.getEartagTotal(farmId);
+        if(eartagTotal != null && eartagTotal != 0){
+            return eartagTotal;
+        }else{
+//            List<Object[]> eartagRegList = eartagRegisterRepo.getEartagCountByFarmId(farmId);
+//            Object[] eartagRegObj = (Object[]) eartagRegList.get(0);
+//            Integer total = Integer.parseInt(eartagRegObj[0].toString());
+            ///
+            Integer liveStatus = 1;
+            //{读取处于工作状态的耳标总数}
+            Integer total = getEartagSum(farmId,liveStatus);
+            //设置耳标总数缓存
+            cacheService.putEartagTotal(total,farmId);
+            //处于工作状态的耳标总数
+            return total;
+        }
+    }
+
+    public Integer getEartagOnelineTotal(String farmId, String todayDateText) {
+        return cacheService.getEartagOnlineTotalFromCache(farmId,todayDateText);
+    }
+
+    /**
+     * @Method : countAct
+     * @Description : 计算act数值
+     * @Params : [deviceCode, nowAct0]
+     * @Return : java.lang.Integer
+     * @Author : ZhuoNing
+     * @Date : 2022/1/18
+     * @Time : 15:25
+     */
+    @Override
+    public Integer countEartagAct(String earmark, String nowAct) {
+        //读取hash
+        Object lastActObj = cacheService.getEartagLastAct(earmark);
+        cacheService.putEartagAct(earmark,nowAct);
+        //
+//        Object testActObj = cacheService.getEartagLastAct(earmark);
+//        System.out.println("## TEST testActObj>>"+testActObj);
+        if (lastActObj != null) {
+            return Integer.parseInt(nowAct) - Integer.parseInt(lastActObj.toString());
+        }else{
+            //{初始化最新的redis记录}
+//            cacheService.putEartagAct(earmark,nowAct);
+            //第一次的运动量计数
+//            return Integer.parseInt(nowAct) - 0;
+            return 0;
+            //验证刚才初始化结果
+//            Object lastAct = cacheService.getEartagLastAct(earmark);
+//            if (lastAct == null) {
+//                log.error("#--- redis数据库有问题,请检查redis是否能正常连接 ---# ");
+//                return 0;
+//            }else{
+//                return Integer.parseInt(lastAct.toString());
+//            }
+        }
+    }
+
+
+
+
+}

+ 12 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BaseTemplete.java

@@ -0,0 +1,12 @@
+package com.huimv.eartag.utils;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class BaseTemplete {
+}

+ 109 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BizConst.java

@@ -0,0 +1,109 @@
+package com.huimv.eartag.utils;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class BizConst {
+    //耳标上一次运动量数值
+    public final static String EARTAG_LAST_ACT_PREFIX = "lastAct:earmark:";
+
+    //所有设备注册信息都要加入缓存
+//    public final static String DEVICE_REGISTER_PREFIX = "device_register_";
+    public final static String DEVICE_REGISTER_PREFIX = "hash:register:device:";
+
+    //在线设备统计信息加入缓存
+//    public final static String DEVICE_ONLINE_PREFIX = "device_online_";
+    public final static String DEVICE_ONLINE_PREFIX = "hash:online:device:";
+
+    //牧场所有采集器设备编号集合+牧场id(Set)
+    public final static String SET_FARM_DEVICE_ALL_PREFIX = "farm_device_all_";
+
+    //牧场在线采集器设备编号集合+牧场id(Set)
+//    public final static String SET_FARM_DEVICE_ONLINE_PREFIX = "set_farm_device_online_";
+    public final static String SET_FARM_DEVICE_ONLINE_PREFIX = "set:onlineDevice:farm:";
+
+    //牧场所有耳标编号集合+牧场id(Set)
+//    public final static String SET_FARM_EARMARK_ALL_PREFIX = "farm_eartag_all_";
+
+    //耳标注册缓存
+//    public final static String EARTAG_REGISTER_PREFIX = "eartag_register_";
+    public final static String EARTAG_REGISTER_PREFIX = "hash:register:eartag:";
+
+    //在线耳标统计信息加入缓存
+//    public final static String EARTAG_ONLINE_PREFIX = "eartag_online_";
+    public final static String EARTAG_ONLINE_PREFIX = "hash:online:eartag:";
+
+    //牧场在线耳标编号集合+牧场id(Set)
+//    public final static String SET_FARM_EARMARK_ONLINE_PREFIX = "set_farm_eartag_online_";
+    public final static String SET_FARM_EARMARK_ONLINE_PREFIX = "set:onlineEartag:farm:";
+
+    //保存平台上所有设备集合
+    public final static String SET_ALL_DEVICE_PREFIX = "set:all:deviceCode";
+
+    //牧场总状态表+牧场id
+    public final static String FARM_ALL_STATUS_PREFIX = "allStatus:farm:";
+
+    //有效设备总数
+    public final static String FARM_DEVICE_TOTAL_PREFIX = "deviceTotal:farm:";
+    //设备在线总数
+//    public final static String FARM_DEVICE_TOTAL_ONLINE_PREFIX = "deviceTotal:online:farm:";
+    //设备取消数量
+    public final static String FARM_DEVICE_CANCEL_PREFIX = "deviceCancel:farm:";
+
+    //耳标总数
+    public final static String FARM_EARTAG_TOTAL_PREFIX = "eartagTotal:farm:";
+    //耳标在线总数
+//    public final static String FARM_EARTAG_TOTAL_ONLINE_PREFIX = "eartagTotal:online:farm:";
+
+    //耳标设备Hash
+    public final static String ONLINE_EARMARK_DEVICE_PREFIX = "hash:onlineTimes:earmark:device:";
+
+    //耳标最新流水
+    public final static String EARTAG_FLOW_PREFIX = "hash:eartag.flow:earmark:";
+
+    //芯片id和设备编码的映射
+    public final static String CHIP_DEVICE_PREFIX = "hash:chipId";
+
+    //环境温度高低温阈值
+    public static final String HASH_ENV_TEMP_TV_PREFIX = "hash:envTempTv:farmId";
+
+    //耳标温度高低温阈值
+    public static final String HASH_EARTAG_TEMP_TV_PREFIX = "hash:eartagTempTv:farmId";
+
+
+    public final static Integer CODE_DEVICE_ONLINE_NO_EXIST = 10001;
+    public final static String MSG_DEVICE_ONLINE_NO_EXIST = "今天无在线设备.";
+
+    public final static Integer CODE_DEVICE_REGISTER_NO_EXIST = 10002;
+    public final static String MSG_DEVICE_REGISTER_NO_EXIST = "该设备的注册信息不存在.";
+
+    public final static Integer CODE_DEVICE_EARTAG_COUNT_NO_EXIST = 10003;
+    public final static String MSG_DEVICE_EARTAG_COUNT_NO_EXIST = "该设备下暂无任何耳标上传数据.";
+
+    public final static Integer CODE_EARTAG_REGISTER_NO_EXIST = 10004;
+    public final static String MSG_EARTAG_REGISTER_NO_EXIST = "该耳标暂无任何注册信息.";
+
+    public final static Integer CODE_EARTAG_FLOW_NO_EXIST = 10005;
+    public final static String MSG_EARTAG_FLOW_NO_EXIST = "该耳标当天暂无流水信息.";
+
+    public final static Integer CODE_EARTAG_ONLINE_NO_EXIST = 10006;
+    public final static String MSG_EARTAG_ONLINE_NO_EXIST = "该耳标暂无在线统计信息.";
+
+    public final static Integer CODE_ENVTEMP_FLOW_NO_EXIST = 10007;
+    public final static String MSG_ENVTEMP_FLOW_NO_EXIST = "该设备暂无温度流水信息.";
+
+    public final static Integer CODE_DEVICE_CODE_EXIST = 10008;
+    public final static String MSG_DEVICE_CODE_EXIST = "该设备编号已经存在.";
+
+    public final static Integer CODE_DEVICE_STATUS_EXIST = 10009;
+
+
+//    public final static Integer CODE_DEVICE_REGISTER_NO_EXIST = 10009;
+//    public final static Integer CODE_DEVICE_STATUS_EXIST = 10009;
+
+}

+ 935 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/BytesUtil.java

@@ -0,0 +1,935 @@
+package com.huimv.eartag.utils;
+
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.nio.charset.Charset;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class BytesUtil {
+    public static final String GBK = "GBK";
+    public static final String UTF8 = "utf-8";
+    public static final char[] ascii = "0123456789ABCDEF".toCharArray();
+    private static char[] HEX_VOCABLE = {'0', '1', '2', '3', '4', '5', '6', '7',
+            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+    /**
+     * 将short整型数值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(short data) {
+        byte[] bytes = new byte[2];
+        bytes[0] = (byte) ((data & 0xff00) >> 8);
+        bytes[1] = (byte) (data & 0xff);
+        return bytes;
+    }
+
+    /**
+     * 将字符转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(char data) {
+        byte[] bytes = new byte[2];
+        bytes[0] = (byte) (data >> 8);
+        bytes[1] = (byte) (data);
+        return bytes;
+    }
+
+    /**
+     * 将布尔值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(boolean data) {
+        byte[] bytes = new byte[1];
+        bytes[0] = (byte) (data ? 1 : 0);
+        return bytes;
+    }
+
+    /**
+     * 将整型数值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(int data) {
+        byte[] bytes = new byte[4];
+        bytes[0] = (byte) ((data & 0xff000000) >> 24);
+        bytes[1] = (byte) ((data & 0xff0000) >> 16);
+        bytes[2] = (byte) ((data & 0xff00) >> 8);
+        bytes[3] = (byte) (data & 0xff);
+        return bytes;
+    }
+
+    /**
+     * 将long整型数值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(long data) {
+        byte[] bytes = new byte[8];
+        bytes[0] = (byte) ((data >> 56) & 0xff);
+        bytes[1] = (byte) ((data >> 48) & 0xff);
+        bytes[2] = (byte) ((data >> 40) & 0xff);
+        bytes[3] = (byte) ((data >> 32) & 0xff);
+        bytes[4] = (byte) ((data >> 24) & 0xff);
+        bytes[5] = (byte) ((data >> 16) & 0xff);
+        bytes[6] = (byte) ((data >> 8) & 0xff);
+        bytes[7] = (byte) (data & 0xff);
+        return bytes;
+    }
+
+    /**
+     * 将float型数值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(float data) {
+        int intBits = Float.floatToIntBits(data);
+        return getBytes(intBits);
+    }
+
+    /**
+     * 将double型数值转换为字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(double data) {
+        long intBits = Double.doubleToLongBits(data);
+        return getBytes(intBits);
+    }
+
+    /**
+     * 将字符串按照charsetName编码格式的字节数组
+     *
+     * @param data
+     *            字符串
+     * @param charsetName
+     *            编码格式
+     * @return
+     */
+    public static byte[] getBytes(String data, String charsetName) {
+        Charset charset = Charset.forName(charsetName);
+        return data.getBytes(charset);
+    }
+
+    /**
+     * 将字符串按照GBK编码格式的字节数组
+     *
+     * @param data
+     * @return
+     */
+    public static byte[] getBytes(String data) {
+        return getBytes(data, GBK);
+    }
+
+    /**
+     * 将字节数组第0字节转换为布尔值
+     *
+     * @param bytes
+     * @return
+     */
+    public static boolean getBoolean(byte[] bytes) {
+        return bytes[0] == 1;
+    }
+
+    /**
+     * 将字节数组的第index字节转换为布尔值
+     *
+     * @param bytes
+     * @param index
+     * @return
+     */
+    public static boolean getBoolean(byte[] bytes, int index) {
+        return bytes[index] == 1;
+    }
+
+    /**
+     * 将字节数组前2字节转换为short整型数值
+     *
+     * @param bytes
+     * @return
+     */
+    public static short getShort(byte[] bytes) {
+        return (short) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1]));
+    }
+
+    /**
+     * 将字节数组从startIndex开始的2个字节转换为short整型数值
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static short getShort(byte[] bytes, int startIndex) {
+        return (short) ((0xff00 & (bytes[startIndex] << 8))
+                | (0xff & bytes[startIndex + 1]));
+    }
+
+    /**
+     * 将字节数组前2字节转换为字符
+     *
+     * @param bytes
+     * @return
+     */
+    public static char getChar(byte[] bytes) {
+        return (char) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1]));
+    }
+
+    /**
+     * 将字节数组从startIndex开始的2个字节转换为字符
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static char getChar(byte[] bytes, int startIndex) {
+        return (char) ((0xff00 & (bytes[startIndex] << 8))
+                | (0xff & bytes[startIndex + 1]));
+    }
+
+    /**
+     * 将字节数组前4字节转换为整型数值
+     *
+     * @param bytes
+     * @return
+     */
+    public static int getInt(byte[] bytes) {
+        return (0xff000000 & (bytes[0] << 24) | (0xff0000 & (bytes[1] << 16))
+                | (0xff00 & (bytes[2] << 8)) | (0xff & bytes[3]));
+    }
+
+    /**
+     * 将字节数组从startIndex开始的4个字节转换为整型数值
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static int getInt(byte[] bytes, int startIndex) {
+        return (0xff000000 & (bytes[startIndex] << 24)
+                | (0xff0000 & (bytes[startIndex + 1] << 16))
+                | (0xff00 & (bytes[startIndex + 2] << 8))
+                | (0xff & bytes[startIndex + 3]));
+    }
+
+    /**
+     * 将字节数组前8字节转换为long整型数值
+     *
+     * @param bytes
+     * @return
+     */
+    public static long getLong(byte[] bytes) {
+        return (0xff00000000000000L & ((long) bytes[0] << 56)
+                | (0xff000000000000L & ((long) bytes[1] << 48))
+                | (0xff0000000000L & ((long) bytes[2] << 40))
+                | (0xff00000000L & ((long) bytes[3] << 32))
+                | (0xff000000L & ((long) bytes[4] << 24))
+                | (0xff0000L & ((long) bytes[5] << 16))
+                | (0xff00L & ((long) bytes[6] << 8))
+                | (0xffL & (long) bytes[7]));
+    }
+
+    /**
+     * 将字节数组从startIndex开始的8个字节转换为long整型数值
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static long getLong(byte[] bytes, int startIndex) {
+        return (0xff00000000000000L & ((long) bytes[startIndex] << 56)
+                | (0xff000000000000L & ((long) bytes[startIndex + 1] << 48))
+                | (0xff0000000000L & ((long) bytes[startIndex + 2] << 40))
+                | (0xff00000000L & ((long) bytes[startIndex + 3] << 32))
+                | (0xff000000L & ((long) bytes[startIndex + 4] << 24))
+                | (0xff0000L & ((long) bytes[startIndex + 5] << 16))
+                | (0xff00L & ((long) bytes[startIndex + 6] << 8))
+                | (0xffL & (long) bytes[startIndex + 7]));
+    }
+
+    /**
+     * 将字节数组前4字节转换为float型数值
+     *
+     * @param bytes
+     * @return
+     */
+    public static float getFloat(byte[] bytes) {
+        return Float.intBitsToFloat(getInt(bytes));
+    }
+
+    /**
+     * 将字节数组从startIndex开始的4个字节转换为float型数值
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static float getFloat(byte[] bytes, int startIndex) {
+        byte[] result = new byte[4];
+        System.arraycopy(bytes, startIndex, result, 0, 4);
+        return Float.intBitsToFloat(getInt(result));
+    }
+
+    /**
+     * 将字节数组前8字节转换为double型数值
+     *
+     * @param bytes
+     * @return
+     */
+    public static double getDouble(byte[] bytes) {
+        long l = getLong(bytes);
+        return Double.longBitsToDouble(l);
+    }
+
+    /**
+     * 将字节数组从startIndex开始的8个字节转换为double型数值
+     *
+     * @param bytes
+     * @param startIndex
+     * @return
+     */
+    public static double getDouble(byte[] bytes, int startIndex) {
+        byte[] result = new byte[8];
+        System.arraycopy(bytes, startIndex, result, 0, 8);
+        long l = getLong(result);
+        return Double.longBitsToDouble(l);
+    }
+
+    /**
+     * 将charsetName编码格式的字节数组转换为字符串
+     *
+     * @param bytes
+     * @param charsetName
+     * @return
+     */
+    public static String getString(byte[] bytes, String charsetName) {
+        return new String(bytes, Charset.forName(charsetName));
+    }
+
+    /**
+     * 将GBK编码格式的字节数组转换为字符串
+     *
+     * @param bytes
+     * @return
+     */
+    public static String getString(byte[] bytes) {
+        return getString(bytes, GBK);
+    }
+
+    /**
+     * 将16进制字符串转换为字节数组
+     *
+     * @param
+     * @return
+     */
+    // @Deprecated
+    // public static byte[] hexStringToBytes(String hex) {
+    // if (hex == null || "".equals(hex)) {
+    // return null;
+    // }
+    // int len = hex.length() / 2;
+    // byte[] result = new byte[len];
+    // char[] chArr = hex.toCharArray();
+    // for (int i = 0; i < len; i++) {
+    // int pos = i * 2;
+    // result[i] = (byte) (toByte(chArr[pos]) << 4 | toByte(chArr[pos + 1]));
+    // }
+    // return result;
+    // }
+
+    public static byte[] hexStringToBytes(String hexString) {
+        if (hexString == null || hexString.equals("")) {
+            return null;
+        }
+        // toUpperCase将字符串中的所有字符转换为大写
+        hexString = hexString.toUpperCase();
+        int length = hexString.length() / 2;
+        // toCharArray将此字符串转换为一个新的字符数组。
+        char[] hexChars = hexString.toCharArray();
+        byte[] d = new byte[length];
+        for (int i = 0; i < length; i++) {
+            int pos = i * 2;
+            d[i] = (byte) (charToByte(hexChars[pos]) << 4
+                    | charToByte(hexChars[pos + 1]));
+        }
+        return d;
+    }
+
+    // charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符
+    private static byte charToByte(char c) {
+        return (byte) "0123456789ABCDEF".indexOf(c);
+    }
+    /**
+     * 将16进制字符串转换为字节数组
+     *
+     * @param hex
+     * @return
+     */
+    public static byte[] hexToBytes(String hex) {
+        if (hex.length() % 2 != 0)
+            throw new IllegalArgumentException(
+                    "input string should be any multiple of 2!");
+        hex.toUpperCase();
+
+        byte[] byteBuffer = new byte[hex.length() / 2];
+
+        byte padding = 0x00;
+        boolean paddingTurning = false;
+        for (int i = 0; i < hex.length(); i++) {
+            if (paddingTurning) {
+                char c = hex.charAt(i);
+                int index = indexOf(hex, c);
+                padding = (byte) ((padding << 4) | index);
+                byteBuffer[i / 2] = padding;
+                padding = 0x00;
+                paddingTurning = false;
+            } else {
+                char c = hex.charAt(i);
+                int index = indexOf(hex, c);
+                padding = (byte) (padding | index);
+                paddingTurning = true;
+            }
+
+        }
+        return byteBuffer;
+    }
+
+    private static int indexOf(String input, char c) {
+        int index = ArrayUtils.indexOf(HEX_VOCABLE, c);
+
+        if (index < 0) {
+            throw new IllegalArgumentException("err input:" + input);
+        }
+        return index;
+
+    }
+
+    /**
+     * 将BCD编码的字节数组转换为字符串
+     *
+     * @param bcds
+     * @return
+     */
+    public static String bcdToString(byte[] bcds) {
+        if (bcds == null || bcds.length == 0) {
+            return null;
+        }
+        byte[] temp = new byte[2 * bcds.length];
+        for (int i = 0; i < bcds.length; i++) {
+            temp[i * 2] = (byte) ((bcds[i] >> 4) & 0x0f);
+            temp[i * 2 + 1] = (byte) (bcds[i] & 0x0f);
+        }
+        StringBuffer res = new StringBuffer();
+        for (int i = 0; i < temp.length; i++) {
+            res.append(ascii[temp[i]]);
+        }
+        return res.toString();
+    }
+
+    /**
+     * 字节转整形
+     *
+     * @param value
+     * @return
+     */
+    public static int bcdToInt(byte value) {
+        return ((value >> 4) * 10) + (value & 0x0F);
+    }
+
+    /**
+     * 字节数组转16进制字符串
+     *
+     * @param bs
+     * @return
+     */
+    public static String bytesToHex(byte[] bs) {
+        StringBuilder sb = new StringBuilder();
+        for (byte b : bs) {
+            int high = (b >> 4) & 0x0f;
+            int low = b & 0x0f;
+            sb.append(HEX_VOCABLE[high]);
+            sb.append(HEX_VOCABLE[low]);
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 字节数组取前len个字节转16进制字符串
+     *
+     * @param bs
+     * @param len
+     * @return
+     */
+    public static String bytesToHex(byte[] bs, int len) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < len; i++) {
+            byte b = bs[i];
+            int high = (b >> 4) & 0x0f;
+            int low = b & 0x0f;
+            sb.append(HEX_VOCABLE[high]);
+            sb.append(HEX_VOCABLE[low]);
+        }
+        return sb.toString();
+    }
+    /**
+     * 字节数组偏移offset长度之后的取len个字节转16进制字符串
+     *
+     * @param bs
+     * @param offset
+     * @param len
+     * @return
+     */
+    public static String bytesToHex(byte[] bs, int offset, int len) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < len; i++) {
+            byte b = bs[offset + i];
+            int high = (b >> 4) & 0x0f;
+            int low = b & 0x0f;
+            sb.append(HEX_VOCABLE[high]);
+            sb.append(HEX_VOCABLE[low]);
+        }
+        return sb.toString();
+    }
+    /**
+     * 字节数组转16进制字符串
+     *
+     * @param
+     * @return
+     */
+    public static String byteToHex(byte b) {
+        StringBuilder sb = new StringBuilder();
+        int high = (b >> 4) & 0x0f;
+        int low = b & 0x0f;
+        sb.append(HEX_VOCABLE[high]);
+        sb.append(HEX_VOCABLE[low]);
+        return sb.toString();
+    }
+    /**
+     * 将字节数组取反
+     *
+     * @param src
+     * @return
+     */
+    public static String negate(byte[] src) {
+        if (src == null || src.length == 0) {
+            return null;
+        }
+        byte[] temp = new byte[2 * src.length];
+        for (int i = 0; i < src.length; i++) {
+            byte tmp = (byte) (0xFF ^ src[i]);
+            temp[i * 2] = (byte) ((tmp >> 4) & 0x0f);
+            temp[i * 2 + 1] = (byte) (tmp & 0x0f);
+        }
+        StringBuffer res = new StringBuffer();
+        for (int i = 0; i < temp.length; i++) {
+            res.append(ascii[temp[i]]);
+        }
+        return res.toString();
+    }
+
+    /**
+     * 比较字节数组是否相同
+     *
+     * @param a
+     * @param b
+     * @return
+     */
+    public static boolean compareBytes(byte[] a, byte[] b) {
+        if (a == null || a.length == 0 || b == null || b.length == 0
+                || a.length != b.length) {
+            return false;
+        }
+        if (a.length == b.length) {
+            for (int i = 0; i < a.length; i++) {
+                if (a[i] != b[i]) {
+                    return false;
+                }
+            }
+        } else {
+            return false;
+        }
+        return true;
+    }
+    /**
+     * 只比对指定长度byte
+     *
+     * @param a
+     * @param b
+     * @param len
+     * @return
+     */
+    public static boolean compareBytes(byte[] a, byte[] b, int len) {
+        if (a == null || a.length == 0 || b == null || b.length == 0
+                || a.length < len || b.length < len) {
+            return false;
+        }
+        for (int i = 0; i < len; i++) {
+            if (a[i] != b[i]) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 将字节数组转换为二进制字符串
+     *
+     * @param items
+     * @return
+     */
+    public static String bytesToBinaryString(byte[] items) {
+        if (items == null || items.length == 0) {
+            return null;
+        }
+        StringBuffer buf = new StringBuffer();
+        for (byte item : items) {
+            buf.append(byteToBinaryString(item));
+        }
+        return buf.toString();
+    }
+
+    /**
+     * 将字节转换为二进制字符串
+     *
+     * @param
+     * @return
+     */
+    public static String byteToBinaryString(byte item) {
+        byte a = item;
+        StringBuffer buf = new StringBuffer();
+        for (int i = 0; i < 8; i++) {
+            buf.insert(0, a % 2);
+            a = (byte) (a >> 1);
+        }
+        return buf.toString();
+    }
+
+    /**
+     * 对数组a,b进行异或运算
+     *
+     * @param a
+     * @param b
+     * @return
+     */
+    public static byte[] xor(byte[] a, byte[] b) {
+        if (a == null || a.length == 0 || b == null || b.length == 0
+                || a.length != b.length) {
+            return null;
+        }
+        byte[] result = new byte[a.length];
+        for (int i = 0; i < a.length; i++) {
+            result[i] = (byte) (a[i] ^ b[i]);
+        }
+        return result;
+    }
+
+    /**
+     * 对数组a,b进行异或运算 运算长度len
+     *
+     * @param a
+     * @param b
+     * @param len
+     * @return
+     */
+    public static byte[] xor(byte[] a, byte[] b, int len) {
+        if (a == null || a.length == 0 || b == null || b.length == 0) {
+            return null;
+        }
+        if (a.length < len || b.length < len) {
+            return null;
+        }
+        byte[] result = new byte[len];
+        for (int i = 0; i < len; i++) {
+            result[i] = (byte) (a[i] ^ b[i]);
+        }
+        return result;
+    }
+    /**
+     * 将short整型数值转换为字节数组
+     *
+     * @param num
+     * @return
+     */
+    public static byte[] shortToBytes(int num) {
+        byte[] temp = new byte[2];
+        for (int i = 0; i < 2; i++) {
+            temp[i] = (byte) ((num >>> (8 - i * 8)) & 0xFF);
+        }
+        return temp;
+    }
+
+    /**
+     * 将字节数组转为整型
+     *
+     * @param
+     * @return
+     */
+    public static int bytesToShort(byte[] arr) {
+        int mask = 0xFF;
+        int temp = 0;
+        int result = 0;
+        for (int i = 0; i < 2; i++) {
+            result <<= 8;
+            temp = arr[i] & mask;
+            result |= temp;
+        }
+        return result;
+    }
+
+    /**
+     * 将整型数值转换为指定长度的字节数组
+     *
+     * @param num
+     * @return
+     */
+    public static byte[] intToBytes(int num) {
+        byte[] temp = new byte[4];
+        for (int i = 0; i < 4; i++) {
+            temp[i] = (byte) ((num >>> (24 - i * 8)) & 0xFF);
+        }
+        return temp;
+    }
+
+    /**
+     * 将整型数值转换为指定长度的字节数组
+     *
+     * @param src
+     * @param len
+     * @return
+     */
+    public static byte[] intToBytes(int src, int len) {
+        if (len < 1 || len > 4) {
+            return null;
+        }
+        byte[] temp = new byte[len];
+        for (int i = 0; i < len; i++) {
+            temp[len - 1 - i] = (byte) ((src >>> (8 * i)) & 0xFF);
+        }
+        return temp;
+    }
+
+    /**
+     * 将字节数组转换为整型数值
+     *
+     * @param arr
+     * @return
+     */
+    public static int bytesToInt(byte[] arr) {
+        int mask = 0xFF;
+        int temp = 0;
+        int result = 0;
+        for (int i = 0; i < 4; i++) {
+            result <<= 8;
+            temp = arr[i] & mask;
+            result |= temp;
+        }
+        return result;
+    }
+
+    /**
+     * 将long整型数值转换为字节数组
+     *
+     * @param num
+     * @return
+     */
+    public static byte[] longToBytes(long num) {
+        byte[] temp = new byte[8];
+        for (int i = 0; i < 8; i++) {
+            temp[i] = (byte) ((num >>> (56 - i * 8)) & 0xFF);
+        }
+        return temp;
+    }
+
+    /**
+     * 将字节数组转换为long整型数值
+     *
+     * @param arr
+     * @return
+     */
+    public static long bytesToLong(byte[] arr) {
+        int mask = 0xFF;
+        int temp = 0;
+        long result = 0;
+        int len = Math.min(8, arr.length);
+        for (int i = 0; i < len; i++) {
+            result <<= 8;
+            temp = arr[i] & mask;
+            result |= temp;
+        }
+        return result;
+    }
+
+    /**
+     * 将16进制字符转换为字节
+     *
+     * @param c
+     * @return
+     */
+    public static byte toByte(char c) {
+        byte b = (byte) "0123456789ABCDEF".indexOf(c);
+        return b;
+    }
+
+    /**
+     * 功能描述:把两个字节的字节数组转化为整型数据,高位补零,例如:<br/>
+     * 有字节数组byte[] data = new byte[]{1,2};转换后int数据的字节分布如下:<br/>
+     * 00000000 00000000 00000001 00000010,函数返回258
+     *
+     * @param lenData
+     *            需要进行转换的字节数组
+     * @return 字节数组所表示整型值的大小
+     */
+    public static int bytesToIntWhereByteLengthEquals2(byte lenData[]) {
+        if (lenData.length != 2) {
+            return -1;
+        }
+        byte fill[] = new byte[]{0, 0};
+        byte real[] = new byte[4];
+        System.arraycopy(fill, 0, real, 0, 2);
+        System.arraycopy(lenData, 0, real, 2, 2);
+        int len = byteToInt(real);
+        return len;
+
+    }
+
+    /**
+     * 功能描述:将byte数组转化为int类型的数据
+     *
+     * @param byteVal
+     *            需要转化的字节数组
+     * @return 字节数组所表示的整型数据
+     */
+    public static int byteToInt(byte[] byteVal) {
+        int result = 0;
+        for (int i = 0; i < byteVal.length; i++) {
+            int tmpVal = (byteVal[i] << (8 * (3 - i)));
+            switch (i) {
+                case 0 :
+                    tmpVal = tmpVal & 0xFF000000;
+                    break;
+                case 1 :
+                    tmpVal = tmpVal & 0x00FF0000;
+                    break;
+                case 2 :
+                    tmpVal = tmpVal & 0x0000FF00;
+                    break;
+                case 3 :
+                    tmpVal = tmpVal & 0x000000FF;
+                    break;
+            }
+
+            result = result | tmpVal;
+        }
+        return result;
+    }
+    public static byte CheckXORSum(byte[] bData) {
+        byte sum = 0x00;
+        for (int i = 0; i < bData.length; i++) {
+            sum ^= bData[i];
+        }
+        return sum;
+    }
+    /**
+     * 从offset开始 将后续长度为len的byte字节转为int
+     *
+     * @param data
+     * @param offset
+     * @param len
+     * @return
+     */
+    public static int bytesToInt(byte[] data, int offset, int len) {
+        int mask = 0xFF;
+        int temp = 0;
+        int result = 0;
+        len = Math.min(len, 4);
+        for (int i = 0; i < len; i++) {
+            result <<= 8;
+            temp = data[offset + i] & mask;
+            result |= temp;
+        }
+        return result;
+    }
+
+    /**
+     * byte字节数组中的字符串的长度
+     *
+     * @param data
+     * @return
+     */
+    public static int getBytesStringLen(byte[] data) {
+        int count = 0;
+        for (byte b : data) {
+            if (b == 0x00) {
+                break;
+            }
+            count++;
+        }
+        return count;
+    }
+
+    /**
+     * 校验和
+     *
+     * @param msg
+     *            需要计算校验和的byte数组
+     * @param length
+     *            校验和位数
+     * @return 计算出的校验和数组
+     */
+    public static byte[] SumCheck(byte[] msg, int length) {
+        long mSum = 0;
+        byte[] mByte = new byte[length];
+
+        /** 逐Byte添加位数和 */
+        for (byte byteMsg : msg) {
+            long mNum = ((long) byteMsg >= 0)
+                    ? (long) byteMsg
+                    : ((long) byteMsg + 256);
+            mSum += mNum;
+        } /** end of for (byte byteMsg : msg) */
+
+        /** 位数和转化为Byte数组 */
+        for (int liv_Count = 0; liv_Count < length; liv_Count++) {
+            mByte[length - liv_Count
+                    - 1] = (byte) (mSum >> (liv_Count * 8) & 0xff);
+        } /** end of for (int liv_Count = 0; liv_Count < length; liv_Count++) */
+
+        return mByte;
+    }
+
+    /**
+     * 字节数据转十进制字符(补码-无符号)
+     *
+     * @param data
+     * @return
+     */
+    public static String getByteToStr(byte[] data) {
+        StringBuffer str = new StringBuffer();
+        for (int i = 0; i < data.length; i++) {
+            if (data[i] < 0) {
+                int tem = data[i] + 256;
+                str.append(tem + " ");
+            } else {
+                str.append(data[i] + " ");
+            }
+        }
+        return str.toString();
+    }
+
+}

+ 51 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/Const.java

@@ -0,0 +1,51 @@
+package com.huimv.eartag.utils;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class Const {
+    public final static String ROUTING_KEY_ASK = "topic.ask.key";
+    public final static String QUEUE_ASK = "topic.ask.queue";
+    public final static String EXCHANGE_ASK = "topic.ask.exchange";
+
+    public final static String EXCHANGE_DEVICE = "topic.device.exchange";
+
+    public final static String QUEUE_DEVICE_HEARTBEAT = "topic.device_heartbeat.queue";
+    public final static String ROUTING_KEY_DEVICE_HEARTBEAT = "topic.device_heartbeat.key";
+
+    public final static String QUEUE_DEVICE_TEMP = "topic.device_temp.queue";
+    public final static String ROUTING_KEY_DEVICE_TEMP = "topic.device_temp.key";
+
+    public final static String EXCHANGE_EARTAG = "topic.eartag.exchange";
+    public final static String QUEUE_EARTAG = "topic.eartag.queue";
+    public final static String ROUTING_KEY_EARTAG = "topic.eartag.key";
+
+    //////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    public final static String EXCHANGE_ASK_DEVICE = "topic.askDevice.exchange";
+    public final static String ROUTING_KEY_ASK_DEVICE = "topic.askDevice.routeKey";
+    public final static String QUEUE_ASK_DEVICE = "topic.askDevice.queue";
+
+    public final static String EXCHANGE_ASK_EARTAG = "topic.askEartag.exchange";
+    public final static String ROUTING_KEY_ASK_EARTAG = "topic.askEartag.routeKey";
+    public final static String QUEUE_ASK_EARTAG = "topic.askEartag.queue";
+
+    public final static String QUEUE_SYNC_DEVICE_REGISTER = "topic.syncDeviceRegister.queue";
+    public final static String EXCHANGE_SYNC_DEVICE_REGISTER = "topic.syncDeviceRegister.exchange";
+    public final static String ROUTING_KEY_SYNC_DEVICE_REGISTER = "topic.syncDeviceRegister.routeKey";
+
+    // ========================== 同步设备总数 ========================== //
+    public final static String QUEUE_SYNC_EARTAG_REGISTER = "topic.syncEartagRegister.queue";
+    public final static String EXCHANGE_SYNC_EARTAG_REGISTER = "topic.syncEartagRegister.exchange";
+    public final static String ROUTING_KEY_SYNC_EARTAG_REGISTER = "topic.syncEartagRegister.routeKey";
+
+    // -------------------------- 同步设备总数 -------------------------- //
+    public final static String QUEUE_SYNC_DEVICE_TOTAL = "topic.syncDeviceTotal.queue";
+    public final static String EXCHANGE_SYNC_DEVICE_TOTAL = "topic.syncDeviceTotal.exchange";
+    public final static String ROUTING_KEY_SYNC_DEVICE_TOTAL = "topic.syncDeviceTotal.routeKey";
+}

+ 300 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/DateUtil.java

@@ -0,0 +1,300 @@
+package com.huimv.eartag.utils;
+
+import cn.hutool.core.date.DateTime;
+import org.springframework.stereotype.Component;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+//@Slf4j
+public class DateUtil {
+
+    //格式化日期(Long --> Date)
+    public String formatLongToDate(Long longDate){
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date= new Date(longDate);
+        return df.format(date);
+    }
+
+    //格式化本年
+    public String getThisYear(){
+        Calendar cal = Calendar.getInstance();
+        int year = cal.get(Calendar.YEAR);
+        return String.valueOf(year);
+    }
+
+    //格式化本月
+    public String getThisMonth(){
+        Calendar cal = Calendar.getInstance();
+        int month = cal.get(Calendar.MONTH) + 1;
+        if(String.valueOf(month).length()==1)
+        {
+            return "0"+String.valueOf(month);
+        }else{
+            return String.valueOf(month);
+        }
+    }
+
+    //格式化日期时间
+    public String formatDateTime(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date = sdf.parse(dateText);
+        return sdf.format(date);
+    }
+
+    public Date parseDateTime(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.parse(dateText);
+    }
+
+    public Date parseDate(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.parse(dateText);
+    }
+
+    public Long parseDateTimeTextToLong(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date = sdf.parse(dateText);
+        return date.getTime();
+    }
+
+    public Long parseDateTextToLong(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        Date date = sdf.parse(dateText);
+        return date.getTime();
+    }
+
+    //
+    public Date getTodayDate() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.parse(sdf.format(new Date()));
+    }
+
+    public Date getTodayDatetime() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.parse(sdf.format(new Date()));
+    }
+
+    public String getTodayDateText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.format(new Date());
+    }
+
+    public java.sql.Date getTodayMySQLDate(){
+        java.sql.Date todayDate = new java.sql.Date(new Date().getTime());
+        return todayDate;
+    }
+
+    public Timestamp getTimestamp(){
+        Timestamp nowTimestamp = new Timestamp(new Date().getTime());
+        return nowTimestamp;
+    }
+
+    public String getTodayText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.format(new Date());
+    }
+
+    public String formatDateText(Date date) throws ParseException {
+        if(date == null){
+            return "";
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.format(date);
+    }
+
+    public String formatDatetimeText(Date date) throws ParseException {
+        if(date == null || date.toString().length()==0){
+            return "";
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.format(date);
+    }
+
+    public String getNowText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+        return sdf.format(new Date());
+    }
+
+    public String getTodayMissionText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+        return sdf.format(new Date());
+    }
+
+    public String getStartDateInThisMonth(){
+        DateTime date = cn.hutool.core.date.DateUtil.date();
+        return (cn.hutool.core.date.DateUtil.beginOfMonth(date) + "").substring(0, 10);
+    }
+
+    public String getEndDateInThisMonth(){
+        DateTime date = cn.hutool.core.date.DateUtil.date();
+        return (date + "").substring(0, 10);
+    }
+
+    /**
+     * 获取过去或者未来 任意天内的日期数组
+     * @param intervals      intervals天内
+     * @return              日期数组
+     */
+    public ArrayList<String> test(int intervals ) {
+        ArrayList<String> pastDaysList = new ArrayList<>();
+        ArrayList<String> fetureDaysList = new ArrayList<>();
+        for (int i = 0; i <intervals; i++) {
+            pastDaysList.add(getPastDate(i));
+            fetureDaysList.add(getFetureDate(i));
+        }
+        return pastDaysList;
+    }
+
+    /**
+     * @Method      : getPastIntervals
+     * @Description : 返回过去N天日期(倒排序)
+     * @Params      : [intervals]
+     * @Return      : java.util.ArrayList<java.lang.String>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7       
+     * @Time        : 15:27
+     */
+    public ArrayList<String> getPastIntervals(int intervals ) {
+        ArrayList<String> pastDaysList = new ArrayList<>();
+        for (int i = 0; i <intervals; i++) {
+            pastDaysList.add(getPastDate(i));
+        }
+        return pastDaysList;
+    }
+
+    /**
+     * @Method      : getPastIntervalsASC
+     * @Description : 正排序
+     * @Params      : [intervals]
+     * @Return      : java.util.ArrayList<java.lang.String>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7       
+     * @Time        : 16:33
+     */
+    public ArrayList<String> getPastIntervalsASC(int intervals ) {
+        ArrayList<String> pastDaysList = new ArrayList<>();
+        for (int i = intervals-1; i >=0; i--) {
+            pastDaysList.add(getPastDate(i));
+        }
+        return pastDaysList;
+    }
+
+    /**
+     * @Method      : getFetureIntervals
+     * @Description : 获取未来N天日期
+     * @Params      : [intervals]
+     * @Return      : java.util.ArrayList<java.lang.String>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2022/3/7       
+     * @Time        : 15:28
+     */
+    public ArrayList<String> getFetureIntervals(int intervals ) {
+        ArrayList<String> fetureDaysList = new ArrayList<>();
+        for (int i = 0; i <intervals; i++) {
+            fetureDaysList.add(getFetureDate(i));
+        }
+        return fetureDaysList;
+    }
+
+
+    /**
+     * 获取过去第几天的日期
+     *
+     * @param past
+     * @return
+     */
+    public String getPastDate(int past) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
+        Date today = calendar.getTime();
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+        String result = format.format(today);
+        return result;
+    }
+
+    /**
+     * 获取未来 第 past 天的日期
+     * @param past
+     * @return
+     */
+    public String getFetureDate(int past) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
+        Date today = calendar.getTime();
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+        String result = format.format(today);
+        return result;
+    }
+
+    //重新构建日期
+    public String rebuildDateTime(String text){
+        return text.substring(0,4)+"-"+text.substring(4,6)+"-"+text.substring(6,8)+" "+text.substring(8,10)+":"+text.substring(10,12)+":"+text.substring(12,14);
+    }
+
+    public static void main(String[] args){
+        DateUtil du = new DateUtil();
+        //
+//        du.test1();
+        List<String> pastList = du.getPastIntervalsASC(5);
+        for(String pastDate:pastList){
+            System.out.println("pastDate>>"+pastDate);
+        }
+
+        List<String> fetureList = du.getFetureIntervals(5);
+        for(String fetureDate:fetureList){
+            System.out.println("fetureDate>>"+fetureDate);
+        }
+
+    }
+
+    private void test1() {
+        String text = "20211201104300";
+//        String text = "1234567890abcd";
+        String date = text.substring(0,4)+"-"+text.substring(4,6)+"-"+text.substring(6,8)+" "+text.substring(8,10)+":"+text.substring(10,12)+":"+text.substring(12,14);
+        System.out.println("date="+date);
+    }
+
+    //获取long时间
+    public Long getNowLong(){
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-1,0,0,0);
+        return calendar.getTime().getTime();
+    }
+
+    public String getAskDate(String askTime) {
+        return askTime.substring(0, 4) + "-" + askTime.substring(4, 6) + "-" + askTime.substring(6, 8) ;
+    }
+}

+ 187 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/DateUtil2.java

@@ -0,0 +1,187 @@
+package com.huimv.eartag.utils;
+
+import cn.hutool.core.date.DateTime;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+@Slf4j
+public class DateUtil2 {
+
+    //格式化日期(Long --> Date)
+    public String formatLongToDate(Long longDate){
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date= new Date(longDate);
+        return df.format(date);
+    }
+
+    //格式化本年
+    public String getThisYear(){
+        Calendar cal = Calendar.getInstance();
+        int year = cal.get(Calendar.YEAR);
+        return String.valueOf(year);
+    }
+
+    //格式化本月
+    public String getThisMonth(){
+        Calendar cal = Calendar.getInstance();
+        int month = cal.get(Calendar.MONTH) + 1;
+        if(String.valueOf(month).length()==1)
+        {
+            return "0"+String.valueOf(month);
+        }else{
+            return String.valueOf(month);
+        }
+    }
+
+    //格式化日期时间
+    public String formatDateTime(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date = sdf.parse(dateText);
+        return sdf.format(date);
+    }
+
+    public Date parseDateTime(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.parse(dateText);
+    }
+
+    public Long parseDateTimeLong(String dateText) throws ParseException {
+        if(dateText.indexOf("T") != -1){
+            dateText = dateText.replace("T"," ");
+        }
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date = sdf.parse(dateText);
+        return date.getTime();
+    }
+
+    //
+    public Date getTodayDate() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.parse(sdf.format(new Date()));
+    }
+
+    public Date getTodayDatetime() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.parse(sdf.format(new Date()));
+    }
+
+    public String getTodayDateText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        return sdf.format(new Date());
+    }
+
+    public String getTodayText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        return sdf.format(new Date());
+    }
+
+    public String getNowText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+        return sdf.format(new Date());
+    }
+
+    public String getTodayMissionText() throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+        return sdf.format(new Date());
+    }
+
+    public String getStartDateInThisMonth(){
+        DateTime date = cn.hutool.core.date.DateUtil.date();
+        return (cn.hutool.core.date.DateUtil.beginOfMonth(date) + "").substring(0, 10);
+    }
+
+    public String getEndDateInThisMonth(){
+        DateTime date = cn.hutool.core.date.DateUtil.date();
+        return (date + "").substring(0, 10);
+    }
+
+    /**
+     * 获取过去或者未来 任意天内的日期数组
+     * @param intervals      intervals天内
+     * @return              日期数组
+     */
+    public ArrayList<String> test(int intervals ) {
+        ArrayList<String> pastDaysList = new ArrayList<>();
+        ArrayList<String> fetureDaysList = new ArrayList<>();
+        for (int i = 0; i <intervals; i++) {
+            pastDaysList.add(getPastDate(i));
+            fetureDaysList.add(getFetureDate(i));
+        }
+        return pastDaysList;
+    }
+
+    /**
+     * 获取过去第几天的日期
+     *
+     * @param past
+     * @return
+     */
+    public String getPastDate(int past) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
+        Date today = calendar.getTime();
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+        String result = format.format(today);
+        return result;
+    }
+
+    /**
+     * 获取未来 第 past 天的日期
+     * @param past
+     * @return
+     */
+    public String getFetureDate(int past) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
+        Date today = calendar.getTime();
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+        String result = format.format(today);
+        return result;
+    }
+
+    //重新构建日期
+    public String rebuildDateTime(String text){
+        return text.substring(0,4)+"-"+text.substring(4,6)+"-"+text.substring(6,8)+" "+text.substring(8,10)+":"+text.substring(10,12)+":"+text.substring(12,14);
+    }
+
+    public static void main(String[] args){
+        DateUtil2 du = new DateUtil2();
+        //
+        du.test1();
+    }
+
+    private void test1() {
+        String text = "20211201104300";
+//        String text = "1234567890abcd";
+        String date = text.substring(0,4)+"-"+text.substring(4,6)+"-"+text.substring(6,8)+" "+text.substring(8,10)+":"+text.substring(10,12)+":"+text.substring(12,14);
+        System.out.println("date="+date);
+    }
+
+    //获取long时间
+    public Long getNowLong(){
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-1,0,0,0);
+        return calendar.getTime().getTime();
+    }
+}

+ 516 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/HttpTemplete.java

@@ -0,0 +1,516 @@
+package com.huimv.eartag.utils;
+
+import com.alibaba.fastjson.JSONObject;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.*;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class HttpTemplete {
+    private String testHttpIp = "http://localhost:9105";
+
+//    public static void main(String[] args) throws Exception {
+//        //
+//        HttpTemplete client = new HttpTemplete();
+////        client.testGetRequest1();
+//        client.testGetRequest2();
+//    }
+    private Integer connectTimeout = null;
+    private Integer requestTimeout = null;
+    private Integer socketTimeout = null;
+
+    static {
+    }
+
+    //发送简单数据
+    public void doPostSimple(String serviceUrl,String data){
+        System.out.println("推送数据地址:"+serviceUrl);
+        //
+        Map<String,String> paramsMap = new HashMap<String,String>();
+        paramsMap.put("data", data);
+        //
+        Map<String,Integer> timeoutMap = new HashMap<String,Integer>();
+        timeoutMap.put("connectTimeout", 5000);
+        timeoutMap.put("requestTimeout", 5000);
+        timeoutMap.put("socketTimeout", 5000);
+        try{
+            // 用Post方法推送接口数据
+            doPost(serviceUrl,paramsMap,timeoutMap);
+        } catch (IOException e) {
+            System.out.println("###错误信息:"+e.getMessage());
+        }
+    }
+
+
+    /**
+     * @Method      : doPost
+     * @Description : post方式推送接口
+     * @Params      : [url, paramsMap, timeoutMap]
+     * @Return      : com.alibaba.fastjson.JSONObject
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/11/19       
+     * @Time        : 14:55
+     */
+    public JSONObject doPost(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
+        // 创建默认的httpClient实例.
+        CloseableHttpClient httpClient = getHttpClientConnection();
+        //
+        int connectTimeout = timeoutMap.get("connectTimeout");
+        int requestTimeout = timeoutMap.get("requestTimeout");
+        int socketTimeout = timeoutMap.get("socketTimeout");
+        // 创建httpPost
+        HttpPost httpPost = new HttpPost(url);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setSocketTimeout(socketTimeout) //服务器响应超时时间
+                .setConnectTimeout(connectTimeout) //连接服务器超时时间
+                .setConnectionRequestTimeout(requestTimeout)
+                .build();
+        httpPost.setConfig(requestConfig);
+        // 创建参数队列
+        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
+        Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
+        for (Map.Entry<String, String> e : entrySet) {
+            String name = e.getKey();
+            String value = e.getValue();
+            NameValuePair pair = new BasicNameValuePair(name, value);
+            paramsList.add(pair);
+        }
+        UrlEncodedFormEntity content = new UrlEncodedFormEntity(paramsList, "UTF-8");
+        //处理乱码
+//        StringEntity content = new StringEntity(paramsList.toString(), Charset.forName("UTF-8"));// 第二个参数,设置后才会对,内容进行编码
+//        content.setContentType("application/soap+xml; charset=UTF-8");
+//        content.setContentEncoding("UTF-8");
+        httpPost.setEntity(content);
+//        HttpUriRequest httpPost = RequestBuilder.post().setUri(url).setEntity(content).setConfig(requestConfig);
+        CloseableHttpResponse response = httpClient.execute(httpPost);
+        // 获取响应实体
+        HttpEntity entity = response.getEntity();
+        try {
+            if (response.getStatusLine().getStatusCode() == 200) {
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", true);
+                resultJo.put("content", text);
+                return resultJo;
+            }else{
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", false);
+                resultJo.put("content", text);
+                return resultJo;
+            }
+        } finally {
+            //释放资源
+            if (response != null) {
+                response.close();
+            }
+            if (httpClient != null) {
+                httpClient.close();
+            }
+        }
+    }
+
+    /**
+     * @Method      : setTimeout
+     * @Description : 
+     * @Params      : [connectTimeout, requestTimeout, socketTimeout]
+     * @Return      : void
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/11/23       
+     * @Time        : 9:36
+     */
+    public Map<String, Integer> setTimeout(Integer connectTimeout, Integer requestTimeout, Integer socketTimeout){
+        //
+        if(connectTimeout == null){
+            this.connectTimeout = 3000;
+        }else{
+            this.connectTimeout = connectTimeout;
+        }
+        //
+        if(requestTimeout == null){
+            this.requestTimeout = 3000;
+        }else{
+            this.requestTimeout = requestTimeout;
+        }
+        //
+        if(socketTimeout == null){
+            this.socketTimeout = 3000;
+        }else{
+            this.socketTimeout = socketTimeout;
+        }
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", this.connectTimeout);
+        timeoutMap.put("requestTimeout", this.requestTimeout);
+        timeoutMap.put("socketTimeout", this.socketTimeout);
+        return timeoutMap;
+    }
+
+    /**
+     * @Method      : setTimeout
+     * @Description : 
+     * @Params      : [connectTimeout, requestTimeout, socketTimeout]
+     * @Return      : java.util.Map<java.lang.String,java.lang.Integer>
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/11/23       
+     * @Time        : 9:41
+     */
+    public Map<String, Integer> setTimeout(String connectTimeout, String requestTimeout, String socketTimeout){
+        //
+        if(connectTimeout == null){
+            this.connectTimeout = 3000;
+        }else{
+            this.connectTimeout = Integer.parseInt(connectTimeout);
+        }
+        //
+        if(requestTimeout == null){
+            this.requestTimeout = 3000;
+        }else{
+            this.requestTimeout = Integer.parseInt(requestTimeout);
+        }
+        //
+        if(socketTimeout == null){
+            this.socketTimeout = 3000;
+        }else{
+            this.socketTimeout = Integer.parseInt(socketTimeout);
+        }
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", this.connectTimeout);
+        timeoutMap.put("requestTimeout", this.requestTimeout);
+        timeoutMap.put("socketTimeout", this.socketTimeout);
+        return timeoutMap;
+    }
+
+    /**
+     * @Method      : doGet
+     * @Description : 
+     * @Params      : [url, paramsMap]
+     * @Return      : com.alibaba.fastjson.JSONObject
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/11/23       
+     * @Time        : 9:34
+     */
+    public JSONObject doGet(String url, Map<String, String> paramsMap) throws IOException {
+        //
+        if(this.connectTimeout == null){
+            this.connectTimeout = 3000;
+        }
+        //
+        if(this.requestTimeout == null)
+        {
+            this.requestTimeout = 3000;
+        }
+        //
+        if(this.socketTimeout == null){
+            this.socketTimeout = 3000;
+        }
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", this.connectTimeout);
+        timeoutMap.put("requestTimeout", this.requestTimeout);
+        timeoutMap.put("socketTimeout", this.socketTimeout);
+        //
+        CloseableHttpClient httpClient = getHttpClientConnection();
+        //执行//获取请求内容
+        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
+        try {
+            // 获取响应实体
+            HttpEntity entity = response.getEntity();
+            // 打印响应状态
+            if (response.getStatusLine().getStatusCode() == 200) {
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", true);
+                resultJo.put("content", text);
+                return resultJo;
+            } else {
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", false);
+                resultJo.put("content", text);
+                return resultJo;
+            }
+        } finally {
+            //释放资源
+            if (response != null) {
+                response.close();
+            }
+            if (httpClient != null) {
+                httpClient.close();
+            }
+        }
+    }
+
+    private CloseableHttpClient httpClient = null;
+    private CloseableHttpResponse response = null;
+
+    public JSONObject doGetBatch(String url, Map<String, String> paramsMap) throws IOException {
+        //
+        if(this.connectTimeout == null){
+            this.connectTimeout = 3000;
+        }
+        //
+        if(this.requestTimeout == null)
+        {
+            this.requestTimeout = 3000;
+        }
+        //
+        if(this.socketTimeout == null){
+            this.socketTimeout = 3000;
+        }
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", this.connectTimeout);
+        timeoutMap.put("requestTimeout", this.requestTimeout);
+        timeoutMap.put("socketTimeout", this.socketTimeout);
+        //
+        httpClient = getHttpClientConnection();
+        //执行//获取请求内容
+        response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
+        // 获取响应实体
+        HttpEntity entity = response.getEntity();
+        // 打印响应状态
+        if (response.getStatusLine().getStatusCode() == 200) {
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", true);
+                resultJo.put("content", text);
+                return resultJo;
+        } else {
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", false);
+                resultJo.put("content", text);
+                return resultJo;
+        }
+    }
+
+    //关闭http连接
+    public void closeHttpConn() throws IOException {
+        System.out.println("开始释放http连接资源");
+        //释放资源
+        if (response != null) {
+            response.close();
+        }
+        if (httpClient != null) {
+            httpClient.close();
+        }
+    }
+
+    /**
+     * @Method : doGet
+     * @Description :get方式推送接口
+     * @Params : [url, paramsMap, timeoutMap]
+     * @Return : com.alibaba.fastjson.JSONObject
+     * @Author : ZhuoNing
+     * @Date : 2021/11/18
+     * @Time : 17:39
+     */
+    public JSONObject doGet(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
+        if (timeoutMap == null) {
+            timeoutMap.put("connectTimeout", 5000);
+            timeoutMap.put("requestTimeout", 5000);
+            timeoutMap.put("socketTimeout", 5000);
+        }
+        //
+        CloseableHttpClient httpClient = getHttpClientConnection();
+        //执行//获取请求内容
+        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
+        try {
+            // 获取响应实体
+            HttpEntity entity = response.getEntity();
+            // 打印响应状态
+            if (response.getStatusLine().getStatusCode() == 200) {
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", true);
+                resultJo.put("content", text);
+                return resultJo;
+            } else {
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", false);
+                resultJo.put("content", text);
+                return resultJo;
+            }
+        } finally {
+            //释放资源
+            if (response != null) {
+                response.close();
+            }
+            if (httpClient != null) {
+                httpClient.close();
+            }
+        }
+    }
+
+    private void testGetRequest1() throws IOException {
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", 5000);
+        timeoutMap.put("requestTimeout", 5000);
+        timeoutMap.put("socketTimeout", 5000);
+        String url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
+        // test error
+        url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
+        CloseableHttpClient httpClient = getHttpClientConnection();
+        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
+        // 打印响应状态
+        System.out.println("响应状态1 =" + response.getStatusLine());
+        try {
+            if (response.getStatusLine().getStatusCode() == 200) {
+                // 获取响应实体
+                HttpEntity entity = response.getEntity();
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                System.out.println("响应内容=" + text);
+
+                JSONObject resultJo = JSONObject.parseObject(text);
+                System.out.println("accessToken=" + resultJo.getString("accessToken"));
+            } else {
+                System.out.println("请求失败");
+            }
+        } finally {
+            //释放资源
+            if (response != null) {
+                response.close();
+            }
+            if (httpClient != null) {
+                httpClient.close();
+            }
+        }
+    }
+
+    //
+    private CloseableHttpClient getHttpClientConnection() {
+        //创建默认实例
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+        //
+//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
+        return httpclient;
+    }
+    //
+    private HttpUriRequest getHttpRequest(String url, Map<String, String> map, Map<String, Integer> timeoutMap) {
+        int connectTimeout = timeoutMap.get("connectTimeout");
+        int requestTimeout = timeoutMap.get("requestTimeout");
+        int socketTimeout = timeoutMap.get("socketTimeout");
+//        System.out.println("core connectTimeout="+connectTimeout);
+//        System.out.println("core requestTimeout="+requestTimeout);
+//        System.out.println("core socketTimeout="+socketTimeout);
+
+        List<NameValuePair> params = new ArrayList<NameValuePair>();
+        Set<Map.Entry<String, String>> entrySet = map.entrySet();
+        for (Map.Entry<String, String> e : entrySet) {
+            String name = e.getKey();
+            String value = e.getValue();
+            NameValuePair pair = new BasicNameValuePair(name, value);
+            params.add(pair);
+        }
+        //
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
+                .setSocketTimeout(socketTimeout).build();
+        HttpUriRequest httpGet = RequestBuilder.get().setUri(url)
+                .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
+                .setConfig(requestConfig).build();
+        return httpGet;
+    }
+    //
+    private HttpGet getHttpRequest(String url, Map<String, Integer> timeoutMap) {
+        int connectTimeout = timeoutMap.get("connectTimeout");
+        int requestTimeout = timeoutMap.get("requestTimeout");
+        int socketTimeout = timeoutMap.get("socketTimeout");
+
+        HttpGet httpGet = new HttpGet(url);
+        //设置超时时间
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
+                .setSocketTimeout(socketTimeout).build();
+        httpGet.setConfig(requestConfig);
+        return httpGet;
+    }
+
+    //test
+    private void get() {
+//        CloseableHttpClient httpclient = HttpClients.createDefault();
+//        try {
+//            // 创建httpget.
+//            HttpGet httpget = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
+//            System.out.println("executing request " + httpget.getURI());
+//            // 执行get请求.
+//            CloseableHttpResponse response = httpclient.execute(httpget);
+//            try {
+//                // 获取响应实体
+//                HttpEntity entity = response.getEntity();
+//                System.out.println("--------------------------------------");
+//                // 打印响应状态
+//                System.out.println(response.getStatusLine());
+//                if (entity != null) {
+//                    // 打印响应内容长度
+//                    System.out.println("Response content length: " + entity.getContentLength());
+//                    // 打印响应内容
+//                    System.out.println("Response content: " + EntityUtils.toString(entity));
+//                }
+//                System.out.println("------------------------------------");
+//            } finally {
+//                response.close();
+//            }
+//        } catch (ClientProtocolException e) {
+//            e.printStackTrace();
+//        } catch (ParseException e) {
+//            e.printStackTrace();
+//        } catch (IOException e) {
+//            e.printStackTrace();
+//        } finally {
+//            // 关闭连接,释放资源
+//            try {
+//                httpclient.close();
+//            } catch (IOException e) {
+//                e.printStackTrace();
+//            }
+//        }
+    }
+
+
+    private void getRequest() throws IOException {
+//        //1.打开浏览器
+//        CloseableHttpClient httpClient = HttpClients.createDefault();
+//        //2.声明get请求
+//        HttpGet httpGet = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
+//        //3.发送请求
+//        CloseableHttpResponse response = httpClient.execute(httpGet);
+//        System.out.println("StatusCode=" + response.getStatusLine().getStatusCode());
+//        //4.判断状态码
+//        if (response.getStatusLine().getStatusCode() == 200) {
+//            HttpEntity entity = response.getEntity();
+//            //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
+//            String string = EntityUtils.toString(entity, "utf-8");
+//            System.out.println(string);
+//        }
+//        //5.关闭资源
+//        response.close();
+//        httpClient.close();
+    }
+}

+ 21 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/JSONUtil.java

@@ -0,0 +1,21 @@
+package com.huimv.eartag.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class JSONUtil {
+    //将实体类转成JSON对象
+    public static JSONObject convertEntityToJSONObject(Object obj){
+        return JSON.parseObject(JSONObject.toJSONString(obj));
+    }
+}

+ 124 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/MathUtil.java

@@ -0,0 +1,124 @@
+package com.huimv.eartag.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.math.BigDecimal;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class MathUtil {
+
+    public static double A = 0.00335396319311466;
+    public static double B = 0.000256376549039663;
+    public static double C = 0.00000248933580817244;
+    public static double D = 0.0000000753805242068686;
+    public static double E = -0.0000000204758173596178;
+
+    public static BigDecimal formatScale(String val1,String val2,Integer scale){
+        if(scale == null){
+            scale = 2;
+        }
+        BigDecimal deviceRateBd= new BigDecimal(val1).divide(new BigDecimal(val2),scale,BigDecimal.ROUND_HALF_UP);
+        return deviceRateBd;
+    }
+
+    public static BigDecimal countEnvtemp(String val1,Integer scale){
+        if(scale == null){
+            scale = 2;
+        }
+        BigDecimal deviceRateBd= new BigDecimal(val1).divide(new BigDecimal(100),scale,BigDecimal.ROUND_HALF_UP);
+        return deviceRateBd;
+    }
+
+    public static BigDecimal countRate(String val1,Integer scale){
+        if(scale == null){
+            scale = 2;
+        }
+        BigDecimal deviceRateBd= new BigDecimal(val1).divide(new BigDecimal(100),scale,BigDecimal.ROUND_HALF_UP);
+        return deviceRateBd;
+    }
+
+    //计算环境温度
+    public static String countEnvtemp(String temp,int scale){
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(scale);
+        float temp2 = Float.parseFloat(new BigDecimal(temp).multiply(new BigDecimal(0.1)).toString());
+        return numberFormat.format(temp2);
+    }
+
+    //保留一位小数
+    public static  double changeDouble(Double dou) {
+        NumberFormat nf = new DecimalFormat("0.0 ");
+        dou = Double.parseDouble(nf.format(dou));
+        return dou;
+    }
+
+    public static double ln(int rv) {
+        int R_REF = 10000;
+        double ln = Math.log((double) rv / R_REF);
+//        System.out.println("$$$$$$$$$ ln>>"+ln);
+        //保留一位小数
+        return changeDouble(1 / (A + B * ln + C * Math.pow(ln, 2) + D * Math.pow(ln, 3) + E * Math.pow(ln, 4)) - 273.15) + 0.001;
+    }
+
+    public String formatBit(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num);
+    }
+
+    public String formatBit(float num) {
+        return String.valueOf(num);
+    }
+
+    //计算比率
+    public String countRate(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num * 100);//所占百分比
+    }
+
+    //计算占比
+    public String countRate(float num, float total,int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        //所占百分比
+        return numberFormat.format((float)  num/ (float)total* 100);
+    }
+
+    //格式化
+    public String format(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num * 100);//所占百分比
+    }
+
+    //格式化
+    public String format(float num, float total,int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        //所占百分比
+        return numberFormat.format((float)  num/ (float)total* 100);
+    }
+
+}

+ 89 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/MathUtil2.java

@@ -0,0 +1,89 @@
+package com.huimv.eartag.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class MathUtil2 {
+
+    public static double A = 0.00335396319311466;
+    public static double B = 0.000256376549039663;
+    public static double C = 0.00000248933580817244;
+    public static double D = 0.0000000753805242068686;
+    public static double E = -0.0000000204758173596178;
+
+    //保留一位小数
+    public static double changeDouble(Double dou) {
+        NumberFormat nf = new DecimalFormat("0.0 ");
+        dou = Double.parseDouble(nf.format(dou));
+        return dou;
+    }
+
+    public static double ln(int rv) {
+        int R_REF = 10000;
+        double ln = Math.log((double) rv / R_REF);
+        //保留一位小数
+        return changeDouble(1 / (A + B * ln + C * Math.pow(ln, 2) + D * Math.pow(ln, 3) + E * Math.pow(ln, 4)) - 273.15) + 0.001;
+    }
+
+    public String formatBit(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num);
+    }
+
+    public String formatBit(float num) {
+        return String.valueOf(num);
+    }
+
+    //计算比率
+    public String countRate(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num * 100);//所占百分比
+    }
+
+    //计算占比
+    public String countRate(float num, float total,int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        //所占百分比
+        return numberFormat.format((float)  num/ (float)total* 100);
+    }
+
+    //格式化
+    public String format(float num, int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        return numberFormat.format(num * 100);//所占百分比
+    }
+
+    //格式化
+    public String format(float num, float total,int bit) {
+        // 创建一个数值格式化对象
+        NumberFormat numberFormat = NumberFormat.getInstance();
+        // 设置精确到小数点后2位
+        numberFormat.setMaximumFractionDigits(bit);
+        //所占百分比
+        return numberFormat.format((float)  num/ (float)total* 100);
+    }
+
+}

+ 31 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/RegexUtil.java

@@ -0,0 +1,31 @@
+package com.huimv.eartag.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class RegexUtil {
+
+    //计算+出现的次数
+    public int countPlus(String str) {//创建countSpace方法用于统计文本的空格个数
+        int count = 0;//创建一个返回值count
+//        Pattern p = Pattern.compile("\\s");//将给定的正则表达式编译并赋予给Pattern类
+        Pattern p = Pattern.compile("\\+");//将给定的正则表达式编译并赋予给Pattern类
+        Matcher m = p.matcher(str);//生成一个给定命名的Matcher对象
+        while(m.find()){//查找类似于Matcher对象的字符
+            count++;//count自加作为标记
+        }
+        return count;//返回count值
+    }
+
+}

+ 266 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/AddressUtils.java

@@ -0,0 +1,266 @@
+package com.huimv.eartag.utils.ip;
+
+import java.io.*;
+import java.net.*;
+import java.util.Enumeration;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class AddressUtils {
+    /**
+     * 获取本机的内网ip地址
+     *
+     * @return
+     * @throws
+     */
+    public String getInnetIp() throws SocketException {
+        String localip = null;// 本地IP,如果没有配置外网IP则返回它
+        String netip = null;// 外网IP
+        Enumeration<NetworkInterface> netInterfaces;
+        netInterfaces = NetworkInterface.getNetworkInterfaces();
+        InetAddress ip = null;
+        boolean finded = false;// 是否找到外网IP
+        while (netInterfaces.hasMoreElements() && !finded) {
+            NetworkInterface ni = netInterfaces.nextElement();
+            Enumeration<InetAddress> address = ni.getInetAddresses();
+            while (address.hasMoreElements()) {
+                ip = address.nextElement();
+                if (!ip.isSiteLocalAddress()
+                        &&!ip.isLoopbackAddress()
+                        &&ip.getHostAddress().indexOf(":") == -1){// 外网IP
+                    netip = ip.getHostAddress();
+                    finded = true;
+                    break;
+                } else if (ip.isSiteLocalAddress()
+                        &&!ip.isLoopbackAddress()
+                        &&ip.getHostAddress().indexOf(":") == -1){// 内网IP
+                    localip = ip.getHostAddress();
+                }
+            }
+        }
+        if (netip != null && !"".equals(netip)) {
+            return netip;
+        } else {
+            return localip;
+        }
+    }
+
+    /**
+     * 获取本机的外网ip地址
+     *
+     * @return
+     */
+    public String getV4IP() {
+        String ip = "";
+        String chinaz = "http://ip.chinaz.com";
+
+        StringBuilder inputLine = new StringBuilder();
+        String read = "";
+        URL url = null;
+        HttpURLConnection urlConnection = null;
+        BufferedReader in = null;
+        try {
+            url = new URL(chinaz);
+            urlConnection = (HttpURLConnection) url.openConnection();
+            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
+            while ((read = in.readLine()) != null) {
+                inputLine.append(read + "\r\n");
+            }
+            //System.out.println(inputLine.toString());
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
+        Matcher m = p.matcher(inputLine.toString());
+        if (m.find()) {
+            String ipstr = m.group(1);
+            ip = ipstr;
+            //System.out.println(ipstr);
+        }
+        System.out.println("## ip>>"+ip);
+        return ip;
+    }
+
+
+    /**
+     * 解析ip地址
+     *
+     * 设置访问地址为http://ip.taobao.com/service/getIpInfo.php
+     * 设置请求参数为ip=[已经获得的ip地址]
+     * 设置解码方式为UTF-8
+     *
+     *
+     * @param content   请求的参数 格式为:ip=192.168.1.101
+     * @param encoding 服务器端请求编码。如GBK,UTF-8等
+     * @return
+     * @throws
+     */
+    public String getAddresses(String content, String encoding) throws UnsupportedEncodingException {
+        //设置访问地址
+        String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
+        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
+        String returnStr = this.getResult(urlStr, content, encoding);
+        if (returnStr != null) {
+            // 处理返回的省市区信息
+            // System.out.println(returnStr);
+            String[] temp = returnStr.split(",");
+            if (temp.length < 3) {
+                return "0";// 无效IP,局域网测试
+            }
+
+            String country = ""; //国家
+            String area = ""; //地区
+            String region = ""; //省份
+            String city = ""; //市区
+            String county = ""; //地区
+            String isp = ""; //ISP公司
+            for (int i = 0; i < temp.length; i++) {
+                switch (i) {
+                    case 2:
+                        country = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        country = URLDecoder.decode(country, encoding);// 国家
+                        break;
+                    case 3:
+                        area = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        area = URLDecoder.decode(area, encoding);// 地区
+                        break;
+                    case 4:
+                        region = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        region = URLDecoder.decode(region, encoding);// 省份
+                        break;
+                    case 5:
+                        city = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        city = URLDecoder.decode(city, encoding);// 市区
+                        if ("内网IP".equals(city)) {
+                            return "地址为:内网IP";
+                        }
+                        break;
+                    case 6:
+                        county = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        county = URLDecoder.decode(county, encoding);// 地区
+                        break;
+                    case 7:
+                        isp = (temp[i].split(":"))[1].replaceAll("\"", "");
+                        isp = URLDecoder.decode(isp, encoding); // ISP公司
+                        break;
+                }
+            }
+            return new StringBuffer("地址为:" + country + ",").append(region + "省,").append(city + "市,").append(county + ",").append("ISP公司:" + isp)
+                    .toString();
+        }
+        return null;
+    }
+
+
+    /**
+     * 访问目标地址并获取返回值
+     *
+     * @param urlStr   请求的地址
+     * @param content  请求的参数 格式为:ip=192.168.1.101
+     * @param encoding 服务器端请求编码。如GBK,UTF-8等
+     * @return
+     */
+    private String getResult(String urlStr, String content, String encoding) {
+        URL url = null;
+        HttpURLConnection connection = null;
+        try {
+            url = new URL(urlStr);
+            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
+            connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒
+            connection.setReadTimeout(33000);// 设置读取数据超时时间,单位毫秒
+            connection.setDoOutput(true);// 是否打开输出流 true|false
+            connection.setDoInput(true);// 是否打开输入流true|false
+            connection.setRequestMethod("POST");// 提交方法POST|GET
+            connection.setUseCaches(false);// 是否缓存true|false
+            connection.connect();// 打开连接端口
+            DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
+            out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
+            out.flush();// 刷新
+            out.close();// 关闭输出流
+            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
+            // 往对端写完数据对端服务器返回数据
+            // ,以BufferedReader流来读取
+            StringBuffer buffer = new StringBuffer();
+            String line = "";
+            while ((line = reader.readLine()) != null) {
+                buffer.append(line);
+            }
+            reader.close();
+            return buffer.toString();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (connection != null) {
+                connection.disconnect();// 关闭连接
+            }
+        }
+        return null;
+    }
+
+
+    /**
+     * 测试方法
+     * 获取本机的内网ip,外网ip和指定ip的地址
+     *
+     * @param args
+     */
+    public static void main(String[] args) {
+        AddressUtils addressUtils = new AddressUtils();
+        //step1.获得内网ip和外网ip,并输出到控制台
+        String ip1 = "";
+        try {
+            ip1 = addressUtils.getInnetIp(); //局域网的ip地址,比如:192.168.1.101
+        } catch (SocketException e1) {
+            e1.printStackTrace();
+        }
+        System.out.println("内网ip:" + ip1);
+        String ip2 = addressUtils.getV4IP(); //用于实际判断地址的ip
+        System.out.println("外网ip:" + ip2);
+        //step2.根据外网ip地址,得到市级地理位置
+        String address = "";
+        try {
+            address = addressUtils.getAddresses("ip=" + ip2, "utf-8");
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+        }
+        // 输出地址,比如:中国,山东省,济南市,联通
+        System.out.println("您的" + address);
+        System.out.println("******************************");
+        System.out.println("请输入想要查询的ip地址(输入exit退出):");
+        Scanner scan = new Scanner(System.in);
+        String ip = "";
+        while (!"exit".equals(ip = scan.next())) {
+            try {
+                address = addressUtils.getAddresses("ip=" + ip, "utf-8");
+            } catch (UnsupportedEncodingException e) {
+                e.printStackTrace();
+            }
+            // 输出地址,比如:中国,山东省,济南市,联通
+            System.out.println(ip + "的" + address);
+            System.out.println("******************************");
+            System.out.println("请输入想要查询的ip地址(输入exit退出):");
+        }
+        scan.close();
+        System.out.println("再见");
+    }
+
+}

+ 58 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/IPMain.java

@@ -0,0 +1,58 @@
+package com.huimv.eartag.utils.ip;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+public class IPMain {
+    public static void main(String args[]) {
+        System.out.println(getip.publicip());
+    }
+}
+
+class getip {
+    public static String publicip() {
+        URL url = null;
+        URLConnection urlconn = null;
+        BufferedReader br = null;
+        try {
+            url = new URL("http://2017.ip138.com/ic.asp");//爬取的网站是百度搜索ip时排名第一的那个
+            urlconn = url.openConnection();
+            br = new BufferedReader(new InputStreamReader(
+                    urlconn.getInputStream()));
+            String buf = null;
+            String get= null;
+            while ((buf = br.readLine()) != null) {
+                get+=buf;
+            }
+            int where,end;
+            for(where=0;where<get.length()&&get.charAt(where)!='[';where++);
+            for(end=where;end<get.length()&&get.charAt(end)!=']';end++);
+            get=get.substring(where+1,end);
+            return get;
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                br.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
+}

+ 60 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/IPUtils.java

@@ -0,0 +1,60 @@
+package com.huimv.eartag.utils.ip;
+
+import org.springframework.stereotype.Component;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+public class IPUtils {
+
+    public String getV4IP() {
+        String ip = "";
+        String chinaz = "ht" + "tp" + ":/" + "/i" + "p.ch" + "in" + "az." + "co" + "m";
+        StringBuilder inputLine = new StringBuilder();
+        String read = "";
+        URL url = null;
+        HttpURLConnection urlConnection = null;
+        BufferedReader in = null;
+        try {
+            url = new URL(chinaz);
+            urlConnection = (HttpURLConnection) url.openConnection();
+            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
+            while ((read = in.readLine()) != null) {
+                inputLine.append(read + "\r\n");
+            }
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        System.out.println("inputLine.toString()>>"+inputLine.toString());
+//        Pattern p = Pattern.compile("\\<dd class\\="\&quot;fz24\&quot;">(.*?)\\&lt;\\/dd&gt;");
+//        Matcher m = p.matcher(inputLine.toString());
+//        if (m.find()) {
+//            String ipstr = m.group(1);
+//            ip = ipstr;
+//        }
+        return ip;
+    }
+}

+ 60 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/utils/ip/MyTest.java

@@ -0,0 +1,60 @@
+package com.huimv.eartag.utils.ip;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class MyTest {
+    public static void main(String[] args) throws Exception {
+        System.out.print(getV4IP());
+    }
+
+    public static String getV4IP() {
+        String ip=null;
+        try {
+            URL url = new URL("http://www.taobao.com/help/getip.php");
+            URLConnection URLconnection = url.openConnection();
+            HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
+            int responseCode = httpConnection.getResponseCode();
+            if (responseCode == HttpURLConnection.HTTP_OK) {
+                System.out.println("成功");
+                InputStream in = httpConnection.getInputStream();
+                InputStreamReader isr = new InputStreamReader(in);
+                BufferedReader bufr = new BufferedReader(isr);
+                String str;
+                while ((str = bufr.readLine()) != null) {
+                    ip=str;
+                    System.out.println(str);
+                }
+                bufr.close();
+            } else {
+                System.err.println("失败");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        if(ip!=null){
+
+            char[] chs=ip.toCharArray();
+            ip="";
+            for(int i=0;i<chs.length;i++){
+                if((chs[i]>=48&&chs[i]<=57)||chs[i]==46){
+                    ip+=chs[i];
+                }
+            }
+        }
+        return ip;
+    }
+}

+ 139 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/EartagDataVo.java

@@ -0,0 +1,139 @@
+package com.huimv.eartag.vo;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class EartagDataVo {
+    String cmdHeader = "";
+    String device = "";
+    String earmark = "";
+    Integer bat ;
+    Integer earTemp;
+    Integer earTemp1;
+    Integer envTemp;
+    Integer envTemp1;
+    Integer act;
+    Integer signal;
+    String askTime = "";
+
+    public String getOther() {
+        return other;
+    }
+
+    public void setOther(String other) {
+        this.other = other;
+    }
+
+    String other = "";
+
+    public String getCmdHeader() {
+        return cmdHeader;
+    }
+
+    public void setCmdHeader(String cmdHeader) {
+        this.cmdHeader = cmdHeader;
+    }
+
+    public String getDevice() {
+        return device;
+    }
+
+    public void setDevice(String device) {
+        this.device = device;
+    }
+
+    public String getEarmark() {
+        return earmark;
+    }
+
+    public void setEarmark(String earmark) {
+        this.earmark = earmark;
+    }
+
+    public Integer getBat() {
+        return bat;
+    }
+
+    public void setBat(Integer bat) {
+        this.bat = bat;
+    }
+
+    public Integer getEarTemp() {
+        return earTemp;
+    }
+
+    public void setEarTemp(Integer earTemp) {
+        this.earTemp = earTemp;
+    }
+
+    public Integer getEarTemp1() {
+        return earTemp1;
+    }
+
+    public void setEarTemp1(Integer earTemp1) {
+        this.earTemp1 = earTemp1;
+    }
+
+    public Integer getEnvTemp() {
+        return envTemp;
+    }
+
+    public void setEnvTemp(Integer envTemp) {
+        this.envTemp = envTemp;
+    }
+
+    public Integer getEnvTemp1() {
+        return envTemp1;
+    }
+
+    public void setEnvTemp1(Integer envTemp1) {
+        this.envTemp1 = envTemp1;
+    }
+
+    public Integer getAct() {
+        return act;
+    }
+
+    public void setAct(Integer act) {
+        this.act = act;
+    }
+
+    public Integer getSignal() {
+        return signal;
+    }
+
+    public void setSignal(Integer signal) {
+        this.signal = signal;
+    }
+
+    public String getAskTime() {
+        return askTime;
+    }
+
+    public void setAskTime(String askTime) {
+        this.askTime = askTime;
+    }
+
+    @Override
+    public String toString() {
+        return "EartagDataVo{" +
+                "cmdHeader='" + cmdHeader + '\'' +
+                ", device='" + device + '\'' +
+                ", earmark='" + earmark + '\'' +
+                ", bat=" + bat +
+                ", earTemp=" + earTemp +
+                ", earTemp1=" + earTemp1 +
+                ", envTemp=" + envTemp +
+                ", envTemp1=" + envTemp1 +
+                ", act=" + act +
+                ", signal=" + signal +
+                ", askTime='" + askTime + '\'' +
+                ", other='" + other + '\'' +
+                '}';
+    }
+}

+ 61 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/FarmAllStatusVo.java

@@ -0,0 +1,61 @@
+package com.huimv.eartag.vo;
+
+import java.sql.Date;
+import java.sql.Timestamp;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class FarmAllStatusVo {
+    private String farmId;
+    private String todayDateText;
+    private Date todayDate;
+    private Timestamp nowTimestamp;
+
+    public String getFarmId() {
+        return farmId;
+    }
+
+    public void setFarmId(String farmId) {
+        this.farmId = farmId;
+    }
+
+    public String getTodayDateText() {
+        return todayDateText;
+    }
+
+    public void setTodayDateText(String todayDateText) {
+        this.todayDateText = todayDateText;
+    }
+
+    public Date getTodayDate() {
+        return todayDate;
+    }
+
+    public void setTodayDate(Date todayDate) {
+        this.todayDate = todayDate;
+    }
+
+    public Timestamp getNowTimestamp() {
+        return nowTimestamp;
+    }
+
+    public void setNowTimestamp(Timestamp nowTimestamp) {
+        this.nowTimestamp = nowTimestamp;
+    }
+
+    @Override
+    public String toString() {
+        return "FarmAllStatusVo{" +
+                "farmId='" + farmId + '\'' +
+                ", todayDateText='" + todayDateText + '\'' +
+                ", todayDate=" + todayDate +
+                ", nowTimestamp=" + nowTimestamp +
+                '}';
+    }
+}

+ 79 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/Result.java

@@ -0,0 +1,79 @@
+package com.huimv.eartag.vo;
+
+import java.io.Serializable;
+
+public class Result implements Serializable {
+
+    private boolean success;
+    private Integer code;
+    private String message;
+
+    public boolean isSuccess() {
+        return success;
+    }
+
+    public void setSuccess(boolean success) {
+        this.success = success;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public void setCode(Integer code) {
+        this.code = code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+
+    private Object data;
+
+    //不需要返回数据时使用
+    public Result(ResultCode code) {
+        this.success = code.success;
+        this.code = code.code;
+        this.message = code.message;
+    }
+
+    public Result(ResultCode code, Object data) {
+        this.success = code.success;
+        this.code = code.code;
+        this.message = code.message;
+        this.data = data;
+    }
+
+    public Result(Integer code, String message, boolean success) {
+        this.code = code;
+        this.message = message;
+        this.success = success;
+    }
+
+    /*
+     * 调用ResultCode类封装常用的返回数据
+     */
+    public static Result SUCCESS(){
+        return new Result(ResultCode.SUCCESS);
+    }
+
+    public static Result ERROR(){
+        return new Result(ResultCode.SERVER_ERROR);
+    }
+
+    public static Result FAIL(){
+        return new Result(ResultCode.FAIL);
+    }
+}

+ 41 - 0
huimv-farm-eartag/src/main/java/com/huimv/eartag/vo/ResultCode.java

@@ -0,0 +1,41 @@
+package com.huimv.eartag.vo;
+
+public enum ResultCode {
+    SUCCESS(true,10000,"操作成功!"),
+    //---系统错误返回码-----
+    FAIL(false,10001,"操作失败"),
+    UNAUTHENTICATED(false,10002,"您还未登录"),
+    UNAUTHORISE(false,10003,"权限不足"),
+    SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!"),
+
+    //---用户操作返回码  2xxxx----
+    MOBILEORPASSWORDERROR(false,20001,"用户名或密码错误");
+    //---企业操作返回码  3xxxx----
+    //---权限操作返回码----
+    //---其他操作返回码----
+
+    //操作是否成功
+    boolean success;
+    //操作代码
+    int code;
+    //提示信息
+    String message;
+
+    ResultCode(boolean success,int code, String message){
+        this.success = success;
+        this.code = code;
+        this.message = message;
+    }
+
+    public boolean success() {
+        return success;
+    }
+
+    public int code() {
+        return code;
+    }
+
+    public String message() {
+        return message;
+    }
+}

+ 107 - 0
huimv-farm-eartag/src/main/resources/application-dev.yml

@@ -0,0 +1,107 @@
+server:
+  port: 8090
+
+spring:
+  application:
+    name: huimv-farm-eartag-input
+
+  datasource:
+    url: jdbc:mysql://192.168.1.7:3306/huimv_farm_eartag?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+    username: root
+    password: hm123456
+    driver-class-name: com.mysql.cj.jdbc.Driver
+  jpa:
+    show-sql: true
+    database: mysql
+    hibernate:
+      ddl-auto: update
+    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
+    open-in-view: true
+
+  #配置rabbitMq 服务器
+#  rabbitmq:
+#    host: 10.0.0.4
+#    port: 5672
+#    username: huimv
+#    password: hm123456
+#    #虚拟host 可以不设置,使用server默认host
+#    virtual-host: /
+  rabbitmq:
+    host: 192.168.1.170
+    port: 5672
+    username: admin
+    password: admin
+    #虚拟host 可以不设置,使用server默认host
+    virtual-host: /
+    listener:
+      simple:
+        acknowledge-mode: none
+
+    #确认消息已发送到交换机(Exchange)
+#    publisher-confirms: true #(过时、弃用)
+    publisher-confirm-type: correlated
+    #确认消息已发送到队列(Queue)
+    publisher-returns: true
+
+  #redis
+  redis:
+    database: 0
+    host: 192.168.1.68
+    port: 6379
+    password: hm123456
+    timeout: 5000ms
+    jedis:
+      pool:
+        max-active: 20
+        max-wait: -1
+        max-idle: 10
+        min-idle: 0
+    lettuce:
+      pool:
+        max-active: 3
+        min-idle: 2
+        max-idle: 3
+        max-wait: 1
+      shutdown-timeout: 100
+
+  data:
+    redis:
+      repositories:
+        enabled: false
+
+  #是否缓存空值
+  cache:
+    redis:
+      cache-null-values: false
+
+
+
+    #server:
+#  port: 9110
+#spring:
+#  application:
+#    name: huimv-hy-autoGetData
+#
+#  datasource:
+##    url: jdbc:mysql://47.98.175.112:3306/huimv_ql_farm_haiyan?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#    #    url: jdbc:mysql://36.22.189.214:3306/huimv_ql_farm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#        url: jdbc:mysql://192.168.1.7:3306/huimv_ql_farm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#    username: root
+#    password: hm123456
+#    driver-class-name: com.mysql.cj.jdbc.Driver
+#  jpa:
+#    properties:
+#      hibernate:
+#        enable_lazy_load_no_trans: true
+#    show-sql: true
+#    database: mysql
+#    hibernate:
+#      ddl-auto: update
+#    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
+#    open-in-view: true
+management:
+  endpoints:
+    web:
+      exposure:
+        include: "*"   # * 在yaml 文件属于关键字,所以需要加引号
+

+ 107 - 0
huimv-farm-eartag/src/main/resources/application-prod.yml

@@ -0,0 +1,107 @@
+server:
+  port: 8092
+spring:
+  application:
+    name: huimv-eartag2-process
+
+  datasource:
+    url: jdbc:mysql://192.168.1.7:3306/huimv_farm_eartag?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+    username: root
+    password: hm123456
+    driver-class-name: com.mysql.cj.jdbc.Driver
+  jpa:
+    show-sql: true
+    database: mysql
+    hibernate:
+      ddl-auto: update
+    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
+    open-in-view: true
+
+  #配置rabbitMq 服务器
+#  rabbitmq:
+#    host: 10.0.0.4
+#    port: 5672
+#    username: huimv
+#    password: hm123456
+#    #虚拟host 可以不设置,使用server默认host
+#    virtual-host: /
+  rabbitmq:
+    host: 192.168.1.170
+    port: 5672
+    username: admin
+    password: admin
+    #虚拟host 可以不设置,使用server默认host
+    virtual-host: /
+    listener:
+      simple:
+        acknowledge-mode: none  #消费端不需要确认
+
+  #redis
+  redis:
+    database: 0
+    host: 192.168.1.68
+    port: 6379
+    password: hm123456
+    timeout: 5000ms
+    jedis:
+      pool:
+        max-active: 20
+        max-wait: -1
+        max-idle: 10
+        min-idle: 0
+
+  #redis
+#  redis:
+#    database: 0
+#    host: 192.168.1.68
+#    port: 6379
+#    password: hm123456
+#    timeout: 5000ms
+#    jedis:
+#      pool:
+#        max-active: 20
+#        max-wait: -1
+#        max-idle: 10
+#        min-idle: 0
+#    lettuce:
+#      pool:
+#        max-active: 3
+#        min-idle: 2
+#        max-idle: 3
+#        max-wait: 1
+#      shutdown-timeout: 100
+
+#  data:
+#    redis:
+#      repositories:
+#        enabled: false
+
+  #是否缓存空值
+#  cache:
+#    redis:
+#      cache-null-values: false
+    #server:
+#  port: 9110
+#spring:
+#  application:
+#    name: huimv-hy-autoGetData
+#
+#  datasource:
+##    url: jdbc:mysql://47.98.175.112:3306/huimv_ql_farm_haiyan?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#    #    url: jdbc:mysql://36.22.189.214:3306/huimv_ql_farm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#        url: jdbc:mysql://192.168.1.7:3306/huimv_ql_farm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+#    username: root
+#    password: hm123456
+#    driver-class-name: com.mysql.cj.jdbc.Driver
+#  jpa:
+#    properties:
+#      hibernate:
+#        enable_lazy_load_no_trans: true
+#    show-sql: true
+#    database: mysql
+#    hibernate:
+#      ddl-auto: update
+#    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
+#    open-in-view: true
+
+

+ 66 - 0
huimv-farm-eartag/src/main/resources/application.properties

@@ -0,0 +1,66 @@
+# 属性配置
+spring.profiles.active=dev
+
+# 开启健康监控
+management.endpoints.web.exposure.include=*
+
+#########################################################
+###             配置undertow取代tomcat                ###
+#########################################################
+# 是否打开 undertow 日志,默认为 false
+server.undertow.accesslog.enabled=false
+# 设置访问日志所在目录
+server.undertow.accesslog.dir=logs
+# 指定工作者线程的 I/0 线程数,默认为 2 或者 CPU 的个数
+server.undertow.io-threads=
+# 指定工作者线程个数,默认为 I/O 线程个数的 8 倍
+server.undertow.worker-threads=
+# 设置 HTTP POST 内容的最大长度,默认不做限制
+server.undertow.max-http-post-size=0
+
+#########################################################
+###   Actuator Monitor  --   Actuator configuration   ###
+#########################################################
+management.security.enabled=false
+
+# 数据处理流程
+data.input.flow=2
+
+# 是否写入测试数据(1:写入 0:不写入)
+data.test.input=0
+
+# Eartag
+device.register.prefix=device_register_
+redis.expire.eartag_online_set=25
+
+# Device
+service.farmAllStatus.url=/deviceController/updateFarmAllStatus
+service.farmAllStatus.host=192.168.1.68
+service.farmAllStatus.ip=8092
+
+################################################################
+# mysql:/cache:
+device.online.access_mode=mysql
+
+# 添加机器和设备过期时间
+cache.chipIdExpire=48
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 24 - 0
huimv-farm-eartag/src/main/resources/assembly.xml

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<assembly>
+    <id>jar-with-dependencies</id>
+    <formats>
+        <format>jar</format>
+    </formats>
+    <includeBaseDirectory>false</includeBaseDirectory>
+    <dependencySets>
+        <!-- 默认的配置 -->
+        <dependencySet>
+            <outputDirectory>/</outputDirectory>
+            <useProjectArtifact>true</useProjectArtifact>
+            <unpack>true</unpack>
+            <scope>runtime</scope>
+        </dependencySet>
+        <!-- 增加scope类型为system的配置 -->
+        <dependencySet>
+            <outputDirectory>/</outputDirectory>
+            <useProjectArtifact>true</useProjectArtifact>
+            <unpack>true</unpack>
+            <scope>system</scope>
+        </dependencySet>
+    </dependencySets>
+</assembly>