CodeReader14Connect.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package com.warewms.hailiang.connect;
  2. import cn.hutool.extra.spring.SpringUtil;
  3. import com.github.rholder.retry.*;
  4. import com.warewms.hailiang.config.CodeReadProperties;
  5. import com.warewms.hailiang.connect.base.TCPConnectBase;
  6. import com.warewms.hailiang.domain.Device;
  7. import com.warewms.hailiang.domain.DeviceLog;
  8. import com.warewms.hailiang.domain.RetroactiveNow;
  9. import com.warewms.hailiang.service.RetroactiveNowService;
  10. import io.netty.bootstrap.Bootstrap;
  11. import io.netty.buffer.ByteBuf;
  12. import io.netty.buffer.Unpooled;
  13. import io.netty.channel.*;
  14. import io.netty.channel.nio.NioEventLoopGroup;
  15. import io.netty.channel.socket.SocketChannel;
  16. import io.netty.channel.socket.nio.NioSocketChannel;
  17. import io.netty.handler.timeout.IdleStateHandler;
  18. import io.netty.util.CharsetUtil;
  19. import lombok.extern.slf4j.Slf4j;
  20. import java.util.concurrent.*;
  21. import java.util.concurrent.atomic.AtomicBoolean;
  22. /**
  23. * Created with IntelliJ IDEA.
  24. *
  25. * @author: liuzhifei
  26. * Date: 2023/8/9
  27. * Time: 15:45
  28. * To change this template use File | Settings | File Templates.
  29. * Description:退火读码器连接
  30. **/
  31. @Slf4j
  32. public class CodeReader14Connect implements TCPConnectBase {
  33. private final String IP_ADDR = "172.20.27.14";
  34. private final int PORT = 51236;
  35. private final String deviceName = "CodeReader14";
  36. private boolean enable = true;
  37. private ChannelFuture future;
  38. private Bootstrap bootstrap;
  39. private EventLoopGroup group;
  40. private ChannelPipeline pipeline;
  41. private RetroactiveNowService retroactiveNowService;
  42. private ScheduledFuture<?> scheduledFuture = null;
  43. private ScheduledExecutorService scheduledExecutorService;
  44. {
  45. retroactiveNowService = SpringUtil.getBean(RetroactiveNowService.class);
  46. scheduledExecutorService = SpringUtil.getBean(ScheduledExecutorService.class);
  47. }
  48. @Override
  49. public void init() throws InterruptedException {
  50. if (enable) {
  51. log.info("ip:{},deviceName:{}正在进行连接", IP_ADDR, deviceName);
  52. group = new NioEventLoopGroup();
  53. try {
  54. bootstrap = new Bootstrap();
  55. bootstrap.group(group).channel(NioSocketChannel.class)
  56. .option(ChannelOption.TCP_NODELAY, true)
  57. .handler(new ChannelInitializer<SocketChannel>() {
  58. @Override
  59. protected void initChannel(SocketChannel socketChannel) throws Exception {
  60. pipeline = socketChannel.pipeline();
  61. pipeline.addLast(new IdleStateHandler(1, 0, 0, TimeUnit.SECONDS));
  62. pipeline.addLast(new ChannelInboundHandlerAdapter() {
  63. @Override
  64. public void channelInactive(ChannelHandlerContext ctx) {
  65. SpringUtil.getApplicationContext().publishEvent(new Device(deviceName, "2"));
  66. log.error("设备:{}连接已断开!", deviceName);
  67. scheduledFuture.cancel(true);
  68. retry();
  69. }
  70. @Override
  71. public void channelRead(ChannelHandlerContext ctx, Object msg) {
  72. ByteBuf byteBuf = (ByteBuf) msg;
  73. processMessages(String.valueOf(byteBuf.toString(CharsetUtil.UTF_8)));
  74. }
  75. });
  76. }
  77. });
  78. future = bootstrap.connect(IP_ADDR, PORT).sync();
  79. future.addListener((channelFuture) -> {
  80. if (channelFuture.isSuccess()) {
  81. SpringUtil.getApplicationContext().publishEvent(new Device(deviceName, "1"));
  82. log.info("ip:{},deviceName:{}连接成功", IP_ADDR, deviceName);
  83. ConnectsTheHeartbeat();
  84. } else {
  85. log.info("ip:{},deviceName:{}连接失败等待重试!", IP_ADDR, deviceName);
  86. retry();
  87. }
  88. });
  89. } catch (Exception e) {
  90. log.error("ip:{},deviceName:{}连接异常,{},准备重试", IP_ADDR, deviceName, e.getMessage());
  91. retry();
  92. }
  93. }
  94. }
  95. @Override
  96. public void retry() {
  97. Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
  98. .retryIfResult(Boolean.FALSE::equals)
  99. .retryIfExceptionOfType(Exception.class)
  100. .withStopStrategy(StopStrategies.neverStop())
  101. .withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS))
  102. .build();
  103. try {
  104. retryer.call(new Callable<Boolean>() {
  105. AtomicBoolean isSuccess = new AtomicBoolean(false);
  106. @Override
  107. public Boolean call() throws Exception {
  108. log.info("ip:{},deviceName:{}连接重试", IP_ADDR, deviceName);
  109. future = bootstrap.connect(IP_ADDR, PORT).sync();
  110. future.addListener((channelFuture) -> {
  111. isSuccess.set(channelFuture.isSuccess());
  112. if (channelFuture.isSuccess()) {
  113. SpringUtil.getApplicationContext().publishEvent(new Device(deviceName, "1"));
  114. log.info("ip:{},deviceName:{}连接成功", IP_ADDR, deviceName);
  115. ConnectsTheHeartbeat();
  116. } else {
  117. log.info("ip:{},deviceName:{}连接失败等待重试!", IP_ADDR, deviceName);
  118. }
  119. });
  120. Thread.sleep(3000);
  121. return isSuccess.get();
  122. }
  123. });
  124. } catch (RetryException | ExecutionException e) {
  125. e.printStackTrace();
  126. }
  127. }
  128. /**
  129. * 连接心跳
  130. */
  131. private void ConnectsTheHeartbeat() {
  132. scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
  133. try {
  134. // log.info("发送心跳,设备:{}", deviceName);
  135. pipeline.writeAndFlush(Unpooled.copiedBuffer(CodeReadProperties.heartbeat, CharsetUtil.UTF_8));
  136. } catch (Exception e) {
  137. log.error("设备:{},连接中断", deviceName);
  138. SpringUtil.getApplicationContext().publishEvent(new Device(deviceName, "2"));
  139. retry();
  140. }
  141. }, 0, 3, TimeUnit.SECONDS);
  142. }
  143. @Override
  144. public void close() {
  145. group.shutdownGracefully();
  146. }
  147. @Override
  148. public String getDeviceName() {
  149. return deviceName;
  150. }
  151. @Override
  152. public ChannelPipeline getChannel() {
  153. return pipeline;
  154. }
  155. @Override
  156. public void processMessages(String message) {
  157. try {
  158. log.info("退货下料读码器消息:{}", message);
  159. if (CodeReadProperties.failureReturnInstruction.equals(message)) {
  160. SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "未识别到码", "2"));
  161. } else {
  162. // 读取到批次号保存到数据库中
  163. RetroactiveNow retroactiveNow = new RetroactiveNow();
  164. retroactiveNow.setLotNo(message);
  165. retroactiveNow.setStatus("7");
  166. retroactiveNow.setDeviceId("Z1_TuiHuoXiaLiao_DMQ-1-27.14");
  167. retroactiveNowService.finishProduce(retroactiveNow);
  168. //添加设备日志
  169. SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "识别到码:" + message, "1"));
  170. }
  171. Thread.sleep(500);
  172. }catch (Exception e){
  173. log.error("退货下料读码任务执行异常,msg:",e);
  174. SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "读码任务出错,msg:"+e.getMessage(), "2"));
  175. }
  176. }
  177. // private int a = 1;
  178. //
  179. // @Override
  180. // public void processMessages(String message) {
  181. // try {
  182. // if (CodeReadProperties.failureReturnInstruction.equals(message)) {
  183. // SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "未识别到码", "2"));
  184. // return;
  185. // }
  186. // SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "识别到码:" + message, "1"));
  187. // Thread.sleep(500);
  188. // if (a <= 300) {
  189. // a++;
  190. // pipeline.writeAndFlush(Unpooled.copiedBuffer(CodeReadProperties.startTheCommand, CharsetUtil.UTF_8));
  191. // }
  192. // } catch (Exception e) {
  193. // e.printStackTrace();
  194. // SpringUtil.getApplicationContext().publishEvent(new DeviceLog("Z1_TuiHuoXiaLiao_DMQ-1-27.14", deviceName, "读码任务出错,msg:" + e.getMessage(), "2"));
  195. // }
  196. // }
  197. }