YiTongGpsServerHandler.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package com.tidecloud.dataacceptance.service.impl;
  2. import java.util.Date;
  3. import javax.xml.bind.DatatypeConverter;
  4. import org.apache.commons.lang.StringUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.slf4j.MDC;
  8. import org.springframework.context.annotation.Scope;
  9. import org.springframework.stereotype.Component;
  10. import com.tidecloud.dataacceptance.codec.HeaderTailDelimiterFrameDecoder;
  11. import com.tidecloud.dataacceptance.common.CRCUtil;
  12. import com.tidecloud.dataacceptance.common.DateUtil;
  13. import com.tidecloud.dataacceptance.common.NumUtil;
  14. import com.tidecloud.dataacceptance.entity.YiTongGPSDevice;
  15. import com.tidecloud.dataacceptance.entity.YiTongGpsForWarnDevice;
  16. import com.tidecloud.dataacceptance.service.HexBinaryAcceptanceHandlerAdapter;
  17. import com.tidecloud.dataacceptance.util.FileUtils;
  18. import io.netty.bootstrap.ServerBootstrap;
  19. import io.netty.buffer.ByteBuf;
  20. import io.netty.buffer.Unpooled;
  21. import io.netty.channel.Channel;
  22. import io.netty.channel.ChannelFuture;
  23. import io.netty.channel.ChannelHandler;
  24. import io.netty.channel.ChannelInitializer;
  25. import io.netty.channel.ChannelOption;
  26. import io.netty.channel.EventLoopGroup;
  27. import io.netty.channel.nio.NioEventLoopGroup;
  28. import io.netty.channel.socket.SocketChannel;
  29. import io.netty.channel.socket.nio.NioServerSocketChannel;
  30. import io.netty.util.concurrent.Future;
  31. import io.netty.util.concurrent.GenericFutureListener;
  32. /**
  33. * @author cdk
  34. */
  35. @Component
  36. @ChannelHandler.Sharable
  37. @Scope("prototype")
  38. public class YiTongGpsServerHandler extends HexBinaryAcceptanceHandlerAdapter {
  39. private static final Logger logger = LoggerFactory.getLogger(YiTongGpsServerHandler.class);
  40. private static final Integer START_BITS = 2;
  41. private static final Byte START_BIT = 0x78;
  42. private static final Byte START_BIT2 = 0X79;
  43. private static final byte LOGIN_MSG = 0x01;
  44. private static final byte LOCATION_MSG = 0x22;
  45. private static final byte STATUS_MSG = 0x13;
  46. private static final byte WARNING_MSG = 0x26;
  47. private static final byte CORRECT_TIME_MSG = (byte) 0x8A;
  48. private static final byte VOLTAGE_MSG = (byte) 0x94;
  49. private static final byte VOLTAGE_SUB_MSG = (byte) 0x00;
  50. private static final byte COMMAND_COPY_MSG = 0x15;
  51. private static final Integer DATA_SIZE = 6;
  52. @Override
  53. protected void handle(ByteBuf in, Channel channel) throws Exception {
  54. if (in.isReadable()) {
  55. in.markReaderIndex();
  56. try {
  57. int index = 0;
  58. byte b = 0;
  59. while (index < START_BITS) {
  60. b = in.readByte();
  61. if (START_BIT != b && START_BIT2 != b) {
  62. channel.close();
  63. }
  64. index++;
  65. }
  66. int length = 0;
  67. if (START_BIT == b) {
  68. length = in.readByte() & 0xff;
  69. } else {
  70. length = in.readShort() & 0xffff;
  71. }
  72. handle(in, length, channel);
  73. } catch (Exception e) {
  74. logger.error(e.getMessage(), e);
  75. }
  76. }
  77. }
  78. private byte[] getOriginalData(ByteBuf in, String deviceId) {
  79. if (StringUtils.isNotBlank(deviceId)) {
  80. in.resetReaderIndex();
  81. byte[] deviceArr = deviceId.getBytes();
  82. int length = in.readableBytes();
  83. byte[] dataByteArray = new byte[length + deviceArr.length];
  84. in.readBytes(dataByteArray,0,in.readableBytes());
  85. System.arraycopy(deviceArr, 0, dataByteArray, length, deviceArr.length);
  86. return dataByteArray;
  87. } else
  88. return null;
  89. }
  90. private void handle(ByteBuf in, int length, Channel channel) throws Exception {
  91. if (in.isReadable()) {
  92. String deviceId = channelDeviceMap.get(channel);
  93. if (deviceId!=null) {
  94. MDC.put(MDC_DEVICEID, deviceId);
  95. }
  96. byte msgType = in.readByte();
  97. if (LOGIN_MSG == msgType) {
  98. resolveLoginMSG(in, channel);
  99. } else if (LOCATION_MSG == msgType) {
  100. logger.info("GPS 定位包");
  101. sendMsg2Kafka(getOriginalData(in, deviceId), deviceId, channel);
  102. // resolveLocationMSG(in, deviceId);
  103. } else if (STATUS_MSG == msgType) {
  104. reply(channel, STATUS_MSG);
  105. } else if (WARNING_MSG == msgType) {
  106. logger.info("报警数据(UTC)");
  107. reply(channel, WARNING_MSG);
  108. sendMsg2Kafka(getOriginalData(in, deviceId), deviceId, channel);
  109. } else if (CORRECT_TIME_MSG == msgType) {
  110. reply(channel, CORRECT_TIME_MSG);
  111. } else if (VOLTAGE_MSG == msgType) {
  112. logger.info("信息传输通用包");
  113. sendMsg2Kafka(getOriginalData(in, deviceId), deviceId, channel);
  114. // resolveVoltageMSG(in, channel);
  115. } else if (COMMAND_COPY_MSG == msgType) {
  116. // resolveCommandCopyMSG(in, channel, length);
  117. } else {
  118. logger.info("client send data without handle type ...");
  119. }
  120. }
  121. }
  122. private void resolveLoginMSG(ByteBuf in, Channel channel) {
  123. byte[] deviceIdBytes = new byte[8];
  124. in.readBytes(deviceIdBytes);
  125. String deviceId = DatatypeConverter.printHexBinary(deviceIdBytes);
  126. MDC.put(MDC_DEVICEID, deviceId);
  127. // 回复和链接管理
  128. String deviceIdInMap = channelDeviceMap.get(channel);
  129. if (!deviceId.equals(deviceIdInMap)) {
  130. manageChannel(channel, deviceId);
  131. }
  132. reply(channel, LOGIN_MSG);
  133. }
  134. private void reply(Channel channel, byte msgType) {
  135. ByteBuf buffer = Unpooled.buffer();
  136. byte[] crcBytes = new byte[] { 0x05, msgType, 0x00, 0x05 };
  137. int doCrc = CRCUtil.do_crc(65535, crcBytes);
  138. byte[] intToByte = NumUtil.intToByte(doCrc, 2);
  139. byte[] bytes = new byte[] { 0x78, 0x78, 0x05, msgType, 0x00, 0x05, intToByte[0], intToByte[1], 0x0D, 0x0A };
  140. buffer.writeBytes(bytes);
  141. ChannelFuture channelFuture = channel.write(buffer);
  142. channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
  143. @Override
  144. public void operationComplete(Future<? super Void> future) throws Exception {
  145. String deviceId = channelDeviceMap.get(channel);
  146. String type = "";
  147. switch (msgType) {
  148. case STATUS_MSG:
  149. type = "心跳包";
  150. break;
  151. case WARNING_MSG:
  152. type = "报警数据(UTC)";
  153. break;
  154. case CORRECT_TIME_MSG:
  155. type = "校时包";
  156. break;
  157. case LOGIN_MSG:
  158. type = "登录包";
  159. break;
  160. default:
  161. break;
  162. }
  163. logger.info("server reply [{}] to client device [{}] success:[{}] ",type,deviceId, DatatypeConverter.printHexBinary(bytes));
  164. }
  165. });
  166. }
  167. public void startAcceptor() {
  168. EventLoopGroup bossGroup = new NioEventLoopGroup();
  169. EventLoopGroup workerGroup = new NioEventLoopGroup();
  170. byte[] headerSplitBytes = new byte[] { 0x78, 0x78 };
  171. byte[] headerSplitBytes1 = new byte[] { 0x79, 0x79 };
  172. byte[] tailSplitBytes = new byte[] { 0x0D, 0x0A };
  173. try {
  174. ServerBootstrap b = new ServerBootstrap();
  175. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
  176. .childHandler(new ChannelInitializer<SocketChannel>() {
  177. @Override
  178. protected void initChannel(SocketChannel ch) throws Exception {
  179. ch.pipeline().addLast(new HeaderTailDelimiterFrameDecoder(65535, false,
  180. Unpooled.copiedBuffer(tailSplitBytes), Unpooled.copiedBuffer(headerSplitBytes),
  181. Unpooled.copiedBuffer(headerSplitBytes1)));
  182. ch.pipeline().addLast(YiTongGpsServerHandler.this);
  183. }
  184. }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
  185. ChannelFuture f = b.bind(port).sync();
  186. logger.info("start accept service for {}, bind address {}:{}", this.getPrefixName(), this.getIp(),
  187. this.getPort());
  188. f.channel().closeFuture().sync();
  189. } catch (InterruptedException e) {
  190. logger.error(e.getMessage());
  191. } finally {
  192. cleanRedisLinkData();
  193. workerGroup.shutdownGracefully();
  194. bossGroup.shutdownGracefully();
  195. }
  196. }
  197. }