All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.iteaj.iot.modbus.server.dtu.ModbusTcpMessageAware Maven / Gradle / Ivy

There is a newer version: 3.1.1
Show newest version
package com.iteaj.iot.modbus.server.dtu;

import com.iteaj.iot.modbus.consts.ModbusCode;
import com.iteaj.iot.modbus.consts.ModbusErrCode;
import com.iteaj.iot.server.dtu.DefaultDtuMessageAware;
import com.iteaj.iot.server.dtu.DtuCommonProtocolType;
import com.iteaj.iot.server.dtu.DtuMessageDecoder;
import com.iteaj.iot.server.dtu.DtuMessageType;
import com.iteaj.iot.utils.ByteUtil;
import io.netty.buffer.ByteBuf;

public class ModbusTcpMessageAware extends DefaultDtuMessageAware {

    public ModbusTcpMessageAware() { }

    public ModbusTcpMessageAware(DtuMessageType messageType) {
        super(messageType);
    }

    @Override
    protected M customizeType(String equipCode, byte[] message, ByteBuf msg) {
        // modbus tcp 协议报文长度不能小于8
        // 小于8说明是dtu的报文
        if(message.length < 8) {
            return null; // 不能校验 等待下一个报文
        }

        // 获取modbus tcp的功能码
        int code = message[7] & 0xFF;
        if(code > 0x80) { // 读取到的功能码可能是modbus的异常码, 异常码大于 0x80
            code = code - 0x80;
            try {
                ModbusCode.INSTANCE((byte) code);
                ModbusErrCode.valueOf(message[8]);
            } catch (IllegalStateException e) {
                return createMessage(DtuCommonProtocolType.DTU, msg);
            }
        }

        // modbus的功能码只能是在 0x01 - 0x10之间
        if(code >= 0x01 && code <= 0x10) {
            try {
                ModbusCode.INSTANCE((byte) code);
            } catch (IllegalStateException e) { // 不是modbus协议的功能码
                return createMessage(DtuCommonProtocolType.DTU, msg);
            }
        } else { // 不存在功能码说明不是modbus协议
            return createMessage(DtuCommonProtocolType.DTU, msg);
        }

        short length = ByteUtil.bytesToShortOfReverse(message, 4);
        if(message.length < length + 6) {
            return null; // 等待下一个报文
        }

        // 交由下个modbus协议处理器处理
        return createMessage(length + 6, msg);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy