Browse Source

优化采集逻辑

prod_202403
mh 11 months ago
parent
commit
db2f64cd54
  1. 10
      user-service/pom.xml
  2. 10
      user-service/src/main/java/com/mh/user/controller/SerialPortController.java
  3. 4
      user-service/src/main/java/com/mh/user/job/CollectionLoopRunner.java
  4. 15
      user-service/src/main/java/com/mh/user/job/DealDataJob.java
  5. 82
      user-service/src/main/java/com/mh/user/job/JobCloud.java
  6. 78
      user-service/src/main/java/com/mh/user/job/JobMeter.java
  7. 190
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
  8. 570
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
  9. 174
      user-service/src/main/java/com/mh/user/netty/NettyClient.java
  10. 534
      user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
  11. 358
      user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
  12. 186
      user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java
  13. 384
      user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java
  14. 184
      user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
  15. 486
      user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java
  16. 6
      user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive.java
  17. 81
      user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java
  18. 4
      user-service/src/main/java/com/mh/user/serialport/SerialPortSingle.java
  19. 4
      user-service/src/main/java/com/mh/user/serialport/SerialPortSingle2.java
  20. 14
      user-service/src/main/java/com/mh/user/serialport/SerialPortThread.java
  21. 3
      user-service/src/main/java/com/mh/user/serialport/SerialTool.java
  22. 2
      user-service/src/main/java/com/mh/user/service/NowDataService.java
  23. 4
      user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java
  24. 152
      user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java
  25. 4
      user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java
  26. 44
      user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java
  27. 52
      user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java
  28. 168
      user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java
  29. 6
      user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java
  30. 41
      user-service/src/main/resources/application-prod.yml
  31. 42
      user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java
  32. 88
      user-service/src/test/java/com/mh/user/socket/NettyClientTest.java
  33. 364
      user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java

10
user-service/pom.xml

@ -74,11 +74,11 @@
<artifactId>mssql-jdbc</artifactId> <artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>io.netty</groupId> <!-- <groupId>io.netty</groupId>-->
<artifactId>netty-all</artifactId> <!-- <artifactId>netty-all</artifactId>-->
<version>5.0.0.Alpha2</version> <!-- <version>5.0.0.Alpha2</version>-->
</dependency> <!-- </dependency>-->
<!-- 登录验证码--> <!-- 登录验证码-->
<dependency> <dependency>
<groupId>com.github.penggle</groupId> <groupId>com.github.penggle</groupId>

10
user-service/src/main/java/com/mh/user/controller/SerialPortController.java

@ -56,11 +56,14 @@ public class SerialPortController {
String deviceType = serialPortModel.getDeviceType();//设备类型 String deviceType = serialPortModel.getDeviceType();//设备类型
String buildingId = serialPortModel.getBuildingId();//楼栋 String buildingId = serialPortModel.getBuildingId();//楼栋
String param = serialPortModel.getParam();//操作参数 String param = serialPortModel.getParam();//操作参数
if (deviceAddr==null || deviceAddr=="" ){ if (deviceAddr == null || deviceAddr.equals("")) {
List<DeviceModel> list = deviceInstallService.selectDevices(buildingId, deviceType); List<DeviceModel> list = deviceInstallService.selectDevices(buildingId, deviceType);
deviceAddr = list.get(0).getDeviceAddr(); deviceAddr = list.get(0).getDeviceAddr();
} }
if(deviceAddr!=null && deviceAddr.length()>0){ if (deviceAddr == null || deviceAddr.length() == 0) {
Constant.WEB_FLAG = false;
return HttpResult.error("通讯ID为空!");
}
DeviceInstallEntity deviceInstallEntity = deviceInstallService.selectDevice(deviceAddr, deviceType, buildingId); DeviceInstallEntity deviceInstallEntity = deviceInstallService.selectDevice(deviceAddr, deviceType, buildingId);
//发送指令实体类 //发送指令实体类
deviceCodeParam.setDeviceAddr(deviceAddr); //传入通讯编号 deviceCodeParam.setDeviceAddr(deviceAddr); //传入通讯编号
@ -183,9 +186,6 @@ public class SerialPortController {
nowDataService.upLevelSet(buildingId, serialPortModel.getDataValue());//更新实时状态表 nowDataService.upLevelSet(buildingId, serialPortModel.getDataValue());//更新实时状态表
} }
serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令 serialPortSingle.serialPortSend(deviceCodeParam);//生成并发送指令
}else{
return HttpResult.error("通讯ID为空!");
}
} }
Constant.WEB_FLAG = false; //单抄,恢复采集 Constant.WEB_FLAG = false; //单抄,恢复采集
return HttpResult.ok(); return HttpResult.ok();

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

@ -60,8 +60,8 @@ public class CollectionLoopRunner implements ApplicationRunner {
if (r2==0){ if (r2==0){
getReadOrder485.createOrderParam3(); //生成采集参数 getReadOrder485.createOrderParam3(); //生成采集参数
} }
// 生成指令缓存 // 分组参数缓存
//CacheUtil instance = CacheUtil.getInstance(); CacheUtil instance = CacheUtil.getInstance();
} }
public void test() throws Exception { public void test() throws Exception {

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

@ -12,8 +12,10 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
/** /**
@ -34,8 +36,7 @@ public class DealDataJob {
private static int taskTimes = 1; private static int taskTimes = 1;
public DealDataJob(DealDataService dealDataService) public DealDataJob(DealDataService dealDataService) {
{
this.dealDataService = dealDataService; this.dealDataService = dealDataService;
} }
@ -64,6 +65,7 @@ public class DealDataJob {
//Constant.WEB_FLAG=false; //Constant.WEB_FLAG=false;
} }
} }
/** /**
* 采集 * 采集
*/ */
@ -89,19 +91,24 @@ public class DealDataJob {
threadName = "3"; threadName = "3";
log.info("------采集设定温度、设定水位、故障状态!" + i + "------"); log.info("------采集设定温度、设定水位、故障状态!" + i + "------");
} }
CountDownLatch countDownLatch = new CountDownLatch(10);
for (int j = 1; j < 11; j++) { for (int j = 1; j < 11; j++) {
SerialPortThread myThread = new SerialPortThread(); SerialPortThread myThread = new SerialPortThread();
myThread.setName(threadName, String.valueOf(j), countDownLatch);
Thread thread = new Thread(myThread); Thread thread = new Thread(myThread);
myThread.setName(threadName, String.valueOf(j));
comThreadPool.execute(thread); comThreadPool.execute(thread);
} }
countDownLatch.await();
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("定时采集异常==>", e);
} finally {
Constant.FLAG = false;
} }
} }
/** /**
* 定时处理数据每十五分钟处理一次 * 定时处理数据每十五分钟处理一次
*/ */

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

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

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

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

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

@ -1,98 +1,98 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import com.mh.user.entity.OrderMessageEntity; //import com.mh.user.entity.OrderMessageEntity;
import io.netty.bootstrap.Bootstrap; //import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; //import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; //import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; //import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; //import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler; //import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler; //import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter; //import lombok.Getter;
import lombok.Setter; //import lombok.Setter;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
//
import java.util.List; //import java.util.List;
import java.util.concurrent.TimeUnit; //import java.util.concurrent.TimeUnit;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description 控制冷水机组和其他设备 // * @description : 控制冷水机组和其他设备
* @updateTime 2020-05-28 // * @updateTime 2020-05-28
* @throws // * @throws :
*/ // */
@Setter //@Setter
@Getter //@Getter
@Slf4j //@Slf4j
public class NettyChillerControlClient { //public class NettyChillerControlClient {
//
// private int port; //// private int port;
// private String host; //// private String host;
// private List<OrderMessageEntity> orderMessageEntityList; //// private List<OrderMessageEntity> orderMessageEntityList;
//
// 构造函数传递值 继承Thread时需要 // // 构造函数传递值 继承Thread时需要
// public NettyChillerControlClient(int port, String host) { //// public NettyChillerControlClient(int port, String host) {
// this.port = port; //// this.port = port;
// this.host = host; //// this.host = host;
// } //// }
//
public void connect(int port, String host, List<OrderMessageEntity> orderMessageEntityList) throws InterruptedException { // public void connect(int port, String host, List<OrderMessageEntity> orderMessageEntityList) throws InterruptedException {
// 配置客户端NIO线程组 // // 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1); // 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 { // try {
// TimeUnit.SECONDS.sleep(5); // Bootstrap bootstrap = new Bootstrap();
// connect(port, host); // 断线重连 // bootstrap.group(group).channel(NioSocketChannel.class)
// } catch (InterruptedException e) { // .option(ChannelOption.TCP_NODELAY, true)
// e.printStackTrace(); // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
// } // .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
} // .handler(new ChannelInitializer<SocketChannel>() {
}
// @SneakyThrows
// @Override // @Override
// public void run() { // protected void initChannel(SocketChannel socketChannel) {
// connect(port, host); // // 基于换行符号
//// 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);
//// }
//} //}
}

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

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

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

@ -1,90 +1,90 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import io.netty.bootstrap.Bootstrap; //import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; //import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; //import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; //import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; //import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler; //import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter; //import lombok.Getter;
import lombok.Setter; //import lombok.Setter;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description Netty客户端采集冷量计 // * @description :Netty客户端,采集冷量计
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
@Setter //@Setter
@Getter //@Getter
public class NettyClient { //public class NettyClient {
//
private int port; // private int port;
private String host; // private String host;
//
// 构造函数传递值 继承Thread时需要 // // 构造函数传递值 继承Thread时需要
// public NettyClient(int port, String host) { //// public NettyClient(int port, String host) {
// this.port = port; //// this.port = port;
// this.host = host; //// this.host = host;
// } //// }
//
public void connect(int port, String host) throws InterruptedException { // public void connect(int port, String host) throws InterruptedException {
// 配置客户端NIO线程组 // // 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1); // 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 { // try {
// TimeUnit.SECONDS.sleep(5); // Bootstrap bootstrap = new Bootstrap();
// connect(port, host); // 断线重连 // bootstrap.group(group).channel(NioSocketChannel.class)
// } catch (InterruptedException e) { // .option(ChannelOption.TCP_NODELAY, true)
// e.printStackTrace(); // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
// } // .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
} // .handler(new ChannelInitializer<SocketChannel>() {
}
// @SneakyThrows
// @Override // @Override
// public void run() { // protected void initChannel(SocketChannel socketChannel) {
// connect(port, host); // // 基于换行符号
//// 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);
//// }
//} //}
}

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

