LedNettyConfig.java 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package com.gzlh.device.led.client;
  2. import com.gzlh.bus.EventConfig;
  3. import com.gzlh.config.ModuleEnum;
  4. import com.gzlh.config.dto.SerialSetting;
  5. import com.gzlh.config.netty.NettyDecoder;
  6. import com.gzlh.device.led.brand.LedBrandType;
  7. import com.gzlh.entity.DeviceStatus;
  8. import com.gzlh.utils.DeviceCache;
  9. import com.gzlh.utils.XorUtils;
  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.codec.string.StringDecoder;
  18. import io.netty.handler.codec.string.StringEncoder;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.context.annotation.Bean;
  22. import org.springframework.context.annotation.Configuration;
  23. import javax.annotation.Resource;
  24. import java.nio.ByteBuffer;
  25. import java.nio.charset.Charset;
  26. import java.nio.charset.StandardCharsets;
  27. import java.util.List;
  28. import java.util.concurrent.TimeUnit;
  29. import java.util.stream.Collectors;
  30. @Configuration
  31. @Slf4j
  32. public class LedNettyConfig {
  33. @Autowired
  34. private LedClientHandler ledClientHandler;
  35. private Channel channel;
  36. @Bean("ledBootstrap")
  37. public Bootstrap bootstrap() {
  38. SerialSetting serialSetting= EventConfig.serialSetting;
  39. String host = serialSetting.getHost();
  40. int port = serialSetting.getLed().getPort();
  41. if (serialSetting.getLed().getEnable()) {
  42. log.info("初始化 led:{},{}", host, port);
  43. }
  44. EventLoopGroup group = new NioEventLoopGroup();
  45. return new Bootstrap()
  46. .group(group)
  47. .channel(NioSocketChannel.class)
  48. .remoteAddress(host, port)
  49. .option(ChannelOption.SO_KEEPALIVE, true)
  50. .handler(new ChannelInitializer<SocketChannel>() {
  51. @Override
  52. protected void initChannel(SocketChannel ch) {
  53. try {
  54. ChannelPipeline pipeline = ch.pipeline();
  55. pipeline.addLast( new NettyDecoder());
  56. pipeline.addLast( new StringEncoder(StandardCharsets.UTF_8));
  57. pipeline.addLast("handler", ledClientHandler);
  58. } catch (Exception e) {
  59. log.info("error connect:{}", e.getMessage());
  60. }
  61. }
  62. });
  63. }
  64. @Bean("ledClientHandler")
  65. public LedClientHandler ledClientHandler() {
  66. return new LedClientHandler(this);
  67. }
  68. public void connect() {
  69. SerialSetting serialSetting= EventConfig.serialSetting;
  70. String host = serialSetting.getHost();
  71. int port = serialSetting.getLed().getPort();
  72. ChannelFuture future = bootstrap().connect();
  73. future.addListener((ChannelFutureListener) future1 -> {
  74. if (future1.isSuccess()) {
  75. channel = future1.channel();
  76. log.info("led 串口服务器连接成功,{},{}", host, port);
  77. DeviceCache.changeDeviceStatus(ModuleEnum.PLC_MODULE.getModuleEn(),1);
  78. } else {
  79. log.error("-------------led 连接服务器失败,{},{}-----------,进行重连", host, port);
  80. future1.channel().eventLoop().schedule(this::connect, 5, TimeUnit.SECONDS);
  81. }
  82. });
  83. try {
  84. future.channel().closeFuture().sync();
  85. } catch (InterruptedException e) {
  86. e.printStackTrace();
  87. }
  88. }
  89. public void send(String message) {
  90. if (channel != null && channel.isActive()) {
  91. ByteBuf bufff = Unpooled.buffer();
  92. bufff.writeBytes(XorUtils.hexString2Bytes(message));
  93. channel.writeAndFlush(bufff);
  94. } else {
  95. log.error("未建立连接,无法发送消息");
  96. }
  97. }
  98. public void close() {
  99. if (channel != null) {
  100. channel.close();
  101. }
  102. }
  103. private byte[] hexStringToByteArray(String hexString) {
  104. int len = hexString.length();
  105. byte[] data = new byte[len / 2];
  106. for (int i = 0; i < len; i += 2) {
  107. data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
  108. + Character.digit(hexString.charAt(i+1), 16));
  109. }
  110. return data;
  111. }
  112. }