Newer
Older
rain_receiver / src / main / java / com / casic / handler / ReceiverServerHandler.java
package com.casic.handler;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.bytecode.ByteArray;
import org.springframework.stereotype.Component;

/**
 * @description: 消息处理handler
 * @author: Stone
 * @create: 2019-01-10 20:01
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class ReceiverServerHandler extends ChannelInboundHandlerAdapter {

    public ReceiverServerHandler() {
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
//        log.info("[{}] : msg = {}", ctx.channel().remoteAddress(), msg);
//        msgProducerService.sendMsg(Common.ACTIVEMQ_QUEUE_NAME,(String)msg);
        log.info("[{}] : msg = {}", ctx.channel().remoteAddress(), msg);
        String msgStr = msg.toString();
        // 以固定行分隔符结尾分割,头部可能有不符合接口协议的字段, 去掉
        int idx = msgStr.indexOf("##");
        if (idx >= 0) {
            msgStr = msgStr.substring(idx);
        }
//        msgProducerService.sendMsg(Common.ACTIVEMQ_QUEUE_NAME, msgStr);
    }

    //ByteBuf byteBuf
    public static void main(String[] main) {
        byte[] hexBytes = {(byte) 0x86, 0x53, 0x28, 0x06, (byte) 0x84, 0x19, (byte) 0x94,
                0x30, (byte) 0xAA, (byte) 0xAA, 0x01, 0x03, (byte) 0x02, 0x02, 0x00, (byte) 0xB8, 0x44};
        ByteBuf out = ByteBufAllocator.DEFAULT.heapBuffer();
        out.writeBytes(hexBytes);
        pareDeviceHex(out);
    }

    private static void pareDeviceHex(ByteBuf byteBuf) {
        //去掉补位
        String devcode = ByteBufUtil.hexDump(byteBuf.slice(0, 8));
        devcode = devcode.substring(0, devcode.length() - 1);
        //数值读取
        byteBuf.readBytes(12);
        byteBuf.markReaderIndex();
        Integer defaultValueLength = byteBuf.readByte() & 0xff;
        long defaultValue = 0;
        for (int i = 0; i < defaultValueLength; i++) {
            long tempLong = byteBuf.readByte() & 0xff;
            defaultValue = defaultValue * 256 + tempLong;
        }
        System.out.println("设备编号为" + devcode + ",设备数据为" + defaultValue);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }

}