@ -1,295 +1,295 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import com.mh.user.constants.Constant; //import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceManageEntity; //import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.service.DeviceManageService; //import com.mh.user.service.DeviceManageService;
import com.mh.user.utils.*; //import com.mh.user.utils.*;
import io.netty.buffer.ByteBuf; //import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel; //import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter; //import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; //import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil; //import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext; //import org.springframework.context.ApplicationContext;
//
import java.text.SimpleDateFormat; //import java.text.SimpleDateFormat;
import java.util.Date; //import java.util.Date;
import java.util.List; //import java.util.List;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description 客户端异步消息处理机制 // * @description :客户端异步消息处理机制
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
public class NettyClientHandler extends ChannelHandlerAdapter { //public class NettyClientHandler extends ChannelHandlerAdapter {
//
private int num = 0; // private int num = 0;
private int size = 0; // private int size = 0;
private String receiveStr = null; // private String receiveStr = null;
private String IP = null; // private String IP = null;
private String port = null; // private String port = null;
List<DeviceManageEntity> deviceManageEntityList; // List<DeviceManageEntity> deviceManageEntityList;
//
// 调用service // // 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext(); // ApplicationContext context = SpringBeanUtil.getApplicationContext();
DeviceManageService deviceManageService = context.getBean(DeviceManageService.class); // DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
//
//
@Override // @Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { // public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册"); // log.info("当前channel从EventLoop取消注册");
super.channelUnregistered(ctx); // super.channelUnregistered(ctx);
} // }
//
@Override // @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause); //// super.exceptionCaught(ctx, cause);
log.info("通信异常!!"); // log.info("通信异常!!");
receiveStr = null;
Channel incoming = ctx.channel();
if (incoming.isActive()){
log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
cause.printStackTrace();
ctx.close();
// receiveStr = null; // receiveStr = null;
// try { // Channel incoming = ctx.channel();
// TimeUnit.SECONDS.sleep(5); // if (incoming.isActive()){
// SocketAddress remoteAddress = ctx.channel().remoteAddress(); // log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":"); // cause.printStackTrace();
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":"); // ctx.close();
// NettyClient nettyClient = new NettyClient(); //// receiveStr = null;
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连 //// try {
// } catch (InterruptedException e) { //// TimeUnit.SECONDS.sleep(5);
// e.printStackTrace(); //// 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 = deviceManageService.queryDevicesByType("3");
size = deviceManageEntityList.size();
// 封装工具类进行采集,update by ljf on 2021-01-26
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),0,IP,port,ctx);
// // 1.创建将要写出的数据
// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
// deviceManageEntityList.get(0).getDataCom(),
// collectionNum, "34");
//// String sendStr = "5803004900021914";
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
}
// String sendStr = "5803004900021914"; // 冷量计
// // 申请一个数据结构存储信息
// ByteBuf buffer = ctx.alloc().buffer();
// // 将信息放入数据结构中
// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
// ctx.writeAndFlush(buffer, ctx.newProgressivePromise());
}
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); // 解析冷量计
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("有指令下发退出定时采集DDC参数");
num = 0;
// 关闭连接
receiveStr = null;
ctx.close();
} else {
// 封装工具类进行采集,update by ljf on 2021-01-26
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
// // 1.创建将要写出的数据
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
// deviceManageEntityList.get(num).getDataCom(),
// collectionNum, "34");
//// String sendStr = "5803004900021914";
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + sendStr);
}
}
} else {
log.info(receiveStr);
receiveStr = null;
ctx.flush();
ctx.close();
}
// if (receiveStr.contains("c0a801fc")) { // 冷量计
// //
// @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 = deviceManageService.queryDevicesByType("3"); // deviceManageEntityList = deviceManageService.queryDevicesByType("3");
// size = deviceManageEntityList.size(); // size = deviceManageEntityList.size();
// //
// log.info("初始连接报文: " + receiveStr); // // 封装工具类进行采集,update by ljf on 2021-01-26
// IP = receiveStr; // SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),0,IP,port,ctx);
// receiveStr = ""; //// // 1.创建将要写出的数据
// // 1.创建将要写出的数据 //// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
// String collectionNum = deviceManageEntityList.get(0).getCollectionNum(); //// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
// String sendStr = GetReadOrder485.createCloudOrder(collectionNum,"34"); //// deviceManageEntityList.get(0).getDataCom(),
//// String sendStr = "5803004900021914"; //// collectionNum, "34");
// ByteBuf buffer = getByteBuf(ctx,sendStr); ////// String sendStr = "5803004900021914";
// // 2.发送数据 //// ByteBuf buffer = getByteBuf(ctx, sendStr);
// ctx.channel().writeAndFlush(buffer); //// // 2.发送数据
// } else if (receiveStr.contains("c0a801f0")) { // 电表 //// ctx.channel().writeAndFlush(buffer);
// }
// //
// // 生成对应的采集指令 //// String sendStr = "5803004900021914"; // 冷量计
// deviceManageEntityList = deviceManageService.queryDevicesByType("1"); //// // 申请一个数据结构存储信息
// size = deviceManageEntityList.size(); //// ByteBuf buffer = ctx.alloc().buffer();
//// // 将信息放入数据结构中
//// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
//// ctx.writeAndFlush(buffer, ctx.newProgressivePromise());
// }
// //
// log.info("初始连接报文: " + receiveStr); // private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// IP = receiveStr; // // byte类型的数据
// receiveStr = ""; //// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
// // 1.创建将要写出的数据 //// String sendStr = "5803004900021914"; // 冷量计
//// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表 // // 申请一个数据结构存储信息
//// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表 // ByteBuf buffer = ctx.alloc().buffer();
// String collectionNum = deviceManageEntityList.get(0).getCollectionNum(); // // 将信息放入数据结构中
// String sendStr = GetReadOrder485.createMeterOrder(collectionNum,"1"); // buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
// ByteBuf buffer = getByteBuf(ctx,sendStr); // return buffer;
// // 2.发送数据 // }
// ctx.channel().writeAndFlush(buffer); //
// } else if ((receiveStr.length() == 18) && (IP.contains("c0a801fc"))) { // @Override
// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计 // 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); // 解析冷量计
// receiveStr = ""; // receiveStr = "";
// // 1.创建将要写出的数据 // // 1.创建将要写出的数据
//// String sendStr = "5803004900021914"; //// String sendStr = "5803004900021914";
// num = num + 1; // num = num + 1;
// Thread.sleep(1000); // Thread.sleep(500);
// if (num >= size-1) { // if (num > size-1) {
// num = 0; // num = 0;
// // 关闭连接 // // 关闭连接
// receiveStr = null; // receiveStr = null;
// ctx.close(); // ctx.close();
//// 保持长连接
//// // 封装工具类进行采集,update by ljf on 2021-01-26
//// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
// } else { // } else {
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum(); // // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// String sendStr = GetReadOrder485.createCloudOrder(collectionNum, "34"); // if (Constant.WEB_FLAG) {
// ByteBuf buffer = getByteBuf(ctx, sendStr); // log.info("有指令下发退出定时采集DDC参数");
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num);
// }
//
// } else if ((receiveStr.length() == 44) && (IP.contains("c0a801f0"))) {
// analysisReceiveOrder485.analysisMeterOrder485(receiveStr); // 解析电表
// receiveStr = "";
// num = num + 1;
// Thread.sleep(1000);
// if (num >= size-1) {
// num = 0; // num = 0;
// receiveStr = null;
// // 关闭连接 // // 关闭连接
// receiveStr = null;
// ctx.close(); // ctx.close();
// } else { // } else {
// // 1.创建将要写出的数据 // // 封装工具类进行采集,update by ljf on 2021-01-26
// // fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16 // SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
//// String sendStr = "FEFEFE6880025007000068010243C3B216"; //// // 1.创建将要写出的数据
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum(); //// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(collectionNum, "1"); //// String sendStr = GetReadOrder485.createCloudOrder(IP, port,
// ByteBuf buffer = getByteBuf(ctx, sendStr); //// deviceManageEntityList.get(num).getDataCom(),
// // 2.发送数据 //// collectionNum, "34");
// ctx.channel().writeAndFlush(buffer); ////// String sendStr = "5803004900021914";
// log.info("客户端再次往服务端发送数据" + num); //// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + sendStr);
// }
// } // }
// } else if ((receiveStr.length() > 44)) { //
// } else {
// log.info(receiveStr); // log.info(receiveStr);
// receiveStr = null; // receiveStr = null;
// ctx.flush(); // ctx.flush();
// ctx.close(); // ctx.close();
// } // }
ctx.flush(); //
} //// if (receiveStr.contains("c0a801fc")) { // 冷量计
////
} //// // 生成对应的采集指令
//// deviceManageEntityList = deviceManageService.queryDevicesByType("3");
//// size = deviceManageEntityList.size();
////
//// log.info("初始连接报文: " + receiveStr);
//// IP = receiveStr;
//// receiveStr = "";
//// // 1.创建将要写出的数据
//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
//// String sendStr = GetReadOrder485.createCloudOrder(collectionNum,"34");
////// String sendStr = "5803004900021914";
//// ByteBuf buffer = getByteBuf(ctx,sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// } else if (receiveStr.contains("c0a801f0")) { // 电表
////
//// // 生成对应的采集指令
//// deviceManageEntityList = deviceManageService.queryDevicesByType("1");
//// size = deviceManageEntityList.size();
////
//// log.info("初始连接报文: " + receiveStr);
//// IP = receiveStr;
//// receiveStr = "";
//// // 1.创建将要写出的数据
////// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
////// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
//// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
//// String sendStr = GetReadOrder485.createMeterOrder(collectionNum,"1");
//// ByteBuf buffer = getByteBuf(ctx,sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// } else if ((receiveStr.length() == 18) && (IP.contains("c0a801fc"))) {
//// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
//// receiveStr = "";
//// // 1.创建将要写出的数据
////// String sendStr = "5803004900021914";
//// num = num + 1;
//// Thread.sleep(1000);
//// if (num >= size-1) {
//// num = 0;
//// // 关闭连接
//// receiveStr = null;
//// ctx.close();
//// } else {
//// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
//// String sendStr = GetReadOrder485.createCloudOrder(collectionNum, "34");
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + num);
//// }
////
//// } else if ((receiveStr.length() == 44) && (IP.contains("c0a801f0"))) {
//// analysisReceiveOrder485.analysisMeterOrder485(receiveStr); // 解析电表
//// receiveStr = "";
//// num = num + 1;
//// Thread.sleep(1000);
//// if (num >= size-1) {
//// num = 0;
//// receiveStr = null;
//// // 关闭连接
//// ctx.close();
//// } else {
//// // 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(collectionNum, "1");
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
//// // 2.发送数据
//// ctx.channel().writeAndFlush(buffer);
//// log.info("客户端再次往服务端发送数据" + num);
//// }
//// } else if ((receiveStr.length() > 44)) {
//// log.info(receiveStr);
//// receiveStr = null;
//// ctx.flush();
//// ctx.close();
//// }
// ctx.flush();
// }
//
//}

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

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

186
user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java

@ -1,97 +1,97 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import io.netty.bootstrap.Bootstrap; //import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; //import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; //import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; //import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; //import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler; //import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler; //import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter; //import lombok.Getter;
import lombok.Setter; //import lombok.Setter;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
//
import java.util.concurrent.TimeUnit; //import java.util.concurrent.TimeUnit;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description Netty客户端采集电表 // * @description :Netty客户端,采集电表
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
@Setter //@Setter
@Getter //@Getter
public class NettyMeterAndCloudClient { //public class NettyMeterAndCloudClient {
// implements Runnable { //// implements Runnable {
//
private int port; // private int port;
private String host; // private String host;
//
// 构造函数传递值 继承Thread时需要 // // 构造函数传递值 继承Thread时需要
public NettyMeterAndCloudClient(int port, String host) { // public NettyMeterAndCloudClient(int port, String host) {
this.port = port; // this.port = port;
this.host = host; // this.host = host;
} // }
//
public NettyMeterAndCloudClient() { // public NettyMeterAndCloudClient() {
super(); // super();
}
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 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 IdleStateHandler(10,10,10, TimeUnit.SECONDS));
// 在管道中添加我们自己的接收数据实现方法
// socketChannel.pipeline().addLast(new NettyClientHandler());
socketChannel.pipeline().addLast(new NettyMeterAndCloudClientHandler());
}
});
// 发起异步连接操作
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 // 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 // @Override
// public void run() { // protected void initChannel(SocketChannel socketChannel) {
// connect(port, host); // // 基于换行符号
//// 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 IdleStateHandler(10,10,10, TimeUnit.SECONDS));
// // 在管道中添加我们自己的接收数据实现方法
//// socketChannel.pipeline().addLast(new NettyClientHandler());
// socketChannel.pipeline().addLast(new NettyMeterAndCloudClientHandler());
// }
// });
// // 发起异步连接操作
// 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);
//// }
//} //}
}

