Browse Source

1、优化代码,删除无用代码;

2、修复系统用户角色管理bug;
pro_v1
mh 2 months ago
parent
commit
1fc44b3555
  1. 8
      common/pom.xml
  2. 93
      user-service/pom.xml
  3. 6
      user-service/src/main/java/com/mh/user/UserServiceApplication.java
  4. 4
      user-service/src/main/java/com/mh/user/aspect/SysLogAspect.java
  5. 12
      user-service/src/main/java/com/mh/user/component/ReceiveHandler.java
  6. 234
      user-service/src/main/java/com/mh/user/config/DruidConfig.java
  7. 344
      user-service/src/main/java/com/mh/user/config/DruidDataSourceProperties.java
  8. 34
      user-service/src/main/java/com/mh/user/config/DruidStatViewServlet.java
  9. 8
      user-service/src/main/java/com/mh/user/config/PrimessionInterceptor.java
  10. 107
      user-service/src/main/java/com/mh/user/config/QuartzConfig.java
  11. 11
      user-service/src/main/java/com/mh/user/config/RabbitmqConfig.java
  12. 2
      user-service/src/main/java/com/mh/user/controller/ChartController.java
  13. 2
      user-service/src/main/java/com/mh/user/controller/ChillersController.java
  14. 2
      user-service/src/main/java/com/mh/user/controller/DeviceInfoController.java
  15. 595
      user-service/src/main/java/com/mh/user/controller/DeviceManageController.java
  16. 5
      user-service/src/main/java/com/mh/user/controller/SysLoginController.java
  17. 9
      user-service/src/main/java/com/mh/user/controller/TestController.java
  18. 154
      user-service/src/main/java/com/mh/user/dynamic/config/DataSourceConfig.java
  19. 56
      user-service/src/main/java/com/mh/user/dynamic/config/MyBatisMapperScannerConfig.java
  20. 142
      user-service/src/main/java/com/mh/user/dynamic/datasource/DataSourceObject.java
  21. 34
      user-service/src/main/java/com/mh/user/entity/BaseResultEntity.java
  22. 23
      user-service/src/main/java/com/mh/user/entity/DataResultChEntity.java
  23. 7
      user-service/src/main/java/com/mh/user/entity/DataResultChillerEntity.java
  24. 32
      user-service/src/main/java/com/mh/user/entity/DataResultClBakEntity.java
  25. 21
      user-service/src/main/java/com/mh/user/entity/DataResultClEntity.java
  26. 18
      user-service/src/main/java/com/mh/user/entity/DataResultEntity.java
  27. 7
      user-service/src/main/java/com/mh/user/entity/DataResultFifteenMiEntity.java
  28. 7
      user-service/src/main/java/com/mh/user/entity/DataResultFiveMiEntity.java
  29. 7
      user-service/src/main/java/com/mh/user/entity/DataResultNowEntity.java
  30. 7
      user-service/src/main/java/com/mh/user/entity/DataResultOneMiEntity.java
  31. 130
      user-service/src/main/java/com/mh/user/entity/DeviceCodeEntity.java
  32. 144
      user-service/src/main/java/com/mh/user/entity/DeviceCodeParamEntity.java
  33. 6
      user-service/src/main/java/com/mh/user/entity/DeviceInfoEntity.java
  34. 13
      user-service/src/main/java/com/mh/user/entity/DeviceInstallEntity.java
  35. 99
      user-service/src/main/java/com/mh/user/entity/EnergyDataEntity.java
  36. 7
      user-service/src/main/java/com/mh/user/entity/GatewayManageEntity.java
  37. 11
      user-service/src/main/java/com/mh/user/entity/MeterInfoEntity.java
  38. 4
      user-service/src/main/java/com/mh/user/entity/ProjectInfoEntity.java
  39. 2
      user-service/src/main/java/com/mh/user/entity/RegisterAddrEntity.java
  40. 71
      user-service/src/main/java/com/mh/user/entity/StrategyInfoEntity.java
  41. 2
      user-service/src/main/java/com/mh/user/entity/chart/ChartEntity.java
  42. 2
      user-service/src/main/java/com/mh/user/entity/chart/Feature.java
  43. 2
      user-service/src/main/java/com/mh/user/entity/chart/Legend.java
  44. 2
      user-service/src/main/java/com/mh/user/entity/chart/Series.java
  45. 2
      user-service/src/main/java/com/mh/user/entity/chart/Title.java
  46. 2
      user-service/src/main/java/com/mh/user/entity/chart/YAxis.java
  47. 226
      user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
  48. 5
      user-service/src/main/java/com/mh/user/job/DealDataJob.java
  49. 39
      user-service/src/main/java/com/mh/user/job/JobChillers.java
  50. 41
      user-service/src/main/java/com/mh/user/job/JobCloud.java
  51. 39
      user-service/src/main/java/com/mh/user/job/JobDDC.java
  52. 45
      user-service/src/main/java/com/mh/user/job/JobFactory.java
  53. 39
      user-service/src/main/java/com/mh/user/job/JobMeter.java
  54. 32
      user-service/src/main/java/com/mh/user/job/JobTest.java
  55. 73
      user-service/src/main/java/com/mh/user/mapper/DataResultChMapper.java
  56. 105
      user-service/src/main/java/com/mh/user/mapper/DataResultChillerMapper.java
  57. 35
      user-service/src/main/java/com/mh/user/mapper/DataResultClBakMapper.java
  58. 42
      user-service/src/main/java/com/mh/user/mapper/DataResultClMapper.java
  59. 36
      user-service/src/main/java/com/mh/user/mapper/DataResultFifteenMiMapper.java
  60. 33
      user-service/src/main/java/com/mh/user/mapper/DataResultFiveMiMapper.java
  61. 225
      user-service/src/main/java/com/mh/user/mapper/DataResultMapper.java
  62. 36
      user-service/src/main/java/com/mh/user/mapper/DataResultNowMapper.java
  63. 46
      user-service/src/main/java/com/mh/user/mapper/DataResultOneMiMapper.java
  64. 55
      user-service/src/main/java/com/mh/user/mapper/DeviceCodeMapper.java
  65. 57
      user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java
  66. 48
      user-service/src/main/java/com/mh/user/mapper/DeviceInfoMapper.java
  67. 10
      user-service/src/main/java/com/mh/user/mapper/DeviceInstallMapper.java
  68. 19
      user-service/src/main/java/com/mh/user/mapper/EnergyDataMapper.java
  69. 1
      user-service/src/main/java/com/mh/user/mapper/EnergyMapper.java
  70. 10
      user-service/src/main/java/com/mh/user/mapper/MeterInfoMapper.java
  71. 3
      user-service/src/main/java/com/mh/user/mapper/ProjectInfoMapper.java
  72. 15
      user-service/src/main/java/com/mh/user/mapper/RegisterAddrMapper.java
  73. 24
      user-service/src/main/java/com/mh/user/mapper/StrategyInfoMapper.java
  74. 1
      user-service/src/main/java/com/mh/user/mapper/SysDeptMapper.java
  75. 2
      user-service/src/main/java/com/mh/user/mapper/SysMenuMapper.java
  76. 1
      user-service/src/main/java/com/mh/user/mapper/SysRoleDeptMapper.java
  77. 1
      user-service/src/main/java/com/mh/user/mapper/SysUserRoleMapper.java
  78. 121
      user-service/src/main/java/com/mh/user/mapper/provider/DataResultProvider.java
  79. 3
      user-service/src/main/java/com/mh/user/mapper/provider/DeviceInfoProvider.java
  80. 1
      user-service/src/main/java/com/mh/user/mapper/provider/EnergyDataProvider.java
  81. 21
      user-service/src/main/java/com/mh/user/mapper/provider/StrategyInfoProvider.java
  82. 3
      user-service/src/main/java/com/mh/user/model/BaseModel.java
  83. 2
      user-service/src/main/java/com/mh/user/model/SysMenu.java
  84. 4
      user-service/src/main/java/com/mh/user/model/SysUser.java
  85. 4
      user-service/src/main/java/com/mh/user/netty/EchoServer.java
  86. 8
      user-service/src/main/java/com/mh/user/netty/EchoServerHandler.java
  87. 95
      user-service/src/main/java/com/mh/user/netty/NettyChillerClient.java
  88. 315
      user-service/src/main/java/com/mh/user/netty/NettyChillerClientHandler.java
  89. 98
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
  90. 315
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
  91. 96
      user-service/src/main/java/com/mh/user/netty/NettyChillerDDCClient.java
  92. 297
      user-service/src/main/java/com/mh/user/netty/NettyChillerDDCClientHandler.java
  93. 90
      user-service/src/main/java/com/mh/user/netty/NettyClient.java
  94. 190
      user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
  95. 180
      user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
  96. 95
      user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
  97. 261
      user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler.java
  98. 7
      user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java
  99. 7
      user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java
  100. 4
      user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
  101. Some files were not shown because too many files have changed in this diff Show More

8
common/pom.xml

@ -23,11 +23,13 @@
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.51</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>

93
user-service/pom.xml

@ -23,32 +23,39 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>import</scope>
<!-- 当时本地启动需要注释掉-->
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.2.2.RELEASE</version>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-config</artifactId>-->
<!-- <version>2.2.2.RELEASE</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.8.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.51</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-config-client</artifactId>-->
@ -74,32 +81,49 @@
</exclusions>
</dependency>
<!-- mybatis配置-->
<!-- <dependency>-->
<!-- <groupId>org.mybatis.spring.boot</groupId>-->
<!-- <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!-- <version>3.0.2</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- mysql数据库链接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>mysql</groupId>-->
<!-- <artifactId>mysql-connector-java</artifactId>-->
<!-- </dependency>-->
<!-- druid配置-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.18</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.alibaba</groupId>-->
<!-- <artifactId>druid-spring-boot-starter</artifactId>-->
<!-- <version>1.1.18</version>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.apache.logging.log4j</groupId>-->
<!-- <artifactId>log4j-core</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入log4j依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.23.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.23.1</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
@ -141,21 +165,16 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>tk.mybatis</groupId>-->
<!-- <artifactId>mapper</artifactId>-->
<!-- <version>3.3.9</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>

6
user-service/src/main/java/com/mh/user/UserServiceApplication.java

