Browse Source

1、代码优化

prod_202403
mh 7 months ago
parent
commit
c2fdcf763d
  1. 16
      user-service/src/main/java/com/mh/user/constants/Constant.java
  2. 3
      user-service/src/main/java/com/mh/user/job/DealDataJob.java
  3. 41
      user-service/src/main/java/com/mh/user/job/JobCloud.java
  4. 39
      user-service/src/main/java/com/mh/user/job/JobMeter.java
  5. 32
      user-service/src/main/java/com/mh/user/job/JobTest.java
  6. 32
      user-service/src/main/java/com/mh/user/job/JobTest1.java
  7. 190
      user-service/src/main/java/com/mh/user/job/SendMeterWaterJob.java
  8. 98
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlClient.java
  9. 311
      user-service/src/main/java/com/mh/user/netty/NettyChillerControlHandler.java
  10. 90
      user-service/src/main/java/com/mh/user/netty/NettyClient.java
  11. 295
      user-service/src/main/java/com/mh/user/netty/NettyClientHandler.java
  12. 179
      user-service/src/main/java/com/mh/user/netty/NettyEchoServer.java
  13. 97
      user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClient.java
  14. 193
      user-service/src/main/java/com/mh/user/netty/NettyMeterAndCloudClientHandler.java
  15. 96
      user-service/src/main/java/com/mh/user/netty/NettyMeterClient.java
  16. 143
      user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler.java
  17. 259
      user-service/src/main/java/com/mh/user/netty/NettyMeterClientHandler1.java
  18. 56
      user-service/src/main/java/com/mh/user/serialport/SerialPortSendReceive2.java
  19. 38
      user-service/src/main/java/com/mh/user/utils/AnalysisReceiveOrder485.java
  20. 14
      user-service/src/test/java/com/mh/user/SysUserTest.java
  21. 40
      user-service/src/test/java/com/mh/user/TestJwtUtils.java

16
user-service/src/main/java/com/mh/user/constants/Constant.java

@ -25,5 +25,21 @@ public class Constant {
public static final String WRITE = "1";
// 远向设备寄存器地址判断:0010:供回水状态;0017-0018:热泵状态
public static final String REG_ADDR_0018 = "0018";
public static final String REG_ADDR_0017 = "0017";
public static final String REG_ADDR_0010 = "0010";
public static final String BRAND_AU_SUN = "澳升";
public static final String BRAND_RU_YI = "汝翊";
public static final String BRAND_MEI_DI = "美的";
public static final String BRAND_MEI_DI_TWO = "美的2";
}

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