384
user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java

@ -1,193 +1,193 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import com.mh.user.constants.Constant; //import com.mh.user.constants.Constant;
import com.mh.user.entity.DeviceManageEntity; //import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.service.DeviceManageService; //import com.mh.user.service.DeviceManageService;
import com.mh.user.utils.*; //import com.mh.user.utils.*;
import io.netty.buffer.ByteBuf; //import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel; //import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter; //import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; //import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState; //import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent; //import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil; //import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext; //import org.springframework.context.ApplicationContext;
//
import java.text.SimpleDateFormat; //import java.text.SimpleDateFormat;
import java.util.Date; //import java.util.Date;
import java.util.List; //import java.util.List;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description 客户端异步消息处理机制 // * @description :客户端异步消息处理机制
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
public class NettyMeterAndCloudClientHandler extends ChannelHandlerAdapter { //public class NettyMeterAndCloudClientHandler extends ChannelHandlerAdapter {
//
//
private int num = 0; // private int num = 0;
private int size = 0; // private int size = 0;
private String receiveStr = null; // private String receiveStr = null;
private int idle_count = 0; // private int idle_count = 0;
private String IP = ""; // private String IP = "";
private String port = ""; // private String port = "";
//
List<DeviceManageEntity> deviceManageEntityList; // List<DeviceManageEntity> deviceManageEntityList;
//
// 调用service // // 调用service
ApplicationContext context = SpringBeanUtil.getApplicationContext(); // ApplicationContext context = SpringBeanUtil.getApplicationContext();
DeviceManageService deviceManageService = context.getBean(DeviceManageService.class); // DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
//
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); // AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
//
@Override // @Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { // public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
log.info("当前channel从EventLoop取消注册"); // log.info("当前channel从EventLoop取消注册");
super.channelUnregistered(ctx); // super.channelUnregistered(ctx);
} // }
//
/** // /**
* 超时处理 // * 超时处理
* 如果120秒没有接受客户端的心跳就触发; // * 如果120秒没有接受客户端的心跳,就触发;
* 如果超过3次则直接关闭; // * 如果超过3次,则直接关闭;
*/ // */
@Override // @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception { // public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
if (obj instanceof IdleStateEvent) { // if (obj instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) obj; // IdleStateEvent event = (IdleStateEvent) obj;
if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令 // if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据"); // System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据");
if (deviceManageEntityList.get(num) == null) { // if (deviceManageEntityList.get(num) == null) {
ctx.channel().close(); // ctx.channel().close();
} else { // } else {
if (idle_count > 3 || num > size - 1) { // if (idle_count > 3 || num > size - 1) {
System.out.println("关闭这个不活跃的channel"); // System.out.println("关闭这个不活跃的channel");
ctx.channel().close(); // ctx.channel().close();
} // }
//
SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx); // SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
idle_count++; // idle_count++;
} // }
} // }
} else { // } else {
super.userEventTriggered(ctx, obj); // super.userEventTriggered(ctx, obj);
} // }
} // }
//
@Override // @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.info("通信异常!!"); // log.info("通信异常!!");
Channel incoming = ctx.channel(); // Channel incoming = ctx.channel();
if (incoming.isActive()) { // if (incoming.isActive()) {
log.info("SimpleClient: " + incoming.remoteAddress() + "异常"); // log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
receiveStr = null; // receiveStr = null;
cause.printStackTrace(); // cause.printStackTrace();
ctx.close(); // ctx.close();
} // }
} // }
//
//
@Override // @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { // public void channelActive(ChannelHandlerContext ctx) throws Exception {
// super.channelActive(ctx); //// super.channelActive(ctx);
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07 // // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
if (Constant.WEB_FLAG) { // if (Constant.WEB_FLAG) {
num = 0; // num = 0;
// 关闭连接 // // 关闭连接
receiveStr = null; // receiveStr = null;
ctx.close(); // ctx.close();
} else { // } else {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date date = new Date(); // Date date = new Date();
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!"); // log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
//
// 截取IP地址 // // 截取IP地址
IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":"); // IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// 截取端口号 // // 截取端口号
port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", ""); // port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
log.info("IP: " + IP + ",端口号: " + port); // log.info("IP: " + IP + ",端口号: " + port);
//
// 生成对应的采集指令 // // 生成对应的采集指令
deviceManageEntityList = deviceManageService.queryDevicesByType(null); // deviceManageEntityList = deviceManageService.queryDevicesByType(null);
size = deviceManageEntityList.size(); // size = deviceManageEntityList.size();
//
log.info("初始连接报文: " + receiveStr); // log.info("初始连接报文: " + receiveStr);
receiveStr = ""; // receiveStr = "";
// 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(0), 0, IP, port, ctx);
}
}
@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);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
log.info("采集电表或者冷量计-数据读取接收完成: " + receiveStr);
if ((receiveStr.length() == 36) && (deviceManageEntityList.get(num).getParamId() == 3)) {
// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
} else if ((receiveStr.length() == 62) && (deviceManageEntityList.get(num).getParamId() == 1)) {
// 把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
analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","",""); // 解析电表
}
receiveStr = "";
num = num + 1;
Thread.sleep(600);
if (num > size - 1) {
num = 0;
receiveStr = null;
// 关闭连接
ctx.close();
// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26 // // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx); // SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(0), 0, IP, port, ctx);
} else { // }
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07 // }
if (Constant.WEB_FLAG) { //
log.info("有指令下发退出定时采集DDC参数"); // @Override
num = 0; // public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 关闭连接 // Thread.sleep(500);
receiveStr = null; // receiveStr = null;
ctx.close(); // ctx.close();
} else { // log.info(ctx.channel().localAddress() + "退出链接!!");
// 封装发送电表工具方法 update by ljf on 2021-01-26 // }
SendOrderUtils.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx); //
} // @Override
} // public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.flush(); // 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);
// }
// }
//
// @Override
// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// log.info("采集电表或者冷量计-数据读取接收完成: " + receiveStr);
// if ((receiveStr.length() == 36) && (deviceManageEntityList.get(num).getParamId() == 3)) {
//// analysisReceiveOrder485.analysisCloudOrder485(receiveStr); // 解析冷量计
// } else if ((receiveStr.length() == 62) && (deviceManageEntityList.get(num).getParamId() == 1)) {
//// 把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
// analysisReceiveOrder485.analysisMeterOrder485(receiveStr,"","","", null); // 解析电表
// }
// 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.sendMeterOrCloud(deviceManageEntityList.get(num), num, IP, port, ctx);
// }
// }
// ctx.flush();
// }
//}

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

@ -1,96 +1,96 @@
package com.mh.user.netty; //package com.mh.user.netty;
//
import io.netty.bootstrap.Bootstrap; //import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; //import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; //import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; //import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; //import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler; //import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.Getter; //import lombok.Getter;
import lombok.Setter; //import lombok.Setter;
import lombok.SneakyThrows; //import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description Netty客户端采集电表 // * @description :Netty客户端,采集电表
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
@Setter //@Setter
@Getter //@Getter
public class NettyMeterClient { //public class NettyMeterClient {
// implements Runnable { //// implements Runnable {
//
private int port; // private int port;
private String host; // private String host;
//
// 构造函数传递值 继承Thread时需要 // // 构造函数传递值 继承Thread时需要
public NettyMeterClient(int port, String host) { // public NettyMeterClient(int port, String host) {
this.port = port; // this.port = port;
this.host = host; // this.host = host;
} // }
//
public NettyMeterClient() { // public NettyMeterClient() {
super(); // 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 NettyMeterClientHandler1());
}
});
// 发起异步连接操作
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 // 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 // @Override
// public void run() { // protected void initChannel(SocketChannel socketChannel) {
// connect(port, host); // // 基于换行符号
//// 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 NettyMeterClientHandler1());
// }
// });
// // 发起异步连接操作
// 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);
//// }
//} //}
}

486
user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java

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

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

@ -137,7 +137,7 @@ public class SerialPortSendReceive {
if (d==1){ if (d==1){
deviceInstallService.updateNotOnline(deviceAddr,deviceType,buildingId,"离线"); //所有设备离线 deviceInstallService.updateNotOnline(deviceAddr,deviceType,buildingId,"离线"); //所有设备离线
if (deviceType.equals("热泵")){ if (deviceType.equals("热泵")){
nowDataService.updateRunState(buildingId,deviceAddr,"离线"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId,deviceAddr,"离线", buildingName); //监控界面状态表热泵在线状态
} }
} }
continue; continue;
@ -174,11 +174,11 @@ public class SerialPortSendReceive {
if (deviceType.equals("热泵")){ if (deviceType.equals("热泵")){
String strState=nowDataService.selectState(buildingId,deviceAddr); String strState=nowDataService.selectState(buildingId,deviceAddr);
if (strState!=null && strState.equals("离线")){ //采集到数据 if (strState!=null && strState.equals("离线")){ //采集到数据
nowDataService.updateRunState(buildingId,deviceAddr,"不运行"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId,deviceAddr,"不运行", buildingName); //监控界面状态表热泵在线状态
} }
} }
try{ try{
SerialPortSendReceive2.analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService); SerialPortSendReceive2.analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService, buildingName);
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); // e.printStackTrace();
Constant.WEB_FLAG=false;//可以采集的状态 Constant.WEB_FLAG=false;//可以采集的状态

81
user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java

