123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264 |
- package com.huimv.env.input.server;
- import cn.hutool.core.util.ObjectUtil;
- import com.alibaba.fastjson.JSONArray;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.huimv.env.input.entity.Chengzhong;
- import com.huimv.env.input.service.IChengzhongService;
- import com.huimv.env.input.utils.ModBusUtils;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.*;
- import io.netty.util.CharsetUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.tomcat.util.codec.binary.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import java.io.IOException;
- import java.nio.charset.Charset;
- import java.text.ParseException;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import static com.huimv.env.input.utils.ModBusUtils.hexStr2Bytes;
- /**
- * @Project : huimv.shiwan
- * @Package : com.huimv.biosafety.uface.controller
- * @Description : TODO
- * @Version : 1.0
- * @Author : ZhuoNing
- * @Create : 2020-12-25
- **/
- @ChannelHandler.Sharable
- @Component
- @Slf4j
- public class EnvInputServerHandler extends ChannelInboundHandlerAdapter {
- private StringBuilder askTextSb = null;
- @Autowired
- private IChengzhongService chengzhongService;
- //
- public void appendClientAsk(String text) {
- if (this.askTextSb == null) {
- askTextSb = new StringBuilder();
- }
- askTextSb.append(text);
- }
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- Channel channel = ctx.channel();
- ByteBuf byteBuf = (ByteBuf) msg;
- byte[] bytes = new byte[byteBuf.readableBytes()];
- byteBuf.readBytes(bytes);
- String str = ModBusUtils.bytes2HexString(bytes);
- saveWeight(str);
- System.out.println("收到的数据:"+str);
- Thread.sleep(10*1000);
- // channel.writeAndFlush(Unpooled.copiedBuffer(hexStr2Bytes("1F 03 00 2A 00 01 A6 7C")));
- channel.writeAndFlush(Unpooled.copiedBuffer(hexStr2Bytes("01 42 3F 02 0D")));
- super.channelRead(ctx, msg);
- }
- private void saveWeight(String str) {
- try {
- if (null != str && str.split(" ").length > 7){
- String[] s = str.split(" ");
- String macAddr = s[0]+s[1]+ s[2]+s[3]+ s[4]+s[5];
- Integer i = countWeight(s);
- Chengzhong chengzhong = new Chengzhong();
- chengzhong.setCreatTime(new Date());
- chengzhong.setMacAddr(macAddr);
- // int i = Integer.parseInt(weight, 16);
- /* if (i>60000){
- i=0;
- }*/
- chengzhong.setWeight(i);
- Chengzhong one = chengzhongService.getOne(new QueryWrapper<Chengzhong>().orderByDesc("id").eq("mac_addr", macAddr).last("limit 1"));
- int num = i;
- if (ObjectUtil.isNotEmpty(one)){
- num = i -one.getWeight();
- }
- System.out.println(i);
- chengzhong.setNum(num);
- chengzhongService.save(chengzhong);
- }
- }catch (Exception e){
- System.out.println(e);
- }
- }
- private Integer countWeight(String[] s) {
- int count = 48;
- return (Integer.parseInt(s[8], 16) -count)
- +((Integer.parseInt(s[9], 16) -count) * 16)
- +((Integer.parseInt(s[10], 16) -count) * 256)
- +((Integer.parseInt(s[11], 16) -count) * 4096)
- +((Integer.parseInt(s[12], 16) -count) * 6556);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- // if (true){
- // ctx.writeAndFlush(Unpooled.copiedBuffer(new byte[]{1, 2, 3}));
- // }
- // if (askTextSb.toString().indexOf("end") != -1) {
- // // {处理客户端消息}
- // handleClientAskCmd(askTextSb.toString(), ctx);
- // //清空重置;
- // askTextSb.delete(0, askTextSb.length());
- // }
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- if (cause.getMessage().indexOf("Connection reset") != -1) {
- log.info("相关采集器设备正在重启:" + cause.toString());
- }
- // cause.printStackTrace();
- ctx.close();
- }
- /**
- * @Method : handleClientAskCmd
- * @Description : 处理请求小心
- * @Params : [clientAskText, ctx]
- * @Return : void
- * @Author : ZhuoNing
- * @Date : 2022/3/28
- * @Time : 17:36
- */
- private void handleClientAskCmd(String clientAskText, ChannelHandlerContext ctx) throws ParseException, IOException {
- clientAskText = clientAskText.replaceAll("\r", "").replaceAll("\n", "");
- //{处理非正常命令}
- // int countPlus = regexUtil.countPlus(clientAskText);
- // if (countPlus < 4) {
- // System.out.println("当前数据为不完整数据,故丢弃.>>" + clientAskText);
- // } else {
- //--处理客户端请求数据
- //{拆分粘包数据}
- JSONArray askJa = parseAskCmdPackage(clientAskText);
- for (int a = 0; a < askJa.size(); a++) {
- String askText = askJa.getString(a);
- //{处理请求命令}
- askCmdActuator(askText, ctx);
- }
- // }
- }
- /**
- * @Method : askCmdActuator
- * @Description :
- * @Params : [askText, ctx]
- * @Return : void
- * @Author : ZhuoNing
- * @Date : 2022/3/23
- * @Time : 18:08
- */
- private void askCmdActuator(String askText, ChannelHandlerContext ctx) throws ParseException, IOException {
- System.out.println("======>接收设备请求:" + askText);
- String[] dataArray = askText.split("\\+");
- String cmdHeader = dataArray[0];
- if (!cmdHeader.trim().equalsIgnoreCase("hm")) {
- log.info("当前命令是非hm命令[" + askText + "]");
- return;
- }
- //芯片id/设备编码
- String idCode = dataArray[1];
- String cmd = dataArray[2];
- Map map = new HashMap();
- map.put("askText", askText);
- switch (cmd) {
- case "1":
- //获取远程设备编码
- getDeviceCode(askText, idCode, ctx);
- break;
- case "2":
- //同步时间
- getServerTime(askText, idCode, ctx);
- break;
- default:
- System.out.println("==>未知命令");
- log.error(">>当前数据为非法数据-未知命令>>" + askText);
- }
- }
- //时间同步请求
- private void getServerTime(String askText, String deviceCode, ChannelHandlerContext ctx) throws ParseException {
- System.out.println("==>时间同步请求:" + askText);
- // if (!cmdProService.isEffectiveDevice(deviceCode)) {
- // System.out.println("##时间同步请求-未注册设备 idCode=" + deviceCode);
- // return;
- // }
- String answerText = "hm+2+" + "+0+4+end";
- // log.info(">>时间同步请求-应答数据>>" + answerText);
- answerCmd(answerText, ctx);
- }
- //获取远程设备编码
- private void getDeviceCode(String askText, String idCode, ChannelHandlerContext ctx) {
- System.out.println("==>获取远程设备编码请求:" + askText.trim());
- //{读取设备编码}
- // String deviceCode = cmdProService.getDeviceCodeByChipId(idCode);
- // log.info("获取远程设备编码请求,芯片id>>" + idCode + " ,deviceCode>>" + deviceCode);
- // if (deviceCode == null) {
- // log.error("该设备未注册,已舍弃请求.");
- // return;
- // }
- // String answerText = "hm+1+0+" + deviceCode + "+123+8+end";
- // log.info("<<获取远程设备编码请求-应答数据:" + answerText);
- //{应答指令}
- // answerCmd(answerText, ctx);
- }
- //应答
- public void answerCmd(String answerText, ChannelHandlerContext ctx) {
- ctx.writeAndFlush(Unpooled.copiedBuffer(answerText.getBytes()));
- }
- //检查无效耳标
- public boolean checkValidEarmark(String earmark) {
- if (earmark.trim().equalsIgnoreCase("ffffffffffffffff") || earmark.trim().equalsIgnoreCase("0000000000000000")) {
- return true;
- } else {
- return false;
- }
- }
- //拆分粘包数据
- public JSONArray parseAskCmdPackage(String text) {
- String key = "end";
- Pattern pattern = Pattern.compile(key);
- Matcher matcher = pattern.matcher(text);
- int count = 0;
- while (matcher.find()) {
- count++;
- }
- JSONArray dataJa = new JSONArray();
- if (count == 1) {
- dataJa.add(text);
- } else {
- for (int a = 0; a < count; a++) {
- int p1 = text.indexOf("end");
- dataJa.add(text.substring(0, p1 + 3));
- text = text.substring(p1 + 3, text.length());
- }
- }
- return dataJa;
- }
- }
|