@ -1,6 +1,6 @@
package com.mh.user;
import org.apache.log4j.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@ -8,13 +8,11 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.PreDestroy;
@Slf4j
@SpringBootApplication(scanBasePackages = "com.mh.user")
@EnableScheduling
public class UserServiceApplication extends SpringBootServletInitializer {
private static final Logger log = Logger.getLogger(UserServiceApplication.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(UserServiceApplication.class);

4
user-service/src/main/java/com/mh/user/aspect/SysLogAspect.java

@ -2,6 +2,7 @@ package com.mh.user.aspect;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson2.JSONObject;
import com.mh.user.annotation.SysLogger;
import com.mh.user.model.SysLog;
import com.mh.user.service.SysLogService;
@ -17,10 +18,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

12
user-service/src/main/java/com/mh/user/component/ReceiveHandler.java

@ -1,20 +1,12 @@
package com.mh.user.component;
import com.alibaba.druid.sql.visitor.functions.Isnull;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONObject;
import com.mh.user.config.RabbitmqConfig;
import com.mh.user.model.QueueParam;
import com.mh.user.utils.AnalysisReceiveOrder485;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.impl.AMQImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@ -23,10 +15,10 @@ import java.io.IOException;
/**
* 队列消费接收消息
*/
@Slf4j
@Component
public class ReceiveHandler {
private static final Logger log = Logger.getLogger(ReceiveHandler.class);
//监听队列
// @RabbitListener(bindings = @QueueBinding(
// value = @Queue(value = "queue_zjjd", durable = "true"),

234
user-service/src/main/java/com/mh/user/config/DruidConfig.java

@ -1,117 +1,117 @@
package com.mh.user.config;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* @author ljf
* @title
* @description
* @updateTime 2020-03-13
* @throws
*/
@Configuration
@EnableConfigurationProperties({DruidDataSourceProperties.class})
public class DruidConfig {
@Autowired
private DruidDataSourceProperties properties;
@Bean
@ConditionalOnMissingBean
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getDriverClassName());
druidDataSource.setUrl(properties.getUrl());
druidDataSource.setUsername(properties.getUsername());
druidDataSource.setPassword(properties.getPassword());
druidDataSource.setInitialSize(properties.getInitialSize());
druidDataSource.setMinIdle(properties.getMinIdle());
druidDataSource.setMaxActive(properties.getMaxActive());
druidDataSource.setMaxWait(properties.getMaxWait());
druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
druidDataSource.setValidationQuery(properties.getValidationQuery());
druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
druidDataSource.setTestOnReturn(properties.isTestOnReturn());
druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
List list=new ArrayList<>();
WallFilter wallFilter=new WallFilter();
WallConfig config = new WallConfig();
//允许一次执行多条语句
config.setMultiStatementAllow(true);
//允许非基本语句的其他语句
//config.setNoneBaseStatementAllow(true);
wallFilter.setConfig(config);
list.add(wallFilter);
druidDataSource.setProxyFilters(list);
try {
druidDataSource.setFilters(properties.getFilters());
druidDataSource.init();
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
/**
* 注册Servlet信息 配置监控视图
*
* @return
*/
@Bean
@ConditionalOnMissingBean
public ServletRegistrationBean<Servlet> druidServlet() {
ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*");
//白名单:
// servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
servletRegistrationBean.addInitParameter("deny","192.168.1.222");
//登录查看信息的账号密码, 用于登录Druid监控后台
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
//是否能够重置数据.
servletRegistrationBean.addInitParameter("resetEnable", "true");
return servletRegistrationBean;
}
/**
* 注册Filter信息, 监控拦截器
*
* @return
*/
@Bean
@ConditionalOnMissingBean
public FilterRegistrationBean<Filter> filterRegistrationBean() {
FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
//package com.mh.user.config;
//
//import java.sql.SQLException;
//import java.util.ArrayList;
//import java.util.List;
//
//import javax.servlet.Filter;
//import javax.servlet.Servlet;
//import javax.sql.DataSource;
//
//import com.alibaba.druid.wall.WallConfig;
//import com.alibaba.druid.wall.WallFilter;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.boot.web.servlet.FilterRegistrationBean;
//import org.springframework.boot.web.servlet.ServletRegistrationBean;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import com.alibaba.druid.pool.DruidDataSource;
//import com.alibaba.druid.support.http.StatViewServlet;
//import com.alibaba.druid.support.http.WebStatFilter;
//
///**
// * @author ljf
// * @title :
// * @description :
// * @updateTime 2020-03-13
// * @throws :
// */
//@Configuration
//@EnableConfigurationProperties({DruidDataSourceProperties.class})
//public class DruidConfig {
// @Autowired
// private DruidDataSourceProperties properties;
//
// @Bean
// @ConditionalOnMissingBean
// public DataSource druidDataSource() {
// DruidDataSource druidDataSource = new DruidDataSource();
// druidDataSource.setDriverClassName(properties.getDriverClassName());
// druidDataSource.setUrl(properties.getUrl());
// druidDataSource.setUsername(properties.getUsername());
// druidDataSource.setPassword(properties.getPassword());
// druidDataSource.setInitialSize(properties.getInitialSize());
// druidDataSource.setMinIdle(properties.getMinIdle());
// druidDataSource.setMaxActive(properties.getMaxActive());
// druidDataSource.setMaxWait(properties.getMaxWait());
// druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
// druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
// druidDataSource.setValidationQuery(properties.getValidationQuery());
// druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
// druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
// druidDataSource.setTestOnReturn(properties.isTestOnReturn());
// druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
// druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
//
// List list=new ArrayList<>();
// WallFilter wallFilter=new WallFilter();
// WallConfig config = new WallConfig();
// //允许一次执行多条语句
// config.setMultiStatementAllow(true);
// //允许非基本语句的其他语句
// //config.setNoneBaseStatementAllow(true);
// wallFilter.setConfig(config);
// list.add(wallFilter);
// druidDataSource.setProxyFilters(list);
//
// try {
// druidDataSource.setFilters(properties.getFilters());
// druidDataSource.init();
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// return druidDataSource;
// }
//
// /**
// * 注册Servlet信息, 配置监控视图
// *
// * @return
// */
// @Bean
// @ConditionalOnMissingBean
// public ServletRegistrationBean<Servlet> druidServlet() {
// ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*");
//
// //白名单:
//// servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
// //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
// servletRegistrationBean.addInitParameter("deny","192.168.1.222");
// //登录查看信息的账号密码, 用于登录Druid监控后台
// servletRegistrationBean.addInitParameter("loginUsername", "admin");
// servletRegistrationBean.addInitParameter("loginPassword", "admin");
// //是否能够重置数据.
// servletRegistrationBean.addInitParameter("resetEnable", "true");
// return servletRegistrationBean;
//
// }
//
// /**
// * 注册Filter信息, 监控拦截器
// *
// * @return
// */
// @Bean
// @ConditionalOnMissingBean
// public FilterRegistrationBean<Filter> filterRegistrationBean() {
// FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>();
// filterRegistrationBean.setFilter(new WebStatFilter());
// filterRegistrationBean.addUrlPatterns("/*");
// filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
// return filterRegistrationBean;
// }
//}

344
user-service/src/main/java/com/mh/user/config/DruidDataSourceProperties.java

@ -1,172 +1,172 @@
package com.mh.user.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author ljf
* @title
* @description
* @updateTime 2020-03-13
* @throws
*/
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidDataSourceProperties {
// jdbc
private String driverClassName;
private String url;
private String username;
private String password;
// jdbc connection pool
private int initialSize;
private int minIdle;
private int maxActive = 100;
private long maxWait;
private long timeBetweenEvictionRunsMillis;
private long minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
// filter
private String filters;
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public long getMaxWait() {
return maxWait;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public int getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//package com.mh.user.config;
//
//import org.springframework.boot.context.properties.ConfigurationProperties;
//
///**
// * @author ljf
// * @title :
// * @description :
// * @updateTime 2020-03-13
// * @throws :
// */
//@ConfigurationProperties(prefix = "spring.datasource.druid")
//public class DruidDataSourceProperties {
//
// // jdbc
// private String driverClassName;
// private String url;
// private String username;
// private String password;
// // jdbc connection pool
// private int initialSize;
// private int minIdle;
// private int maxActive = 100;
// private long maxWait;
// private long timeBetweenEvictionRunsMillis;
// private long minEvictableIdleTimeMillis;
// private String validationQuery;
// private boolean testWhileIdle;
// private boolean testOnBorrow;
// private boolean testOnReturn;
// private boolean poolPreparedStatements;
// private int maxPoolPreparedStatementPerConnectionSize;
// // filter
// private String filters;
//
// public int getInitialSize() {
// return initialSize;
// }
//
// public void setInitialSize(int initialSize) {
// this.initialSize = initialSize;
// }
//
// public int getMinIdle() {
// return minIdle;
// }
//
// public void setMinIdle(int minIdle) {
// this.minIdle = minIdle;
// }
//
// public int getMaxActive() {
// return maxActive;
// }
//
// public void setMaxActive(int maxActive) {
// this.maxActive = maxActive;
// }
//
// public long getMaxWait() {
// return maxWait;
// }
//
// public void setMaxWait(long maxWait) {
// this.maxWait = maxWait;
// }
//
// public long getTimeBetweenEvictionRunsMillis() {
// return timeBetweenEvictionRunsMillis;
// }
//
// public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
// this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
// }
//
// public long getMinEvictableIdleTimeMillis() {
// return minEvictableIdleTimeMillis;
// }
//
// public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
// this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
// }
//
// public String getValidationQuery() {
// return validationQuery;
// }
//
// public void setValidationQuery(String validationQuery) {
// this.validationQuery = validationQuery;
// }
//
// public boolean isTestWhileIdle() {
// return testWhileIdle;
// }
//
// public void setTestWhileIdle(boolean testWhileIdle) {
// this.testWhileIdle = testWhileIdle;
// }
//
// public boolean isTestOnBorrow() {
// return testOnBorrow;
// }
//
// public void setTestOnBorrow(boolean testOnBorrow) {
// this.testOnBorrow = testOnBorrow;
// }
//
// public boolean isTestOnReturn() {
// return testOnReturn;
// }
//
// public void setTestOnReturn(boolean testOnReturn) {
// this.testOnReturn = testOnReturn;
// }
//
// public boolean isPoolPreparedStatements() {
// return poolPreparedStatements;
// }
//
// public void setPoolPreparedStatements(boolean poolPreparedStatements) {
// this.poolPreparedStatements = poolPreparedStatements;
// }
//
// public int getMaxPoolPreparedStatementPerConnectionSize() {
// return maxPoolPreparedStatementPerConnectionSize;
// }
//
// public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
// this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
// }
//
// public String getFilters() {
// return filters;
// }
//
// public void setFilters(String filters) {
// this.filters = filters;
// }
//
// public String getDriverClassName() {
// return driverClassName;
// }
//
// public void setDriverClassName(String driverClassName) {
// this.driverClassName = driverClassName;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
//}

34
user-service/src/main/java/com/mh/user/config/DruidStatViewServlet.java

@ -1,17 +1,17 @@
package com.mh.user.config;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* druid监控视图配置
*/
//@WebServlet(urlPatterns = "/druid/*", initParams={
// @WebInitParam(name="allow",value="192.168.6.195"), // IP白名单 (没有配置或者为空,则允许所有访问)
// @WebInitParam(name="deny",value="192.168.6.73"), // IP黑名单 (存在共同时,deny优先于allow)
// @WebInitParam(name="loginUsername",value="admin"), // 用户名
// @WebInitParam(name="loginPassword",value="admin"), // 密码
// @WebInitParam(name="resetEnable",value="true") // 禁用HTML页面上的“Reset All”功能
//})
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = 7359758657306626394L;
}
//package com.mh.user.config;
//
//import com.alibaba.druid.support.http.StatViewServlet;
//
///**
// * druid监控视图配置
// */
////@WebServlet(urlPatterns = "/druid/*", initParams={
//// @WebInitParam(name="allow",value="192.168.6.195"), // IP白名单 (没有配置或者为空,则允许所有访问)
//// @WebInitParam(name="deny",value="192.168.6.73"), // IP黑名单 (存在共同时,deny优先于allow)
//// @WebInitParam(name="loginUsername",value="admin"), // 用户名
//// @WebInitParam(name="loginPassword",value="admin"), // 密码
//// @WebInitParam(name="resetEnable",value="true") // 禁用HTML页面上的“Reset All”功能
////})
//public class DruidStatViewServlet extends StatViewServlet {
// private static final long serialVersionUID = 7359758657306626394L;
//}

8
user-service/src/main/java/com/mh/user/config/PrimessionInterceptor.java

@ -1,13 +1,9 @@
package com.mh.user.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mh.user.dynamic.datasource.DataSourceContextHolder;
import com.mh.user.dynamic.datasource.DataSourceObject;
import com.mh.user.entity.DBEntity;
import com.mh.user.service.SysUserService;
import com.mh.user.utils.JwtTokenUtils;
import com.mh.user.utils.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

107
user-service/src/main/java/com/mh/user/config/QuartzConfig.java

@ -1,54 +1,53 @@
package com.mh.user.config;
import com.mh.user.job.JobFactory;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
* @author ljf
* @title Quartz配置
* @description
* @updateTime 2020-04-03
* @throws
*/
@Slf4j
@Configuration
public class QuartzConfig {
private JobFactory jobFactory;
/**
* @author jinhaoxun
* @description 构造器
* @param jobFactory
*/
public QuartzConfig(JobFactory jobFactory){
this.jobFactory = jobFactory;
}
/**
* @author jinhaoxun
* @description 配置SchedulerFactoryBean将一个方法产生为Bean并交给Spring容器管理
* @return SchedulerFactoryBean
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
// log.info("开始注入定时任务调度器工厂...");
System.out.println("开始注入定时任务调度器工厂...");
SchedulerFactoryBean factory = new SchedulerFactoryBean();// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
factory.setJobFactory(jobFactory);// 设置自定义Job Factory,用于Spring管理Job bean
factory.setOverwriteExistingJobs(true);// 覆盖存在的定时任务
factory.setStartupDelay(30); //延时30秒启动定时任务,避免系统未完全启动却开始执行定时任务的情况
// log.info("注入定时任务调度器工厂成功!");
System.out.println("注入定时任务调度器工厂成功!");
return factory;
}
@Bean(name = "scheduler")
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
//package com.mh.user.config;
//
//import lombok.extern.slf4j.Slf4j;
//import org.quartz.Scheduler;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.scheduling.quartz.SchedulerFactoryBean;
//
///**
// * @author ljf
// * @title : Quartz配置
// * @description :
// * @updateTime 2020-04-03
// * @throws :
// */
//@Slf4j
//@Configuration
//public class QuartzConfig {
//
// private JobFactory jobFactory;
//
// /**
// * @author jinhaoxun
// * @description 构造器
// * @param jobFactory
// */
// public QuartzConfig(JobFactory jobFactory){
// this.jobFactory = jobFactory;
// }
//
// /**
// * @author jinhaoxun
// * @description 配置SchedulerFactoryBean,将一个方法产生为Bean并交给Spring容器管理
// * @return SchedulerFactoryBean
// */
// @Bean
// public SchedulerFactoryBean schedulerFactoryBean() {
//// log.info("开始注入定时任务调度器工厂...");
// System.out.println("开始注入定时任务调度器工厂...");
// SchedulerFactoryBean factory = new SchedulerFactoryBean();// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
// factory.setJobFactory(jobFactory);// 设置自定义Job Factory,用于Spring管理Job bean
// factory.setOverwriteExistingJobs(true);// 覆盖存在的定时任务
// factory.setStartupDelay(30); //延时30秒启动定时任务,避免系统未完全启动却开始执行定时任务的情况
//// log.info("注入定时任务调度器工厂成功!");
// System.out.println("注入定时任务调度器工厂成功!");
// return factory;
// }
//
// @Bean(name = "scheduler")
// public Scheduler scheduler() {
// return schedulerFactoryBean().getScheduler();
// }
//}

11
user-service/src/main/java/com/mh/user/config/RabbitmqConfig.java

@ -1,30 +1,21 @@
package com.mh.user.config;
import com.mh.user.component.ReceiveHandler;
import com.mh.user.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
/**
*队列绑定队列绑定交换机绑定路由KEY
*/
@Slf4j
@Configuration
public class RabbitmqConfig {
private static final Logger log = Logger.getLogger(RabbitmqConfig.class);
// public static final String QUEUE_NAME = "queue_zjjd"; //采集队列,珠江酒店
// public static final String QUEUE_NAME = "queue_gdkj"; //采集队列,广大科技

2
user-service/src/main/java/com/mh/user/controller/ChartController.java

@ -1,6 +1,6 @@
package com.mh.user.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONArray;
import com.mh.common.http.HttpResult;
import com.mh.user.entity.chart.ChartEntity;
import com.mh.user.entity.chart.GetChartParams;

2
user-service/src/main/java/com/mh/user/controller/ChillersController.java

@ -1,6 +1,6 @@
package com.mh.user.controller;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONObject;
import com.mh.common.http.HttpResult;
import com.mh.user.dto.DisplayBoxDataDTO;
import com.mh.user.dto.TableInfoDTO;

2
user-service/src/main/java/com/mh/user/controller/DeviceInfoController.java

@ -25,7 +25,7 @@ public class DeviceInfoController {
@PostMapping("/query")
public HttpResult queryMeterInfo(@RequestParam(value = "systemID") String systemID,
@RequestParam(value = "projectID") String projectID,
@RequestParam(value = "deviceType") String deviceType){
@RequestParam(value = "deviceType", required = false) String deviceType){
List<DeviceInfoEntity> list=deviceInfoService.queryDeviceInfo(systemID,projectID,deviceType);
return HttpResult.ok(list);

595
user-service/src/main/java/com/mh/user/controller/DeviceManageController.java

@ -1,299 +1,296 @@
package com.mh.user.controller;
import com.alibaba.fastjson.JSONObject;
import com.mh.common.http.HttpResult;
import com.mh.user.annotation.SysLogger;
import com.mh.user.dto.DeviceMessageDTO;
import com.mh.user.entity.*;
import com.mh.user.manage.QuartzManager;
import com.mh.user.netty.NettyChillerControlClient;
import com.mh.user.service.chillers.DeviceDisplayService;
import com.mh.user.constants.Constant;
import com.mh.user.service.chillers.DeviceManageService;
import com.mh.user.service.chillers.DeviceParamService;
import com.mh.user.service.chillers.GatewayManageService;
import com.mh.user.utils.GetReadOrder485;
import com.mh.user.utils.QuerySendThread;
import com.mh.user.constants.SocketMessage;
import com.mh.user.utils.TimeDifferenceUtil;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ljf
* @title
* @description 设备管理接口
* @updateTime 2020-05-29
* @updateTime 2020-07-17
* @throws
*/
@RestController
public class DeviceManageController {
private final DeviceDisplayService deviceDisplayService;
private final GatewayManageService gatewayManageService;
private final DeviceManageService deviceManageService;
private final DeviceParamService deviceParamService;
public DeviceManageController(DeviceDisplayService deviceDisplayService, GatewayManageService gatewayManageService, DeviceManageService deviceManageService, DeviceParamService deviceParamService) {
this.deviceDisplayService = deviceDisplayService;
this.gatewayManageService = gatewayManageService;
this.deviceManageService = deviceManageService;
this.deviceParamService = deviceParamService;
}
@Resource
QuartzManager quartzManager;
@Autowired
private SocketMessage socketMessage;
// 查询设备信息状态
@GetMapping("/operation/getColdStation")
public HttpResult getColdStation(@RequestParam(value = "deviceType", required = true) String deviceType) {
List<DeviceMessageDTO> deviceMessageList = deviceDisplayService.queryDeviceStatus(deviceType);
Map<String, Object> formValues = new HashMap<>();
formValues.put("formValues",deviceMessageList);
return HttpResult.ok("success", formValues);
}
// 对设备进行操作处理
@PostMapping("/operation/operationDevice")
public HttpResult operationDevice(@RequestBody List<OrderEntity> changeValues) {
String result;
try {
List<OrderMessageEntity> orderMessageEntityList;
// type值 0:修改频率, 1:修改开关状态, 2: 关闭冷却泵之前,查询最近关闭的冷却塔时间,3: 群控手自动切换类型,4: 修改温度, 5: 修改压力
// // 添加网页发送指令状态 update by ljf on 2020-08-07
Constant.CONTROL_WEB_FLAG = true;
// 暂停采集
// quartzManager.pauseJob("DDC","JobDDCGroup");
// Thread.sleep(2000);
// 修改成不用暂停采集处理
GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// 判断是否是去关闭冷却泵,如果是,需要检查最近冷却塔有没有关闭并且关闭时间大于8分钟
// 判断changeValues大小
int size = changeValues.size();
int type = changeValues.get(0).getType();
if (type == 3 && size == 1) {
// 生成指令
orderMessageEntityList = getReadOrder485.createOrder(changeValues);
if (orderMessageEntityList.size() != 0) {
// 开启发送指令
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// 开启线程监测标志
QuerySendThread querySendThread = new QuerySendThread();
querySendThread.start();
if (Constant.SEND_STATUS) {
result = "success";
} else {
result = "fail";
}
} else {
result = "fail";
}
} else if (type == 2 && size == 1) {
TimeDifferenceUtil timeDifferenceUtil = new TimeDifferenceUtil();
Boolean a = timeDifferenceUtil.timeDifference(socketMessage.getOverTime());
if (a) {
// 生成指令
orderMessageEntityList = getReadOrder485.createOrder(changeValues);
if (orderMessageEntityList.size() != 0) {
// 开启发送指令
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// 开启线程监测标志
QuerySendThread querySendThread = new QuerySendThread();
querySendThread.start();
if (Constant.SEND_STATUS) {
result = "success";
} else {
result = "fail";
}
} else {
result = "fail";
}
} else {
result = "冷却塔关机还没有超过8分钟";
}
} else {
// 生成指令
orderMessageEntityList = getReadOrder485.createOrder(changeValues);
if (orderMessageEntityList.size() != 0) {
// 开启发送指令
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// 开启线程监测标志
QuerySendThread querySendThread = new QuerySendThread();
querySendThread.start();
if (Constant.SEND_STATUS) {
result = "success";
} else {
result = "fail";
}
} else {
result = "fail";
}
}
Constant.CONTROL_WEB_FLAG = false;
// 不需要停止采集
// Constant.WEB_FLAG = false;
// // 延迟5秒处理,等待线程处理数据
Thread.sleep(500);
// // 重新开启定时采集
// quartzManager.resumeAllJob();
// quartzManager.resumeJob("DDC","JobDDCGroup");
} catch (InterruptedException | ParseException e) {
e.printStackTrace();
result = "fail";
}
// 异常情况处理
return HttpResult.ok(result);
}
/**
* 查询网关信息
* @param requestJson
* @return
*/
@PostMapping("/gateWay/getGateWayList")
public HttpResult gateWayList(@RequestBody String requestJson){
JSONObject jsonObject =JSONObject.parseObject(requestJson);
Integer operator = null;
Integer grade = null;
if(jsonObject.get("operator") != null){
if(jsonObject.get("operator").equals("中国移动")){
operator = 0;
}else if(jsonObject.get("operator").equals("中国联通")){
operator = 1;
}else if(jsonObject.get("operator").equals("中国电信")){
operator = 2;
}
}
if(jsonObject.get("grade") != null){
if(jsonObject.get("grade").equals("正常")){
grade = 0;
}else if(jsonObject.get("grade").equals("不在线")){
grade = 1;
}else if(jsonObject.get("grade").equals("异常")){
grade = 2;
}
}
List<GatewayManageEntity> gateWayList = gatewayManageService.queryByOther(grade,operator);
JSONObject tableData = new JSONObject();
tableData.put("tableData",gateWayList);
return HttpResult.ok(tableData);
// System.out.println(requestJson);
// return null;
}
/**
* 新增或更新网关信息
* @param reqestJson
* @return
*/
@PostMapping("/gateWay/addOrUpdateGateWayInfo")
public HttpResult addOrUpdateGateWayInfo(@RequestBody GatewayManageEntity reqestJson){
try {
System.out.println(reqestJson.toString());
gatewayManageService.addOrUpdateGateWayInfo(reqestJson);
return HttpResult.ok();
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error(e.getMessage());
}
}
/**
* 删除网关/基表/基表参数信息
* @param requestJson
* @return
*/
@PostMapping("/device/deleteDeviceInfo")
public HttpResult deleteDeviceInfo(@RequestBody String requestJson){
JSONObject jsonObject =JSONObject.parseObject(requestJson);
System.out.println(jsonObject.get("deviceId"));
try {
deviceManageService.deleteDeviceInfo((Integer)jsonObject.get("deviceId"),jsonObject.get("deviceType").toString());
return HttpResult.ok();
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error(e.getMessage());
}
}
/**
* 查询基表管理中的基表数据
* @param requestJson
* @return
*/
@PostMapping("/baseMeter/getBaseMeterList")
public HttpResult getBaseMeterList(@RequestBody String requestJson){
JSONObject jsonObject =JSONObject.parseObject(requestJson);
List<DeviceManageEntity> list = deviceManageService.getDeviceByOther(jsonObject.get("deviceNum").toString());
JSONObject tableData = new JSONObject();
tableData.put("tableData",list);
return HttpResult.ok(tableData);
}
/**
* 增加或更新基表信息数据
* @param requestJson
* @return
*/
@PostMapping("/baseMeter/addOrUpdateBaseMeter")
public HttpResult addOrUpdateBaseMeter(@RequestBody DeviceManageEntity requestJson){
try {
deviceManageService.addOrUpdateBaseMeter(requestJson);
return HttpResult.ok();
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error("检查输入的设备码是否有误!");
}
}
/**
* 查询基表参数管理中的基表参数数据
* @param requestJson
* @return
*/
@PostMapping("/baseMeterParam/getBaseMeterParamList")
public HttpResult getBaseMeterParamList(@RequestBody String requestJson){
JSONObject jsonObject =JSONObject.parseObject(requestJson);
System.out.println(jsonObject.get("baseMeterType"));
String baseMeterType = (String) jsonObject.get("baseMeterType");
List<DeviceParameterEntity> list = deviceParamService.getBaseMeterParamList(baseMeterType);
JSONObject tableData = new JSONObject();
tableData.put("tableData",list);
return HttpResult.ok(tableData);
}
/**
* 添加或更新基表参数信息
* @param requestJson
* @return
*/
@PostMapping("/baseMeterParam/addOrUpdateBaseMeterParam")
public HttpResult addOrUpdateBaseMeterParam(@RequestBody DeviceParameterEntity requestJson){
try {
deviceParamService.addOrUpdateBaseMeterParam(requestJson);
return HttpResult.ok();
} catch (Exception e) {
e.printStackTrace();
return HttpResult.error(e.getMessage());
}
}
}
//package com.mh.user.controller;
//
//import com.alibaba.fastjson.JSONObject;
//import com.mh.common.http.HttpResult;
//import com.mh.user.dto.DeviceMessageDTO;
//import com.mh.user.entity.*;
//import com.mh.user.manage.QuartzManager;
//import com.mh.user.service.chillers.DeviceDisplayService;
//import com.mh.user.constants.Constant;
//import com.mh.user.service.chillers.DeviceManageService;
//import com.mh.user.service.chillers.DeviceParamService;
//import com.mh.user.service.chillers.GatewayManageService;
//import com.mh.user.utils.GetReadOrder485;
//import com.mh.user.utils.QuerySendThread;
//import com.mh.user.constants.SocketMessage;
//import com.mh.user.utils.TimeDifferenceUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import javax.annotation.Resource;
//import java.text.ParseException;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * @author ljf
// * @title :
// * @description : 设备管理接口
// * @updateTime 2020-05-29
// * @updateTime 2020-07-17
// * @throws :
// */
//@RestController
//public class DeviceManageController {
//
// private final DeviceDisplayService deviceDisplayService;
// private final GatewayManageService gatewayManageService;
// private final DeviceManageService deviceManageService;
// private final DeviceParamService deviceParamService;
//
// public DeviceManageController(DeviceDisplayService deviceDisplayService, GatewayManageService gatewayManageService, DeviceManageService deviceManageService, DeviceParamService deviceParamService) {
// this.deviceDisplayService = deviceDisplayService;
// this.gatewayManageService = gatewayManageService;
// this.deviceManageService = deviceManageService;
// this.deviceParamService = deviceParamService;
// }
//
// @Resource
// QuartzManager quartzManager;
//
// @Autowired
// private SocketMessage socketMessage;
//
// // 查询设备信息状态
// @GetMapping("/operation/getColdStation")
// public HttpResult getColdStation(@RequestParam(value = "deviceType", required = true) String deviceType) {
// List<DeviceMessageDTO> deviceMessageList = deviceDisplayService.queryDeviceStatus(deviceType);
// Map<String, Object> formValues = new HashMap<>();
// formValues.put("formValues",deviceMessageList);
// return HttpResult.ok("success", formValues);
// }
//
// // 对设备进行操作处理
// @PostMapping("/operation/operationDevice")
// public HttpResult operationDevice(@RequestBody List<OrderEntity> changeValues) {
// String result;
// try {
// List<OrderMessageEntity> orderMessageEntityList;
// // type值 0:修改频率, 1:修改开关状态, 2: 关闭冷却泵之前,查询最近关闭的冷却塔时间,3: 群控手自动切换类型,4: 修改温度, 5: 修改压力
//// // 添加网页发送指令状态 update by ljf on 2020-08-07
// Constant.CONTROL_WEB_FLAG = true;
// // 暂停采集
//// quartzManager.pauseJob("DDC","JobDDCGroup");
//// Thread.sleep(2000);
// // 修改成不用暂停采集处理
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// // 判断是否是去关闭冷却泵,如果是,需要检查最近冷却塔有没有关闭并且关闭时间大于8分钟
// // 判断changeValues大小
// int size = changeValues.size();
// int type = changeValues.get(0).getType();
// if (type == 3 && size == 1) {
// // 生成指令
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
// if (orderMessageEntityList.size() != 0) {
// // 开启发送指令
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// // 开启线程监测标志
// QuerySendThread querySendThread = new QuerySendThread();
// querySendThread.start();
// if (Constant.SEND_STATUS) {
// result = "success";
// } else {
// result = "fail";
// }
// } else {
// result = "fail";
// }
// } else if (type == 2 && size == 1) {
// TimeDifferenceUtil timeDifferenceUtil = new TimeDifferenceUtil();
// Boolean a = timeDifferenceUtil.timeDifference(socketMessage.getOverTime());
// if (a) {
// // 生成指令
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
// if (orderMessageEntityList.size() != 0) {
// // 开启发送指令
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// // 开启线程监测标志
// QuerySendThread querySendThread = new QuerySendThread();
// querySendThread.start();
// if (Constant.SEND_STATUS) {
// result = "success";
// } else {
// result = "fail";
// }
// } else {
// result = "fail";
// }
// } else {
// result = "冷却塔关机还没有超过8分钟";
// }
// } else {
// // 生成指令
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
// if (orderMessageEntityList.size() != 0) {
// // 开启发送指令
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
// // 开启线程监测标志
// QuerySendThread querySendThread = new QuerySendThread();
// querySendThread.start();
// if (Constant.SEND_STATUS) {
// result = "success";
// } else {
// result = "fail";
// }
// } else {
// result = "fail";
// }
// }
// Constant.CONTROL_WEB_FLAG = false;
// // 不需要停止采集
//// Constant.WEB_FLAG = false;
//// // 延迟5秒处理,等待线程处理数据
// Thread.sleep(500);
//// // 重新开启定时采集
//// quartzManager.resumeAllJob();
//// quartzManager.resumeJob("DDC","JobDDCGroup");
// } catch (InterruptedException | ParseException e) {
// e.printStackTrace();
// result = "fail";
// }
// // 异常情况处理
// return HttpResult.ok(result);
// }
//
// /**
// * 查询网关信息
// * @param requestJson
// * @return
// */
// @PostMapping("/gateWay/getGateWayList")
// public HttpResult gateWayList(@RequestBody String requestJson){
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
// Integer operator = null;
// Integer grade = null;
// if(jsonObject.get("operator") != null){
// if(jsonObject.get("operator").equals("中国移动")){
// operator = 0;
// }else if(jsonObject.get("operator").equals("中国联通")){
// operator = 1;
// }else if(jsonObject.get("operator").equals("中国电信")){
// operator = 2;
// }
// }
// if(jsonObject.get("grade") != null){
// if(jsonObject.get("grade").equals("正常")){
// grade = 0;
// }else if(jsonObject.get("grade").equals("不在线")){
// grade = 1;
// }else if(jsonObject.get("grade").equals("异常")){
// grade = 2;
// }
// }
// List<GatewayManageEntity> gateWayList = gatewayManageService.queryByOther(grade,operator);
// JSONObject tableData = new JSONObject();
// tableData.put("tableData",gateWayList);
// return HttpResult.ok(tableData);
//// System.out.println(requestJson);
//// return null;
// }
//
// /**
// * 新增或更新网关信息
// * @param reqestJson
// * @return
// */
// @PostMapping("/gateWay/addOrUpdateGateWayInfo")
// public HttpResult addOrUpdateGateWayInfo(@RequestBody GatewayManageEntity reqestJson){
// try {
// System.out.println(reqestJson.toString());
// gatewayManageService.addOrUpdateGateWayInfo(reqestJson);
// return HttpResult.ok();
// } catch (Exception e) {
// e.printStackTrace();
// return HttpResult.error(e.getMessage());
// }
// }
//
// /**
// * 删除网关/基表/基表参数信息
// * @param requestJson
// * @return
// */
// @PostMapping("/device/deleteDeviceInfo")
// public HttpResult deleteDeviceInfo(@RequestBody String requestJson){
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
// System.out.println(jsonObject.get("deviceId"));
// try {
// deviceManageService.deleteDeviceInfo((Integer)jsonObject.get("deviceId"),jsonObject.get("deviceType").toString());
// return HttpResult.ok();
// } catch (Exception e) {
// e.printStackTrace();
// return HttpResult.error(e.getMessage());
// }
// }
//
// /**
// * 查询基表管理中的基表数据
// * @param requestJson
// * @return
// */
// @PostMapping("/baseMeter/getBaseMeterList")
// public HttpResult getBaseMeterList(@RequestBody String requestJson){
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
// List<DeviceManageEntity> list = deviceManageService.getDeviceByOther(jsonObject.get("deviceNum").toString());
// JSONObject tableData = new JSONObject();
// tableData.put("tableData",list);
// return HttpResult.ok(tableData);
// }
//
// /**
// * 增加或更新基表信息数据
// * @param requestJson
// * @return
// */
// @PostMapping("/baseMeter/addOrUpdateBaseMeter")
// public HttpResult addOrUpdateBaseMeter(@RequestBody DeviceManageEntity requestJson){
// try {
// deviceManageService.addOrUpdateBaseMeter(requestJson);
// return HttpResult.ok();
// } catch (Exception e) {
// e.printStackTrace();
// return HttpResult.error("检查输入的设备码是否有误!");
// }
// }
//
// /**
// * 查询基表参数管理中的基表参数数据
// * @param requestJson
// * @return
// */
// @PostMapping("/baseMeterParam/getBaseMeterParamList")
// public HttpResult getBaseMeterParamList(@RequestBody String requestJson){
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
// System.out.println(jsonObject.get("baseMeterType"));
// String baseMeterType = (String) jsonObject.get("baseMeterType");
// List<DeviceParameterEntity> list = deviceParamService.getBaseMeterParamList(baseMeterType);
// JSONObject tableData = new JSONObject();
// tableData.put("tableData",list);
// return HttpResult.ok(tableData);
// }
//
// /**
// * 添加或更新基表参数信息
// * @param requestJson
// * @return
// */
// @PostMapping("/baseMeterParam/addOrUpdateBaseMeterParam")
// public HttpResult addOrUpdateBaseMeterParam(@RequestBody DeviceParameterEntity requestJson){
// try {
// deviceParamService.addOrUpdateBaseMeterParam(requestJson);
// return HttpResult.ok();
// } catch (Exception e) {
// e.printStackTrace();
// return HttpResult.error(e.getMessage());
// }
// }
//
//
//}

5
user-service/src/main/java/com/mh/user/controller/SysLoginController.java

@ -12,15 +12,10 @@ import javax.servlet.http.HttpServletResponse;
import com.mh.common.http.HttpResult;
import com.mh.common.utils.IOUtils;
import com.mh.user.annotation.SysLogger;
import com.mh.user.dynamic.datasource.DataSourceContextHolder;
import com.mh.user.dynamic.datasource.DataSourceObject;
import com.mh.user.entity.DBEntity;
import com.mh.user.model.SysRole;
import com.mh.user.model.SysUser;
import com.mh.user.security.JwtAuthenticatioToken;
import com.mh.user.service.SysRoleService;
import com.mh.user.service.SysUserService;
import com.mh.user.utils.AESUtil;
import com.mh.user.utils.PasswordUtils;
import com.mh.user.utils.SecurityUtils;
import com.mh.user.vo.LoginBean;

9
user-service/src/main/java/com/mh/user/controller/TestController.java

@ -1,27 +1,18 @@
package com.mh.user.controller;
import com.mh.user.constants.Constant;
import com.mh.user.dynamic.datasource.DataSourceContextHolder;
import com.mh.user.dynamic.datasource.DataSourceObject;
import com.mh.user.entity.DBEntity;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.manage.QuartzManager;
import com.mh.user.service.SysUserService;
import com.mh.user.utils.AESUtil;
import com.mh.user.utils.AnalysisReceiveOrder485;
import com.mh.user.utils.ExchangeStringUtil;
import com.mh.user.utils.GetReadOrder485;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
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 javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
public class TestController {

154
user-service/src/main/java/com/mh/user/dynamic/config/DataSourceConfig.java

@ -1,77 +1,77 @@
package com.mh.user.dynamic.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.mh.user.dynamic.datasource.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @author chison
* @date 2020-04-02 09:39
* @Description
*/
@Configuration
@MapperScan("com.mh.*.mapper") // 扫描DAO
public class DataSourceConfig {
@Value("${spring.datasource.druid.url}")
private String defaultDBUrl;
@Value("${spring.datasource.druid.username}")
private String defaultDBUser;
@Value("${spring.datasource.druid.password}")
private String defaultDBPassword;
@Value("${spring.datasource.druid.driver-class-name}")
private String defaultDBDreiverName;
@Bean
public DynamicDataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
DruidDataSource defaultDataSource = new DruidDataSource();
defaultDataSource.setUrl(defaultDBUrl);
defaultDataSource.setUsername(defaultDBUser);
defaultDataSource.setPassword(defaultDBPassword);
defaultDataSource.setDriverClassName(defaultDBDreiverName);
Map<Object,Object> map = new HashMap<>();
map.put("default", defaultDataSource);
dynamicDataSource.setTargetDataSources(map);
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
return dynamicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(
@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setTypeAliasesPackage("com.mh.*.model"); // 扫描Model
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:**/sqlmapper/*.xml"));
return bean.getObject();
}
@Bean(name = "sqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(
@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)
throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
//package com.mh.user.dynamic.config;
//
//import com.alibaba.druid.pool.DruidDataSource;
//import com.mh.user.dynamic.datasource.DynamicDataSource;
//import org.apache.ibatis.session.SqlSessionFactory;
//import org.mybatis.spring.SqlSessionFactoryBean;
//import org.mybatis.spring.SqlSessionTemplate;
//import org.mybatis.spring.annotation.MapperScan;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
//
//import javax.sql.DataSource;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author chison
// * @date 2020-04-02 09:39
// * @Description
// */
//@Configuration
//@MapperScan("com.mh.*.mapper") // 扫描DAO
//public class DataSourceConfig {
//
// @Value("${spring.datasource.druid.url}")
// private String defaultDBUrl;
// @Value("${spring.datasource.druid.username}")
// private String defaultDBUser;
// @Value("${spring.datasource.druid.password}")
// private String defaultDBPassword;
// @Value("${spring.datasource.druid.driver-class-name}")
// private String defaultDBDreiverName;
//
//
// @Bean
// public DynamicDataSource dynamicDataSource() {
// DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
//
// DruidDataSource defaultDataSource = new DruidDataSource();
// defaultDataSource.setUrl(defaultDBUrl);
// defaultDataSource.setUsername(defaultDBUser);
// defaultDataSource.setPassword(defaultDBPassword);
// defaultDataSource.setDriverClassName(defaultDBDreiverName);
//
// Map<Object,Object> map = new HashMap<>();
// map.put("default", defaultDataSource);
// dynamicDataSource.setTargetDataSources(map);
// dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
//
// return dynamicDataSource;
// }
//
// @Bean
// public SqlSessionFactory sqlSessionFactory(
// @Qualifier("dynamicDataSource") DataSource dynamicDataSource)
// throws Exception {
// SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
// bean.setDataSource(dynamicDataSource);
// bean.setTypeAliasesPackage("com.mh.*.model"); // 扫描Model
//
// bean.setMapperLocations(new PathMatchingResourcePatternResolver()
// .getResources("classpath*:**/sqlmapper/*.xml"));
// return bean.getObject();
//
// }
//
// @Bean(name = "sqlSessionTemplate")
// public SqlSessionTemplate sqlSessionTemplate(
// @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)
// throws Exception {
// return new SqlSessionTemplate(sqlSessionFactory);
// }
//
//}

56
user-service/src/main/java/com/mh/user/dynamic/config/MyBatisMapperScannerConfig.java

@ -1,28 +1,28 @@
package com.mh.user.dynamic.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
/**
* @author chison
* @date 2020-04-02 09:40
* @Description
*/
@EnableAutoConfiguration
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.mh.user.mapper");
Properties properties = new Properties();
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
//package com.mh.user.dynamic.config;
//
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.context.annotation.Bean;
//import tk.mybatis.spring.mapper.MapperScannerConfigurer;
//
//import java.util.Properties;
//
///**
// * @author chison
// * @date 2020-04-02 09:40
// * @Description
// */
//@EnableAutoConfiguration
//public class MyBatisMapperScannerConfig {
// @Bean
// public MapperScannerConfigurer mapperScannerConfigurer() {
// MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
// mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
// mapperScannerConfigurer.setBasePackage("com.mh.user.mapper");
// Properties properties = new Properties();
// properties.setProperty("notEmpty", "false");
// properties.setProperty("IDENTITY", "MYSQL");
// mapperScannerConfigurer.setProperties(properties);
// return mapperScannerConfigurer;
// }
//
//}

142
user-service/src/main/java/com/mh/user/dynamic/datasource/DataSourceObject.java

@ -1,71 +1,71 @@
package com.mh.user.dynamic.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.mh.user.entity.DBEntity;
import java.util.HashMap;
import java.util.Map;
/**
* @author chison
* @date 2020-04-02 09:40
* @Description
*/
public class DataSourceObject {
private Long MaxWait=6000L;
private Integer maxActive=10;
private Long timeBetweenEvictionRunsMillis=6000L;
/**
* 切换sqlserver数据库并动态赋值
* @param dbInfo
* @param SourceName
*/
public void SwitchMySQLDataSource(DBEntity dbInfo, String SourceName) {
System.out.println("mysql进入数据源切换");
System.out.println("MaxWait:"+MaxWait);
DruidDataSource dynamicDataSource = new DruidDataSource();
dynamicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dynamicDataSource.setUrl("jdbc:mysql://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+"/"+dbInfo.getDB_Names()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&autoReconnect=true");
dynamicDataSource.setUsername(dbInfo.getDB_UserName());
dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
dynamicDataSource.setMaxWait(MaxWait);
dynamicDataSource.setMaxActive(maxActive);
dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
DynamicDataSource dataSource = DynamicDataSource.getInstance();
Map<Object, Object> map=new HashMap<Object, Object>();
map.put(SourceName, dynamicDataSource);
dataSource.setTargetDataSources(map);
System.out.println(dynamicDataSource.getUrl());
System.out.println(SourceName);
}
/**
* 第二个sqlserver数据库
* @param dbInfo
* @param SourceName
*/
public void SwitchSQLServerDataSource(DBEntity dbInfo,String SourceName) {
System.out.println("进入数据源切换");
System.out.println("MaxWait:"+MaxWait);
DruidDataSource dynamicDataSource = new DruidDataSource();
dynamicDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dynamicDataSource.setUrl("jdbc:sqlserver://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+";Databasename="+dbInfo.getDB_Names());
dynamicDataSource.setUsername(dbInfo.getDB_UserName());
dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
System.out.println(dbInfo.getDB_UserName());
System.out.println(dbInfo.getDB_Pwd());
dynamicDataSource.setMaxWait(MaxWait);
dynamicDataSource.setMaxActive(maxActive);
dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
DynamicDataSource dataSource = DynamicDataSource.getInstance();
Map<Object, Object> map=new HashMap<Object, Object>();
map.put(SourceName, dynamicDataSource);
dataSource.setTargetDataSources(map);
System.out.println(dynamicDataSource.getUrl());
System.out.println(SourceName);
}
}
//package com.mh.user.dynamic.datasource;
//
//import com.alibaba.druid.pool.DruidDataSource;
//import com.mh.user.entity.DBEntity;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author chison
// * @date 2020-04-02 09:40
// * @Description
// */
//public class DataSourceObject {
//
// private Long MaxWait=6000L;
// private Integer maxActive=10;
// private Long timeBetweenEvictionRunsMillis=6000L;
//
// /**
// * 切换sqlserver数据库,并动态赋值
// * @param dbInfo
// * @param SourceName
// */
// public void SwitchMySQLDataSource(DBEntity dbInfo, String SourceName) {
// System.out.println("mysql进入数据源切换");
// System.out.println("MaxWait:"+MaxWait);
// DruidDataSource dynamicDataSource = new DruidDataSource();
// dynamicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
// dynamicDataSource.setUrl("jdbc:mysql://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+"/"+dbInfo.getDB_Names()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&autoReconnect=true");
// dynamicDataSource.setUsername(dbInfo.getDB_UserName());
// dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
// dynamicDataSource.setMaxWait(MaxWait);
// dynamicDataSource.setMaxActive(maxActive);
// dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
//
// DynamicDataSource dataSource = DynamicDataSource.getInstance();
// Map<Object, Object> map=new HashMap<Object, Object>();
// map.put(SourceName, dynamicDataSource);
// dataSource.setTargetDataSources(map);
// System.out.println(dynamicDataSource.getUrl());
// System.out.println(SourceName);
// }
// /**
// * 第二个sqlserver数据库
// * @param dbInfo
// * @param SourceName
// */
// public void SwitchSQLServerDataSource(DBEntity dbInfo,String SourceName) {
// System.out.println("进入数据源切换");
// System.out.println("MaxWait:"+MaxWait);
// DruidDataSource dynamicDataSource = new DruidDataSource();
// dynamicDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// dynamicDataSource.setUrl("jdbc:sqlserver://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+";Databasename="+dbInfo.getDB_Names());
// dynamicDataSource.setUsername(dbInfo.getDB_UserName());
// dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
// System.out.println(dbInfo.getDB_UserName());
// System.out.println(dbInfo.getDB_Pwd());
// dynamicDataSource.setMaxWait(MaxWait);
// dynamicDataSource.setMaxActive(maxActive);
// dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
//
// DynamicDataSource dataSource = DynamicDataSource.getInstance();
// Map<Object, Object> map=new HashMap<Object, Object>();
// map.put(SourceName, dynamicDataSource);
// dataSource.setTargetDataSources(map);
//
// System.out.println(dynamicDataSource.getUrl());
// System.out.println(SourceName);
// }
//}

34
user-service/src/main/java/com/mh/user/entity/BaseResultEntity.java

@ -0,0 +1,34 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 数据结果集基本类
* @date 2024-07-10 16:49:24
*/
@Data
public class BaseResultEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String deviceAddr;
private String deviceType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date curDate;
private String curValue;
private String funCode;
private String registerAddr;
private String registerName;
private int grade;
private String projectId;
private String projectName;
}

23
user-service/src/main/java/com/mh/user/entity/DataResultChEntity.java

@ -1,24 +1,7 @@
package com.mh.user.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
@Data
public class DataResultChEntity {
private Long id;
private String deviceAddr;
private String deviceType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date curDate;
// private String curDate;
private String curValue;
private String funCode;
private String registerAddr;
private String registerName;
private int grade;
private String projectID;
private String projectName;
@TableName("data_result_ch")
public class DataResultChEntity extends BaseResultEntity {
}

7
user-service/src/main/java/com/mh/user/entity/DataResultChillerEntity.java

@ -0,0 +1,7 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("data_result_ch")
public class DataResultChillerEntity extends BaseResultEntity {
}

32
user-service/src/main/java/com/mh/user/entity/DataResultClBakEntity.java

@ -0,0 +1,32 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName("data_result_cl")
public class DataResultClBakEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String deviceAddr;
private String deviceType;
private Date curDate;
private BigDecimal curValue;
private BigDecimal lastValue;
private Date lastDate;
private BigDecimal ratio;
private BigDecimal calcValue;
private int grade;
private String havedUpdate;
private String registerAddr;
private String registerName;
private String projectName;
private String projectId;
}

21
user-service/src/main/java/com/mh/user/entity/DataResultClEntity.java

@ -1,23 +1,32 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName("data_result_cl")
public class DataResultClEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String deviceAddr;
private String deviceType;
private double lastValue;
private Date lastDate;
private double curValue;
private Date curDate;
private double ratio;
private double calcValue;
private BigDecimal curValue;
private BigDecimal lastValue;
private Date lastDate;
private BigDecimal ratio;
private BigDecimal calcValue;
private int grade;
private String havedUpdate;
private String registerAddr;
private String registerName;
private String projectName;
private String projectID;
private String projectId;
}

18
user-service/src/main/java/com/mh/user/entity/DataResultEntity.java

@ -1,22 +1,32 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@TableName("data_result")
@Data
public class DataResultEntity {
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String deviceAddr;
private String deviceType;
private double lastValue;
private BigDecimal lastValue;
private Date lastDate;
private double curValue;
private BigDecimal curValue;
private Date curDate;
private double ratio;
private double calcValue;
private BigDecimal ratio;
private BigDecimal calcValue;
private int grade;
private String havedUpdate;
private String projectName;
private String projectID;
}

7
user-service/src/main/java/com/mh/user/entity/DataResultFifteenMiEntity.java

@ -0,0 +1,7 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("data_result_fifteen_mi")
public class DataResultFifteenMiEntity extends BaseResultEntity {
}

7
user-service/src/main/java/com/mh/user/entity/DataResultFiveMiEntity.java

@ -0,0 +1,7 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("data_result_five_mi")
public class DataResultFiveMiEntity extends BaseResultEntity {
}

7
user-service/src/main/java/com/mh/user/entity/DataResultNowEntity.java

@ -0,0 +1,7 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("data_result_now")
public class DataResultNowEntity extends BaseResultEntity {
}

7
user-service/src/main/java/com/mh/user/entity/DataResultOneMiEntity.java

@ -0,0 +1,7 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("data_result_one_mi")
public class DataResultOneMiEntity extends BaseResultEntity {
}

130
user-service/src/main/java/com/mh/user/entity/DeviceCodeEntity.java

@ -0,0 +1,130 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 设备基表安装信息
* @date 2024-07-11 13:57:36
*/
@Data
@TableName("device_code")
public class DeviceCodeEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 通讯编号
*/
private String deviceAddr;
/**
* 设备类型
*/
private String deviceType;
/**
* 串口
*/
private String dataCom;
/**
* 端口
*/
private String dataPort;
/**
* 设备规格
*/
private String standard;
/**
* 安装位置
*/
private String installPosition;
/**
* 初始值
*/
private BigDecimal initValue;
/**
* 倍率
*/
private BigDecimal ratio;
/**
* 是否时总表
*/
private String isTotal;
/**
* 是否停用
*/
private String isForbid;
/**
* 停用时间
*/
private Date forbidDate;
/**
* 上次抄表读数
*/
private BigDecimal lastValue;
/**
* 上次抄表时间
*/
private Date lastDate;
/**
* 级别
*/
private int grade;
/**
* 波特率
*/
private int baudRate;
/**
* 项目ID
*/
private String projectId;
/**
* 设备名称
*/
private String deviceName;
/**
* 品牌
*/
private String brand;
/**
* 安装时间
*/
private Date installDate;
/**
* 奇偶校验
*/
private String parity;
/**
* 备注
*/
private String remarks;
}

144
user-service/src/main/java/com/mh/user/entity/DeviceCodeParamEntity.java

@ -1,7 +1,16 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
@Setter
@Getter
@ToString
@TableName("device_code_param")
public class DeviceCodeParamEntity {
private Long id;
@ -22,139 +31,4 @@ public class DeviceCodeParamEntity {
private Date createTime;
private String projectID;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDeviceAddr() {
return deviceAddr;
}
public void setDeviceAddr(String deviceAddr) {
this.deviceAddr = deviceAddr;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getStrData() {
return strData;
}
public void setStrData(String strData) {
this.strData = strData;
}
public String getDataPort() {
return dataPort;
}
public void setDataPort(String dataPort) {
this.dataPort = dataPort;
}
public int getBaudRate() {
return baudRate;
}
public void setBaudRate(int baudRate) {
this.baudRate = baudRate;
}
public String getParity() {
return parity;
}
public void setParity(String parity) {
this.parity = parity;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getFunCode() {
return funCode;
}
public void setFunCode(String funCode) {
this.funCode = funCode;
}
public String getRegisterAddr() {
return registerAddr;
}
public void setRegisterAddr(String registerAddr) {
this.registerAddr = registerAddr;
}
public String getRegisterName() {
return registerName;
}
public void setRegisterName(String registerName) {
this.registerName = registerName;
}
public int getDigit() {
return digit;
}
public void setDigit(int digit) {
this.digit = digit;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getDataValue() {
return dataValue;
}
public void setDataValue(String dataValue) {
this.dataValue = dataValue;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getProjectID() {
return projectID;
}
public void setProjectID(String projectID) {
this.projectID = projectID;
}
}

6
user-service/src/main/java/com/mh/user/entity/DeviceInfoEntity.java

@ -12,9 +12,9 @@ public class DeviceInfoEntity {
private String power; //功率
private String madeTime; //制造时间
private String flow; //流量
private String isFC; //是否变频
private String isFc; //是否变频
private String motorBrand; //机电品牌
private String projectID; //项目ID
private String systemID; //系统ID
private String projectId; //项目ID
private String systemId; //系统ID
}

13
user-service/src/main/java/com/mh/user/entity/DeviceInstallEntity.java

@ -1,6 +1,8 @@
package com.mh.user.entity;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@ -14,9 +16,9 @@ public class DeviceInstallEntity {
private String dataPort;
private int baudRate;
private String parity;
private double ratio;
private double initValue;
private double lastValue;
private BigDecimal ratio;
private BigDecimal initValue;
private BigDecimal lastValue;
private Date lastDate;
private String standard;
private String isTotal;
@ -27,5 +29,8 @@ public class DeviceInstallEntity {
private Date installDate;
private String projectID;
private String remarks;
private String registerAddr;
private String registerName;
private String funCode;
private int digit;
}

99
user-service/src/main/java/com/mh/user/entity/EnergyDataEntity.java

@ -2,7 +2,6 @@ package com.mh.user.entity;
import lombok.Data;
@Data
public class EnergyDataEntity {
private long id;
@ -13,6 +12,102 @@ public class EnergyDataEntity {
private Double elect;
private Double cl;
private Double cop;
private String projectID;
private String projectId;
private String projectName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCurDate() {
return curDate;
}
public void setCurDate(String curDate) {
this.curDate = curDate;
}
public String getAmbTemp() {
return ambTemp;
}
public void setAmbTemp(String ambTemp) {
this.ambTemp = ambTemp;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public Double getWater() {
return water;
}
public void setWater(Double water) {
this.water = water;
}
public Double getElect() {
return elect;
}
public void setElect(Double elect) {
this.elect = elect;
}
public Double getCl() {
return cl;
}
public void setCl(Double cl) {
this.cl = cl;
}
public Double getCop() {
return cop;
}
public void setCop(Double cop) {
this.cop = cop;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
@Override
public String toString() {
return "EnergyDataEntity{" +
"id=" + id +
", curDate='" + curDate + '\'' +
", ambTemp='" + ambTemp + '\'' +
", humidity='" + humidity + '\'' +
", water=" + water +
", elect=" + elect +
", cl=" + cl +
", cop=" + cop +
", projectId='" + projectId + '\'' +
", projectName='" + projectName + '\'' +
'}';
}
}

7
user-service/src/main/java/com/mh/user/entity/GatewayManageEntity.java

@ -3,6 +3,7 @@ package com.mh.user.entity;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@ -14,12 +15,14 @@ import java.util.Date;
* @updateTime 2020-05-21
* @throws
*/
@Data
@Setter
@Getter
@ToString
public class GatewayManageEntity extends BaseEntity {
private String gatewayName; // 网关名称
private String gatewayIP; // 网关IP地址
private String gatewayIp; // 网关IP地址
private String gatewayAddress; // 网关安装地址
private String dataCom; // 串口号
private String createDate; // 安装时间

11
user-service/src/main/java/com/mh/user/entity/MeterInfoEntity.java

@ -1,10 +1,16 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("meter_info")
@Data
public class MeterInfoEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String meterName; //表名称
private String meterType; //表类型
@ -16,6 +22,7 @@ public class MeterInfoEntity {
private String caliber; //口径
private String range; //测量范围
private String structural; //结构形式
private String projectID; //项目ID
private String systemID; //系统ID
private String projectId; //项目ID
private String systemId; //系统ID
}

4
user-service/src/main/java/com/mh/user/entity/ProjectInfoEntity.java

@ -1,11 +1,13 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("project_info")
@Data
public class ProjectInfoEntity {
private String id;
private Long id;
private String projectName; //项目名称
private String pAddress; //地址
private int pScale;

2
user-service/src/main/java/com/mh/user/entity/RegisterAddrEntity.java

@ -1,7 +1,9 @@
package com.mh.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("register_addr")
@Data
public class RegisterAddrEntity {

71
user-service/src/main/java/com/mh/user/entity/StrategyInfoEntity.java

@ -1,14 +1,77 @@
package com.mh.user.entity;
import lombok.Data;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@Data
@TableName("strategy_info")
public class StrategyInfoEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String dataAnalysis;
private String operationOpt;
private String controlOpt;
private String projectID;
private String systemID;
private String projectId;
private String systemId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDataAnalysis() {
return dataAnalysis;
}
public void setDataAnalysis(String dataAnalysis) {
this.dataAnalysis = dataAnalysis;
}
public String getOperationOpt() {
return operationOpt;
}
public void setOperationOpt(String operationOpt) {
this.operationOpt = operationOpt;
}
public String getControlOpt() {
return controlOpt;
}
public void setControlOpt(String controlOpt) {
this.controlOpt = controlOpt;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
@Override
public String toString() {
return "StrategyInfoEntity{" +
"id=" + id +
", dataAnalysis='" + dataAnalysis + '\'' +
", operationOpt='" + operationOpt + '\'' +
", controlOpt='" + controlOpt + '\'' +
", projectId='" + projectId + '\'' +
", systemId='" + systemId + '\'' +
'}';
}
}

2
user-service/src/main/java/com/mh/user/entity/chart/ChartEntity.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

2
user-service/src/main/java/com/mh/user/entity/chart/Feature.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

2
user-service/src/main/java/com/mh/user/entity/chart/Legend.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

2
user-service/src/main/java/com/mh/user/entity/chart/Series.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

2
user-service/src/main/java/com/mh/user/entity/chart/Title.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

2
user-service/src/main/java/com/mh/user/entity/chart/YAxis.java

@ -1,6 +1,6 @@
package com.mh.user.entity.chart;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Getter;
import lombok.Setter;

226
user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java

@ -1,26 +1,16 @@
package com.mh.user.job;
import com.mh.user.entity.AddCronJobReq;
import com.mh.user.entity.ProjectInfoEntity;
import com.mh.user.manage.QuartzManager;
import com.mh.user.netty.EchoServer;
import com.mh.user.serialport.SerialPortListener;
import com.mh.user.serialport.SerialPortUtil;
import com.mh.user.service.ProjectInfoService;
import com.mh.user.utils.GetReadOrder485;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ljf
@ -29,11 +19,10 @@ import java.util.Map;
* @updateTime 2020-05-15
* @throws
*/
@Slf4j
@Component
public class CollectionLoopRunner implements ApplicationRunner {
private static final Logger log = Logger.getLogger(CollectionLoopRunner.class);
public static SerialPort serialPort = null;
@Autowired
@ -45,7 +34,7 @@ public class CollectionLoopRunner implements ApplicationRunner {
List<ProjectInfoEntity> projectInfoEntities = projectInfoService.queryProjectInfo("1");
if (null != projectInfoEntities && !projectInfoEntities.isEmpty()) {
for (ProjectInfoEntity projectInfoEntity : projectInfoEntities) {
getReadOrder485.createOrderParam(projectInfoEntity.getId()); //生成采集参数,1新珠江(6000),2广合科技(6001),3广大科技(6002),6珠江国际,7保利山庄,8东莞迎宾馆
getReadOrder485.createOrderParam(String.valueOf(projectInfoEntity.getId())); //生成采集参数,1新珠江(6000),2广合科技(6001),3广大科技(6002),6珠江国际,7保利山庄,8东莞迎宾馆
}
}
try{
@ -55,215 +44,4 @@ public class CollectionLoopRunner implements ApplicationRunner {
}
}
// public void test() throws Exception {
// System.out.println("测试定时采集开关");
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "2");
// params.put("name", "test1");
// //每 1 分钟 执行一次
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// addCronJobReq.setDate("0/10 * * * * ?");
//// addCronJobReq.setDate("0/5 * * * * ?");
// addCronJobReq.setJobClass("JobTest1");
// addCronJobReq.setJobGroupName("JobTestGroup1");
// addCronJobReq.setJobName("Test1");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerTestGroup1");
// addCronJobReq.setTriggerName("triggerTest1");
// quartzManager.addCronJob(addCronJobReq);
// }
//
// /**
// * 定时采集电表和冷量计
// *
// * @throws Exception
// */
// public void collectionMeterAndCloud() throws Exception {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "6");
// params.put("name", "cloud_meter");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每 15 分钟 执行一次
// addCronJobReq.setDate("0 0/15 * * * ?");
// //每 3 分钟 执行一次
//// addCronJobReq.setDate("35 0/2 * * * ?");
// //每 2 分钟 执行一次
//// addCronJobReq.setDate("25 0/2 * * * ?");
// //每 1 分钟 执行一次
//// addCronJobReq.setDate("0/10 * * * * ?");
//// addCronJobReq.setDate("0/5 * * * * ?");
// addCronJobReq.setJobClass("JobCloudAndMeter");
// addCronJobReq.setJobGroupName("JobCloudAndMeterGroup");
// addCronJobReq.setJobName("CloudAndMeter");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerCloudAndMeterGroup");
// addCronJobReq.setTriggerName("triggerCloudAndMeter");
// quartzManager.addCronJob(addCronJobReq);
// }
//
// /**
// * 定时采集冷量计
// *
// * @throws Exception
// */
// public void collectionCloud() throws Exception {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "1");
// params.put("name", "cloud");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每 2 分钟 执行一次
// addCronJobReq.setDate("25 0/2 * * * ?");
//// addCronJobReq.setDate("0/5 * * * * ?");
// addCronJobReq.setJobClass("JobCloud");
// addCronJobReq.setJobGroupName("JobCloudGroup");
// addCronJobReq.setJobName("Cloud");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerCloudGroup");
// addCronJobReq.setTriggerName("triggerCloud");
// quartzManager.addCronJob(addCronJobReq);
// }
// /**
// * 定时采集电表
// *
// * @throws Exception
// */
// public void collectionMeter() throws Exception {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "2");
// params.put("name", "meter");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每 3 分钟 执行一次
// addCronJobReq.setDate("35 0/2 * * * ?");
//// addCronJobReq.setDate("0/20 * * * * ?");
// addCronJobReq.setJobClass("JobMeter");
// addCronJobReq.setJobGroupName("JobMeterGroup");
// addCronJobReq.setJobName("Meter");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerMeterGroup");
// addCronJobReq.setTriggerName("triggerMeter");
// quartzManager.addCronJob(addCronJobReq);
// }
//
// /**
// * 定时采集DDC设备
// *
// * @throws Exception
// */
// public void collectionDDC() throws Exception {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "3");
// params.put("name", "ddc");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每 1分钟 执行一次
//// addCronJobReq.setDate("3,33 * * * * ?");
// addCronJobReq.setDate("45 0/1 * * * ?");
// addCronJobReq.setJobClass("JobDDC");
// addCronJobReq.setJobGroupName("JobDDCGroup");
// addCronJobReq.setJobName("DDC");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerDDCGroup");
// addCronJobReq.setTriggerName("triggerDDC");
// quartzManager.addCronJob(addCronJobReq);
// }
//
// /**
// * 定时采集冷水机组设备
// *
// * @throws Exception
// */
// public void collectionChillers() throws Exception {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "4");
// params.put("name", "chillers");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每3分钟 执行一次
// addCronJobReq.setDate("55 0/2 * * * ? ");
//// addCronJobReq.setDate("0/30 * * * * ?");
// addCronJobReq.setJobClass("JobChillers");
// addCronJobReq.setJobGroupName("JobChillersGroup");
// addCronJobReq.setJobName("Chillers");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerChillersGroup");
// addCronJobReq.setTriggerName("triggerChillers");
// quartzManager.addCronJob(addCronJobReq);
// }
//
// /**
// * 4分钟,采集第二个冷水机组数据
// */
// public void collectionChillers1() {
// // 执行定义的定时采集程序
// Map<String, String> params = new HashMap<>();
// params.put("id", "5");
// params.put("name", "chillers1");
// AddCronJobReq addCronJobReq = new AddCronJobReq();
// //每 4分钟 执行一次
// addCronJobReq.setDate("0 0/5 * * * ? ");
//// addCronJobReq.setDate("0/30 * * * * ?");
// addCronJobReq.setJobClass("JobChillers1");
// addCronJobReq.setJobGroupName("JobChillersGroup1");
// addCronJobReq.setJobName("Chillers1");
// addCronJobReq.setParams(params);
// addCronJobReq.setTriggerGroupName("triggerChillersGroup1");
// addCronJobReq.setTriggerName("triggerChillers1");
// try {
// quartzManager.addCronJob(addCronJobReq);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// public void testSerialPort(){
//
// String portname = "COM7";
// //TestA();
// //查看所有串口
// SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
// ArrayList<String> port = serialPortUtil.findPort();
// System.out.println("发现全部串口:" + port);
//
// System.out.println("打开指定portname:" + portname);
// //打开该对应portname名字的串口
// CollectionLoopRunner.serialPort = serialPortUtil.openPort(portname, 2400, SerialPort.DATABITS_8, SerialPort.PARITY_EVEN, SerialPort.PARITY_ODD);
//
// byte[] HEX = SerialPortListener.hexStr2Byte("FEFEFE6810398710810000000103901F007C16");
// serialPortUtil.sendToPort(CollectionLoopRunner.serialPort, HEX);
//
// //给对应的serialPort添加监听器
// serialPortUtil.addListener(CollectionLoopRunner.serialPort, new SerialPortListener());
//
// }
//
// public void plcAnalytic() {
// String portName = "COM1";
// //查看所有串口
// SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
// //打开该对应portName名字的串口
// if (CollectionLoopRunner.serialPort == null) {
// CollectionLoopRunner.serialPort = serialPortUtil.openPort(portName, 19200, SerialPort.DATABITS_8, SerialPort.PARITY_NONE, SerialPort.PARITY_ODD);
// byte[] hex = SerialPortListener.hexStr2Byte("A55A230000000022".replaceAll("\\s*", ""));
// serialPortUtil.sendToPort(CollectionLoopRunner.serialPort, hex);
//
// //给对应的serialPort添加监听器-->设置串口的Listener
// SerialPortUtil.setListenerToSerialPort(CollectionLoopRunner.serialPort, serialPortEvent -> {
// if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
// byte[] bytes = serialPortUtil.readFromPort(CollectionLoopRunner.serialPort);
//
// String needData = SerialPortListener.printHexString(bytes);
//
// //数据校验 校验数据长度、起始5A A5、数据sum位
//// if (PlcUtil.makeChecksum(needData)) {
//// //数据解析方法 此处编写你的解析方法,根据获取到的数据编写适合自己的方法
//// }
// }
// });
// }
// }
}

5
user-service/src/main/java/com/mh/user/job/DealDataJob.java

@ -3,7 +3,7 @@ package com.mh.user.job;
import com.mh.user.service.chillers.DealDataService;
import com.mh.user.utils.ExchangeStringUtil;
import com.mh.user.utils.SimpleWeather;
import org.apache.log4j.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
@ -16,12 +16,11 @@ import java.util.*;
* @updateTime 2020-07-28
* @throws
*/
@Slf4j
@Component
public class DealDataJob {
private final DealDataService dealDataService;
private final SimpleWeather simpleWeather=new SimpleWeather();
private static final Logger log = Logger.getLogger(DealDataJob.class);
public DealDataJob(DealDataService dealDataService) {
this.dealDataService = dealDataService;
}

39
user-service/src/main/java/com/mh/user/job/JobChillers.java

@ -1,39 +0,0 @@
package com.mh.user.job;
import com.mh.user.constants.SocketMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author ljf
* @title
* @description 定时采集冷水机组参数
* @updateTime 2020-06-24
* @throws
*/
/**
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
* 否则会在3秒时再启用新的线程执行
*/
@DisallowConcurrentExecution
@Slf4j
public class JobChillers implements Job {
@Autowired
private SocketMessage socketMessage;
@SneakyThrows
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("定时采集冷水机组");
// NettyChillerClient nettyChillerClient = new NettyChillerClient();
}
}

41
user-service/src/main/java/com/mh/user/job/JobCloud.java

@ -1,41 +0,0 @@
package com.mh.user.job;
import com.mh.user.netty.NettyClient;
import com.mh.user.constants.SocketMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author ljf
* @title
* @description 定时采集冷量计任务
* @updateTime 2020-05-18
* @throws
*/
/**
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
* 否则会在3秒时再启用新的线程执行
*/
@DisallowConcurrentExecution
@Slf4j
public class JobCloud implements Job {
@Autowired
private SocketMessage socketMessage;
@SneakyThrows
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
// 定时采集冷量计
log.info("定时采集冷量计");
NettyClient nettyClient = new NettyClient();
nettyClient.connect(socketMessage.getPort(),socketMessage.getIP());
}
}

39
user-service/src/main/java/com/mh/user/job/JobDDC.java

@ -1,39 +0,0 @@
package com.mh.user.job;
import com.mh.user.constants.SocketMessage;
import com.mh.user.netty.NettyChillerDDCClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author ljf
* @title 定时采集DDC设备
* @description
* @updateTime 2020-06-09
* @throws
*/
/**
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
* 否则会在3秒时再启用新的线程执行
*/
@DisallowConcurrentExecution
@Slf4j
public class JobDDC implements Job {
@Autowired
private SocketMessage socketMessage;
@SneakyThrows
@Override
public void execute(JobExecutionContext jobExecutionContext) {
log.info("定时采集DDC设备");
// NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient();
NettyChillerDDCClient.connect(socketMessage.getPort(), socketMessage.getIP());
}
}

45
user-service/src/main/java/com/mh/user/job/JobFactory.java

@ -1,45 +0,0 @@
package com.mh.user.job;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
* @author ljf
* @title 创建JobFactory实例
* @description
* @updateTime 2020-04-03
* @throws
*/
@Component
public class JobFactory extends AdaptableJobFactory {
/**
* AutowireCapableBeanFactory接口是BeanFactory的子类
* 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例
*/
private AutowireCapableBeanFactory factory;
/**
* @author jinhaoxun
* @description 构造器
* @param factory
*/
public JobFactory(AutowireCapableBeanFactory factory) {
this.factory = factory;
}
/**
* @author jinhaoxun
* @description 创建Job实例
* @param bundle
* @return Object
*/
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object job = super.createJobInstance(bundle);// 实例化对象
factory.autowireBean(job);// 进行注入(Spring管理该Bean)
return job;//返回对象
}
}

39
user-service/src/main/java/com/mh/user/job/JobMeter.java

@ -1,39 +0,0 @@
package com.mh.user.job;
import com.mh.user.netty.NettyMeterClient;
import com.mh.user.constants.SocketMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author ljf
* @title
* @description 定时采集电表数据任务
* @updateTime 2020-05-18
* @throws
*/
/**
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
* 否则会在3秒时再启用新的线程执行
*/
@DisallowConcurrentExecution
@Slf4j
public class JobMeter implements Job {
@Autowired
private SocketMessage socketMessage;
@SneakyThrows
@Override
public void execute(JobExecutionContext jobExecutionContext) {
log.info("定时采集电表数据任务开始");
NettyMeterClient nettyMeterClient = new NettyMeterClient();
nettyMeterClient.connect(socketMessage.getPort(), socketMessage.getIP());
}
}

32
user-service/src/main/java/com/mh/user/job/JobTest.java

@ -1,32 +0,0 @@
package com.mh.user.job;
import com.mh.user.constants.Constant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行.
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行,
* 否则会在3秒时再启用新的线程执行
*/
@DisallowConcurrentExecution
@Slf4j
public class JobTest implements Job {
@SneakyThrows
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
for (int i = 0; i < 30; i++) {
if (Constant.FLAG) {
break;
}
Thread.sleep(1000);
log.info("第" + i + "个," +jobExecutionContext.getJobDetail()+"---------------------定时任务测试----------------------");
}
}
}

73
user-service/src/main/java/com/mh/user/mapper/DataResultChMapper.java

@ -0,0 +1,73 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultClEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 数据冷量计
* @date 2024-07-10 15:20:55
*/
@Mapper
public interface DataResultChMapper extends BaseMapper<DataResultChEntity> {
//----------------------------------------------------------------------------------------------
//保存冷量计数据
@Insert("insert into data_result_ch(device_addr,device_type,fun_code,register_addr,register_name,cur_value,cur_date,project_id,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultCh(DataResultChEntity dataResultChEntity);
@Update("<script>" +
" update data_result_ch set " +
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" +
" <if test='funCode!=null'> , fun_code = #{funCode} </if>" +
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , register_name = #{registerName} </if>" +
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" +
" <if test='projectID!=null'> , project_id = #{projectID} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and device_type=#{deviceType}" +
"</script>")
void updateDataResultCh(DataResultChEntity dataResultChEntity);
@Select("select count(*) from data_result_ch " +
" where cur_date=#{curDate} " +
" and device_addr=#{deviceAddr} " +
" and register_addr=#{registerAddr} " +
" and project_id=#{projectID} " +
" and grade = #{grade} ")
int selectDataResultChCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID,
@Param("grade") int grade);
@Select("select " +
" t1.project_id, " +
" sum(cast (t1.curValue AS decimal(18, 2)))as cur_value, " +
" t1.cur_date, " +
" t2.project_name " +
"from " +
" data_result_ch t1 " +
"join project_info t2 on " +
" t1.project_id = t2.id " +
"where " +
" t1.project_id = #{projectID} " +
" and t1.cur_date >= #{startDate} " +
" and t1.cur_date <= #{curDate} " +
"group by " +
" t1.cur_date, " +
" t1.project_id, " +
" t2.project_name " +
"order by " +
" t1.cur_date ")
List<DataResultChEntity> queryDataResultCh(@Param("projectID") String projectID, @Param("startDate") String startDate, @Param("curDate") String curDate);
}

105
user-service/src/main/java/com/mh/user/mapper/DataResultChillerMapper.java

@ -0,0 +1,105 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultChillerEntity;
import com.mh.user.mapper.provider.DataResultProvider;
import com.mh.user.model.ChillerModel;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 主机参数保存
* @date 2024-07-10 15:41:15
*/
@Mapper
public interface DataResultChillerMapper extends BaseMapper<DataResultChillerEntity> {
//保存冷水机数据
@Insert("insert into data_result_chiller(device_addr,device_type,fun_code,register_addr,register_name,cur_value,cur_date,project_id,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultChiller(DataResultChEntity dataResultChEntity);
@Update("<script>" +
" update data_result_chiller set " +
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" +
" <if test='funCode!=null'> , fun_code = #{funCode} </if>" +
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , register_name = #{registerName} </if>" +
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" +
" <if test='projectID!=null'> , project_id = #{projectID} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and register_addr=#{registerAddr} and project_id=#{projectID} " +
"</script>")
void updateDataResultChiller(DataResultChEntity dataResultChEntity);
@Select("select count(*) from data_result_chiller where cur_date=#{curDate} " +
" and device_addr=#{deviceAddr} " +
" and register_addr=#{registerAddr} " +
" and project_id=#{projectID} " +
" and fun_code = #{funCode} ")
int selectDataResultChillerCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID,
@Param("funCode") String funCode);
@Results({
@Result(property="deviceAddr",column="deviceAddr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="curDate",column="curDate"),
@Result(property ="curValue",column ="curValue"),
@Result(property="funCode",column="funCode"),
@Result(property="registerAddr",column="registerAddr"),
@Result(property="registerName",column="registerName"),
@Result(property="grade",column="grade"),
@Result(property="projectID",column="projectID"),
@Result(property="projectName",column="project_name")
})
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultChiller")
List<DataResultChEntity> queryDataResultChiller(@Param("projectID") String projectID,
@Param("deviceAddr") String deviceAddr,
@Param("registerName") String registerName,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
@SelectProvider(type = DataResultProvider.class,method = "dataResultChillerCount")
int dataResultChillerCount(@Param("projectID") String projectID,
@Param("deviceAddr") String deviceAddr,
@Param("registerName") String registerName,
@Param("startDate") String startDate,
@Param("curDate") String curDate);
//保存冷水机参数数据
@Insert("insert into data_chiller" +
"(device_addr," +
"device_name," +
"run_state," +
"set_soint," +
"enter_chw," +
"leave_chw," +
"enter_cow," +
"leave_cow," +
"power," +
"rated_power," +
"chiller_amps," +
"refrigeration," +
"rated_ref," +
"chw_flow," +
"approach_cow," +
"approach_chw," +
"cop," +
"rated_cop," +
"copy_date) values (" +
" #{deviceAddr},#{deviceName},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade})")
void saveDataChiller(ChillerModel chillerModel);
}

35
user-service/src/main/java/com/mh/user/mapper/DataResultClBakMapper.java

@ -0,0 +1,35 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultClBakEntity;
import com.mh.user.entity.DataResultClEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 数据冷量计
* @date 2024-07-10 15:20:55
*/
@Mapper
public interface DataResultClBakMapper extends BaseMapper<DataResultClBakEntity> {
@Insert("insert into data_result_cl_bak(device_addr,device_type,project_id,last_value,last_date,cur_value,cur_date,ratio,calc_value,grade,register_addr,register_name) values (" +
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})")
void saveDataResultCl_bak(DataResultClEntity dataResultClEntity);
@Select("select count(1) from data_result_cl_bak " +
" where cur_date = #{curDate} " +
" and device_addr = #{deviceAddr} " +
" and registerAddr = #{registerAddr} " +
" and project_id = #{projectId} ")
int selectDataResultChBakCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectId") String projectId);
}

42
user-service/src/main/java/com/mh/user/mapper/DataResultClMapper.java

@ -0,0 +1,42 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultClEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 数据冷量计
* @date 2024-07-10 15:20:55
*/
@Mapper
public interface DataResultClMapper extends BaseMapper<DataResultClEntity> {
//----------------------------------------------------------------------------------------------
//保存冷量计数据
@Insert("insert into data_result_cl(device_addr,device_type,project_id,last_value,last_date,cur_value,cur_date,ratio,calc_value,grade,register_addr,register_mame) values (" +
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})")
void saveDataResultCl(DataResultClEntity dataResultClEntity);
@Update("<script>" +
" update data_result_cl set " +
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" +
" <if test='projectID!=null'> , project_id = #{projectID} </if>" +
" <if test='lastValue!=null'> , last_value = #{lastValue} </if>" +
" <if test='lastDate!=null'> , last_date = #{lastDate} </if>" +
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" +
" <if test='ratio!=null'> , ratio = #{ratio} </if>" +
" <if test='calcValue!=null'> , calc_value = #{calcValue} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , register_name = #{registerName} </if>" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and device_type=#{deviceType}" +
"</script>")
void updateDataResultCl(DataResultClEntity dataResultClEntity);
}

36
user-service/src/main/java/com/mh/user/mapper/DataResultFifteenMiMapper.java

@ -0,0 +1,36 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultFifteenMiEntity;
import com.mh.user.entity.DataResultFiveMiEntity;
import com.mh.user.mapper.provider.DataResultProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.SelectProvider;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 每分钟保存数据
* @date 2024-07-10 17:34:30
*/
@Mapper
public interface DataResultFifteenMiMapper extends BaseMapper<DataResultFifteenMiEntity> {
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFifteenMi")
List<DataResultChEntity> queryDataResultFifteenMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
//@Select("select count(*) from data_result_fifteen_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultFifteenMiCount")
int dataResultFifteenMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
}

33
user-service/src/main/java/com/mh/user/mapper/DataResultFiveMiMapper.java

@ -0,0 +1,33 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultFiveMiEntity;
import com.mh.user.entity.DataResultOneMiEntity;
import com.mh.user.mapper.provider.DataResultProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 每分钟保存数据
* @date 2024-07-10 17:34:30
*/
@Mapper
public interface DataResultFiveMiMapper extends BaseMapper<DataResultFiveMiEntity> {
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFiveMi")
List<DataResultChEntity> queryDataResultFiveMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
// @Select("select count(*) from data_result_five_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultFiveMiCount")
int dataResultFiveMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
}

225
user-service/src/main/java/com/mh/user/mapper/DataResultMapper.java

@ -1,5 +1,6 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultClEntity;
import com.mh.user.entity.DataResultEntity;
import com.mh.user.entity.DataResultChEntity;
@ -10,34 +11,34 @@ import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface DataResultMapper {
public interface DataResultMapper extends BaseMapper<DataResultEntity> {
//保存水电表等数据
@Insert("insert into data_result(device_addr,deviceType,project_id,lastValue,lastDate,cur_value,cur_date,ratio,calc_value,grade) values (" +
@Insert("insert into data_result(device_addr,device_type,project_id,last_value,last_date,cur_value,cur_date,ratio,calc_value,grade) values (" +
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade})")
void saveDataResult(DataResultEntity dataResultEntity);
@Update("<script>" +
" update data_result set " +
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , deviceType = #{deviceType} </if>" +
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" +
" <if test='projectID!=null'> , project_id = #{projectID} </if>" +
" <if test='lastValue!=null'> , lastValue = #{lastValue} </if>" +
" <if test='lastDate!=null'> , lastDate = #{lastDate} </if>" +
" <if test='lastValue!=null'> , last_value = #{lastValue} </if>" +
" <if test='lastDate!=null'> , last_date = #{lastDate} </if>" +
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" +
" <if test='ratio!=null'> , ratio = #{ratio} </if>" +
" <if test='calcValue!=null'> , calc_value = #{calcValue} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and deviceType=#{deviceType}" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and device_type=#{deviceType}" +
"</script>")
void updateDataResult(DataResultEntity dataResultEntity);
@Results(id="rs", value = {
@Result(property="deviceAddr",column="device_addr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="deviceType",column="device_type"),
@Result(property="projectID",column="project_id"),
@Result(property="lastValue",column="lastValue"),
@Result(property ="lastDate",column ="lastDate"),
@Result(property="lastValue",column="last_value"),
@Result(property ="lastDate",column ="last_date"),
@Result(property ="curValue",column ="cur_value"),
@Result(property="curDate",column="cur_date"),
@Result(property="ratio",column="ratio"),
@ -75,210 +76,4 @@ public interface DataResultMapper {
@Param("deviceAddr") String deviceAddr,
@Param("deviceType") String deviceType);
//----------------------------------------------------------------------------------------------
//保存冷量计数据
@Insert("insert into data_result_cl(device_addr,deviceType,project_id,lastValue,lastDate,cur_value,cur_date,ratio,calc_value,grade,registerAddr,registerName) values (" +
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})")
void saveDataResultCl(DataResultClEntity dataResultClEntity);
@Update("<script>" +
" update data_result_cl set " +
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , deviceType = #{deviceType} </if>" +
" <if test='projectID!=null'> , project_id = #{projectID} </if>" +
" <if test='lastValue!=null'> , lastValue = #{lastValue} </if>" +
" <if test='lastDate!=null'> , lastDate = #{lastDate} </if>" +
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" +
" <if test='ratio!=null'> , ratio = #{ratio} </if>" +
" <if test='calcValue!=null'> , calc_value = #{calcValue} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" <if test='registerAddr!=null'> , registerAddr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , registerName = #{registerName} </if>" +
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and deviceType=#{deviceType}" +
"</script>")
void updateDataResultCl(DataResultClEntity dataResultClEntity);
@Insert("insert into data_result_cl_bak(device_addr,deviceType,project_id,lastValue,lastDate,cur_value,cur_date,ratio,calc_value,grade,registerAddr,registerName) values (" +
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})")
void saveDataResultCl_bak(DataResultClEntity dataResultClEntity);
//----------------------------------------------------------------------------------------------
//保存冷量计数据
@Insert("insert into data_result_ch(deviceAddr,deviceType,funCode,registerAddr,registerName,curValue,curDate,projectID,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultCh(DataResultChEntity dataResultChEntity);
@Update("<script>" +
" update data_result_ch set " +
" <if test='deviceAddr!=null'> deviceAddr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , deviceType = #{deviceType} </if>" +
" <if test='funCode!=null'> , funCode = #{funCode} </if>" +
" <if test='registerAddr!=null'> , registerAddr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , registerName = #{registerName} </if>" +
" <if test='curValue!=null'> , curValue = #{curValue} </if>" +
" <if test='projectID!=null'> , projectID = #{projectID} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" where curDate=#{curDate} and deviceAddr=#{deviceAddr} and deviceType=#{deviceType}" +
"</script>")
void updateDataResultCh(DataResultChEntity dataResultChEntity);
@Select("select count(*) from data_result_ch " +
" where curDate=#{curDate} " +
" and deviceAddr=#{deviceAddr} " +
" and registerAddr=#{registerAddr} " +
" and projectID=#{projectID} " +
" and grade = #{grade} ")
int selectDataResultChCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID,
@Param("grade") int grade);
//----------------------------------------------------------------------------------------------------
@Results(id="rsc", value = {
@Result(property="deviceAddr",column="deviceAddr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="curDate",column="curDate"),
@Result(property ="curValue",column ="curValue"),
@Result(property="funCode",column="funCode"),
@Result(property="registerAddr",column="registerAddr"),
@Result(property="registerName",column="registerName"),
@Result(property="grade",column="grade"),
@Result(property="projectID",column="projectID"),
@Result(property="projectName",column="project_name")
})
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultOneMi")
List<DataResultChEntity> queryDataResultOneMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
//查询记录数
// @Select("select count(*) from data_result_one_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultOneMiCount")
int dataResultOneMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
@ResultMap("rsc")
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFiveMi")
List<DataResultChEntity> queryDataResultFiveMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
// @Select("select count(*) from data_result_five_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultFiveMiCount")
int dataResultFiveMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
@ResultMap("rsc")
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFifteenMi")
List<DataResultChEntity> queryDataResultFifteenMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
//@Select("select count(*) from data_result_fifteen_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultFifteenMiCount")
int dataResultFifteenMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
@ResultMap("rsc")
@Select("select t1.projectID,sum(cast (t1.curValue AS decimal(18,2)))as curValue,t1.curDate,t2.project_name from data_result_ch t1 join project_info t2 on t1.projectID=t2.id " +
"where t1.projectID=#{projectID} and t1.curDate>=#{startDate} and t1.curDate<=#{curDate} group by t1.curDate,t1.projectID,t2.project_name order by t1.curDate ")
List<DataResultChEntity> queryDataResultCh(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
//保存冷水机数据
@Insert("insert into data_result_chiller(deviceAddr,deviceType,funCode,registerAddr,registerName,curValue,curDate,projectID,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultChiller(DataResultChEntity dataResultChEntity);
@Update("<script>" +
" update data_result_chiller set " +
" <if test='deviceAddr!=null'> deviceAddr = #{deviceAddr} </if>" +
" <if test='deviceType!=null'> , deviceType = #{deviceType} </if>" +
" <if test='funCode!=null'> , funCode = #{funCode} </if>" +
" <if test='registerAddr!=null'> , registerAddr = #{registerAddr} </if>" +
" <if test='registerName!=null'> , registerName = #{registerName} </if>" +
" <if test='curValue!=null'> , curValue = #{curValue} </if>" +
" <if test='projectID!=null'> , projectID = #{projectID} </if>" +
" <if test='grade!=null'> , grade = #{grade} </if>" +
" where curDate=#{curDate} and deviceAddr=#{deviceAddr} and registerAddr=#{registerAddr} and projectID=#{projectID} " +
"</script>")
void updateDataResultChiller(DataResultChEntity dataResultChEntity);
@Select("select count(*) from data_result_chiller where curDate=#{curDate} " +
" and deviceAddr=#{deviceAddr} " +
" and registerAddr=#{registerAddr} " +
" and projectID=#{projectID} " +
" and funCode = #{funCode} ")
int selectDataResultChillerCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID,
@Param("funCode") String funCode);
@Insert("insert into data_result_now(deviceAddr,deviceType,funCode,registerAddr,registerName,curValue,curDate,projectID,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultNow(DataResultChEntity dataResultChEntity);
@Delete("delete from data_result_now where deviceAddr=#{deviceAddr} and deviceType = #{deviceType} and registerAddr=#{registerAddr} and projectID=#{projectID}")
void deleteDataResultNow(@Param("deviceAddr") String deviceAddr,
@Param("deviceType") String deviceType,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID);
//实时参数读取
@Select("select * from data_result_now where deviceAddr=#{deviceAddr} and deviceType=#{deviceType} and projectID=#{projectID} ")
List<DataResultChEntity> selectDataResultNow(@Param("deviceAddr") String deviceAddr,
@Param("deviceType") String deviceType,
@Param("projectID") String projectID);
@Results({
@Result(property="deviceAddr",column="deviceAddr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="curDate",column="curDate"),
@Result(property ="curValue",column ="curValue"),
@Result(property="funCode",column="funCode"),
@Result(property="registerAddr",column="registerAddr"),
@Result(property="registerName",column="registerName"),
@Result(property="grade",column="grade"),
@Result(property="projectID",column="projectID"),
@Result(property="projectName",column="project_name")
})
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultChiller")
List<DataResultChEntity> queryDataResultChiller(@Param("projectID") String projectID,
@Param("deviceAddr") String deviceAddr,
@Param("registerName") String registerName,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
@SelectProvider(type = DataResultProvider.class,method = "dataResultChillerCount")
int dataResultChillerCount(@Param("projectID") String projectID,
@Param("deviceAddr") String deviceAddr,
@Param("registerName") String registerName,
@Param("startDate") String startDate,
@Param("curDate") String curDate);
//保存冷水机参数数据
@Insert("insert into data_chiller(deviceAddr,deviceName,runState,setPoint,enterChw,leaveChw,enterCow,leaveCow,power,ratedPower,chillerAmps,refrigeration,ratedRef,chwFlow,ApproachCow,ApproachChw,cop,ratedCop,copyDate) values (" +
" #{deviceAddr},#{deviceName},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade})")
void saveDataChiller(ChillerModel chillerModel);
@Select("select count(1) from data_result_cl_bak " +
" where cur_date = #{curDate} " +
" and device_addr = #{deviceAddr} " +
" and registerAddr = #{registerAddr} " +
" and project_id = #{projectId} ")
int selectDataResultChBakCount(@Param("curDate") String curDate,
@Param("deviceAddr") String deviceAddr,
@Param("registerAddr") String registerAddr,
@Param("projectId") String projectId);
}

36
user-service/src/main/java/com/mh/user/mapper/DataResultNowMapper.java

@ -0,0 +1,36 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultNowEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 当前记录
* @date 2024-07-11 13:41:04
*/
@Mapper
public interface DataResultNowMapper extends BaseMapper<DataResultNowEntity> {
@Insert("insert into data_result_now(deviceAddr,deviceType,funCode,registerAddr,registerName,curValue,curDate,projectID,grade) values (" +
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})")
void saveDataResultNow(DataResultChEntity dataResultChEntity);
@Delete("delete from data_result_now where deviceAddr=#{deviceAddr} and deviceType = #{deviceType} and registerAddr=#{registerAddr} and projectID=#{projectID}")
void deleteDataResultNow(@Param("deviceAddr") String deviceAddr,
@Param("deviceType") String deviceType,
@Param("registerAddr") String registerAddr,
@Param("projectID") String projectID);
//实时参数读取
@Select("select * from data_result_now where deviceAddr=#{deviceAddr} and deviceType=#{deviceType} and projectID=#{projectID} ")
List<DataResultChEntity> selectDataResultNow(@Param("deviceAddr") String deviceAddr,
@Param("deviceType") String deviceType,
@Param("projectID") String projectID);
}

46
user-service/src/main/java/com/mh/user/mapper/DataResultOneMiMapper.java

@ -0,0 +1,46 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DataResultChEntity;
import com.mh.user.entity.DataResultOneMiEntity;
import com.mh.user.mapper.provider.DataResultProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 每分钟保存数据
* @date 2024-07-10 17:34:30
*/
@Mapper
public interface DataResultOneMiMapper extends BaseMapper<DataResultOneMiEntity> {
//----------------------------------------------------------------------------------------------------
@Results(id="rsc", value = {
@Result(property="deviceAddr",column="deviceAddr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="curDate",column="curDate"),
@Result(property ="curValue",column ="curValue"),
@Result(property="funCode",column="funCode"),
@Result(property="registerAddr",column="registerAddr"),
@Result(property="registerName",column="registerName"),
@Result(property="grade",column="grade"),
@Result(property="projectID",column="projectID"),
@Result(property="projectName",column="project_name")
})
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultOneMi")
List<DataResultChEntity> queryDataResultOneMi(@Param("projectID") String projectID,
@Param("startDate") String startDate,
@Param("curDate") String curDate,
@Param("page") int page,
@Param("limit") int limit);
//查询记录数
// @Select("select count(*) from data_result_one_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
@SelectProvider(type = DataResultProvider.class,method = "dataResultOneMiCount")
int dataResultOneMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate);
}

55
user-service/src/main/java/com/mh/user/mapper/DeviceCodeMapper.java

@ -0,0 +1,55 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DeviceCodeEntity;
import com.mh.user.model.ChillerModel;
import com.mh.user.model.DeviceModel;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author LJF
* @version 1.0
* @project mh_esi
* @description 设备参数mapper
* @date 2024-07-11 15:37:48
*/
@Mapper
public interface DeviceCodeMapper extends BaseMapper<DeviceCodeEntity> {
//查询冷水机设备列表
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),
@Result(column = "device_name", property = "deviceName")
})
@Select("select * from device_code where project_id=#{projectID} and device_type='冷水机'")
List<DeviceModel> selectDevices(@Param("projectID") String projectID);
//查询多个冷水机相关信息
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),
@Result(column = "device_name", property = "deviceName"),
@Result(column = "runState", property = "runState"),
@Result(column = "setPoint", property = "setPoint"),
@Result(column = "enterChw", property = "enterChw"),
@Result(column = "leaveChw", property = "leaveChw"),
@Result(column = "enterCow", property = "enterCow"),
@Result(column = "leaveCow", property = "leaveCow"),
@Result(column = "power", property = "power"),
@Result(column = "ratedPower", property = "ratedPower"),
@Result(column = "chillerAmps", property = "chillerAmps"),
@Result(column = "refrigeration", property = "refrigeration"),
@Result(column = "ratedRef", property = "ratedRef"),
@Result(column = "chwFlow", property = "chwFlow"),
@Result(column = "ApproachCow", property = "ApproachCow"),
@Result(column = "ApproachChw", property = "ApproachChw"),
@Result(column = "cop", property = "cop"),
@Result(column = "ratedCop", property = "ratedCop"),
@Result(column = "copyDate", property = "copyDate")
})
@Select("select * from device_code where project_id=#{projectID} and device_addr=#{deviceAddr} ")
List<ChillerModel> queryChiller(@Param("projectID") String projectID, @Param("device_addr") String deviceAddr);
}

57
user-service/src/main/java/com/mh/user/mapper/DeviceCodeParamMapper.java

@ -1,5 +1,6 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.entity.OrderMessageEntity;
import org.apache.ibatis.annotations.*;
@ -7,10 +8,10 @@ import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface DeviceCodeParamMapper {
public interface DeviceCodeParamMapper extends BaseMapper<DeviceCodeParamEntity> {
//插入指令参数
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_com,baudrate,brand,fun_code,register_addr,create_time)" +
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_com,baud_rate,brand,fun_code,register_addr,create_time)" +
"values(#{deviceAddr},#{deviceName},#{deviceType},#{dataCom},#{baudrate},#{brand},#{funCode},#{registerAddr},getDate())")
void insertDeviceCodeParam(DeviceCodeParamEntity deviceCodeParamEntity);
@ -18,36 +19,36 @@ public interface DeviceCodeParamMapper {
@Results(id="rs", value = {
@Result(property="id",column="id"),
@Result(property="deviceAddr",column="device_addr"),
@Result(property="deviceType",column="deviceType"),
@Result(property="strData",column="strData"),
@Result(property="dataPort",column="dataPort"),
@Result(property="baudRate",column="baudrate"),
@Result(property="deviceType",column="device_type"),
@Result(property="strData",column="str_data"),
@Result(property="dataPort",column="data_port"),
@Result(property="baudRate",column="baud_rate"),
@Result(property ="brand",column ="brand"),
@Result(property ="funCode",column ="fun_code"),
@Result(property ="registerAddr",column ="register_addr"),
@Result(property ="registerName",column ="registerName"),
@Result(property ="deviceName",column ="deviceName"),
@Result(property ="createTime",column ="createTime"),
@Result(property ="registerName",column ="register_name"),
@Result(property ="deviceName",column ="device_name"),
@Result(property ="createTime",column ="create_time"),
@Result(property ="grade",column ="grade"),
@Result(property ="digit",column ="digit"),
@Result(property ="projectID",column ="project_id")
})
@Select("select id, " +
"device_addr, " +
"deviceType, " +
"strData, " +
"dataPort, " +
"device_type, " +
"str_data, " +
"data_port, " +
"baudrate, " +
"brand, " +
"fun_code, " +
"register_addr, " +
"deviceName, " +
"createTime, " +
"device_name, " +
"create_time, " +
"grade, " +
"project_id, " +
"digit, " +
"registerName " +
" from device_code_param where dataPort=#{gatewayPort} order by deviceType ")
"register_name " +
" from device_code_param where data_port=#{gatewayPort} order by device_type ")
List<DeviceCodeParamEntity> queryCodeParam(@Param("gatewayPort") String gatewayPort);
//查询指令参数,传入串口
@ -57,12 +58,12 @@ public interface DeviceCodeParamMapper {
//查询所有指令参数
@ResultMap("rs")
@Select("select * from device_code_param order by data_com,deviceType")
@Select("select * from device_code_param order by data_com,device_type")
List<DeviceCodeParamEntity> queryCodeParam3();
//查询所有指令参数
@ResultMap("rs")
@Select("select * from device_code_param where project_id=#{projectID} and deviceType=#{deviceType} and device_addr=#{deviceAddr} and register_addr=#{registerAddr}")
@Select("select * from device_code_param where project_id=#{projectID} and device_type=#{deviceType} and device_addr=#{deviceAddr} and register_addr=#{registerAddr}")
DeviceCodeParamEntity queryDeviceCodeParam(@Param("projectID") String projectID,
@Param("deviceType") String deviceType,
@Param("deviceAddr") String deviceAddr,
@ -80,20 +81,20 @@ public interface DeviceCodeParamMapper {
@Insert("<script>" +
"insert into device_code_param(" +
"device_addr, " +
"deviceName, " +
"deviceType, " +
"dataPort, " +
"baudRate, " +
"device_name, " +
"device_type, " +
"data_port, " +
"baud_rate, " +
"brand, " +
"fun_code, " +
"register_addr," +
"registerName," +
"createTime," +
"register_name," +
"create_time," +
"project_id," +
"parity," +
"digit," +
"grade," +
"strData" +
"str_data" +
")" +
"values " +
"<foreach collection='deviceCodeParamEntityList' item='item' separator=','>" +
@ -103,7 +104,7 @@ public interface DeviceCodeParamMapper {
void insertDeviceCodeParamList(@Param("deviceCodeParamEntityList") List<DeviceCodeParamEntity> deviceCodeParamEntityList);
//查询插入
@Insert("insert into device_code_param(device_addr,deviceName,deviceType,dataPort,baudRate,parity,brand,createTime,project_id,digit,grade) select device_addr,deviceName,deviceType,dataPort,baudRate,parity,brand,getDate(),project_id,2,grade from device_code " +
" where (deviceType='电表' or deviceType='水表') and project_id=#{ProjectID} ")
void selectInsertDeviceCodeParam(@Param("ProjectID") String ProjectID);
@Insert("insert into device_code_param(device_addr,device_name,device_type,data_port,baud_rate,parity,brand,create_time,project_id,digit,grade) select device_addr,device_name,device_type,data_port,baud_rate,parity,brand,getDate(),project_id,2,grade from device_code " +
" where (device_type='电表' or device_type='水表') and project_id=#{projectId} ")
void selectInsertDeviceCodeParam(@Param("projectId") String projectId);
}

48
user-service/src/main/java/com/mh/user/mapper/DeviceInfoMapper.java

@ -15,55 +15,21 @@ public interface DeviceInfoMapper {
@SelectProvider(type = DeviceInfoProvider.class,method = "queryDeviceInfo")
@Results(value = {
@Result(property="id",column="id"),
@Result(property="deviceName",column="deviceName"),
@Result(property="deviceType",column="deviceType"),
@Result(property="deviceName",column="device_name"),
@Result(property="deviceType",column="device_type"),
@Result(property="brand",column="brand"),
@Result(property ="power",column ="power"),
@Result(property ="madeTime",column ="madeTime"),
@Result(property ="madeTime",column ="made_time"),
@Result(property="flow",column="flow"),
@Result(property="isFC",column="isFC"),
@Result(property="motorBrand",column="motorBrand"),
@Result(property="projectID",column="project_id"),
@Result(property="systemID",column="system_id")
@Result(property="isFc",column="is_fc"),
@Result(property="motorBrand",column="motor_brand"),
@Result(property="projectId",column="project_id"),
@Result(property="systemId",column="system_id")
})
List<DeviceInfoEntity> queryDeviceInfo(@Param("systemID") String systemID,
@Param("projectID") String projectID,
@Param("deviceType") String deviceType);
//查询冷水机设备列表
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),
@Result(column = "device_name", property = "deviceName")
})
@Select("select * from device_code where project_id=#{projectID} and device_type='冷水机'")
List<DeviceModel> selectDevices(@Param("projectID") String projectID);
//查询多个冷水机相关信息
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),
@Result(column = "device_name", property = "deviceName"),
@Result(column = "runState", property = "runState"),
@Result(column = "setPoint", property = "setPoint"),
@Result(column = "enterChw", property = "enterChw"),
@Result(column = "leaveChw", property = "leaveChw"),
@Result(column = "enterCow", property = "enterCow"),
@Result(column = "leaveCow", property = "leaveCow"),
@Result(column = "power", property = "power"),
@Result(column = "ratedPower", property = "ratedPower"),
@Result(column = "chillerAmps", property = "chillerAmps"),
@Result(column = "refrigeration", property = "refrigeration"),
@Result(column = "ratedRef", property = "ratedRef"),
@Result(column = "chwFlow", property = "chwFlow"),
@Result(column = "ApproachCow", property = "ApproachCow"),
@Result(column = "ApproachChw", property = "ApproachChw"),
@Result(column = "cop", property = "cop"),
@Result(column = "ratedCop", property = "ratedCop"),
@Result(column = "copyDate", property = "copyDate")
})
@Select("select * from device_code where project_id=#{projectID} and device_addr=#{deviceAddr} ")
List<ChillerModel> queryChiller(@Param("projectID") String projectID, @Param("device_addr") String deviceAddr);
//查询单个冷水机相关信息
@Results({
@Result(column = "device_addr",property = "deviceAddr" ),

10
user-service/src/main/java/com/mh/user/mapper/DeviceInstallMapper.java

@ -1,16 +1,16 @@
package com.mh.user.mapper;
import com.mh.user.entity.BuildingEntity;
import com.mh.user.entity.DeviceInstallEntity;
import com.mh.user.entity.DeviceInstallTempEntity;
import com.mh.user.mapper.provider.DeviceInstallProvider;
import com.mh.user.model.DeviceModel;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Mapper
public interface DeviceInstallMapper {
/**
@ -45,7 +45,7 @@ public interface DeviceInstallMapper {
//按id更新水电表读数和采集日期
@Update("update device_code set lastValue=#{lastValue},lastDate=#{lastDate} where id=#{id}")
void updateLastValue(@Param("id") Long id,@Param("lastValue") double lastValue,@Param("lastDate") Date lastDate);
void updateLastValue(@Param("id") Long id, @Param("lastValue") BigDecimal lastValue, @Param("lastDate") Date lastDate);
/**
* 设备管理模块
* 查询设备资料
@ -71,8 +71,8 @@ public interface DeviceInstallMapper {
@Result(property="remarks",column="remarks"),
@Result(property ="projectID",column ="project_id"),
})
@Select("select * from (\n" +
"select *,ROW_NUMBER() over(order by id) as rn from device_code \n" +
@Select("select * from ( " +
"select *,ROW_NUMBER() over(order by id) as rn from device_code " +
") t where rn between (#{page}-1)*#{limit} and #{page}*#{limit}")
List<DeviceInstallEntity> getAllDevice(@Param("page") int page, @Param("limit") int limit);

19
user-service/src/main/java/com/mh/user/mapper/EnergyDataMapper.java

@ -1,5 +1,6 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.EnergyDataEntity;
import com.mh.user.mapper.provider.EnergyDataProvider;
import org.apache.ibatis.annotations.*;
@ -7,7 +8,7 @@ import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface EnergyDataMapper {
public interface EnergyDataMapper extends BaseMapper<EnergyDataEntity> {
//按10分钟
@SelectProvider(type = EnergyDataProvider.class, method = "queryEnergyDataMi")
@ -32,10 +33,22 @@ public interface EnergyDataMapper {
//按小时
@SelectProvider(type = EnergyDataProvider.class, method = "queryEnergyDataHour")
@ResultMap("rs")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "curDate", column = "cur_date"),
@Result(property = "ambTemp", column = "amb_temp"),
@Result(property = "humidity", column = "humidity"),
@Result(property = "water", column = "water"),
@Result(property = "elect", column = "elect"),
@Result(property = "cl", column = "cl"),
@Result(property = "cop", column = "cop"),
@Result(property = "projectId", column = "project_id"),
@Result(property = "projectName", column = "project_name")
})
List<EnergyDataEntity> queryEnergyDataHour(@Param("projectID") String projectID,
@Param("curDate") String curDate,
@Param("page") int page, @Param("limit") int limit);
@Param("page") int page,
@Param("limit") int limit);
@SelectProvider(type = EnergyDataProvider.class, method = "getEnergyDataHourCount")
int getEnergyDataHourCount(@Param("projectID") String projectID, @Param("curDate") String curDate);

1
user-service/src/main/java/com/mh/user/mapper/EnergyMapper.java

@ -5,6 +5,7 @@ import com.mh.user.mapper.provider.EnergyProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface EnergyMapper {
/**

10
user-service/src/main/java/com/mh/user/mapper/MeterInfoMapper.java

@ -13,17 +13,17 @@ public interface MeterInfoMapper {
@SelectProvider(type = MeterInfoProvider.class,method = "queryMeterInfo")
@Results(value = {
@Result(property="id",column="id"),
@Result(property="meterName",column="meterName"),
@Result(property="meterType",column="meterType"),
@Result(property="meterName",column="meter_name"),
@Result(property="meterType",column="meter_type"),
@Result(property="brand",column="brand"),
@Result(property="currentValue",column="currentValue"),
@Result(property="currentValue",column="current_value"),
@Result(property ="model",column ="model"),
@Result(property ="pulse",column ="pulse"),
@Result(property="caliber",column="caliber"),
@Result(property="range",column="range"),
@Result(property="structural",column="structural"),
@Result(property="projectID",column="project_id"),
@Result(property="systemID",column="system_id")
@Result(property="projectId",column="project_id"),
@Result(property="systemId",column="system_id")
})
List<MeterInfoEntity> queryMeterInfo(@Param("systemID") String systemID,
@Param("projectID") String projectID);

3
user-service/src/main/java/com/mh/user/mapper/ProjectInfoMapper.java

@ -1,12 +1,13 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.ProjectInfoEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ProjectInfoMapper {
public interface ProjectInfoMapper extends BaseMapper<ProjectInfoEntity> {
//查询项目列表
@Results(value = {

15
user-service/src/main/java/com/mh/user/mapper/RegisterAddrMapper.java

@ -1,5 +1,6 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.RegisterAddrEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
@ -8,16 +9,16 @@ import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface RegisterAddrMapper {
public interface RegisterAddrMapper extends BaseMapper<RegisterAddrEntity> {
@Results(value = {
@Result(property="registerAddr",column="registerAddr"),
@Result(property="regName",column="regName"),
@Result(property="funFlag",column="funFlag"),
@Result(property="floatFlag",column="floatFlag"),
@Result(property="registerAddr",column="register_addr"),
@Result(property="regName",column="reg_name"),
@Result(property="funFlag",column="fun_flag"),
@Result(property="floatFlag",column="float_flag"),
@Result(property="grade",column="grade"),
@Result(property ="otherName",column ="otherName")
@Result(property ="otherName",column ="other_name")
})
@Select("select * from RegisterAddrs ")
@Select("select * from register_addr ")
List<RegisterAddrEntity> selectRegisterAddr();
}

24
user-service/src/main/java/com/mh/user/mapper/StrategyInfoMapper.java

@ -1,24 +1,24 @@
package com.mh.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mh.user.entity.StrategyInfoEntity;
import com.mh.user.mapper.provider.DeviceInfoProvider;
import com.mh.user.mapper.provider.StrategyInfoProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface StrategyInfoMapper {
public interface StrategyInfoMapper extends BaseMapper<StrategyInfoEntity> {
//查询仪表信息
@SelectProvider(type = StrategyInfoProvider.class,method = "queryStrategyInfo")
@Results(value = {
@Result(property="id",column="id"),
@Result(property="dataAnalysis",column="dataAnalysis"),
@Result(property="operationOpt",column="operation_opt"),
@Result(property="controlOpt",column="control_opt"),
@Result(property="projectID",column="project_id"),
@Result(property="systemID",column="system_id")
})
@Select("<script>" +
"select * from strategy_info where 1=1 " +
"<if test='systemID != null and systemID != \"\"'>" +
" and system_id = #{systemID} " +
"</if>" +
"<if test='projectID != null and projectID != \"\"'>" +
" and project_id = #{projectID} " +
"</if>" +
" order by id " +
"</script>")
List<StrategyInfoEntity> queryStrategyInfo(@Param("systemID") String systemID,@Param("projectID") String projectID);
}

1
user-service/src/main/java/com/mh/user/mapper/SysDeptMapper.java

@ -9,6 +9,7 @@ import java.util.List;
* author: ljf
* desc: 部门Mapper
*/
@Mapper
public interface SysDeptMapper {
int deleteByPrimaryKey(Long id);

2
user-service/src/main/java/com/mh/user/mapper/SysMenuMapper.java

@ -1,6 +1,7 @@
package com.mh.user.mapper;
import com.mh.user.model.SysMenu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@ -9,6 +10,7 @@ import java.util.List;
* author: ljf
* desc: 系统菜单Mapper
*/
@Mapper
public interface SysMenuMapper {
int deleteByPrimaryKey(Long id);

1
user-service/src/main/java/com/mh/user/mapper/SysRoleDeptMapper.java

@ -7,6 +7,7 @@ import org.apache.ibatis.annotations.Mapper;
* author: ljf
* desc: 角色对应部门Mapper
*/
@Mapper
public interface SysRoleDeptMapper {
int deleteByPrimaryKey(Long id);

1
user-service/src/main/java/com/mh/user/mapper/SysUserRoleMapper.java

@ -10,6 +10,7 @@ import java.util.List;
* author: ljf
* desc: 用户对应角色Mapper
*/
@Mapper
public interface SysUserRoleMapper {
int deleteByPrimaryKey(Long id);

121
user-service/src/main/java/com/mh/user/mapper/provider/DataResultProvider.java

@ -17,14 +17,13 @@ public class DataResultProvider {
sql.append(" AND convert(varchar(10),cur_date,121)<=#{endDate} ");
}
if (deviceType != null && !deviceType.equals("")){
sql.append(" AND deviceType = #{deviceType} ");
sql.append(" AND device_type = #{deviceType} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" ) T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit}");
} else if (page == 0){
sql.append(" ) T ");
}
// System.out.println(sql.toString());
return sql.toString();
}
@ -44,32 +43,31 @@ public class DataResultProvider {
sql.append(" AND convert(varchar(10),cur_date,121)<=#{endDate} ");
}
if (deviceType != null && !deviceType.equals("")){
sql.append(" AND deviceType = #{deviceType} ");
sql.append(" AND device_type = #{deviceType} ");
}
sql.append(" ) T ");
// System.out.println(sql.toString());
return sql.toString();
}
//-----------------------------------------------------------------------------------------------
//时间显示间隔为1分钟
public String queryDataResultOneMi(String projectID, String startDate,String curDate, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_one_mi " +
sql.append("select * from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_one_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.cur_date desc");
} else if (page == 0){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id order by t2.cur_date desc");
}
// System.out.println(sql.toString());
return sql.toString();
@ -77,20 +75,19 @@ public class DataResultProvider {
public String dataResultOneMiCount(String projectID, String startDate,String curDate){
StringBuffer sql = new StringBuffer("");
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_one_mi " +
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_one_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
sql.append(" group by curDate,projectID)t1) t2 ");
// System.out.println(sql.toString());
sql.append(" group by cur_date,project_id)t1) t2 ");
return sql.toString();
}
@ -98,140 +95,134 @@ public class DataResultProvider {
//时间显示间隔为5分钟
public String queryDataResultFiveMi(String projectID,String startDate,String curDate, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_five_mi " +
sql.append("select * from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_five_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.cur_date desc");
} else if (page == 0){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id order by t2.cur_date desc");
}
// System.out.println(sql.toString());
return sql.toString();
}
public String dataResultFiveMiCount(String projectID, String startDate,String curDate){
StringBuffer sql = new StringBuffer("");
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_five_mi " +
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_five_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
sql.append(" group by curDate,projectID)t1) t2 ");
// System.out.println(sql.toString());
sql.append(" group by cur_date,project_id)t1) t2 ");
return sql.toString();
}
//时间显示间隔为15分钟
public String queryDataResultFifteenMi(String projectID,String startDate,String curDate, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_fifteen_mi " +
sql.append("select * from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_fifteen_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id where t2.rn>(#{page}-1)*#{limit} and t2.rn<=#{page}*#{limit} order by t2.cur_date desc");
} else if (page == 0){
sql.append(" group by curDate,projectID)t1) t2 join project_info t3 ON t2.projectID=t3.id order by t2.curDate desc");
sql.append(" group by cur_date,project_id)t1) t2 join project_info t3 ON t2.project_id=t3.id order by t2.cur_date desc");
}
// System.out.println(sql.toString());
return sql.toString();
}
public String dataResultFifteenMiCount(String projectID, String startDate,String curDate){
StringBuffer sql = new StringBuffer("");
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by curDate) as rn from ( " +
" select projectID,curDate,sum(cast(curValue as decimal(18,2))) as curValue from data_result_five_mi " +
sql.append("select count(*) from (select *,ROW_NUMBER() over(order by cur_date) as rn from ( " +
" select project_id,cur_date,sum(cast(cur_value as decimal(18,2))) as cur_value from data_result_five_mi " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
sql.append(" group by curDate,projectID)t1) t2 ");
// System.out.println(sql.toString());
sql.append(" group by cur_date,project_id)t1) t2 ");
return sql.toString();
}
//查询冷水机参数历史数据情况
public String queryDataResultChiller(String projectID,String deviceAddr,String registerName,String startDate,String curDate, int page, int limit){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (select *,ROW_NUMBER() over(order by curDate) as rn from data_result_chiller " +
sql.append("select * from (select *,ROW_NUMBER() over(order by cur_date) as rn from data_result_chiller " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (deviceAddr!= null && !deviceAddr.equals("")) {
sql.append(" AND deviceAddr=#{deviceAddr} ");
sql.append(" AND device_addr=#{deviceAddr} ");
}
if (registerName!= null && !registerName.equals("")) {
sql.append(" AND registerName=#{registerName} ");
sql.append(" AND register_name=#{registerName} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
if ((page != 0) && (limit != 0)){
sql.append(" )T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit} order by T.curDate desc");
sql.append(" )T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit} order by T.cur_date desc");
} else if (page == 0){
sql.append(" )T order by T.curDate desc");
sql.append(" )T order by T.cur_date desc");
}
// System.out.println(sql.toString());
return sql.toString();
}
//查询记录数
public String dataResultChillerCount(String projectID,String deviceAddr,String registerName,String startDate,String curDate){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (select *,ROW_NUMBER() over(order by curDate) as rn from data_result_chiller " +
sql.append("select * from (select *,ROW_NUMBER() over(order by cur_date) as rn from data_result_chiller " +
" where 1=1 ");
if (projectID!= null && !projectID.equals("")) {
sql.append(" AND projectID=#{projectID} ");
sql.append(" AND project_id=#{projectID} ");
}
if (deviceAddr!= null && !deviceAddr.equals("")) {
sql.append(" AND deviceAddr=#{deviceAddr} ");
sql.append(" AND device_addr=#{deviceAddr} ");
}
if (registerName!= null && !registerName.equals("")) {
sql.append(" AND registerName=#{registerName} ");
sql.append(" AND register_name=#{registerName} ");
}
if (startDate!= null && !startDate.equals("")) {
sql.append(" AND curDate>=#{startDate} ");
sql.append(" AND cur_date>=#{startDate} ");
}
if (curDate!= null && !curDate.equals("")) {
sql.append(" AND curDate<=#{curDate} ");
sql.append(" AND cur_date<=#{curDate} ");
}
sql.append(" )T order by T.curDate desc");
// System.out.println(sql.toString());
sql.append(" )T order by T.cur_date desc");
return sql.toString();
}
}

3
user-service/src/main/java/com/mh/user/mapper/provider/DeviceInfoProvider.java

@ -14,10 +14,9 @@ public class DeviceInfoProvider {
sql.append(" AND project_id = #{projectID} ");
}
if (deviceType != null && !deviceType.equals("")){
sql.append(" AND deviceType = #{deviceType} ");
sql.append(" AND device_type = #{deviceType} ");
}
sql.append(" ) T ");
// System.out.println(sql.toString());
return sql.toString();
}
}

1
user-service/src/main/java/com/mh/user/mapper/provider/EnergyDataProvider.java

@ -70,6 +70,7 @@ public class EnergyDataProvider {
if (curDate != null && !curDate.equals("")) {
sql.append(" AND LEFT(cur_date,10)=#{curDate} ");
}
assert projectID != null;
if(projectID.equals("所有")){
if ((page != 0) && (limit != 0)){
sql.append(" )T where T.rn>(#{page}-1)*#{limit} and T.rn<=#{page}*#{limit} order by T.cur_date ");

21
user-service/src/main/java/com/mh/user/mapper/provider/StrategyInfoProvider.java

@ -1,21 +0,0 @@
package com.mh.user.mapper.provider;
public class StrategyInfoProvider {
public String queryStrategyInfo(String systemID,String projectID){
StringBuffer sql = new StringBuffer("");
sql.append("select * from (" +
" select *,ROW_NUMBER() over(order by id) as rn from strategy_info " +
" where 1=1 ");
if (systemID != null && !systemID.equals("")){
sql.append(" AND system_id = #{systemID} ");
}
if (projectID != null && !projectID.equals("")){
sql.append(" AND project_id = #{projectID} ");
}
sql.append(" ) T ");
System.out.println(sql.toString());
return sql.toString();
}
}

3
user-service/src/main/java/com/mh/user/model/BaseModel.java

@ -1,5 +1,6 @@
package com.mh.user.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
@ -18,10 +19,12 @@ public class BaseModel {
private String createBy;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private String lastUpdateBy;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date lastUpdateTime;
@Override

2
user-service/src/main/java/com/mh/user/model/SysMenu.java

@ -2,11 +2,13 @@ package com.mh.user.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Setter
@Getter
@ToString
public class SysMenu extends BaseModel {
private Long parentId;

4
user-service/src/main/java/com/mh/user/model/SysUser.java

@ -1,5 +1,7 @@
package com.mh.user.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.Getter;
import lombok.Setter;
@ -13,8 +15,10 @@ public class SysUser extends BaseModel {
private String userName;
@JsonIgnore
private String password;
@JsonIgnore
private String salt;
private String email;

4
user-service/src/main/java/com/mh/user/netty/EchoServer.java

@ -5,12 +5,12 @@ import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EchoServer {
private final int port;
private static final Logger log = Logger.getLogger(EchoServer.class);
public EchoServer(int port) {
this.port = port;

8
user-service/src/main/java/com/mh/user/netty/EchoServerHandler.java

@ -1,6 +1,6 @@
package com.mh.user.netty;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONObject;
import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.service.DeviceCodeParamService;
@ -12,16 +12,16 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Slf4j
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
List<DeviceCodeParamEntity> deviceCodeParamList;
private static final Logger log = Logger.getLogger(EchoServerHandler.class);
// 调用service层的接口信息
ApplicationContext context = SpringBeanUtil.getApplicationContext();
@ -178,7 +178,7 @@ public class EchoServerHandler extends ChannelInboundHandlerAdapter {
} else if (receiveStr.length() == 18) {
//冷量计返回数据解析
idleCount=1;
log.info("冷量计接收==>" + receiveStr+",长度:"+receiveStr.length());
log.info("冷量计接收==>{},长度:{}", receiveStr, receiveStr.length());
// 解析采集的报文,并保存到数据库
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisCloudOrder485(receiveStr,deviceCodeParamList.get(num) );

95
user-service/src/main/java/com/mh/user/netty/NettyChillerClient.java

@ -1,95 +0,0 @@
//package com.mh.user.netty;
//
//import io.netty.bootstrap.Bootstrap;
//import io.netty.channel.*;
//import io.netty.channel.nio.NioEventLoopGroup;
//import io.netty.channel.socket.SocketChannel;
//import io.netty.channel.socket.nio.NioSocketChannel;
//import io.netty.handler.timeout.IdleStateHandler;
//import io.netty.handler.timeout.ReadTimeoutHandler;
//import io.netty.handler.timeout.WriteTimeoutHandler;
//import lombok.Getter;
//import lombok.Setter;
//import lombok.extern.slf4j.Slf4j;
//
//import java.util.concurrent.TimeUnit;
//
///**
// * @author ljf
// * @title :
// * @description :Netty冷水机组客户端
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//@Setter
//@Getter
//public class NettyChillerClient {
//
// private volatile static NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient();
//
// private int port;
// private String host;
//
// // 构造函数传递值 继承Thread时需要
//// public NettyClient(int port, String host) {
//// this.port = port;
//// this.host = host;
//// }
//
// public static void connect(int port, String host) throws InterruptedException {
// // 配置客户端NIO线程组
// EventLoopGroup group = new NioEventLoopGroup(1);
// try {
// Bootstrap bootstrap = new Bootstrap();
// bootstrap.group(group).channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// protected void initChannel(SocketChannel socketChannel) {
// // 基于换行符号
//// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
//// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
// socketChannel.pipeline().addLast(new IdleStateHandler(10,10,10, TimeUnit.SECONDS));
// // 在管道中添加我们自己的接收数据实现方法
// socketChannel.pipeline().addLast(new NettyChillerClientHandler());
//// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
// }
// });
// // 发起异步连接操作
// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
// if (channelFuture.isSuccess()) {
// log.info("connect server 成功---------");
// } else {
// log.info("连接失败!");
// log.info("准备重连!");
//// connect(port, host);
// }
//
// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
// channelFuture.channel().closeFuture().sync();
// } catch (Exception e) {
// log.error("error>>>>>>" + e.getMessage());
// } finally {
// group.shutdownGracefully();
//// try {
//// TimeUnit.SECONDS.sleep(5);
//// connect(port, host); // 断线重连
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
// }
// }
//
//// @SneakyThrows
//// @Override
//// public void run() {
//// connect(port, host);
//// }
//}

315
user-service/src/main/java/com/mh/user/netty/NettyChillerClientHandler.java

@ -1,315 +0,0 @@
//package com.mh.user.netty;
//
//import com.mh.user.constants.Constant;
//import com.mh.user.entity.ChillersEntity;
//import com.mh.user.entity.DeviceCodeParamEntity;
//import com.mh.user.service.DeviceCodeParamService;
//import com.mh.user.service.chillers.ChillersService;
//import com.mh.user.service.chillers.GatewayManageService;
//import com.mh.user.utils.AnalysisReceiveOrder485;
//import com.mh.user.utils.ExchangeStringUtil;
//import com.mh.user.utils.GetReadOrder485;
//import com.mh.user.utils.SpringBeanUtil;
//import io.netty.buffer.ByteBuf;
//import io.netty.channel.Channel;
//import io.netty.channel.ChannelHandlerAdapter;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.handler.timeout.IdleState;
//import io.netty.handler.timeout.IdleStateEvent;
//import io.netty.util.ReferenceCountUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.ApplicationContext;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//
///**
// * @author ljf
// * @title :
// * @description :客户端异步消息处理机制,采集冷水机组
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//public class NettyChillerClientHandler extends ChannelHandlerAdapter {
//
// private int num = 0;
// private int size = 0;
// private int idle_count = 0;
// private String receiveStr = "";
// List<DeviceCodeParamEntity> deviceCodeParamList;
//
// // 调用service
// ApplicationContext context = SpringBeanUtil.getApplicationContext();
// DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class);
// GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class);
//
// /**
// * 超时处理
// * 如果120秒没有接受客户端的心跳,就触发;
// * 如果超过3次,则直接关闭;
// */
// @Override
// public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
// if (obj instanceof IdleStateEvent) {
// IdleStateEvent event = (IdleStateEvent) obj;
// if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
// System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据");
// if (deviceCodeParamList.get(num) == null) {
// System.out.println("关闭这个不活跃的channel");
// ctx.channel().close();
// } else {
// if ((num > size - 1) || (idle_count > 3)) {
// System.out.println("关闭这个不活跃的channel");
// ctx.channel().close();
// }
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
// ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr));
// idle_count++;
// }
// }
// } else {
// super.userEventTriggered(ctx, obj);
// }
// }
//
// @Override
// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// log.info("当前channel从EventLoop取消注册");
// ctx.close();
// super.channelUnregistered(ctx);
// }
//
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//// super.exceptionCaught(ctx, cause);
// log.info("通信异常!!");
//// // 发送采集冷水机组指令
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
//// // 获取采集参数个数
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// receiveStr = null;
// cause.printStackTrace();
// ctx.close();
//// Channel incoming = ctx.channel();
//// if (incoming.isActive()) {
//// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
//// cause.printStackTrace();
//// ctx.close();
//// receiveStr = null;
//// try {
//// TimeUnit.SECONDS.sleep(5);
//// SocketAddress remoteAddress = ctx.channel().remoteAddress();
//// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
//// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
//// NettyClient nettyClient = new NettyClient();
//// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
//// }
// }
//
//
// @Override
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
// super.channelActive(ctx);
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// if (Constant.WEB_FLAG) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
// } else {
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
// Date date = new Date();
// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// // 截取IP地址
// String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// // 截取端口号
// String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
// log.info("IP: " + IP + ",端口号: " + port);
// // 更新对应的网关在线情况
// gatewayManageService.updateGatewayManage(IP, port);
// // 生成采集指令
// deviceCodeParamList = deviceCodeParamService.queryCodeParam(port);
// size = deviceCodeParamList.size();
//
// // 发送采集冷水机组指令
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
// // 获取采集参数个数
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 发送数据
// ctx.channel().writeAndFlush(buffer);
// }
// }
//
// private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// // byte类型的数据
//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
//// String sendStr = "5803004900021914"; // 冷量计
// // 申请一个数据结构存储信息
// ByteBuf buffer = ctx.alloc().buffer();
// // 将信息放入数据结构中
// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
// return buffer;
// }
//
// @Override
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// Thread.sleep(100);
// ctx.close();
// log.info(ctx.channel().localAddress() + "退出链接!!");
// }
//
// @Override
// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// try {
// ByteBuf buf = (ByteBuf) msg;
// byte[] bytes = new byte[buf.readableBytes()];
// buf.readBytes(bytes);//复制内容到字节数组bytes
// buf.clear();
// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
// if (bytes.length <= 36) {
//// receiveStr = receiveStr.replace("null", "");
//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// receiveStr = receiveStr.replace("null", "");
// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// ReferenceCountUtil.release(msg);
// }
// }
//
// @Override
// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// log.info("冷水机组--数据读取接收完成: " + receiveStr);
// if (receiveStr.length() == 30) {
// log.info("采集完整的报文: " + receiveStr);
// // 解析采集的报文,并保存到数据库
// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
// analysisReceiveOrder485.analysisChillerOrder485(receiveStr,deviceCodeParamList.get(num));
// // 清空receiveStr
// receiveStr = "";
// // 判断发送的下标,如果不等于指令数组大小
// num = num + 1;
// if (num > size - 1) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
//// // 继续发送下一个采集冷水机设备指令
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// } else {
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// if (Constant.WEB_FLAG) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
// } else {
// Thread.sleep(1000);
// // 继续发送下一个采集冷水机设备指令
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// }
// }
// } else if (receiveStr.length() == 32) {
// log.info("采集完整的报文: " + receiveStr);
// // 解析采集的报文,并保存到数据库
// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
// analysisReceiveOrder485.analysisChillerOrder485(receiveStr,deviceCodeParamList.get(num));
// // 清空receiveStr
// receiveStr = "";
// // 判断发送的下标,如果不等于指令数组大小
// num = num + 1;
// if (num > size - 1) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
//// // 继续发送下一个采集冷水机设备指令
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// } else {
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// if (Constant.WEB_FLAG) {
// log.info("有指令下发退出定时采集冷水机组参数");
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
// } else {
// Thread.sleep(1000);
// // 继续发送下一个采集冷水机设备指令
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// }
// }
// } else if (receiveStr.length() > 36) {
// // 清空receiveStr
// receiveStr = null;
// // 判断发送的下标,如果不等于指令数组大小
// num = num + 1;
// if (num > size - 1) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
//// // 继续发送下一个采集冷水机设备指令
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// } else {
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// if (Constant.WEB_FLAG) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
// } else {
// Thread.sleep(1000);
// // 继续发送下一个采集冷水机设备指令
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
// }
// }
// }
// ctx.flush();
// }
//
//}

98
user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java

@ -1,98 +0,0 @@
package com.mh.user.netty;
import com.mh.user.entity.OrderMessageEntity;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author ljf
* @title
* @description 控制冷水机组和其他设备
* @updateTime 2020-05-28
* @throws
*/
@Setter
@Getter
@Slf4j
public class NettyChillerControlClient {
// private int port;
// private String host;
// private List<OrderMessageEntity> orderMessageEntityList;
// 构造函数传递值 继承Thread时需要
// public NettyChillerControlClient(int port, String host) {
// this.port = port;
// this.host = host;
// }
public void connect(int port, String host, List<OrderMessageEntity> orderMessageEntityList) throws InterruptedException {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 基于换行符号
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
// 超过10秒钟没有数据读取自动断开连接
// socketChannel.pipeline().addLast(new ReadTimeoutHandler(30));
// 超过10秒没有返回触发心跳机制 update by ljf on 2021-01-30
socketChannel.pipeline().addLast(new IdleStateHandler(10,10,6, TimeUnit.SECONDS));
// 在管道中添加我们自己的接收数据实现方法
socketChannel.pipeline().addLast(new NettyChillerControlHandler(orderMessageEntityList));
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
}
});
// 发起异步连接操作
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
if (channelFuture.isSuccess()) {
log.info("connect server 成功---------");
} else {
log.info("连接失败!");
log.info("准备重连!");
// connect(port, host);
}
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
group.shutdownGracefully();
// try {
// TimeUnit.SECONDS.sleep(5);
// connect(port, host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
// @SneakyThrows
// @Override
// public void run() {
// connect(port, host);
// }
}

315
user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java

@ -1,315 +0,0 @@
package com.mh.user.netty;
import com.mh.user.entity.OrderMessageEntity;
import com.mh.user.service.chillers.GatewayManageService;
import com.mh.user.service.chillers.OrderMessageService;
import com.mh.user.utils.AnalysisReceiveOrder485;
import com.mh.user.constants.Constant;
import com.mh.user.utils.ExchangeStringUtil;
import com.mh.user.utils.GetReadOrder485;
import com.mh.user.utils.SpringBeanUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author ljf
* @title
* @description 客户端异步消息处理机制
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
public class NettyChillerControlHandler extends ChannelHandlerAdapter {
private int num = 0;
private int size = 0;
private String receiveStr = "";
private int sendNum = 0;
private int idle_count = 1;
List<OrderMessageEntity> orderMessageEntityList;
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class);
OrderMessageService orderMessageService = context.getBean(OrderMessageService.class);
public NettyChillerControlHandler(List<OrderMessageEntity> orderMessageEntityList) {
this.orderMessageEntityList = orderMessageEntityList;
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册");
// Constant.SEND_STATUS = false;
// super.channelUnregistered(ctx);
ctx.close();
}
/**
* 超时处理
* 如果120秒没有接受客户端的心跳就触发;
* 如果超过3次则直接关闭;
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
if (obj instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) obj;
if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据");
if (num > size - 1) {
num = 0;
// 关闭连接
receiveStr = null;
Constant.SEND_STATUS = true;
System.out.println("关闭这个不活跃的channel");
ctx.close();
} else if (idle_count > 3) {
System.out.println("关闭这个不活跃的channel");
num = 0;
// 关闭连接
receiveStr = null;
Constant.SEND_STATUS = false;
ctx.close();
} else {
// 发送采集DDC指令
// 判断空值
if (orderMessageEntityList.get(num).getRegisterAddr() == null ||
orderMessageEntityList.get(num).getRegisterAddr().equalsIgnoreCase("")) {
num = 0;
// 关闭连接
receiveStr = null;
Constant.SEND_STATUS = true;
ctx.close();
} else {
String sendStr = orderMessageEntityList.get(num).getOrderStr();
// // 获取采集参数个数
// size = orderMessageEntityList.size();
// 2.发送数据
ByteBuf buffer = getByteBuf(ctx, sendStr);
ctx.channel().writeAndFlush(buffer);
idle_count++;
}
}
}
} else {
super.userEventTriggered(ctx, obj);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
log.info("通信异常!!");
cause.printStackTrace();
// receiveStr = null;
// Channel incoming = ctx.channel();
// if (incoming.isActive()) {
// // 重新发送
// if (sendNum > 2) {
// // 通信异常,发送失败
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
// cause.printStackTrace();
// Constant.SEND_STATUS = false;
// ctx.close();
// } else {
// // 发送采集DDC指令
// String sendStr = orderMessageEntityList.get(num).getOrderStr();
// // 获取采集参数个数
// size = orderMessageEntityList.size();
// // 2.发送数据
// ByteBuf buffer = getByteBuf(ctx,sendStr);
// ctx.channel().writeAndFlush(buffer);
// sendNum += 1;
// }
// }
// // 判断发送的下标,如果不等于指令数组大小
// num = num + 1;
// if (num > size-1) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// Constant.SEND_STATUS = true;
// ctx.close();
// }
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date=new Date();
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// 截取IP地址
String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"","/", ":");
// 截取端口号
String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"",":", "");
log.info("IP: " + IP + ",端口号: " + port);
// 更新对应的网关在线情况
gatewayManageService.updateGatewayManage(IP, port);
// 发送控制DDC指令
String sendStr = orderMessageEntityList.get(num).getOrderStr();
// 获取采集参数个数
size = orderMessageEntityList.size();
// 2.发送数据
ByteBuf buffer = getByteBuf(ctx,sendStr);
ctx.channel().writeAndFlush(buffer);
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// Thread.sleep(100);
ctx.close();
log.info(ctx.channel().localAddress() + "退出链接!!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// super.channelRead(ctx, msg);
// ByteBuf buf = (ByteBuf)msg;
// byte[] req = new byte[buf.readableBytes()];
// buf.readBytes(req);
// String body = new String(req, "UTF-8");
try {
ByteBuf buf = (ByteBuf)msg;
byte [] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
buf.clear();
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
// if (bytes.length <= 24) {
if (bytes.length != 0) {
// receiveStr = receiveStr.replace("null", "");
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
receiveStr = receiveStr.replace("null", "");
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
log.info("数据读取接收完成: " + receiveStr);
if (receiveStr.length() == 24) {
if (receiveStr.equalsIgnoreCase(orderMessageEntityList.get(num).getOrderStr())) {
// 解析采集回来的数据
log.info("采集完整的报文: " + receiveStr + ",指令下标: " + size);
// 解析采集的报文
// 更新发送后的指令
OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
orderMessageEntity.setGrade(1);
orderMessageEntity.setSendNum(1);
orderMessageEntity.setStatus(1);
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
orderMessageService.updateOrderMessage(orderMessageEntity);
// // 关闭连接
// receiveStr = null;
// Constant.SEND_STATUS = true;
// ctx.close();
// 清空receiveStr
receiveStr = "";
// 判断发送的下标,如果不等于指令数组大小
num = num + 1;
if (num > size - 1) {
num = 0;
// 关闭连接
receiveStr = null;
Constant.SEND_STATUS = true;
ctx.close();
} else {
Thread.sleep(4000);
// 继续发送下一个采集DDC设备指令
String sendStr = orderMessageEntityList.get(num).getOrderStr();
ByteBuf buffer = getByteBuf(ctx, sendStr);
// 2.发送数据
ctx.channel().writeAndFlush(buffer);
log.info("客户端再次往服务端发送数据" + num + ",报文: " + sendStr);
}
}
} else if ((receiveStr.length() > 24) && (num == 0)) {
// 发送采集DDC指令
String sendStr = orderMessageEntityList.get(num).getOrderStr();
// 获取采集参数个数
size = orderMessageEntityList.size();
// 2.发送数据
ByteBuf buffer = getByteBuf(ctx,sendStr);
ctx.channel().writeAndFlush(buffer);
// 清空receiveStr
receiveStr = "";
sendNum += 1;
} else if (sendNum > 2){
// 更新发送后的指令
OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
orderMessageEntity.setGrade(1);
orderMessageEntity.setSendNum(sendNum);
orderMessageEntity.setStatus(0);
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
orderMessageService.updateOrderMessage(orderMessageEntity);
Constant.SEND_STATUS = false;
ctx.close();
} else if ((receiveStr.length() > 24)) {
// 接收采集DDC的数据
// 解析采集的报文
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisChillersDDC(receiveStr);
// 清空receiveStr
receiveStr = "";
// 更新发送后的指令
OrderMessageEntity orderMessageEntity = new OrderMessageEntity();
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr());
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime());
orderMessageEntity.setGrade(1);
orderMessageEntity.setSendNum(1);
orderMessageEntity.setStatus(1);
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr());
orderMessageService.updateOrderMessage(orderMessageEntity);
// 判断发送的下标,如果不等于指令数组大小
num = num + 1;
// Thread.sleep(500);
if (num > size-1) {
num = 0;
// 关闭连接
receiveStr = null;
Constant.SEND_STATUS = true;
ctx.close();
}
}
ctx.flush();
}
}

96
user-service/src/main/java/com/mh/user/netty/NettyChillerDDCClient.java

@ -1,96 +0,0 @@
package com.mh.user.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* @author ljf
* @title
* @description Netty客户端采集DDC设备数据
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
@Setter
@Getter
public class NettyChillerDDCClient {
private volatile static NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient();
private int port;
private String host;
// 构造函数传递值 继承Thread时需要
// public NettyClient(int port, String host) {
// this.port = port;
// this.host = host;
// }
public static void connect(int port, String host) throws InterruptedException {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 基于换行符号
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
// 超过10秒钟没有数据读取自动断开连接
// socketChannel.pipeline().addLast(new ReadTimeoutHandler(40));
socketChannel.pipeline().addLast(new IdleStateHandler(20,20,20, TimeUnit.SECONDS));
// 在管道中添加我们自己的接收数据实现方法
socketChannel.pipeline().addLast(new NettyChillerDDCClientHandler());
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
}
});
// 发起异步连接操作
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
if (channelFuture.isSuccess()) {
log.info("connect server 成功---------");
} else {
log.info("连接失败!");
log.info("准备重连!");
// connect(port, host);
}
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
group.shutdownGracefully();
// try {
// TimeUnit.SECONDS.sleep(5);
// connect(port, host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
// @SneakyThrows
// @Override
// public void run() {
// connect(port, host);
// }
}

297
user-service/src/main/java/com/mh/user/netty/NettyChillerDDCClientHandler.java

@ -1,297 +0,0 @@
package com.mh.user.netty;
import com.mh.user.constants.Constant;
import com.mh.user.entity.ChillersEntity;
import com.mh.user.service.chillers.ChillersService;
import com.mh.user.service.chillers.GatewayManageService;
import com.mh.user.utils.AnalysisReceiveOrder485;
import com.mh.user.utils.ExchangeStringUtil;
import com.mh.user.utils.GetReadOrder485;
import com.mh.user.utils.SpringBeanUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author ljf
* @title
* @description 客户端异步消息处理机制
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
public class NettyChillerDDCClientHandler extends ChannelHandlerAdapter {
private int num = 0;
private int size = 0;
private int collectionSize = 0;
private String receiveStr = null;
private int idle_count = 0;
List<ChillersEntity> chillersEntityList;
List<ChillersEntity> chillersEntityList1;
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
ChillersService chillersService = context.getBean(ChillersService.class);
GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class);
/**
* 超时处理
* 如果120秒没有接受客户端的心跳就触发;
* 如果超过3次则直接关闭;
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
if (obj instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) obj;
if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据");
if (chillersEntityList.get(num) == null) {
ctx.close();
} else {
String sendStr = GetReadOrder485.createDDCOrder(chillersEntityList.get(num));
ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr));
if ((num > size - 1) || (idle_count > 3)) {
//System.out.println("关闭这个不活跃的channel");
//ctx.close();
//继续发送下一个ddc采集指令
log.info("当前DDC无返回数据超过三次,DDC为:"+chillersEntityList.get(num).getDdcAddr());
if (num >= size - 1){
log.info("结束DDC采集,当前DDC=====>>>"+chillersEntityList.get(num).getDdcAddr());
ctx.close();
}else {
//下发下一个ddc指令之前清除前面的数据
receiveStr = null;
//String sendStr1 = GetReadOrder485.createDDCOrder(chillersEntityList.get(++num));
//ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr1));
num++;
sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
}
idle_count = 0;
}
idle_count++;
}
}
} else {
super.userEventTriggered(ctx, obj);
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册");
super.channelUnregistered(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
log.info("通信异常!!");
receiveStr = null;
cause.printStackTrace();
ctx.close();
// Channel incoming = ctx.channel();
// if (incoming.isActive()) {
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
// cause.printStackTrace();
// ctx.close();
// receiveStr = null;
// try {
// TimeUnit.SECONDS.sleep(5);
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
// NettyClient nettyClient = new NettyClient();
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.CONTROL_WEB_FLAG) {
// 关闭连接
receiveStr = null;
ctx.close();
} else {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = new Date();
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// 截取IP地址
String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// 截取端口号
String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
log.info("IP: " + IP + ",端口号: " + port);
// 更新对应的网关在线情况
gatewayManageService.updateGatewayManage(IP, port);
// 生成采集指令
chillersEntityList = chillersService.queryChillersDDC(2);
size = chillersEntityList.size();
// 发送采集DDC指令
String sendStr = GetReadOrder485.createDDCOrder(chillersEntityList.get(num));
// 获取采集参数个数,grade=2,代表采集DDC设备所对应的参数
chillersEntityList1 = chillersService.queryChillersByOther(2, chillersEntityList.get(num).getDdcAddr());
StringBuffer getStr = new StringBuffer();
for (int i = 0; i < chillersEntityList1.size(); i++) {
getStr.append(chillersEntityList1.get(i).getRegisterAddress());
// getStr = getStr + chillersEntityList1.get(i).getRegisterAddress();
}
collectionSize = getStr.length() / 2;
log.info("发送的数据: " + sendStr + ",报文大小: " + collectionSize);
ByteBuf buffer = getByteBuf(ctx, sendStr);
// 2.发送数据
ctx.channel().writeAndFlush(buffer);
}
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// byte类型的数据
// 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Thread.sleep(100);
ctx.close();
log.info(ctx.channel().localAddress() + "退出链接!!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
buf.clear();
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
if (bytes.length <= (11 + collectionSize * 3) * 2) {
// if (bytes.length <= 142) {
// receiveStr = receiveStr.replace("null", "");
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
receiveStr = receiveStr.replace("null", "");
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
log.info("接收的数据: " + receiveStr + ",报文大小: " + collectionSize);
if (receiveStr.length() == (11 + 3 * collectionSize) * 2) {
// if (receiveStr.length() == 142) {
// 解析采集回来的数据
log.info("采集完整的报文: " + receiveStr);
if (!Constant.CONTROL_WEB_FLAG) {
// 解析采集的报文
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisChillersDDC(receiveStr);
}
// 清空receiveStr
receiveStr = "";
// 判断发送的下标,如果不等于指令数组大小
num = num + 1;
if (num > size - 1) {
// 关闭连接
receiveStr = null;
ctx.close();
// // 设置长连接,封装发送 update by ljf on 2021-01-26
// sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
} else {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.CONTROL_WEB_FLAG) {
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 设置长连接,封装发送 update by ljf on 2021-01-26
sendDDCOrder(chillersEntityList, chillersEntityList.get(num), ctx, num);
}
}
} else if (receiveStr.length() == 20) {
// if (receiveStr.length() == 142) {
// 解析采集回来的数据
log.info("采集完整的报文: " + receiveStr);
// 清空receiveStr
receiveStr = "";
// 判断发送的下标,如果不等于指令数组大小
num = num + 1;
if (num > size - 1) {
// 关闭连接
receiveStr = null;
ctx.close();
// // 设置长连接,封装发送 update by ljf on 2021-01-26
// sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
} else {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.CONTROL_WEB_FLAG) {
log.info("有指令下发退出定时采集DDC参数");
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 封装发送
sendDDCOrder(chillersEntityList, chillersEntityList.get(num), ctx, num);
}
}
}else if (receiveStr.length() > (11 + 3 * collectionSize) * 2){
log.info("当前DDC: "+chillersEntityList.get(num).getDdcAddr()+"长度为: "+receiveStr.length());
receiveStr = null;
//继续后面的DDC采集
//String sendStr1 = GetReadOrder485.createDDCOrder(chillersEntityList.get(++num));
//ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr1));
num++;
sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
}
ctx.flush();
}
public void sendDDCOrder(List<ChillersEntity> chillersEntityList,
ChillersEntity chillersEntity,
ChannelHandlerContext ctx,
int num) throws InterruptedException {
Thread.sleep(800);
// 继续发送下一个采集DDC设备指令
String sendStr = GetReadOrder485.createDDCOrder(chillersEntity);
// 获取采集参数个数,grade=2,代表采集DDC设备所对应的参数
chillersEntityList1 = chillersService.queryChillersByOther(2, chillersEntityList.get(num).getDdcAddr());
StringBuilder getStr = new StringBuilder();
for (ChillersEntity entity : chillersEntityList1) {
getStr.append(entity.getRegisterAddress());
}
collectionSize = getStr.length() / 2;
log.info("发送的数据: " + sendStr + ",报文大小: " + collectionSize);
log.info("客户端再次往服务端发送数据 " + num + "," + sendStr);
ByteBuf buffer = getByteBuf(ctx, sendStr);
// 2.发送数据
ctx.channel().writeAndFlush(buffer);
}
}

90
user-service/src/main/java/com/mh/user/netty/NettyClient.java

@ -1,90 +0,0 @@
package com.mh.user.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* @author ljf
* @title
* @description Netty客户端采集冷量计
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
@Setter
@Getter
public class NettyClient {
private int port;
private String host;
// 构造函数传递值 继承Thread时需要
// public NettyClient(int port, String host) {
// this.port = port;
// this.host = host;
// }
public void connect(int port, String host) throws InterruptedException {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 基于换行符号
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
// 超过10秒钟没有数据读取自动断开连接
socketChannel.pipeline().addLast(new ReadTimeoutHandler(10));
// 在管道中添加我们自己的接收数据实现方法
socketChannel.pipeline().addLast(new NettyClientHandler());
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
}
});
// 发起异步连接操作
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
if (channelFuture.isSuccess()) {
log.info("connect server 成功---------");
} else {
log.info("连接失败!");
log.info("准备重连!");
// connect(port, host);
}
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
group.shutdownGracefully();
// try {
// TimeUnit.SECONDS.sleep(5);
// connect(port, host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
// @SneakyThrows
// @Override
// public void run() {
// connect(port, host);
// }
}

190
user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java

@ -1,190 +0,0 @@
package com.mh.user.netty;
import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.service.chillers.DeviceManageService;
import com.mh.user.utils.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author ljf
* @title
* @description 客户端异步消息处理机制
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
public class NettyClientHandler extends ChannelHandlerAdapter {
private int num = 0;
private int size = 0;
private String receiveStr = null;
private String IP = null;
private String port = null;
List<DeviceCodeParamEntity> deviceManageEntityList;
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class);
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册");
super.channelUnregistered(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
log.info("通信异常!!");
receiveStr = null;
Channel incoming = ctx.channel();
if (incoming.isActive()){
log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
cause.printStackTrace();
ctx.close();
// receiveStr = null;
// try {
// TimeUnit.SECONDS.sleep(5);
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
// NettyClient nettyClient = new NettyClient();
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) {
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
ctx.channel().read();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = new Date();
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// 截取IP地址
IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// 截取端口号
port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
log.info("IP: " + IP + ",端口号: " + port);
// 生成对应采集冷量计的命令
deviceManageEntityList = deviceCodeParamService.queryCodeParam(port);
size = deviceManageEntityList.size();
// 封装工具类进行采集,update by ljf on 2021-01-26
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),ctx,num,size);
}
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// byte类型的数据
// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
// String sendStr = "5803004900021914"; // 冷量计
// 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Thread.sleep(100);
ctx.close();
log.info(ctx.channel().localAddress() + "退出链接!!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte [] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
buf.clear();
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
if (bytes.length <= 36) {
// receiveStr = receiveStr.replace("null", "");
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
receiveStr = receiveStr.replace("null", "");
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
log.info("采集冷量计-数据读取接收完成: " + receiveStr);
// A9 FE C2 C7 1F 90 01 58 03 04 4A 30 00 53 65 1C C4 06
if (receiveStr.length() == 36) {
// 接收到的报文
log.info("接收完整报文: " + receiveStr);
// 解析报文
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
analysisReceiveOrder485.analysisCloudOrder485(receiveStr,deviceManageEntityList.get(num)); // 解析冷量计
receiveStr = "";
// 1.创建将要写出的数据
// String sendStr = "5803004900021914";
num = num + 1;
Thread.sleep(500);
if (num > size-1) {
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
// 保持长连接
// // 封装工具类进行采集,update by ljf on 2021-01-26
// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
} else {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) {
log.info("有指令下发退出定时采集参数");
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 封装工具类进行采集,update by ljf on 2021-01-26
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),ctx,num,size);
}
}
} else {
log.info(receiveStr);
receiveStr = null;
ctx.flush();
ctx.close();
}
ctx.flush();
}
}

180
user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java

@ -1,180 +0,0 @@
package com.mh.user.netty;
import com.mh.user.utils.ExchangeStringUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* @author ljf
* @title Netty
* @description netty 使用
* @updateTime 2020-04-21
* @throws
*/
@Slf4j
public class NettyEchoServer {
public void bind(int port) throws Exception {
// accept线程组,用来接收连接
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// IO 线程组,用来处理业务逻辑
EventLoopGroup workerGroup = new NioEventLoopGroup(1);
try {
// 服务端启动引导
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
.channel(NioServerSocketChannel.class) // 指定通道类型
.option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
.handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
}
});
// 通过bind启动服务
ChannelFuture f = serverBootstrap.bind(port).sync();
// 阻塞主线程,知道网络服务被关闭
f.channel().closeFuture().sync();
} catch (Exception e){
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
static class EchoServerHandler extends ChannelHandlerAdapter {
// 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte [] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
log.info("接收到的数据: "+ receiveStr);
//返回16进制到客户端
writeToClient(receiveStr,ctx,"测试");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
// ctx.fireChannelRead(msg);
}
// 数据读取完后被调用
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
// 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
/**
* 客户端与服务端第一次建立连接时 执行
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
{
super.channelActive(ctx);
ctx.channel().read();
InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = ifsock.getAddress().getHostAddress();
//此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
log.info("channelActive: "+clientIp + ctx.name());
}
/**
* 客户端与服务端 断连时 执行
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
{
super.channelInactive(ctx);
InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = ifsock.getAddress().getHostAddress();
ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
System.out.println("channelInactive:"+clientIp);
}
/**
* 服务端当read超时, 会调用这个方法
*
* @param ctx
* @param evt
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
{
super.userEventTriggered(ctx, evt);
InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = ifsock.getAddress().getHostAddress();
ctx.close();//超时时断开连接
System.out.println("userEventTriggered:"+clientIp);
}
/**
* 公用回写数据到客户端的方法
* @param channel
* @param mark 用于打印/log的输出
* <br>//channel.writeAndFlush(msg);//不行
* <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
* <br>在netty里进出的都是ByteBuf楼主应确定服务端是否有对应的编码器将字符串转化为ByteBuf
*/
private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) {
try {
ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
channel.writeAndFlush(buff).addListener((ChannelFutureListener) future -> {
StringBuilder sb = new StringBuilder("");
if(!StringUtils.isEmpty(mark)){
sb.append("【").append(mark).append("】");
}
if (future.isSuccess()) {
System.out.println(sb.toString()+"回写成功"+receiveStr);
log.info(sb.toString()+"回写成功"+receiveStr);
} else {
System.out.println(sb.toString()+"回写失败"+receiveStr);
log.error(sb.toString()+"回写失败"+receiveStr);
}
});
} catch (Exception e) {
e.printStackTrace();
System.out.println("调用通用writeToClient()异常"+e.getMessage());
log.error("调用通用writeToClient()异常:",e);
}
}
}
}

95
user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java

@ -1,95 +0,0 @@
package com.mh.user.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* @author ljf
* @title
* @description Netty客户端采集电表
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
@Setter
@Getter
public class NettyMeterClient {
// implements Runnable {
private int port;
private String host;
// 构造函数传递值 继承Thread时需要
public NettyMeterClient(int port, String host) {
this.port = port;
this.host = host;
}
public NettyMeterClient() {
super();
}
public void connect(int port, String host) throws InterruptedException {
// 配置客户端NIO线程组
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 基于换行符号
// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
// 超过10秒钟没有数据读取自动断开连接
socketChannel.pipeline().addLast(new ReadTimeoutHandler(20));
// 在管道中添加我们自己的接收数据实现方法
// socketChannel.pipeline().addLast(new NettyClientHandler());
socketChannel.pipeline().addLast(new NettyMeterClientHandler());
}
});
// 发起异步连接操作
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
if (channelFuture.isSuccess()) {
log.info("connect server 成功---------");
} else {
log.info("连接失败!");
log.info("准备重连!");
// connect(port, host);
}
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
group.shutdownGracefully();
// try {
// TimeUnit.SECONDS.sleep(5);
// connect(port, host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
//
// @SneakyThrows
// @Override
// public void run() {
// connect(port, host);
// }
}

261
user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler.java

@ -1,261 +0,0 @@
package com.mh.user.netty;
import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.service.chillers.DeviceManageService;
import com.mh.user.utils.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author ljf
* @title
* @description 客户端异步消息处理机制
* @updateTime 2020-05-13
* @throws
*/
@Slf4j
public class NettyMeterClientHandler extends ChannelHandlerAdapter {
private int num = 0;
private int size = 0;
private String receiveStr = null;
private String IP = "";
private String port = "";
List<DeviceCodeParamEntity> deviceManageEntityList;
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class);
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册");
super.channelUnregistered(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
log.info("通信异常!!");
// receiveStr = null;
Channel incoming = ctx.channel();
if (incoming.isActive()) {
log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
receiveStr = null;
cause.printStackTrace();
ctx.close();
// receiveStr = null;
// try {
// TimeUnit.SECONDS.sleep(5);
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
// NettyClient nettyClient = new NettyClient();
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// super.channelActive(ctx);
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) {
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
ctx.channel().read();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = new Date();
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// 截取IP地址
IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// 截取端口号
port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
log.info("IP: " + IP + ",端口号: " + port);
// 生成对应的采集指令
// 修改生成指令(冷量计和电量一起采集) update by ljf on 2021-01-27
deviceManageEntityList = deviceCodeParamService.queryCodeParam(port);
size = deviceManageEntityList.size();
log.info("初始连接报文: " + receiveStr);
receiveStr = "";
// 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(0),ctx,num,size);
// 1.创建将要写出的数据
// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
// deviceManageEntityList.get(0).getDataCom(), collectionNum, "1");
//// FileUtils.createFileAndWrite(sendStr, 0);
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
}
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// byte类型的数据
// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
// String sendStr = "5803004900021914"; // 冷量计
// 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Thread.sleep(500);
receiveStr = null;
ctx.close();
log.info(ctx.channel().localAddress() + "退出链接!!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);//复制内容到字节数组bytes
buf.clear();
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
if (bytes.length <= 62) {
// if (bytes.length <= 142) {
// receiveStr = receiveStr.replace("null", "");
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
receiveStr = receiveStr.replace("null", "");
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
// super.channelRead(ctx, msg);
// ByteBuf buf = (ByteBuf)msg;
// byte[] req = new byte[buf.readableBytes()];
// buf.readBytes(req);
// String body = new String(req, "UTF-8");
// ByteBuf buf = (ByteBuf)msg;
// byte [] bytes = new byte[buf.readableBytes()];
// buf.readBytes(bytes);//复制内容到字节数组bytes
// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
// if (bytes.length != 0) {
//// receiveStr = receiveStr.replace("null", "");
//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// receiveStr = receiveStr.replace("null", "");
// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
// }
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
log.info("采集电表-数据读取接收完成: " + receiveStr);
// 把receiveStr的"null"值去掉
// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
if ((receiveStr.length() == 62)) {
// log.info(receiveStr);
analysisReceiveOrder485.analysisMeterOrder485(receiveStr,deviceManageEntityList.get(num)); // 解析电表
receiveStr = "";
num = num + 1;
Thread.sleep(600);
if (num > size - 1) {
num = 0;
receiveStr = null;
// 关闭连接
ctx.close();
// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
} else {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) {
log.info("有指令下发退出定时采集DDC参数");
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 封装发送电表工具方法 update by ljf on 2021-01-26
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),ctx,num,size);
// 1.创建将要写出的数据
// fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
// String sendStr = "FEFEFE6880025007000068010243C3B216";
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num);
}
}
} else if ((receiveStr.length() > 62)) {
receiveStr = null;
num = num + 1;
Thread.sleep(500);
if (num > size - 1) {
num = 0;
receiveStr = null;
// 关闭连接
ctx.close();
// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
} else {
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) {
log.info("有指令下发退出定时采集DDC参数");
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 封装发送电表工具方法 update by ljf on 2021-01-26
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),ctx,num,size);
// 1.创建将要写出的数据
// fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
// String sendStr = "FEFEFE6880025007000068010243C3B216";
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num);
}
}
}
ctx.flush();
}
}

7
user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java

@ -5,15 +5,11 @@ import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
//import purejavacomm.SerialPort;
import gnu.io.SerialPort;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
@ -24,7 +20,7 @@ import java.util.List;
* @throws
*/
//@Slf4j
@Slf4j
public class SerialPortSendReceive {
private String receiveStr = null;
@ -33,7 +29,6 @@ public class SerialPortSendReceive {
private int baudrate=9600;
private String parity=null;
List<DeviceCodeParamEntity> deviceManageEntityList;
private static final Logger log = Logger.getLogger(SerialPortSendReceive.class);
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();
DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class);

7
user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java

@ -7,15 +7,11 @@ import com.mh.user.utils.AnalysisReceiveOrder485;
import com.mh.user.utils.SendOrderUtils;
import com.mh.user.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
//import purejavacomm.SerialPort;
import gnu.io.SerialPort;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @author nxr
@ -24,13 +20,12 @@ import java.util.List;
* @updateTime 2022-08-10
* @throws
*/
//@Slf4j
@Slf4j
public class SerialPortSingle {
public SerialPort serialPort = null;
private String receiveStr = null;
private int baudrate=9600;
private static final Logger log = Logger.getLogger(SerialPortSingle.class);
// 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext();

4
user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java

@ -5,7 +5,6 @@ import com.mh.user.service.DeviceCodeParamService;
import com.mh.user.utils.*;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import java.util.List;
@ -17,10 +16,9 @@ import java.util.List;
* @throws
*/
//@Slf4j
@Slf4j
public class SerialPortThread implements Runnable{
private static final Logger log = Logger.getLogger(SerialPortThread.class);
private int num = 0;
private int size = 0;
public static SerialPort serialPort = null;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save