@ -45,9 +45,6 @@ public class SerialPortSendReceive2 {
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
public void serialPortSend(String sort, String thread) { public void serialPortSend(String sort, String thread) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = df.format(date);
SerialPort serialPort = null; SerialPort serialPort = null;
CacheUtil cacheUtil = CacheUtil.getInstance(); CacheUtil cacheUtil = CacheUtil.getInstance();
// if (port.contains(comName)){ // if (port.contains(comName)){
@ -70,8 +67,8 @@ public class SerialPortSendReceive2 {
.filter(value -> value.getThread().equals(thread)) .filter(value -> value.getThread().equals(thread))
.sorted(Comparator.comparing(DeviceCodeParamEntity::getDataCom)) .sorted(Comparator.comparing(DeviceCodeParamEntity::getDataCom))
.collect(Collectors.toList()); .collect(Collectors.toList());
size = deviceManageEntityList.size(); // size = deviceManageEntityList.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < deviceManageEntityList.size(); i++) {
//判断网页端是否有操作设备的 //判断网页端是否有操作设备的
if (Constant.WEB_FLAG) { if (Constant.WEB_FLAG) {
Constant.FLAG = false; Constant.FLAG = false;
@ -125,38 +122,35 @@ public class SerialPortSendReceive2 {
byte[] bytes = SerialTool.readFromPort(serialPort); byte[] bytes = SerialTool.readFromPort(serialPort);
if (bytes == null) { if (bytes == null) {
SerialTool.closePort(serialPort); SerialTool.closePort(serialPort);
Thread.sleep(2000); Thread.sleep(1000);
log.info("串口" + serialPort + "没有数据返回!" + i); log.info("串口" + serialPort + "没有数据返回!" + i);
log.info("----------------" + deviceType + "离线,设备号:" + deviceAddr + ",所属楼栋:" + buildingName + "----------------"); log.info("----------------" + deviceType + "离线,设备号:" + deviceAddr + ",所属楼栋:" + buildingName + "----------------");
Constant.WEB_FLAG = false;//可以采集的状态 Constant.WEB_FLAG = false;//可以采集的状态
if (i == size - 1) {
Constant.FLAG = false;
}
String time1 = deviceInstallService.selectLastDate(deviceType, deviceAddr, buildingId); String time1 = deviceInstallService.selectLastDate(deviceType, deviceAddr, buildingId);
Date date1 = new Date(); Date date1 = new Date();
String time2 = df.format(date1); String time2 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
if (time1 == null) { if (time1 == null) {
time1 = df.format(date1); time1 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
} }
int d = ExchangeStringUtil.compareCopyTime(time1, time2); int d = ExchangeStringUtil.compareCopyTime(time1, time2);
if (d == 1) { if (d == 1) {
deviceInstallService.updateNotOnline(deviceAddr, deviceType, buildingId, "离线"); //所有设备离线 deviceInstallService.updateNotOnline(deviceAddr, deviceType, buildingId, "离线"); //所有设备离线
if (deviceType.equals("热泵")) { if (deviceType.equals("热泵")) {
nowDataService.updateRunState(buildingId, deviceAddr, "离线"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId, deviceAddr, "离线", buildingName); //监控界面状态表热泵在线状态
} }
} }
continue; continue;
} }
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
// 处理返回来的数据报文 // 处理返回来的数据报文
dealReceiveData(dateStr, serialPort, i, deviceAddr, deviceType, registerAddr, brand, buildingId, buildingName, bytes); dealReceiveData(dateStr, serialPort, i, deviceAddr, deviceType, registerAddr, brand, buildingId, buildingName, bytes);
} }
Constant.FLAG = false; Constant.FLAG = false;
log.info("-------------一轮采集完,采集标志Constant.Flag=false-------------"); log.info("-------------一轮采集完,采集标志Constant.Flag=false-------------");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
Constant.WEB_FLAG = false;//可以采集的状态 Constant.WEB_FLAG = false;//可以采集的状态
Constant.FLAG = false; Constant.FLAG = false;
log.error("-------------串口采集异常!-------------"); log.error("-------------串口采集异常!----------->>", e);
} }
} }
@ -184,7 +178,7 @@ public class SerialPortSendReceive2 {
String buildingId, String buildingId,
String buildingName, byte[] bytes) throws InterruptedException { String buildingName, byte[] bytes) throws InterruptedException {
receiveStr = ""; receiveStr = "";
receiveStr = printHexString(bytes); receiveStr = ExchangeStringUtil.parseByte2HexStr(bytes);
//去掉空格和null //去掉空格和null
receiveStr = receiveStr.replace("null", ""); receiveStr = receiveStr.replace("null", "");
receiveStr = receiveStr.replace(" ", ""); receiveStr = receiveStr.replace(" ", "");
@ -194,9 +188,6 @@ public class SerialPortSendReceive2 {
log.info("关闭" + serialPort); log.info("关闭" + serialPort);
} catch (Exception e) { } catch (Exception e) {
Constant.WEB_FLAG = false;//可以采集的状态 Constant.WEB_FLAG = false;//可以采集的状态
if (i == size - 1) {
Constant.FLAG = false;
}
log.error("关闭" + serialPort + "失败!", e); log.error("关闭" + serialPort + "失败!", e);
} }
//返回值全部变成大写 //返回值全部变成大写
@ -215,12 +206,12 @@ public class SerialPortSendReceive2 {
if (deviceType.equals("热泵")) { if (deviceType.equals("热泵")) {
String strState = nowDataService.selectState(buildingId, deviceAddr); String strState = nowDataService.selectState(buildingId, deviceAddr);
if (strState != null && strState.equals("离线")) { //采集到数据 if (strState != null && strState.equals("离线")) { //采集到数据
nowDataService.updateRunState(buildingId, deviceAddr, "不运行"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId, deviceAddr, "不运行", buildingName); //监控界面状态表热泵在线状态
} }
} }
try { try {
// 解析返回来的数据 // 解析返回来的数据
analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService); analysisReceiveData(dateStr, deviceType, registerAddr, brand, buildingId, dataStr, analysisReceiveOrder485, nowDataService, buildingName);
} catch (Exception e) { } catch (Exception e) {
Constant.WEB_FLAG = false;//可以采集的状态 Constant.WEB_FLAG = false;//可以采集的状态
log.error(deviceManageEntityList.get(i).getDeviceType() + "保存数据库失败!" + i,e); log.error(deviceManageEntityList.get(i).getDeviceType() + "保存数据库失败!" + i,e);
@ -228,51 +219,41 @@ public class SerialPortSendReceive2 {
Thread.sleep(1000); Thread.sleep(1000);
} }
static void analysisReceiveData(String dateStr, String deviceType, String registerAddr, String brand, String buildingId, String dataStr, AnalysisReceiveOrder485 analysisReceiveOrder485, NowDataService nowDataService) { static void analysisReceiveData(String dateStr,
String deviceType,
String registerAddr,
String brand,
String buildingId,
String dataStr,
AnalysisReceiveOrder485 analysisReceiveOrder485,
NowDataService nowDataService,
String buildingName) {
if ((dataStr.length() == 36 || dataStr.length() == 44 || dataStr.length() == 40 || dataStr.length() == 50) && deviceType.equals("电表")) { if ((dataStr.length() == 36 || dataStr.length() == 44 || dataStr.length() == 40 || dataStr.length() == 50) && deviceType.equals("电表")) {
analysisReceiveOrder485.analysisMeterOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisMeterOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位 nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位
} else if ((dataStr.length() == 18 || dataStr.length() == 70 || dataStr.length() == 44) && deviceType.equals("水表")) { } else if ((dataStr.length() == 18 || dataStr.length() == 70 || dataStr.length() == 44) && deviceType.equals("水表")) {
analysisReceiveOrder485.analysisWtMeterOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisWtMeterOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("压变")) { } else if (deviceType.equals("压变")) {
analysisReceiveOrder485.analysisPressureOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisPressureOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵")) { } else if (deviceType.equals("热泵")) {
analysisReceiveOrder485.analysisPumpOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisPumpOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("温控")) { } else if (deviceType.equals("温控")) {
analysisReceiveOrder485.analysisTempOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("时控")) { } else if (deviceType.equals("时控")) {
analysisReceiveOrder485.analysisTimeSetOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisTimeSetOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) { } else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
analysisReceiveOrder485.analysisRelayOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisRelayOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (dataStr.length() == 30 && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统 } else if (dataStr.length() == 30 && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && registerAddr.equals("0010")) { } else if (deviceType.equals("水位开关") && registerAddr.equals("0010")) {
analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId); //创新,热泵状态与水位共用一个8路设备 analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName); //创新,热泵状态与水位共用一个8路设备
// analysisReceiveOrder485.analysisRelayOrder485(dataStr,registerAddr,brand,buildingId); //华厦 // analysisReceiveOrder485.analysisRelayOrder485(dataStr,registerAddr,brand,buildingId); //华厦
nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位 nowDataService.proWaterLevel(dateStr, buildingId); //保存时间点楼栋水位
} else if (deviceType.equals("温度变送器")) { } else if (deviceType.equals("温度变送器")) {
analysisReceiveOrder485.analysisMulTempOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisMulTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵状态")) { } else if (deviceType.equals("热泵状态")) {
analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName);
}
}
/**
* 字节数组转16进制字符串
*
* @param b 字节数组
* @return 16进制字符串
*/
public static String printHexString(byte[] b) {
StringBuilder sbf = new StringBuilder();
for (byte value : b) {
String hex = Integer.toHexString(value & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sbf.append(hex.toUpperCase()).append(" ");
} }
return sbf.toString().trim();
} }
/** /**

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

@ -103,7 +103,7 @@ public class SerialPortSingle {
if (deviceType.equals("热泵")) { if (deviceType.equals("热泵")) {
String strState = nowDataService.selectState(buildingId, deviceAddr); String strState = nowDataService.selectState(buildingId, deviceAddr);
if (strState != null && strState.equals("离线")) { //采集到数据 if (strState != null && strState.equals("离线")) { //采集到数据
nowDataService.updateRunState(buildingId, deviceAddr, "不运行"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId, deviceAddr, "不运行", buildingName); //监控界面状态表热泵在线状态
} }
} }
try { try {
@ -114,7 +114,7 @@ public class SerialPortSingle {
} else if (deviceType.equals("压变")) { } else if (deviceType.equals("压变")) {
rtData = analysisReceiveOrder485.analysisPressureOrder4852(dataStr, registerAddr, brand, buildingId); rtData = analysisReceiveOrder485.analysisPressureOrder4852(dataStr, registerAddr, brand, buildingId);
} else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统 } else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId); analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) { } else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
rtData = analysisReceiveOrder485.analysisRelayOrder4852(dataStr, registerAddr, brand, buildingId); rtData = analysisReceiveOrder485.analysisRelayOrder4852(dataStr, registerAddr, brand, buildingId);
} else if (deviceType.equals("热泵")) { } else if (deviceType.equals("热泵")) {

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

@ -87,7 +87,7 @@ public class SerialPortSingle2 {
if (deviceType.equals("热泵")){ if (deviceType.equals("热泵")){
String strState=nowDataService.selectState(buildingId,deviceAddr); String strState=nowDataService.selectState(buildingId,deviceAddr);
if (strState!=null && strState.equals("离线")){ //采集到数据 if (strState!=null && strState.equals("离线")){ //采集到数据
nowDataService.updateRunState(buildingId,deviceAddr,"不运行"); //监控界面状态表热泵在线状态 nowDataService.updateRunState(buildingId,deviceAddr,"不运行", buildingName); //监控界面状态表热泵在线状态
} }
} }
try{ try{
@ -98,7 +98,7 @@ public class SerialPortSingle2 {
} else if (deviceType.equals("压变")) { } else if (deviceType.equals("压变")) {
rtData=analysisReceiveOrder485.analysisPressureOrder4852(dataStr,registerAddr,brand,buildingId); rtData=analysisReceiveOrder485.analysisPressureOrder4852(dataStr,registerAddr,brand,buildingId);
} else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统 } else if ((dataStr.length() == 30) && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
analysisReceiveOrder485.analysisStateOrder485(dataStr,registerAddr,brand,buildingId); analysisReceiveOrder485.analysisStateOrder485(dataStr,registerAddr,brand,buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) { } else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
rtData=analysisReceiveOrder485.analysisRelayOrder4852(dataStr,registerAddr,brand,buildingId); rtData=analysisReceiveOrder485.analysisRelayOrder4852(dataStr,registerAddr,brand,buildingId);
} else if (deviceType.equals("热泵")) { } else if (deviceType.equals("热泵")) {

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

@ -3,6 +3,8 @@ package com.mh.user.serialport;
import gnu.io.SerialPort; import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
/** /**
* @author nxr * @author nxr
* @title * @title
@ -19,14 +21,24 @@ public class SerialPortThread implements Runnable{
// 调用service // 调用service
//ApplicationContext context = SpringBeanUtil.getApplicationContext(); //ApplicationContext context = SpringBeanUtil.getApplicationContext();
private CountDownLatch countDownLatch;
public void setName(String name,String thread){ public void setName(String name,String thread){
this.name = name; this.name = name;
this.thread=thread; this.thread=thread;
} }
public void setName(String name,String thread, CountDownLatch countDownLatch){
this.name = name;
this.thread=thread;
this.countDownLatch = countDownLatch;
}
public void run(){ public void run(){
log.info("创建发送接收数据线程>>>>>>>>>>>>>>"+thread);
SerialPortSendReceive2 serial=new SerialPortSendReceive2(); SerialPortSendReceive2 serial=new SerialPortSendReceive2();
serial.serialPortSend(name,thread); serial.serialPortSend(name,thread);
log.info("创建发送接收数据线程>>>>>>>>>>>>>>"+thread); this.countDownLatch.countDown();
} }
} }

3
user-service/src/main/java/com/mh/user/serialport/SerialTool.java

@ -172,9 +172,6 @@ public class SerialTool {
out.close(); out.close();
out = null; out = null;
} }
// if (serialPort != null) {
// serialPort.close();
// }
} catch (IOException e) { } catch (IOException e) {
log.error("关闭串口对象的输出流出错"); log.error("关闭串口对象的输出流出错");
throw e; throw e;

2
user-service/src/main/java/com/mh/user/service/NowDataService.java

@ -103,7 +103,7 @@ public interface NowDataService {
void proWaterLevel(String curDate,String buildingID); void proWaterLevel(String curDate,String buildingID);
//在没有接收到返回值前设置监控界面热泵是否离线 //在没有接收到返回值前设置监控界面热泵是否离线
void updateRunState(String buildingId,String pumpId,String strState); void updateRunState(String buildingId,String pumpId,String strState, String buildingName);
//计算热泵运行时间,按分钟 //计算热泵运行时间,按分钟
void proPumpMinutes(String buildingId,String pumpId,String runState); void proPumpMinutes(String buildingId,String pumpId,String runState);

4
user-service/src/main/java/com/mh/user/service/impl/NowDataServiceImpl.java

@ -447,9 +447,9 @@ public class NowDataServiceImpl implements NowDataService {
} }
@Override @Override
public void updateRunState(String buildingId, String pumpId,String strState) { public void updateRunState(String buildingId, String pumpId,String strState, String buildingName) {
DeviceInstallEntity deviceInstallEntity=deviceInstallMapper.selectDevice(pumpId,"热泵",buildingId); DeviceInstallEntity deviceInstallEntity=deviceInstallMapper.selectDevice(pumpId,"热泵",buildingId);
String buildingName=buildingService.queryBuildingName(buildingId); // String buildingName=buildingService.queryBuildingName(buildingId);
NowDataEntity data=new NowDataEntity(); NowDataEntity data=new NowDataEntity();
int r1 = nowDataMapper.selectNowDataCount(buildingId,pumpId);//判断now_data表是否存在记录 int r1 = nowDataMapper.selectNowDataCount(buildingId,pumpId);//判断now_data表是否存在记录
if(r1==0){ if(r1==0){

152
user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java

@ -34,11 +34,8 @@ public class AnalysisReceiveOrder485 {
* 解析电表返回的数据 * 解析电表返回的数据
* @param dataStr * @param dataStr
*/ */
public void analysisMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) { public void analysisMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
if (dataStr.length() == 36 || dataStr.length() == 40 || dataStr.length() == 44 || dataStr.length() == 50) { if (dataStr.length() == 36 || dataStr.length() == 40 || dataStr.length() == 44 || dataStr.length() == 50) {
String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码 String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码
String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码 String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码
@ -67,25 +64,25 @@ public class AnalysisReceiveOrder485 {
data = String.format("%08d", Long.parseLong(data)); data = String.format("%08d", Long.parseLong(data));
data = data.substring(0, 6) + "." + data.substring(6, 8); data = data.substring(0, 6) + "." + data.substring(6, 8);
log.info("电表表号:" + meterId+",电表读数:" + data); log.info("电表表号:" + meterId+",电表读数:" + data);
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称 // String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
try { try {
DataResultEntity dataResultEntity = new DataResultEntity(); DataResultEntity dataResultEntity = new DataResultEntity();
dataResultEntity.setDeviceAddr(meterId);//通讯编号 dataResultEntity.setDeviceAddr(meterId);//通讯编号
dataResultEntity.setDeviceType("电表"); dataResultEntity.setDeviceType("电表");
dataResultEntity.setBuildingId(buildingId); dataResultEntity.setBuildingId(buildingId);
dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数 dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数
dataResultEntity.setCurDate(sdf1.parse(dateStr)); //当前日期 Date date = new Date();
dataResultEntity.setCurDate(date); //当前日期
dataResultService.saveDataResult(dataResultEntity); dataResultService.saveDataResult(dataResultEntity);
log.info("电表数据保存数据库成功! 楼栋名称:"+buildingName); log.info("电表数据保存数据库成功! 楼栋名称:"+buildingName);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("电表数据保存数据库失败!楼栋名称:"+buildingName, e);
log.error("电表数据保存数据库失败!楼栋名称:"+buildingName);
} }
}else { }else {
log.info("电表报文检验失败: " + dataStr); log.info("电表报文检验失败: " + dataStr);
} }
} }
}); // });
} }
public String analysisMeterOrder4852(final String dataStr,final String registerAddr,final String brand,String buildingId) { public String analysisMeterOrder4852(final String dataStr,final String registerAddr,final String brand,String buildingId) {
@ -146,11 +143,8 @@ public class AnalysisReceiveOrder485 {
} }
// 水表 // 水表
public void analysisWtMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) { public void analysisWtMeterOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String data = ""; String data = "";
String meterId=""; String meterId="";
if (dataStr.length() == 44 || dataStr.length() == 70) { if (dataStr.length() == 44 || dataStr.length() == 70) {
@ -189,14 +183,14 @@ public class AnalysisReceiveOrder485 {
log.info("水表报文检验失败: " + dataStr); log.info("水表报文检验失败: " + dataStr);
} }
} }
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
log.info("水表表号: " + meterId+",水表读数:" + data); log.info("水表表号: " + meterId+",水表读数:" + data);
try { try {
DataResultEntity dataResultEntity = new DataResultEntity(); DataResultEntity dataResultEntity = new DataResultEntity();
dataResultEntity.setDeviceAddr(meterId);//通讯编号 dataResultEntity.setDeviceAddr(meterId);//通讯编号
dataResultEntity.setDeviceType("水表"); dataResultEntity.setDeviceType("水表");
dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数 dataResultEntity.setCurValue(Double.parseDouble(data)); //当前读数
dataResultEntity.setCurDate(sdf1.parse(dateStr)); //当前日期 Date date = new Date();
dataResultEntity.setCurDate(date); //当前日期
dataResultEntity.setBuildingId(buildingId); dataResultEntity.setBuildingId(buildingId);
dataResultService.saveDataResult(dataResultEntity); dataResultService.saveDataResult(dataResultEntity);
log.info("水表数据保存数据库成功!楼栋名称:"+buildingName); log.info("水表数据保存数据库成功!楼栋名称:"+buildingName);
@ -204,7 +198,7 @@ public class AnalysisReceiveOrder485 {
e.printStackTrace(); e.printStackTrace();
log.error("水表数据保存数据库失败!楼栋名称:"+buildingName); log.error("水表数据保存数据库失败!楼栋名称:"+buildingName);
} }
}); // });
} }
// 水表 // 水表
@ -276,12 +270,12 @@ public class AnalysisReceiveOrder485 {
} }
// 热泵 // 热泵
public void analysisPumpOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisPumpOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) { // if (!Constant.CONTROL_WEB_FLAG) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(); // Date date = new Date();
String dateStr = sdf1.format(date); String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String checkStr = receiveData.substring(0, receiveData.length() - 4);//检验报文 String checkStr = receiveData.substring(0, receiveData.length() - 4);//检验报文
String checkWord=ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码 String checkWord=ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码
String sValue=null; String sValue=null;
@ -289,7 +283,7 @@ public class AnalysisReceiveOrder485 {
if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) { if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址 String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = ""; String data = "";
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称 // String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("美的")){ if (brand==null || brand.equals("") || brand.equals("美的")){
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {//读 if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {//读
if (registerAddr.equalsIgnoreCase("0641")) { //运行状态 if (registerAddr.equalsIgnoreCase("0641")) { //运行状态
@ -359,10 +353,11 @@ public class AnalysisReceiveOrder485 {
} }
nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId); nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId);
log.info("热泵ID:" + addr + ",数据: " + sValue+",保存数据库成功!楼栋名称:"+buildingName); log.info("热泵ID:" + addr + ",数据: " + sValue+",保存数据库成功!楼栋名称:"+buildingName);
}else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
|| registerAddr.equalsIgnoreCase("065E")) { //定时设置值
sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
} }
// else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
// || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
// sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
// }
} else if (checkStr.substring(2, 4).equalsIgnoreCase("10") ) { } else if (checkStr.substring(2, 4).equalsIgnoreCase("10") ) {
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " ); log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " );
} }
@ -438,10 +433,11 @@ public class AnalysisReceiveOrder485 {
} }
nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId); nowDataService.saveNowHistoryData(addr,"热泵",sValue,dataType,buildingId);
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",数据: " + sValue+"保存数据库成功!楼栋名称:"+buildingName); log.info("时间: " + dateStr + ",热泵ID: " + addr + ",数据: " + sValue+"保存数据库成功!楼栋名称:"+buildingName);
}else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
|| registerAddr.equalsIgnoreCase("065E")) { //定时设置值
sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
} }
// else if (registerAddr.equalsIgnoreCase("0656") || registerAddr.equalsIgnoreCase("065A")
// || registerAddr.equalsIgnoreCase("065E")) { //定时设置值
// sValue = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
// }
} else if (checkStr.substring(2, 4).equalsIgnoreCase("06") ) { } else if (checkStr.substring(2, 4).equalsIgnoreCase("06") ) {
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " ); log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! " );
} }
@ -451,7 +447,7 @@ public class AnalysisReceiveOrder485 {
}else{ }else{
log.info("热泵报文检验失败: " + receiveData); log.info("热泵报文检验失败: " + receiveData);
} }
}); // });
// } // }
} }
@ -621,23 +617,20 @@ public class AnalysisReceiveOrder485 {
} }
// 温度变送器,长度42,读功能03 // 温度变送器,长度42,读功能03
public void analysisMulTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisMulTempOrder485(final String receiveData, final String registerAddr,final String brand,final String buildingId, final String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) { // threadPoolService.execute(() -> {
threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文 String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr); byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
int checkNum = CRC16.CRC16_MODBUS(strOrder); int checkNum = CRC16.CRC16_MODBUS(strOrder);
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) { if (!checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
log.info("温度变送器报文检验失败: " + receiveData);
}
//log.info("温度变送器报文检验成功: " + receiveData); //log.info("温度变送器报文检验成功: " + receiveData);
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址 String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
//log.info("温度变送器:" + addr); //log.info("温度变送器:" + addr);
String data = ""; String data = "";
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读 if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
Map<String,String> map= new HashMap<>(); Map<String,String> map= new HashMap<>();
String L1=checkStr.substring(6, 10); //1路 String L1=checkStr.substring(6, 10); //1路
@ -659,10 +652,11 @@ public class AnalysisReceiveOrder485 {
int count=buildingService.selectPumpCount(buildingId); //楼栋热泵数 int count=buildingService.selectPumpCount(buildingId); //楼栋热泵数
if (count>0){ if (count>0){
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
for (Map.Entry<String, String> entry : map.entrySet()) { for (Map.Entry<String, String> entry : map.entrySet()) {
addr=entry.getKey(); addr=entry.getKey();
data=entry.getValue(); data=entry.getValue();
if(addr!=null && Integer.valueOf(addr)<=count){ if(addr!=null && Integer.parseInt(addr)<=count){
nowDataService.saveNowHistoryData3(addr,"温度变送器",data,"waterTemp",buildingId); nowDataService.saveNowHistoryData3(addr,"温度变送器",data,"waterTemp",buildingId);
nowDataService.proWaterTemp(dateStr,buildingId,addr); //保存时间点温度 nowDataService.proWaterTemp(dateStr,buildingId,addr); //保存时间点温度
} }
@ -676,11 +670,7 @@ public class AnalysisReceiveOrder485 {
nowPublicDataService.saveNowHistoryPublicData(publicData); nowPublicDataService.saveNowHistoryPublicData(publicData);
} }
} }
}else{ // });
log.info("温度变送器报文检验失败: " + receiveData);
}
});
// }
} }
// 温度变送器,长度42,读功能03 // 温度变送器,长度42,读功能03
@ -745,23 +735,19 @@ public class AnalysisReceiveOrder485 {
} }
// 温控,长度18,读功能03,用于检测水箱水温 // 温控,长度18,读功能03,用于检测水箱水温
public void analysisTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisTempOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) { // threadPoolService.execute(() -> {
threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
// 检验报文 // 检验报文
String checkStr = receiveData.substring(0, receiveData.length() - 4); String checkStr = receiveData.substring(0, receiveData.length() - 4);
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr); byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
int checkNum = CRC16.CRC16_MODBUS(strOrder); int checkNum = CRC16.CRC16_MODBUS(strOrder);
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2);
if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) { if (!checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
log.info("温控报文检验失败: " + receiveData);
}
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址 String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
//log.info("温控号:" + addr);
String data = ""; String data = "";
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读 if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
data=ExchangeStringUtil.hexToDec(checkStr.substring(6, 10)); data=ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));
Double fdata=Double.parseDouble(data)/10; Double fdata=Double.parseDouble(data)/10;
@ -771,6 +757,7 @@ public class AnalysisReceiveOrder485 {
fdata=65.0; fdata=65.0;
} }
nowDataService.saveNowHistoryData2(addr,"温控",String.valueOf(fdata),"waterTemp",buildingId); nowDataService.saveNowHistoryData2(addr,"温控",String.valueOf(fdata),"waterTemp",buildingId);
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
nowDataService.proWaterTemp(dateStr,buildingId,"");//保存时间点温度 nowDataService.proWaterTemp(dateStr,buildingId,"");//保存时间点温度
String avgTemp=nowDataService.selectAve(buildingId); String avgTemp=nowDataService.selectAve(buildingId);
NowPublicDataEntity publicData=new NowPublicDataEntity(); NowPublicDataEntity publicData=new NowPublicDataEntity();
@ -781,17 +768,13 @@ public class AnalysisReceiveOrder485 {
nowPublicDataService.saveNowHistoryPublicData(publicData); nowPublicDataService.saveNowHistoryPublicData(publicData);
log.info("温控号:" + addr+",温度值:"+fdata+",保存数据库成功!楼栋名称:"+buildingName); log.info("温控号:" + addr+",温度值:"+fdata+",保存数据库成功!楼栋名称:"+buildingName);
} }
}else{ // });
log.info("温控报文检验失败: " + receiveData);
}
});
// }
} }
// 压变,长度14,18读功能03 // 压变,长度14,18读功能03
public void analysisPressureOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisPressureOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) { // if (!Constant.CONTROL_WEB_FLAG) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文 String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr); byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
int checkNum = CRC16.CRC16_MODBUS(strOrder); int checkNum = CRC16.CRC16_MODBUS(strOrder);
@ -804,7 +787,7 @@ public class AnalysisReceiveOrder485 {
String dateStr = sdf1.format(date); String dateStr = sdf1.format(date);
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址 String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = ""; String data = "";
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称 // String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读 if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
Double wtHeight=0.0; Double wtHeight=0.0;
if (brand==null || brand.equals("")){ if (brand==null || brand.equals("")){
@ -835,7 +818,7 @@ public class AnalysisReceiveOrder485 {
}else{ }else{
log.info("压变报文检验失败: " + receiveData); log.info("压变报文检验失败: " + receiveData);
} }
}); // });
// } // }
} }
@ -890,11 +873,9 @@ public class AnalysisReceiveOrder485 {
} }
// 水位开关,长度42,128 // 水位开关,长度42,128
public void analysisRelayOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisRelayOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String l1=""; String l1="";
String l2=""; String l2="";
String l3=""; String l3="";
@ -905,7 +886,6 @@ public class AnalysisReceiveOrder485 {
String l8=""; String l8="";
String waterLevelSet=""; String waterLevelSet="";
String addr=""; String addr="";
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("中凯")){ if (brand==null || brand.equals("") || brand.equals("中凯")){
String checkStr = receiveData.substring(0, receiveData.length() - 4); //减去校验码 String checkStr = receiveData.substring(0, receiveData.length() - 4); //减去校验码
addr = ExchangeStringUtil.hexToDec(checkStr.substring(2, 4)); addr = ExchangeStringUtil.hexToDec(checkStr.substring(2, 4));
@ -1039,7 +1019,7 @@ public class AnalysisReceiveOrder485 {
log.info("-----------------状态保存数据库成功!楼栋名称:"+buildingName+"-----------------"); log.info("-----------------状态保存数据库成功!楼栋名称:"+buildingName+"-----------------");
} }
} }
}); // });
} }
// 水位开关,长度42,128 // 水位开关,长度42,128
@ -1178,11 +1158,9 @@ public class AnalysisReceiveOrder485 {
} }
// 热泵状态处理(水位开关),长度42,128 // 热泵状态处理(水位开关),长度42,128
public void analysisPumpStateOrder(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisPumpStateOrder(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String l1=""; String l1="";
String l2=""; String l2="";
String l3=""; String l3="";
@ -1194,7 +1172,6 @@ public class AnalysisReceiveOrder485 {
String runState=""; String runState="";
String addr=""; String addr="";
Map<String,String> map=new HashMap<String, String>(); Map<String,String> map=new HashMap<String, String>();
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (brand==null || brand.equals("") || brand.equals("顶威")){ if (brand==null || brand.equals("") || brand.equals("顶威")){
String checkStr = receiveData.substring(0, receiveData.length() - 4); //检验报文减,去校验码 String checkStr = receiveData.substring(0, receiveData.length() - 4); //检验报文减,去校验码
String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码 String checkNum = ExchangeStringUtil.makeChecksum(checkStr); //生成校验码
@ -1354,7 +1331,7 @@ public class AnalysisReceiveOrder485 {
} }
//} //}
//} //}
}); // });
} }
// 热泵状态处理(水位开关),长度42,128 // 热泵状态处理(水位开关),长度42,128
@ -1538,12 +1515,8 @@ public class AnalysisReceiveOrder485 {
} }
//状态检测 //状态检测
public void analysisStateOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId) { public void analysisStateOrder485(final String dataStr,final String registerAddr,final String brand,String buildingId, String buildingName) {
threadPoolService.execute(() -> { // threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String buildingName=buildingService.queryBuildingName(buildingId); //查询楼栋名称
if (dataStr.length() == 30) { if (dataStr.length() == 30) {
//检验报文 //检验报文
String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码 String checkStr = dataStr.substring(0, dataStr.length() - 4); //减去校验码
@ -1601,18 +1574,15 @@ public class AnalysisReceiveOrder485 {
log.info("状态检测报文检验失败: " + dataStr); log.info("状态检测报文检验失败: " + dataStr);
} }
} }
}); // });
} }
//时间控制器,长度26、22 //时间控制器,长度26、22
public void analysisTimeSetOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId) { public void analysisTimeSetOrder485(final String receiveData, final String registerAddr,final String brand,String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) { // threadPoolService.execute(() -> {
threadPoolService.execute(() -> {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(); Date date = new Date();
String dateStr = sdf1.format(date); String dateStr = sdf1.format(date);
// 去掉空格
// String receiveData = receiveData1.replace(" ", "");
// 检验报文 // 检验报文
String checkStr = receiveData.substring(0, receiveData.length() - 4); String checkStr = receiveData.substring(0, receiveData.length() - 4);
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr); byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(checkStr);
@ -1623,7 +1593,6 @@ public class AnalysisReceiveOrder485 {
String sValue=null; String sValue=null;
if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) { if (checkWord.equalsIgnoreCase(receiveData.substring(receiveData.length() - 4))) {
log.info("时控报文检验成功: " + receiveData); log.info("时控报文检验成功: " + receiveData);
// System.out.println("时控报文检验成功: " + receiveData);
//地址 //地址
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2)); String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));
log.info("时控号: " + addr); log.info("时控号: " + addr);
@ -1649,8 +1618,7 @@ public class AnalysisReceiveOrder485 {
// System.out.println("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! "); // System.out.println("时间: " + dateStr + ",时控ID: " + addr + ",操作成功! ");
} }
} }
}); // });
// }
} }
//时间控制器,长度26、22 //时间控制器,长度26、22

