EnvInputServerHandler.java 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package com.huimv.env.input.server;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import com.huimv.env.input.entity.Chengzhong;
  6. import com.huimv.env.input.service.IChengzhongService;
  7. import com.huimv.env.input.utils.ModBusUtils;
  8. import io.netty.buffer.ByteBuf;
  9. import io.netty.buffer.Unpooled;
  10. import io.netty.channel.*;
  11. import io.netty.util.CharsetUtil;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.apache.tomcat.util.codec.binary.StringUtils;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.stereotype.Component;
  16. import java.io.IOException;
  17. import java.nio.charset.Charset;
  18. import java.text.ParseException;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import static com.huimv.env.input.utils.ModBusUtils.hexStr2Bytes;
  25. /**
  26. * @Project : huimv.shiwan
  27. * @Package : com.huimv.biosafety.uface.controller
  28. * @Description : TODO
  29. * @Version : 1.0
  30. * @Author : ZhuoNing
  31. * @Create : 2020-12-25
  32. **/
  33. @ChannelHandler.Sharable
  34. @Component
  35. @Slf4j
  36. public class EnvInputServerHandler extends ChannelInboundHandlerAdapter {
  37. private StringBuilder askTextSb = null;
  38. @Autowired
  39. private IChengzhongService chengzhongService;
  40. //
  41. public void appendClientAsk(String text) {
  42. if (this.askTextSb == null) {
  43. askTextSb = new StringBuilder();
  44. }
  45. askTextSb.append(text);
  46. }
  47. @Override
  48. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  49. Channel channel = ctx.channel();
  50. ByteBuf byteBuf = (ByteBuf) msg;
  51. byte[] bytes = new byte[byteBuf.readableBytes()];
  52. byteBuf.readBytes(bytes);
  53. String str = ModBusUtils.bytes2HexString(bytes);
  54. saveWeight(str);
  55. System.out.println("收到的数据:"+str);
  56. Thread.sleep(10*1000);
  57. // channel.writeAndFlush(Unpooled.copiedBuffer(hexStr2Bytes("1F 03 00 2A 00 01 A6 7C")));
  58. channel.writeAndFlush(Unpooled.copiedBuffer(hexStr2Bytes("01 42 3F 02 0D")));
  59. super.channelRead(ctx, msg);
  60. }
  61. private void saveWeight(String str) {
  62. try {
  63. if (null != str && str.split(" ").length > 7){
  64. String[] s = str.split(" ");
  65. String macAddr = s[0]+s[1]+ s[2]+s[3]+ s[4]+s[5];
  66. Integer i = countWeight(s);
  67. Chengzhong chengzhong = new Chengzhong();
  68. chengzhong.setCreatTime(new Date());
  69. chengzhong.setMacAddr(macAddr);
  70. // int i = Integer.parseInt(weight, 16);
  71. /* if (i>60000){
  72. i=0;
  73. }*/
  74. chengzhong.setWeight(i);
  75. Chengzhong one = chengzhongService.getOne(new QueryWrapper<Chengzhong>().orderByDesc("id").eq("mac_addr", macAddr).last("limit 1"));
  76. int num = i;
  77. if (ObjectUtil.isNotEmpty(one)){
  78. num = i -one.getWeight();
  79. }
  80. System.out.println(i);
  81. chengzhong.setNum(num);
  82. chengzhongService.save(chengzhong);
  83. }
  84. }catch (Exception e){
  85. System.out.println(e);
  86. }
  87. }
  88. private Integer countWeight(String[] s) {
  89. int count = 48;
  90. return (Integer.parseInt(s[8], 16) -count)
  91. +((Integer.parseInt(s[9], 16) -count) * 16)
  92. +((Integer.parseInt(s[10], 16) -count) * 256)
  93. +((Integer.parseInt(s[11], 16) -count) * 4096)
  94. +((Integer.parseInt(s[12], 16) -count) * 6556);
  95. }
  96. @Override
  97. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  98. // if (true){
  99. // ctx.writeAndFlush(Unpooled.copiedBuffer(new byte[]{1, 2, 3}));
  100. // }
  101. // if (askTextSb.toString().indexOf("end") != -1) {
  102. // // {处理客户端消息}
  103. // handleClientAskCmd(askTextSb.toString(), ctx);
  104. // //清空重置;
  105. // askTextSb.delete(0, askTextSb.length());
  106. // }
  107. }
  108. @Override
  109. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  110. if (cause.getMessage().indexOf("Connection reset") != -1) {
  111. log.info("相关采集器设备正在重启:" + cause.toString());
  112. }
  113. // cause.printStackTrace();
  114. ctx.close();
  115. }
  116. /**
  117. * @Method : handleClientAskCmd
  118. * @Description : 处理请求小心
  119. * @Params : [clientAskText, ctx]
  120. * @Return : void
  121. * @Author : ZhuoNing
  122. * @Date : 2022/3/28
  123. * @Time : 17:36
  124. */
  125. private void handleClientAskCmd(String clientAskText, ChannelHandlerContext ctx) throws ParseException, IOException {
  126. clientAskText = clientAskText.replaceAll("\r", "").replaceAll("\n", "");
  127. //{处理非正常命令}
  128. // int countPlus = regexUtil.countPlus(clientAskText);
  129. // if (countPlus < 4) {
  130. // System.out.println("当前数据为不完整数据,故丢弃.>>" + clientAskText);
  131. // } else {
  132. //--处理客户端请求数据
  133. //{拆分粘包数据}
  134. JSONArray askJa = parseAskCmdPackage(clientAskText);
  135. for (int a = 0; a < askJa.size(); a++) {
  136. String askText = askJa.getString(a);
  137. //{处理请求命令}
  138. askCmdActuator(askText, ctx);
  139. }
  140. // }
  141. }
  142. /**
  143. * @Method : askCmdActuator
  144. * @Description :
  145. * @Params : [askText, ctx]
  146. * @Return : void
  147. * @Author : ZhuoNing
  148. * @Date : 2022/3/23
  149. * @Time : 18:08
  150. */
  151. private void askCmdActuator(String askText, ChannelHandlerContext ctx) throws ParseException, IOException {
  152. System.out.println("======>接收设备请求:" + askText);
  153. String[] dataArray = askText.split("\\+");
  154. String cmdHeader = dataArray[0];
  155. if (!cmdHeader.trim().equalsIgnoreCase("hm")) {
  156. log.info("当前命令是非hm命令[" + askText + "]");
  157. return;
  158. }
  159. //芯片id/设备编码
  160. String idCode = dataArray[1];
  161. String cmd = dataArray[2];
  162. Map map = new HashMap();
  163. map.put("askText", askText);
  164. switch (cmd) {
  165. case "1":
  166. //获取远程设备编码
  167. getDeviceCode(askText, idCode, ctx);
  168. break;
  169. case "2":
  170. //同步时间
  171. getServerTime(askText, idCode, ctx);
  172. break;
  173. default:
  174. System.out.println("==>未知命令");
  175. log.error(">>当前数据为非法数据-未知命令>>" + askText);
  176. }
  177. }
  178. //时间同步请求
  179. private void getServerTime(String askText, String deviceCode, ChannelHandlerContext ctx) throws ParseException {
  180. System.out.println("==>时间同步请求:" + askText);
  181. // if (!cmdProService.isEffectiveDevice(deviceCode)) {
  182. // System.out.println("##时间同步请求-未注册设备 idCode=" + deviceCode);
  183. // return;
  184. // }
  185. String answerText = "hm+2+" + "+0+4+end";
  186. // log.info(">>时间同步请求-应答数据>>" + answerText);
  187. answerCmd(answerText, ctx);
  188. }
  189. //获取远程设备编码
  190. private void getDeviceCode(String askText, String idCode, ChannelHandlerContext ctx) {
  191. System.out.println("==>获取远程设备编码请求:" + askText.trim());
  192. //{读取设备编码}
  193. // String deviceCode = cmdProService.getDeviceCodeByChipId(idCode);
  194. // log.info("获取远程设备编码请求,芯片id>>" + idCode + " ,deviceCode>>" + deviceCode);
  195. // if (deviceCode == null) {
  196. // log.error("该设备未注册,已舍弃请求.");
  197. // return;
  198. // }
  199. // String answerText = "hm+1+0+" + deviceCode + "+123+8+end";
  200. // log.info("<<获取远程设备编码请求-应答数据:" + answerText);
  201. //{应答指令}
  202. // answerCmd(answerText, ctx);
  203. }
  204. //应答
  205. public void answerCmd(String answerText, ChannelHandlerContext ctx) {
  206. ctx.writeAndFlush(Unpooled.copiedBuffer(answerText.getBytes()));
  207. }
  208. //检查无效耳标
  209. public boolean checkValidEarmark(String earmark) {
  210. if (earmark.trim().equalsIgnoreCase("ffffffffffffffff") || earmark.trim().equalsIgnoreCase("0000000000000000")) {
  211. return true;
  212. } else {
  213. return false;
  214. }
  215. }
  216. //拆分粘包数据
  217. public JSONArray parseAskCmdPackage(String text) {
  218. String key = "end";
  219. Pattern pattern = Pattern.compile(key);
  220. Matcher matcher = pattern.matcher(text);
  221. int count = 0;
  222. while (matcher.find()) {
  223. count++;
  224. }
  225. JSONArray dataJa = new JSONArray();
  226. if (count == 1) {
  227. dataJa.add(text);
  228. } else {
  229. for (int a = 0; a < count; a++) {
  230. int p1 = text.indexOf("end");
  231. dataJa.add(text.substring(0, p1 + 3));
  232. text = text.substring(p1 + 3, text.length());
  233. }
  234. }
  235. return dataJa;
  236. }
  237. }