@ -96,6 +96,9 @@ public class DealDataJob {
int batchSize = 10; // 定义一个批次大小
int index = 0;
for (int k = 0; k < dataComMap.size(); ) {
if (Constant.WEB_FLAG) {
break;
}
CountDownLatch countDownLatch = new CountDownLatch(Math.min(batchSize, dataComMap.size() - k));
index = k;
for (int j = 0; j < Math.min(batchSize, dataComMap.size() - k); j++) {

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

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

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

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

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

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

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

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

190
user-service/src/main/java/com/mh/user/job/SendMeterWaterJob.java

@ -1,190 +0,0 @@
package com.mh.user.job;//package com.mh.quartz.job;
//
//import com.mh.quartz.manage.SerialPortManager;
//import com.mh.quartz.utils.AnalysisReceiveOrder485;
//import com.mh.quartz.utils.ExchangeStringUtil;
//import com.mh.quartz.utils.GetReadOrder485;
//import gnu.io.PortInUseException;
//import gnu.io.SerialPort;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import java.util.Date;
//import java.util.concurrent.BlockingQueue;
//import java.util.concurrent.LinkedBlockingQueue;
//
///**
// * @author ljf
// * @title :
// * @description : 定时采集发送水电表数据
// * @updateTime 2020-04-22
// * @throws :
// */
//@Component
//@Slf4j
//public class SendMeterWaterJob {
//
// // 串口对象
// private SerialPort mSerialPort;
//
// AnalysisReceiveOrder485 analysisReceiveOrder485;
//
// // 测试
// @Scheduled(cron = "0,5 * * * * ? ")
// public void test() throws InterruptedException {
// Thread.sleep(10000);
// log.info("延迟10s");
// }
//
// @Scheduled(cron = "0,20,40 * * * * ? ")
// public void task1() throws PortInUseException, InterruptedException {
//
// // 堵塞队列用来存放读到的数据
// BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
// log.info("每0、20、40秒执行一次!");
// if (mSerialPort == null){
// // 打开串口
// } else {
// // 关闭串口
// SerialPortManager.closePort(mSerialPort);
// }
//
// mSerialPort = SerialPortManager.openPort("COM2",1200);
//
// // 发送数据(采集冷量计累计流量)
// String sendMeterOrderStr = "FEFEFE" + GetReadOrder485.createMeterOrder("080140001125","1");
// SerialPortManager.sendToPort(mSerialPort, ExchangeStringUtil.hexStrToBinaryStr(sendMeterOrderStr));
//
// // 添加串口监听
// SerialPort finalMSerialPort = mSerialPort;
// SerialPortManager.addListener(mSerialPort, () -> {
// byte[] data = null;
// try {
// // 读取串口数据
// data = SerialPortManager.readFromPort(finalMSerialPort);
// String needData = ExchangeStringUtil.printHexString(data);
// msgQueue.add(needData);
// } catch (Exception e) {
// log.info(e.getMessage());
// }
// });
//
// // 创建线程解析队列信息
// Thread thread = new Thread(() -> {
// try {
// log.info("--------------任务处理线程运行了--------------");
// String vo = "";
// String vos[] = new String[0];
// while (true) {
// // 判断数组是否完整
// // 电表
// if (vos.length >= 22) {
// log.info("获取到数据长度: " + vos.length);
// log.info("电表: " + new Date() + " 完整收到的数据为:-----" + vo);
// // 解析接收到的报文
// analysisReceiveOrder485.analysisMeterOrder485(vo);
// vos = new String[0];
// vo = "";
//// sendOrder();
// } else {
// // 如果堵塞队列中存在数据就将其输出
// if (msgQueue.size() > 0) {
// if (vo == "") {
// vo = msgQueue.peek();
// } else {
// vo = vo + " " + msgQueue.peek();
// }
// vos = vo.split(" ", -1);
//// getData(vos);
// msgQueue.take();
// }
// }
// }
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// });
//
// thread.start();
//
// }
//
// @Scheduled(cron = "10,30,50 * * * * ? ")
// public void task2() throws PortInUseException, InterruptedException {
// // 堵塞队列用来存放读到的数据
// BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
// log.info("每10、30、50秒执行一次!");
// if (mSerialPort == null){
// // 打开串口
// } else {
// // 关闭串口
// SerialPortManager.closePort(mSerialPort);
// }
// mSerialPort = SerialPortManager.openPort("COM3",9600);
//
// // 发送数据(采集冷量计累计流量)
// String sendOrderStr = GetReadOrder485.createCloudOrder("88","34");
// SerialPortManager.sendToPort(mSerialPort, ExchangeStringUtil.hexStrToBinaryStr(sendOrderStr));
//
// // 添加串口监听
// SerialPort finalMSerialPort = mSerialPort;
// SerialPortManager.addListener(mSerialPort, () -> {
// byte[] data = null;
// try {
// // 读取串口数据
// data = SerialPortManager.readFromPort(finalMSerialPort);
// String needData = ExchangeStringUtil.printHexString(data);
// msgQueue.add(needData);
// } catch (Exception e) {
// log.info(e.getMessage());
// }
// });
//
// // 创建线程解析队列信息
// Thread thread = new Thread(() -> {
// try {
// log.info("--------------任务处理线程运行了--------------");
// String vo = "";
// String vos[] = new String[0];
// while (true) {
// // 判断数组是否完整
// // 冷量计
// if (vos.length >= 9) {
// if (vos.length == 9) {
// log.info("获取到数据长度: " + vos.length);
// log.info("冷量计: " + new Date() + " 完整收到的数据为:-----" + vo);
// // 解析接收到的报文
// analysisReceiveOrder485.analysisCloudOrder485(vo);
// }
// vos = new String[0];
// vo = "";
//// sendOrder();
// } else {
// // 如果堵塞队列中存在数据就将其输出
// if (msgQueue.size() > 0) {
// if (vo.equalsIgnoreCase("")){
// vo = msgQueue.peek();
// } else {
// vo = vo + " " + msgQueue.peek();
// }
// vos = vo.split(" ", -1);
//// getData(vos);
// msgQueue.take();
// }
// }
//
//
// }
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// });
//
// thread.start();
//
// }
//
//}

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

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

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

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

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

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

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

@ -1,295 +0,0 @@
//package com.mh.user.netty;
//
//import com.mh.user.constants.Constant;
//import com.mh.user.entity.DeviceManageEntity;
//import com.mh.user.service.DeviceManageService;
//import com.mh.user.utils.*;
//import io.netty.buffer.ByteBuf;
//import io.netty.channel.Channel;
//import io.netty.channel.ChannelHandlerAdapter;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.util.ReferenceCountUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.ApplicationContext;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//
///**
// * @author ljf
// * @title :
// * @description :客户端异步消息处理机制
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//public class NettyClientHandler extends ChannelHandlerAdapter {
//
// private int num = 0;
// private int size = 0;
// private String receiveStr = null;
// private String IP = null;
// private String port = null;
// List<DeviceManageEntity> deviceManageEntityList;
//
// // 调用service
// ApplicationContext context = SpringBeanUtil.getApplicationContext();
// DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
//
//
// @Override
// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// log.info("当前channel从EventLoop取消注册");
// super.channelUnregistered(ctx);
// }
//
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//// super.exceptionCaught(ctx, cause);
// log.info("通信异常!!");
// receiveStr = null;
// Channel incoming = ctx.channel();
// if (incoming.isActive()){
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
// cause.printStackTrace();
// ctx.close();
//// receiveStr = null;
//// try {
//// TimeUnit.SECONDS.sleep(5);
//// SocketAddress remoteAddress = ctx.channel().remoteAddress();
//// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
//// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
//// NettyClient nettyClient = new NettyClient();
//// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
// }
// }
//
//
// @Override
// public void channelActive(ChannelHandlerContext ctx) {
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
// if (Constant.WEB_FLAG) {
// num = 0;
// // 关闭连接
// receiveStr = null;
// ctx.close();
// } else {
// ctx.channel().read();
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
// Date date = new Date();
// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
// // 截取IP地址
// IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
// // 截取端口号
// port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
// log.info("IP: " + IP + ",端口号: " + port);
// // 生成对应采集冷量计的命令
// // 生成对应的采集指令
// deviceManageEntityList = 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")) { // 冷量计
////
//// // 生成对应的采集指令
//// 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();
// }
//
//}

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

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

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

@ -1,97 +0,0 @@
//package com.mh.user.netty;
//
//import io.netty.bootstrap.Bootstrap;
//import io.netty.channel.*;
//import io.netty.channel.nio.NioEventLoopGroup;
//import io.netty.channel.socket.SocketChannel;
//import io.netty.channel.socket.nio.NioSocketChannel;
//import io.netty.handler.timeout.IdleStateHandler;
//import io.netty.handler.timeout.ReadTimeoutHandler;
//import lombok.Getter;
//import lombok.Setter;
//import lombok.extern.slf4j.Slf4j;
//
//import java.util.concurrent.TimeUnit;
//
///**
// * @author ljf
// * @title :
// * @description :Netty客户端,采集电表
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//@Setter
//@Getter
//public class NettyMeterAndCloudClient {
//// implements Runnable {
//
// private int port;
// private String host;
//
// // 构造函数传递值 继承Thread时需要
// public NettyMeterAndCloudClient(int port, String host) {
// this.port = port;
// this.host = host;
// }
//
// public NettyMeterAndCloudClient() {
// 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
//// @Override
//// public void run() {
//// connect(port, host);
//// }
//}

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

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

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

@ -1,96 +0,0 @@
//package com.mh.user.netty;
//
//import io.netty.bootstrap.Bootstrap;
//import io.netty.channel.*;
//import io.netty.channel.nio.NioEventLoopGroup;
//import io.netty.channel.socket.SocketChannel;
//import io.netty.channel.socket.nio.NioSocketChannel;
//import io.netty.handler.timeout.ReadTimeoutHandler;
//import lombok.Getter;
//import lombok.Setter;
//import lombok.SneakyThrows;
//import lombok.extern.slf4j.Slf4j;
//
///**
// * @author ljf
// * @title :
// * @description :Netty客户端,采集电表
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//@Setter
//@Getter
//public class NettyMeterClient {
//// implements Runnable {
//
// private int port;
// private String host;
//
// // 构造函数传递值 继承Thread时需要
// public NettyMeterClient(int port, String host) {
// this.port = port;
// this.host = host;
// }
//
// public NettyMeterClient() {
// super();
// }
//
// public void connect(int port, String host) throws InterruptedException {
// // 配置客户端NIO线程组
// // 配置客户端NIO线程组
// EventLoopGroup group = new NioEventLoopGroup(1);
// try {
// Bootstrap bootstrap = new Bootstrap();
// bootstrap.group(group).channel(NioSocketChannel.class)
// .option(ChannelOption.TCP_NODELAY, true)
// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
// .handler(new ChannelInitializer<SocketChannel>() {
// @Override
// protected void initChannel(SocketChannel socketChannel) {
// // 基于换行符号
//// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
// // 超过10秒钟没有数据读取自动断开连接
// socketChannel.pipeline().addLast(new ReadTimeoutHandler(20));
// // 在管道中添加我们自己的接收数据实现方法
//// socketChannel.pipeline().addLast(new NettyClientHandler());
// socketChannel.pipeline().addLast(new 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);
//// }
//}

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

@ -1,143 +0,0 @@
//package com.mh.user.netty;
//
//import com.mh.user.entity.DeviceManageEntity;
//import com.mh.user.service.DeviceManageService;
//import com.mh.user.utils.AnalysisReceiveOrder485;
//import com.mh.user.utils.ExchangeStringUtil;
//import com.mh.user.utils.GetReadOrder485;
//import com.mh.user.utils.SpringBeanUtil;
//import io.netty.buffer.ByteBuf;
//import io.netty.channel.Channel;
//import io.netty.channel.ChannelHandlerAdapter;
//import io.netty.channel.ChannelHandlerContext;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.ApplicationContext;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//
///**
// * @author ljf
// * @title :
// * @description :客户端异步消息处理机制
// * @updateTime 2020-05-13
// * @throws :
// */
//@Slf4j
//public class NettyMeterClientHandler extends ChannelHandlerAdapter {
//
// private static int num = 0;
// private static int size = 0;
// private static String receiveStr = "";
// private static String IP = "";
// List<DeviceManageEntity> deviceManageEntityList;
//
// // 调用service
// ApplicationContext context = SpringBeanUtil.getApplicationContext();
// DeviceManageService deviceManageService = context.getBean(DeviceManageService.class);
//
// AnalysisReceiveOrder485 analysisReceiveOrder485;
//
// // 到处理IO事件,异常抛出时调用,已丢弃
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// Channel incoming = ctx.channel();
// if (!incoming.isActive()){
// log.info("通信异常!!");
// receiveStr = "";
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
// cause.printStackTrace();
// ctx.close();
// }
// }
//
// @Override
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
// SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
// Date date=new Date();
// log.info(sdf1.format(date) + "链接服务端成功!");
// }
//
// 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);
// ctx.close();
// log.info("退出链接!!");
// }
//
// @Override
// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//// ByteBuf buf = (ByteBuf)msg;
//// byte[] req = new byte[buf.readableBytes()];
//// buf.readBytes(req);
//// String body = new String(req, "UTF-8");
// ByteBuf buf = (ByteBuf)msg;
// byte [] bytes = new byte[buf.readableBytes()];
// buf.readBytes(bytes);//复制内容到字节数组bytes
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
// }
//
// @Override
// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// log.info("数据读取接收完成");
// if (receiveStr.contains("c0a801f0")) { // 电表
//
// // 生成对应的采集指令
// deviceManageEntityList = deviceManageService.queryDevicesByType("1");
// size = deviceManageEntityList.size();
//
// log.info("初始连接报文: " + receiveStr);
// IP = receiveStr;
// receiveStr = "";
// num = 0;
// // 1.创建将要写出的数据
//// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
//// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
// String sendStr = GetReadOrder485.createMeterOrder(collectionNum,"1");
// ByteBuf buffer = getByteBuf(ctx,sendStr);
// // 2.发送数据
// ctx.channel().writeAndFlush(buffer);
// } else if ((receiveStr.length() == 44) && (IP.contains("c0a801f0"))) {
// analysisReceiveOrder485.analysisMeterOrder485(receiveStr); // 解析电表
// receiveStr = "";
// num = num + 1;
// Thread.sleep(1000);
// if (num >= size-1) {
// num = 0;
// // 关闭连接
// 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 = "";
// ctx.flush();
// ctx.close();
// }
// ctx.flush();
// }
//
//}

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

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

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

@ -12,7 +12,6 @@ import purejavacomm.SerialPort;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
@ -109,18 +108,18 @@ public class SerialPortSendReceive2 {
//从串口读取数据
byte[] bytes = SerialTool.readFromPort(serialPort);
Date date1 = new Date();
String dateStr = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");
if (bytes == null) {
SerialTool.closePort(serialPort);
log.info("串口" + serialPort + "没有数据返回!" + i);
log.info("----------------" + deviceType + "离线,设备号:" + deviceAddr + ",所属楼栋:" + buildingName + "----------------");
Constant.FLAG = false;//可以采集的状态
String time1 = deviceInstallService.selectLastDate(deviceType, deviceAddr, buildingId);
Date date1 = new Date();
String time2 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
if (time1 == null) {
time1 = DateUtil.dateToString(date1, "yyyy-MM-dd HH:mm:ss");;
time1 = dateStr;
}
int d = ExchangeStringUtil.compareCopyTime(time1, time2);
int d = ExchangeStringUtil.compareCopyTime(time1, dateStr);
if (d == 1) {
deviceInstallService.updateNotOnline(deviceAddr, deviceType, buildingId, "离线"); //所有设备离线
if (deviceType.equals("热泵")) {
@ -129,7 +128,6 @@ public class SerialPortSendReceive2 {
}
continue;
}
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
// 处理返回来的数据报文
dealReceiveData(dateStr, serialPort, i, deviceAddr, deviceType, registerAddr, brand, buildingId, buildingName, bytes);
}
@ -218,35 +216,39 @@ public class SerialPortSendReceive2 {
} else if ((dataStr.length() == 18 || dataStr.length() == 70 || dataStr.length() == 44) && deviceType.equals("水表")) {
analysisReceiveOrder485.analysisWtMeterOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("压变")) {
analysisReceiveOrder485.analysisPressureOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
analysisReceiveOrder485.analysisPressureOrder485(dateStr ,dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵")) {
analysisReceiveOrder485.analysisPumpOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
analysisReceiveOrder485.analysisPumpOrder485(dateStr ,dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("温控")) {
analysisReceiveOrder485.analysisTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("时控")) {
analysisReceiveOrder485.analysisTimeSetOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (registerAddr.equals("0018") || registerAddr.equals("0017"))) {
analysisReceiveOrder485.analysisRelayOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
analysisReceiveOrder485.analysisTimeSetOrder485(dateStr,dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && (Constant.REG_ADDR_0018.equals(registerAddr) || Constant.REG_ADDR_0017.equals(registerAddr))) {
analysisReceiveOrder485.analysisRelayOrder485(dateStr ,dataStr, registerAddr, brand, buildingId, buildingName);
} else if (dataStr.length() == 30 && deviceType.equals("状态检测")) {//五路状态读取,兼容旧版系统
analysisReceiveOrder485.analysisStateOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("水位开关") && registerAddr.equals("0010")) {
log.info("进入水位开关,地址==>{}", registerAddr);
SysParamEntity sysParamEntity = sysParamService.selectSysParam();
if (null != sysParamEntity && !StringUtils.isBlank(sysParamEntity.getCustomName())) {
if (sysParamEntity.getCustomName().contains(Constant.CUSTOM_NAME_HUAXIA)
|| sysParamEntity.getCustomName().contains(Constant.CUSTOM_NAME_GUANGSHANG)) {
analysisReceiveOrder485.analysisRelayOrder485(dataStr,registerAddr,brand,buildingId, buildingName); //华厦
} else {
analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName); //创新,热泵状态与水位共用一个8路设备
}
} else {
analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName); //创新,热泵状态与水位共用一个8路设备
}
nowDataService.proWaterLevel(dateStr, buildingId, ""); //保存时间点楼栋水位
} else if (deviceType.equals("水位开关") && Constant.REG_ADDR_0010.equals(registerAddr)) {
handleWaterSwitch(dateStr, dataStr, registerAddr, brand, buildingId, buildingName, analysisReceiveOrder485);
} else if (deviceType.equals("温度变送器")) {
analysisReceiveOrder485.analysisMulTempOrder485(dataStr, registerAddr, brand, buildingId, buildingName);
analysisReceiveOrder485.analysisMulTempOrder485(dateStr, dataStr, registerAddr, brand, buildingId, buildingName);
} else if (deviceType.equals("热泵状态")) {
analysisReceiveOrder485.analysisPumpStateOrder(dataStr, registerAddr, brand, buildingId, buildingName);
analysisReceiveOrder485.analysisPumpStateOrder(dateStr, dataStr, registerAddr, brand, buildingId, buildingName);
}
}
private void handleWaterSwitch(String dateStr, String dataStr, String registerAddr, String brand,
String buildingId, String buildingName, AnalysisReceiveOrder485 analysisReceiveOrder485) {
log.info("进入水位开关,地址==>{}", registerAddr);
SysParamEntity sysParamEntity = sysParamService.selectSysParam();
if (null != sysParamEntity && !StringUtils.isBlank(sysParamEntity.getCustomName())) {
if (sysParamEntity.getCustomName().contains(Constant.CUSTOM_NAME_HUAXIA)
|| sysParamEntity.getCustomName().contains(Constant.CUSTOM_NAME_GUANGSHANG)) {
analysisReceiveOrder485.analysisRelayOrder485(dateStr, dataStr,registerAddr,brand,buildingId, buildingName);
} else {
analysisReceiveOrder485.analysisPumpStateOrder(dateStr, dataStr, registerAddr, brand, buildingId, buildingName);
}
} else {
analysisReceiveOrder485.analysisPumpStateOrder(dateStr, dataStr, registerAddr, brand, buildingId, buildingName);
}
}

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

@ -263,10 +263,9 @@ public class AnalysisReceiveOrder485 {
}
// 热泵
public void analysisPumpOrder485(final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
public void analysisPumpOrder485(final String dateStr,final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
// if (!Constant.CONTROL_WEB_FLAG) {
// threadPoolService.execute(() -> {
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String checkStr = receiveData.substring(0, receiveData.length() - 4);//检验报文
String checkWord = ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码
String sValue = null;
@ -277,7 +276,7 @@ public class AnalysisReceiveOrder485 {
}
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = "";
if (brand == null || brand.equals("") || brand.equals("美的")) {
if (brand == null || brand.equals("") || Constant.BRAND_MEI_DI.equals(brand)) {
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {//读
if (registerAddr.equalsIgnoreCase("0641")) { //运行状态
dataType = "runState";
@ -354,7 +353,7 @@ public class AnalysisReceiveOrder485 {
} else if (checkStr.substring(2, 4).equalsIgnoreCase("10")) {
log.info("时间: " + dateStr + ",热泵ID: " + addr + ",操作成功! ");
}
} else if (brand.equals("美的2")) {
} else if (Constant.BRAND_MEI_DI_TWO.equals(brand)) {
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
if (registerAddr.equalsIgnoreCase("0BBD")) { //运行状态
dataType = "runState";
@ -668,7 +667,7 @@ public class AnalysisReceiveOrder485 {
}
// 温度变送器,长度42,读功能03
public void analysisMulTempOrder485(final String receiveData, final String registerAddr, final String brand, final String buildingId, final String buildingName) {
public void analysisMulTempOrder485(final String dateStr, final String receiveData, final String registerAddr, final String brand, final String buildingId, final String buildingName) {
// threadPoolService.execute(() -> {
String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
String checkWord = ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码
@ -700,7 +699,6 @@ public class AnalysisReceiveOrder485 {
int count = buildingService.selectPumpCount(buildingId); //楼栋热泵数
if (count > 0) {
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
for (Map.Entry<String, String> entry : map.entrySet()) {
addr = entry.getKey();
data = entry.getValue();
@ -817,7 +815,7 @@ public class AnalysisReceiveOrder485 {
}
// 压变,长度14,18读功能03
public void analysisPressureOrder485(final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
public void analysisPressureOrder485(final String dateStr,final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
// threadPoolService.execute(() -> {
String checkStr = receiveData.substring(0, receiveData.length() - 4);// 检验报文
String checkWord = ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码
@ -825,9 +823,6 @@ public class AnalysisReceiveOrder485 {
log.info("压变报文检验失败: " + receiveData);
return;
}
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf1.format(date);
String addr = ExchangeStringUtil.hexToDec(checkStr.substring(0, 2));//地址
String data = "";
if (checkStr.substring(2, 4).equalsIgnoreCase("03")) {// 读
@ -835,7 +830,7 @@ public class AnalysisReceiveOrder485 {
if (brand == null || brand.equals("")) {
float fdata = ExchangeStringUtil.hexToSingle(checkStr.substring(6, 14));//十六进制转浮点型
wtHeight = fdata * 1.02; //通过压力求水高
} else if (brand.equals("澳升") || brand.equals("汝翊")) {
} else if (Constant.BRAND_AU_SUN.equals(brand) || Constant.BRAND_RU_YI.equals(brand)) {
data = ExchangeStringUtil.hexToDec(checkStr.substring(6, 10));//十六进制转整形
wtHeight = Double.parseDouble(data) / 100 * 0.102; //通过压力求水高
}
@ -915,9 +910,8 @@ public class AnalysisReceiveOrder485 {
}
// 水位开关,长度42,128
public void analysisRelayOrder485(final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
public void analysisRelayOrder485(final String dateStr,final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
// threadPoolService.execute(() -> {
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String l1 = "";
String l2 = "";
String l3 = "";
@ -1199,9 +1193,8 @@ public class AnalysisReceiveOrder485 {
}
// 热泵状态处理(水位开关),长度42,128
public void analysisPumpStateOrder(final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
public void analysisPumpStateOrder(final String dateStr, final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
// threadPoolService.execute(() -> {
String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String l1 = "";
String l2 = "";
String l3 = "";
@ -1361,7 +1354,7 @@ public class AnalysisReceiveOrder485 {
for (Map.Entry<String, String> entry : map.entrySet()) {
addr = entry.getKey(); //获取Key值作为热泵ID
runState = entry.getValue();
if (addr != null && Integer.valueOf(addr) <= count) {
if (addr != null && Integer.parseInt(addr) <= count) {
nowDataService.saveNowHistoryData3(addr, "热泵状态", runState, "runState", buildingId);
nowDataService.proPumpMinutes(buildingId, addr, runState); //计算热泵运行时长
nowDataService.proWaterTemp(dateStr, buildingId, addr); //保存时间点温度
@ -1572,25 +1565,25 @@ public class AnalysisReceiveOrder485 {
String strStatus = ExchangeStringUtil.hexString2binaryString(data);
strStatus = String.format("%08d", Long.parseLong(strStatus));
String backWater;
if (strStatus.substring(7, 8).equals("1")) {//回水
if (strStatus.charAt(7) == '1') {//回水
backWater = "运行";
} else {
backWater = "不运行";
}
String hotPump;
if (strStatus.substring(6, 7).equals("1")) {//热泵
if (strStatus.charAt(6) == '1') {//热泵
hotPump = "运行";
} else {
hotPump = "不运行";
}
String upWater;
if (strStatus.substring(5, 6).equals("1")) {//上水或者补水
if (strStatus.charAt(5) == '1') {//上水或者补水
upWater = "运行";
} else {
upWater = "不运行";
}
String useWater;
if (strStatus.substring(4, 5).equals("1")) {//用水或者供水
if (strStatus.charAt(4) == '1') {//用水或者供水
useWater = "运行";
} else {
useWater = "不运行";
@ -1616,11 +1609,8 @@ public class AnalysisReceiveOrder485 {
}
//时间控制器,长度26、22
public void analysisTimeSetOrder485(final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
public void analysisTimeSetOrder485(final String dateStr, final String receiveData, final String registerAddr, final String brand, String buildingId, String buildingName) {
// 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 checkWord = ExchangeStringUtil.getStrCRC16(checkStr);//生成校验码

14
user-service/src/test/java/com/mh/user/SysUserTest.java

@ -2,12 +2,16 @@ package com.mh.user;
import com.mh.common.page.PageRequest;
import com.mh.common.page.PageResult;
import com.mh.user.entity.DeviceCodeParamEntity;
import com.mh.user.mapper.SysUserMapper;
import com.mh.user.model.SysUser;
import com.mh.user.service.SysUserService;
import com.mh.user.utils.CacheUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author ljf
* @title
@ -28,4 +32,14 @@ public class SysUserTest extends UserServiceApplicationTests {
// System.out.println(sysUserList);
}
@Test
public void testCache() {
for (int i = 0; i < 5; i++) {
CacheUtil cacheUtil = CacheUtil.getInstance();
cacheUtil.deleteCache();
List<DeviceCodeParamEntity> deviceParamsByType = cacheUtil.getDeviceParamsByType("1");
System.out.println(deviceParamsByType.size());
}
}
}

40
user-service/src/test/java/com/mh/user/TestJwtUtils.java

@ -4,6 +4,7 @@ import com.alibaba.fastjson2.JSONObject;
import com.mh.user.constants.Constant;
import com.mh.user.model.SysUser;
import com.mh.user.serialport.SerialPortThread;
import com.mh.user.utils.CacheUtil;
import com.mh.user.utils.ComThreadPoolService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
@ -147,38 +148,13 @@ public class TestJwtUtils {
* @param args
*/
public static void main(String[] args) throws InterruptedException {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("no", "abc");
// jsonObject.put("model", 1);
// jsonObject.put("scheme", 202);
// String inputString = "85b5cebb6132a189570d51bf5e34d93c"+jsonObject.toJSONString();
//
// try {
// // 获取MessageDigest实例用于MD5算法
// MessageDigest md = MessageDigest.getInstance("MD5");
//
// // 将输入字符串转换为字节数组并进行更新
// byte[] messageBytes = inputString.getBytes();
// md.update(messageBytes);
//
// // 完成哈希计算并获取结果字节数组
// byte[] digestBytes = md.digest();
//
// // 将字节数组转换为大写的十六进制字符串表示形式
// BigInteger no = new BigInteger(1, digestBytes);
// String hashtext = no.toString(16);
//
// // 如果生成的十六进制字符串长度小于32,则前面补0以达到32位
// while (hashtext.length() < 32) {
// hashtext = "0" + hashtext;
// }
//
// System.out.println("MD5 Hash: " + hashtext);
//
// } catch (NoSuchAlgorithmException e) {
// // 处理MD5算法不可用的情况
// e.printStackTrace();
// }
for (int i = 0; i < 5; i++) {
CacheUtil cacheUtil = CacheUtil.getInstance();
cacheUtil.deleteCache();
}
}
private static void createBatchSend() throws InterruptedException {
for (int a = 0; a < 100; a++) {
if (comThreadPool.isShutdown()) {
comThreadPool = ComThreadPoolService.getInstance();

Loading…
Cancel
Save