4
user-service/src/main/java/com/mh/user/utils/ComThreadPoolService.java

@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
public class ComThreadPoolService { public class ComThreadPoolService {
/** 线程池保持ALIVE状态线程数 */ /** 线程池保持ALIVE状态线程数 */
public static final int CORE_POOL_SIZE = 10; public static final int CORE_POOL_SIZE = 11;
/** 线程池最大线程数 */ /** 线程池最大线程数 */
public static final int MAX_POOL_SIZE = 50; public static final int MAX_POOL_SIZE = 50;
@ -23,7 +23,7 @@ public class ComThreadPoolService {
public static final int KEEP_ALIVE_TIME = 30000; public static final int KEEP_ALIVE_TIME = 30000;
/** 线程池等待队列 */ /** 线程池等待队列 */
public static final int BLOCKING_QUEUE_SIZE = 1000; public static final int BLOCKING_QUEUE_SIZE = 500;
// 私有化构造器 // 私有化构造器
private ComThreadPoolService(){} private ComThreadPoolService(){}

44
user-service/src/main/java/com/mh/user/utils/ExchangeStringUtil.java

@ -1,8 +1,8 @@
package com.mh.user.utils; package com.mh.user.utils;
import com.mh.common.utils.StringUtils; import com.mh.common.utils.StringUtils;
import io.netty.buffer.ByteBuf; //import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; //import io.netty.channel.ChannelHandlerContext;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -81,22 +81,22 @@ public class ExchangeStringUtil {
return c - '0'; return c - '0';
} }
/** // /**
* 获取到对应的buffer // * 获取到对应的buffer
* @param ctx // * @param ctx
* @param sendStr // * @param sendStr
* @return // * @return
*/ // */
public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { // public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// byte类型的数据 // // byte类型的数据
// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8")); //// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
// String sendStr = "5803004900021914"; // 冷量计 //// String sendStr = "5803004900021914"; // 冷量计
// 申请一个数据结构存储信息 // // 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer(); // ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中 // // 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制 // buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer; // return buffer;
} // }
/** /**
* double转换为String 当为整数时只显示整数当小数时直接显示小数 * double转换为String 当为整数时只显示整数当小数时直接显示小数
@ -992,16 +992,16 @@ public class ExchangeStringUtil {
} }
//将二进字节数组制转换为十六进制 //将二进字节数组制转换为十六进制
public static String parseByte2HexStr(byte binary[]){ public static String parseByte2HexStr(byte[] binary){
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for(int i = 0; i < binary.length; i++){ for (byte b : binary) {
String hex = Integer.toHexString(binary[i] & 0xFF); String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) { if (hex.length() == 1) {
hex = '0' + hex; hex = '0' + hex;
} }
sb.append(hex.toUpperCase()); sb.append(hex.toUpperCase());
} }
return sb.toString(); return sb.toString().trim();
} }
/** /**
* 十六进制字符串转IEEE754浮点型 * 十六进制字符串转IEEE754浮点型

52
user-service/src/main/java/com/mh/user/utils/GetReadOrder485.java

@ -28,7 +28,7 @@ public class GetReadOrder485 {
// 电表 // 电表
public static String createMeterOrder(DeviceCodeParamEntity orderParamModel){ public static String createMeterOrder(DeviceCodeParamEntity orderParamModel){
String str=null; String str="";
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
if (deviceAddr!=null && deviceAddr.length()>0){ if (deviceAddr!=null && deviceAddr.length()>0){
try{ try{
@ -45,10 +45,9 @@ public class GetReadOrder485 {
String checkSum = ExchangeStringUtil.makeChecksum(str); String checkSum = ExchangeStringUtil.makeChecksum(str);
str = "FEFEFE" + str + checkSum + "16"; str = "FEFEFE" + str + checkSum + "16";
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); log.error("生成采集电表指令错误==>",e);
} }
} }
// log.info("发送电表采集数据>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -56,7 +55,7 @@ public class GetReadOrder485 {
public static String createWtMeterOrder(DeviceCodeParamEntity orderParamModel){ public static String createWtMeterOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand(); String brand=orderParamModel.getBrand();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
if (brand==null || brand.equals("") || brand.equals("艾美柯")){ if (brand==null || brand.equals("") || brand.equals("艾美柯")){
@ -78,9 +77,9 @@ public class GetReadOrder485 {
} }
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); e.printStackTrace();
log.error("生成水表采集指令异常>>>>", e);
} }
} }
// log.info("生成水表采集指令>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -91,7 +90,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode(); String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue(); String dataValue=orderParamModel.getDataValue();
String str=null; String str="";
String param=""; String param="";
if(deviceAddr!=null && deviceAddr.length()>0) { if(deviceAddr!=null && deviceAddr.length()>0) {
try{ try{
@ -164,7 +163,7 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验 String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord; str = str + checkWord;
}catch (Exception e){ }catch (Exception e){
e.printStackTrace(); log.info("热泵"+param+"指令>>>>异常" + str, e);
} }
} }
log.info("热泵"+param+"指令>>>>" + str); log.info("热泵"+param+"指令>>>>" + str);
@ -178,7 +177,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode(); String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue(); String dataValue=orderParamModel.getDataValue();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
if (brand==null || brand.equals("") || brand.equals("中凯")) if (brand==null || brand.equals("") || brand.equals("中凯"))
@ -299,9 +298,9 @@ public class GetReadOrder485 {
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); // e.printStackTrace();
if(registerAddr.equals("0010")){ if(registerAddr.equals("0010")){
log.info("生成热泵状态指令出错!" + str); log.error("生成热泵状态指令出错!" + str);
}else{ }else{
log.info("生成水位开关指令出错!" + str); log.error("生成水位开关指令出错!" + str);
} }
} }
} }
@ -319,7 +318,7 @@ public class GetReadOrder485 {
String brand=orderParamModel.getBrand(); String brand=orderParamModel.getBrand();
String funCode=orderParamModel.getFunCode(); String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
if (brand==null || brand.equals("") || brand.equals("中凯")) if (brand==null || brand.equals("") || brand.equals("中凯"))
@ -361,7 +360,7 @@ public class GetReadOrder485 {
} }
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); // e.printStackTrace();
log.info("生成热泵状态指令出错!" + str); log.error("生成热泵状态指令出错!" + str, e);
} }
} }
log.info("生成热泵状态采集指令>>>>" + str); log.info("生成热泵状态采集指令>>>>" + str);
@ -372,7 +371,7 @@ public class GetReadOrder485 {
public static String createStateOrder(DeviceCodeParamEntity orderParamModel){ public static String createStateOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand(); String brand=orderParamModel.getBrand();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
// 0代表前面补充0,12代表长度为12,d代表参数为正数型.12位通讯地址,以0补位 // 0代表前面补充0,12代表长度为12,d代表参数为正数型.12位通讯地址,以0补位
@ -390,10 +389,9 @@ public class GetReadOrder485 {
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); // e.printStackTrace();
log.info("生成状态检测指令出错!" + str); log.error("生成状态检测指令出错!" + str,e);
} }
} }
// log.info("生成状态检测采集指令>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -401,7 +399,7 @@ public class GetReadOrder485 {
public static String createPressureOrder(DeviceCodeParamEntity orderParamModel){ public static String createPressureOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
String brand=orderParamModel.getBrand(); String brand=orderParamModel.getBrand();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
str = ExchangeStringUtil.decToHex(deviceAddr); //十进制转为十六进制 str = ExchangeStringUtil.decToHex(deviceAddr); //十进制转为十六进制
@ -416,11 +414,9 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验 String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord; str = str + checkWord;
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); log.info("生成压变指令出错!" + str, e);
log.info("生成压变指令出错!" + str);
} }
} }
// log.info("生成压变采集指令>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -428,7 +424,7 @@ public class GetReadOrder485 {
public static String createTempOrder(DeviceCodeParamEntity orderParamModel){ public static String createTempOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
str = ExchangeStringUtil.decToHex(deviceAddr); str = ExchangeStringUtil.decToHex(deviceAddr);
@ -443,11 +439,9 @@ public class GetReadOrder485 {
str = str + checkWord; str = str + checkWord;
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); // e.printStackTrace();
log.info("生成温控指令出错!" + str); log.error("生成温控指令出错!" + str, e);
} }
} }
// log.info("生成温控采集指令>>>>" + str);
// System.out.println("生成温控采集指令>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -455,7 +449,7 @@ public class GetReadOrder485 {
public static String createMulTempOrder(DeviceCodeParamEntity orderParamModel){ public static String createMulTempOrder(DeviceCodeParamEntity orderParamModel){
String deviceAddr=orderParamModel.getDeviceAddr(); String deviceAddr=orderParamModel.getDeviceAddr();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
try{ try{
str = ExchangeStringUtil.decToHex(deviceAddr); str = ExchangeStringUtil.decToHex(deviceAddr);
@ -464,11 +458,9 @@ public class GetReadOrder485 {
String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验 String checkWord=ExchangeStringUtil.getStrCRC16(str); //CRC16校验
str = str + checkWord; str = str + checkWord;
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); log.info("生成多路温度变送器指令出错!" + str, e);
log.info("生成多路温度变送器指令出错!" + str);
} }
} }
// log.info("生成多路温度变送器采集指令>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }
@ -479,7 +471,7 @@ public class GetReadOrder485 {
String funCode=orderParamModel.getFunCode(); String funCode=orderParamModel.getFunCode();
String registerAddr=orderParamModel.getRegisterAddr(); String registerAddr=orderParamModel.getRegisterAddr();
String dataValue=orderParamModel.getDataValue(); String dataValue=orderParamModel.getDataValue();
String str=null; String str="";
if(deviceAddr!=null && deviceAddr.length()>0){ if(deviceAddr!=null && deviceAddr.length()>0){
str = ExchangeStringUtil.decToHex(deviceAddr); str = ExchangeStringUtil.decToHex(deviceAddr);
str = ExchangeStringUtil.addZeroForNum(str, 2); //以0补位 str = ExchangeStringUtil.addZeroForNum(str, 2); //以0补位
@ -501,11 +493,9 @@ public class GetReadOrder485 {
str = str + checkWord; str = str + checkWord;
// } // }
}catch (Exception e){ }catch (Exception e){
// e.printStackTrace(); log.error("生成时控指令出错!" + str, e);
log.info("生成时控指令出错!" + str);
} }
} }
// log.info("发送时控采集数据>>>>" + str);
return str.toUpperCase(); return str.toUpperCase();
} }

168
user-service/src/main/java/com/mh/user/utils/SendOrderUtils.java

@ -1,16 +1,9 @@
package com.mh.user.utils; package com.mh.user.utils;
import com.mh.user.entity.ChillersEntity;
import com.mh.user.entity.DeviceCodeParamEntity; import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.model.OrderParamModel;
import com.mh.user.serialport.SerialPortListener; import com.mh.user.serialport.SerialPortListener;
import com.mh.user.serialport.SerialPortUtil; import com.mh.user.serialport.SerialPortUtil;
import com.mh.user.serialport.SerialTool;
//import purejavacomm.SerialPort;
import gnu.io.SerialPort; import gnu.io.SerialPort;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
@ -23,80 +16,80 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class SendOrderUtils { public class SendOrderUtils {
/** // /**
* 发送采集冷水机组 // * 发送采集冷水机组
* @param chillersEntity // * @param chillersEntity
* @param ctx // * @param ctx
* @param num // * @param num
* @param size // * @param size
*/ // */
public static void sendChillersOrder(ChillersEntity chillersEntity, ChannelHandlerContext ctx, int num, int size) { // public static void sendChillersOrder(ChillersEntity chillersEntity, ChannelHandlerContext ctx, int num, int size) {
// 继续发送下一个采集冷水机设备指令 // // 继续发送下一个采集冷水机设备指令
GetReadOrder485 getReadOrder485 = new GetReadOrder485(); // GetReadOrder485 getReadOrder485 = new GetReadOrder485();
String sendStr = getReadOrder485.createChillersOrder(chillersEntity); // String sendStr = getReadOrder485.createChillersOrder(chillersEntity);
ByteBuf buffer = getByteBuf(ctx, sendStr); // ByteBuf buffer = getByteBuf(ctx, sendStr);
// 2.发送数据 // // 2.发送数据
ctx.channel().writeAndFlush(buffer); // ctx.channel().writeAndFlush(buffer);
log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size); // log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
} // }
//
public static void sendMeterOrCloud(DeviceManageEntity deviceManageEntity, // public static void sendMeterOrCloud(DeviceManageEntity deviceManageEntity,
int num, // int num,
String IP, // String IP,
String port, // String port,
ChannelHandlerContext ctx) { // ChannelHandlerContext ctx) {
if (deviceManageEntity.getParamId() == 1) { // if (deviceManageEntity.getParamId() == 1) {
sendMeterOrder(deviceManageEntity, num, IP, port, ctx); // sendMeterOrder(deviceManageEntity, num, IP, port, ctx);
} else if (deviceManageEntity.getParamId() == 3) { // } else if (deviceManageEntity.getParamId() == 3) {
sendCloudOrder(deviceManageEntity, num, IP, port, ctx); // sendCloudOrder(deviceManageEntity, num, IP, port, ctx);
} // }
} // }
/** // /**
* 发送采集电表 // * 发送采集电表
* @param deviceManageEntity // * @param deviceManageEntity
* @param num // * @param num
* @param IP // * @param IP
* @param port // * @param port
* @param ctx // * @param ctx
*/ // */
public static void sendMeterOrder(DeviceManageEntity deviceManageEntity, // public static void sendMeterOrder(DeviceManageEntity deviceManageEntity,
int num, // int num,
String IP, // String IP,
String port, // String port,
ChannelHandlerContext ctx) { // ChannelHandlerContext ctx) {
//// String collectionNum = deviceManageEntity.getCollectionNum();
//// String sendStr = GetReadOrder485.createMeterOrder();
// String sendStr="";
// ByteBuf buffer = getByteBuf(ctx, sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + num);
// }
//
// /**
// * 发送采集冷量计工具类
// * @param deviceManageEntity
// * @param num
// * @param IP
// * @param port
// * @param ctx
// */
// public static void sendCloudOrder(DeviceManageEntity deviceManageEntity,
// int num,
// String IP,
// String port,
// ChannelHandlerContext ctx) {
// // 1.创建将要写出的数据
// String collectionNum = deviceManageEntity.getCollectionNum(); // String collectionNum = deviceManageEntity.getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(); // String sendStr = GetReadOrder485.createCloudOrder(IP, port,
String sendStr=""; // deviceManageEntity.getDataCom(),
ByteBuf buffer = getByteBuf(ctx, sendStr); // collectionNum, "34");
// 2.发送数据 //// String sendStr = "5803004900021914";
ctx.channel().writeAndFlush(buffer); // ByteBuf buffer = getByteBuf(ctx, sendStr);
log.info("客户端再次往服务端发送数据" + num); // // 2.发送数据
} // ctx.channel().writeAndFlush(buffer);
// log.info("客户端再次往服务端发送数据" + sendStr);
/** // }
* 发送采集冷量计工具类
* @param deviceManageEntity
* @param num
* @param IP
* @param port
* @param ctx
*/
public static void sendCloudOrder(DeviceManageEntity deviceManageEntity,
int num,
String IP,
String port,
ChannelHandlerContext ctx) {
// 1.创建将要写出的数据
String collectionNum = deviceManageEntity.getCollectionNum();
String sendStr = GetReadOrder485.createCloudOrder(IP, port,
deviceManageEntity.getDataCom(),
collectionNum, "34");
// String sendStr = "5803004900021914";
ByteBuf buffer = getByteBuf(ctx, sendStr);
// 2.发送数据
ctx.channel().writeAndFlush(buffer);
log.info("客户端再次往服务端发送数据" + sendStr);
}
//向串口发指令数据 //向串口发指令数据
public static void sendSerialPort(DeviceCodeParamEntity deviceCodeParamEntity,SerialPort serialPort ) { public static void sendSerialPort(DeviceCodeParamEntity deviceCodeParamEntity,SerialPort serialPort ) {
@ -165,7 +158,6 @@ public class SendOrderUtils {
// orderParamModel.setDataValue(deviceCodeParamEntity.getDataValue());//传入数据 // orderParamModel.setDataValue(deviceCodeParamEntity.getDataValue());//传入数据
String deviceType=deviceCodeParamEntity.getDeviceType(); String deviceType=deviceCodeParamEntity.getDeviceType();
String registerAddr=deviceCodeParamEntity.getRegisterAddr();
String sendStr=null; String sendStr=null;
switch (deviceType) { switch (deviceType) {
case "电表": case "电表":
@ -205,11 +197,11 @@ public class SendOrderUtils {
private static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { // private static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// 申请一个数据结构存储信息 // // 申请一个数据结构存储信息
ByteBuf buffer = ctx.alloc().buffer(); // ByteBuf buffer = ctx.alloc().buffer();
// 将信息放入数据结构中 // // 将信息放入数据结构中
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制 // buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
return buffer; // return buffer;
} // }
} }

6
user-service/src/main/java/com/mh/user/utils/ThreadPoolService.java

@ -12,16 +12,16 @@ import java.util.concurrent.*;
public class ThreadPoolService { public class ThreadPoolService {
/** 线程池保持ALIVE状态线程数 */ /** 线程池保持ALIVE状态线程数 */
public static final int CORE_POOL_SIZE = 10; public static final int CORE_POOL_SIZE = 5;
/** 线程池最大线程数 */ /** 线程池最大线程数 */
public static final int MAX_POOL_SIZE = 50; public static final int MAX_POOL_SIZE = 10;
/** 空闲线程回收时间 */ /** 空闲线程回收时间 */
public static final int KEEP_ALIVE_TIME = 30000; public static final int KEEP_ALIVE_TIME = 30000;
/** 线程池等待队列 */ /** 线程池等待队列 */
public static final int BLOCKING_QUEUE_SIZE = 1000; public static final int BLOCKING_QUEUE_SIZE = 100;
// 私有化构造器 // 私有化构造器
private ThreadPoolService(){} private ThreadPoolService(){}

41
user-service/src/main/resources/application-prod.yml

@ -1,6 +1,8 @@
server: server:
port: 8761 #8761创新、8762广商、8763华厦、广州理工 port: 8763 #8761创新、8762广商、8763华厦、广州理工
spring: spring:
application:
name: user-service
datasource: datasource:
name: druidDataSource name: druidDataSource
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
@ -12,20 +14,20 @@ spring:
# password: mh@803 # password: mh@803
## url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=M_CHWS;allowMultiQueries=true ## url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=M_CHWS;allowMultiQueries=true
#阿里云服务器-广州理工 #阿里云服务器-广州理工
# url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=CHWS;allowMultiQueries=true url: jdbc:sqlserver://120.25.220.177:32012;DatabaseName=CHWS;allowMultiQueries=true
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
# username: test username: test
# password: minghan123456@ password: minghan123456@
#华厦云服务器 #华厦云服务器
# url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=CHWS;allowMultiQueries=true # url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=CHWS;allowMultiQueries=true
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver # driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
# username: chws # username: chws
# password: minghan123456@ # password: minghan123456@
#创新服务器 #创新服务器
url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_chx;allowMultiQueries=true # url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_chx;allowMultiQueries=true
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver # driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: chws # username: chws
password: mh@803 # password: mh@803
#广商服务器 #广商服务器
# url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_gsh;allowMultiQueries=true # url: jdbc:sqlserver://119.29.33.133:2008;DatabaseName=chws_gsh;allowMultiQueries=true
# driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver # driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
@ -88,8 +90,6 @@ spring:
# port: 8500 # port: 8500
# discovery: # discovery:
# service-name: ${spring.application.name} # service-name: ${spring.application.name}
# application:
# name: user-service
# 开放健康检查接口 # 开放健康检查接口
#management: #management:
# endpoints: # endpoints:
@ -102,22 +102,15 @@ spring:
#files: #files:
# path: ${file-path:d:/files} # path: ${file-path:d:/files}
log:
level:
root: info
my: debug
file:
maxsize: 30MB
#设置将SQL语句打印到控制台 level后面是 mybatis接口目录
logging: logging:
# level: level:
# com: com:
# mh: mh:
# user: user:
# mapper: DEBUG mapper: DEBUG
file: file:
max-size: 30 max-size: 30
path: logs/${spring.application.name}
##软件最后更新日期20230111 ##软件最后更新日期20230111

42
user-service/src/test/java/com/mh/user/UserServiceApplicationTests.java

@ -2,17 +2,17 @@ package com.mh.user;
import com.mh.user.entity.DeviceManageEntity; import com.mh.user.entity.DeviceManageEntity;
import com.mh.user.entity.GaugeEntity; import com.mh.user.entity.GaugeEntity;
import com.mh.user.serialport.SerialPortThread;
import com.mh.user.service.DeviceManageService; import com.mh.user.service.DeviceManageService;
import com.mh.user.service.GaugeService; import com.mh.user.service.GaugeService;
import com.mh.user.utils.AnalysisReceiveOrder485; import com.mh.user.utils.*;
import com.mh.user.utils.GetReadOrder485;
import com.mh.user.utils.PasswordEncoder;
import com.mh.user.utils.PasswordUtils;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
@SpringBootTest @SpringBootTest
class UserServiceApplicationTests { class UserServiceApplicationTests {
@ -59,7 +59,37 @@ class UserServiceApplicationTests {
// getReadOrder485.createOrderParam(); // getReadOrder485.createOrderParam();
// analysis.analysisRelayOrder485("220611000000013A220611000000023B220611000000033C220611000000043D220611000000053E220611000000063F22061100000007402206110000000841","0017","中凯"); // analysis.analysisRelayOrder485("220611000000013A220611000000023B220611000000033C220611000000043D220611000000053E220611000000063F22061100000007402206110000000841","0017","中凯");
} }
@Test
public void testHotWater() throws InterruptedException {
while (true) {
ThreadPoolExecutor comThreadPool = ComThreadPoolService.getInstance();
try {
for (int i = 1; i <= 4; i++) {
String threadName;
if (i == 1 || i == 3) {
threadName = "1";
System.out.println("------采集水位、水温!" + i + "------");
} else if (i == 2) {
threadName = "2";
System.out.println("------采集水、电、运行状态!" + i + "------");
} else {
threadName = "3";
System.out.println("------采集设定温度、设定水位、故障状态!" + i + "------");
}
CountDownLatch countDownLatch = new CountDownLatch(10);
for (int j = 1; j < 11; j++) {
SerialPortThread myThread = new SerialPortThread();
myThread.setName(threadName, String.valueOf(j), countDownLatch);
Thread thread = new Thread(myThread);
comThreadPool.submit(thread);
}
countDownLatch.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
}
}
}
} }

88
user-service/src/test/java/com/mh/user/socket/NettyClientTest.java

@ -1,44 +1,44 @@
package com.mh.user.socket; //package com.mh.user.socket;
//
import com.mh.user.netty.NettyClient; //import com.mh.user.netty.NettyClient;
import com.mh.user.netty.NettyMeterClient; //import com.mh.user.netty.NettyMeterClient;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test; //import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.boot.test.context.SpringBootTest;
//
/** ///**
* @author ljf // * @author ljf
* @title // * @title :
* @description // * @description :
* @updateTime 2020-05-13 // * @updateTime 2020-05-13
* @throws // * @throws :
*/ // */
@Slf4j //@Slf4j
@SpringBootTest //@SpringBootTest
public class NettyClientTest { //public class NettyClientTest {
//
@Test // @Test
void Test() throws InterruptedException { // void Test() throws InterruptedException {
NettyClient nettyClient = new NettyClient(); // NettyClient nettyClient = new NettyClient();
nettyClient.connect(1008,"192.168.1.222"); // nettyClient.connect(1008,"192.168.1.222");
// Thread.sleep(5000); //// Thread.sleep(5000);
// nettyClient.connect(10100,"192.168.1.222"); //// nettyClient.connect(10100,"192.168.1.222");
} // }
//
@Test // @Test
void Test1() throws InterruptedException { // void Test1() throws InterruptedException {
NettyClient nettyClient = new NettyClient(); // NettyClient nettyClient = new NettyClient();
nettyClient.connect(8080,"192.168.2.10"); // nettyClient.connect(8080,"192.168.2.10");
// Thread.sleep(5000); //// Thread.sleep(5000);
// nettyClient.connect(10100,"192.168.1.222"); //// nettyClient.connect(10100,"192.168.1.222");
} // }
//
//
@Test // @Test
void testMeterChillers() throws InterruptedException { // void testMeterChillers() throws InterruptedException {
NettyMeterClient nettyMeterClient = new NettyMeterClient(); // NettyMeterClient nettyMeterClient = new NettyMeterClient();
nettyMeterClient.connect(8080,"192.168.2.10"); // nettyMeterClient.connect(8080,"192.168.2.10");
// nettyMeterClient.connect(9000,"192.168.2.54"); //// nettyMeterClient.connect(9000,"192.168.2.54");
} // }
//
} //}

364
user-service/src/test/java/com/mh/user/socket/NettyEchoServer.java

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

Loading…
Cancel
Save