public class ModbusRequestDecoder implements ModbusPduDecoder {

    @Override
    public ModbusPdu decode(ByteBuf buffer) throws DecoderException {
        int code = buffer.readByte();

        FunctionCode functionCode = FunctionCode
            .fromCode(code)
            .orElseThrow(() -> new DecoderException("invalid function code: " + code));

        return decodeResponse(functionCode, buffer);
    }

    private ModbusPdu decodeResponse(FunctionCode functionCode, ByteBuf buffer) throws DecoderException {
        switch (functionCode) {
            case ReadCoils:
                return decodeReadCoils(buffer);

            case ReadDiscreteInputs:
                return decodeReadDiscreteInputs(buffer);

            case ReadHoldingRegisters:
                return decodeReadHoldingRegisters(buffer);

            case ReadInputRegisters:
                return decodeReadInputRegisters(buffer);

            case WriteSingleCoil:
                return decodeWriteSingleCoil(buffer);

            case WriteSingleRegister:
                return decodeWriteSingleRegister(buffer);

            case WriteMultipleCoils:
                return decodeWriteMultipleCoils(buffer);

            case WriteMultipleRegisters:
                return decodeWriteMultipleRegisters(buffer);

            case MaskWriteRegister:
                return decodeMaskWriteRegister(buffer);

            case ReadWriteMultipleRegisters:
                return decodeReadWriteMultipleRegisters(buffer);

            default:
                return new UnsupportedPdu(functionCode);
        }
    }

    private ReadCoilsRequest decodeReadCoils(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();

        return new ReadCoilsRequest(address, quantity);
    }

    private ReadDiscreteInputsRequest decodeReadDiscreteInputs(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();

        return new ReadDiscreteInputsRequest(address, quantity);
    }

    private ReadHoldingRegistersRequest decodeReadHoldingRegisters(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();

        return new ReadHoldingRegistersRequest(address, quantity);
    }

    private ReadInputRegistersRequest decodeReadInputRegisters(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();

        return new ReadInputRegistersRequest(address, quantity);
    }

    private WriteSingleCoilRequest decodeWriteSingleCoil(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        boolean value = buffer.readUnsignedShort() == 0xFF00;

        return new WriteSingleCoilRequest(address, value);
    }

    private WriteSingleRegisterRequest decodeWriteSingleRegister(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int value = buffer.readUnsignedShort();

        return new WriteSingleRegisterRequest(address, value);
    }

    private WriteMultipleCoilsRequest decodeWriteMultipleCoils(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();
        int byteCount = buffer.readUnsignedByte();
        ByteBuf values = buffer.readSlice(byteCount).retain();

        return new WriteMultipleCoilsRequest(address, quantity, values);
    }

    private WriteMultipleRegistersRequest decodeWriteMultipleRegisters(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int quantity = buffer.readUnsignedShort();
        int byteCount = buffer.readUnsignedByte();
        ByteBuf values = buffer.readSlice(byteCount).retain();

        return new WriteMultipleRegistersRequest(address, quantity, values);
    }

    private MaskWriteRegisterRequest decodeMaskWriteRegister(ByteBuf buffer) {
        int address = buffer.readUnsignedShort();
        int andMask = buffer.readUnsignedShort();
        int orMask = buffer.readUnsignedShort();

        return new MaskWriteRegisterRequest(address, andMask, orMask);
    }

    private ReadWriteMultipleRegistersRequest decodeReadWriteMultipleRegisters(ByteBuf buffer) {
        int readAddress = buffer.readUnsignedShort();
        int readQuantity = buffer.readUnsignedShort();
        int writeAddress = buffer.readUnsignedShort();
        int writeQuantity = buffer.readUnsignedShort();
        int byteCount = buffer.readUnsignedByte();
        ByteBuf values = buffer.readSlice(byteCount).retain();

        return new ReadWriteMultipleRegistersRequest(readAddress, readQuantity, writeAddress, writeQuantity, values);
    }

} public class ModbusRequestEncoder implements ModbusPduEncoder {

    @Override
    public ByteBuf encode(ModbusPdu modbusPdu, ByteBuf buffer) throws EncoderException {
        try {
            switch (modbusPdu.getFunctionCode()) {
                case ReadCoils:
                    return encodeReadCoils((ReadCoilsRequest) modbusPdu, buffer);

                case ReadDiscreteInputs:
                    return encodeReadDiscreteInputs((ReadDiscreteInputsRequest) modbusPdu, buffer);

                case ReadHoldingRegisters:
                    return encodeReadHoldingRegisters((ReadHoldingRegistersRequest) modbusPdu, buffer);

                case ReadInputRegisters:
                    return encodeReadInputRegisters((ReadInputRegistersRequest) modbusPdu, buffer);

                case WriteSingleCoil:
                    return encodeWriteSingleCoil((WriteSingleCoilRequest) modbusPdu, buffer);

                case WriteSingleRegister:
                    return encodeWriteSingleRegister((WriteSingleRegisterRequest) modbusPdu, buffer);

                case WriteMultipleCoils:
                    return encodeWriteMultipleCoils((WriteMultipleCoilsRequest) modbusPdu, buffer);

                case WriteMultipleRegisters:
                    return encodeWriteMultipleRegisters((WriteMultipleRegistersRequest) modbusPdu, buffer);

                case MaskWriteRegister:
                    return encodeMaskWriteRegister((MaskWriteRegisterRequest) modbusPdu, buffer);

                case ReadWriteMultipleRegisters:
                    return encodeReadWriteMultipleRegisters((ReadWriteMultipleRegistersRequest) modbusPdu, buffer);

                default:
                    throw new EncoderException("FunctionCode not supported: " + modbusPdu.getFunctionCode());
            }
        } finally {
            ReferenceCountUtil.release(modbusPdu);
        }
    }

    public ByteBuf encodeReadCoils(ReadCoilsRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        return buffer;
    }

    public ByteBuf encodeReadDiscreteInputs(ReadDiscreteInputsRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        return buffer;
    }

    public ByteBuf encodeReadHoldingRegisters(ReadHoldingRegistersRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        return buffer;
    }

    public ByteBuf encodeReadInputRegisters(ReadInputRegistersRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        return buffer;
    }

    public ByteBuf encodeWriteSingleCoil(WriteSingleCoilRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getValue());

        return buffer;
    }

    public ByteBuf encodeWriteSingleRegister(WriteSingleRegisterRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getValue());

        return buffer;
    }

    public ByteBuf encodeWriteMultipleCoils(WriteMultipleCoilsRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        int byteCount = (request.getQuantity() + 7) / 8;
        buffer.writeByte(byteCount);

        buffer.writeBytes(request.getValues(), byteCount);

        return buffer;
    }

    public ByteBuf encodeWriteMultipleRegisters(WriteMultipleRegistersRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getQuantity());

        int byteCount = request.getQuantity() * 2;
        buffer.writeByte(byteCount);

        buffer.writeBytes(request.getValues(), byteCount);

        return buffer;
    }

    public ByteBuf encodeMaskWriteRegister(MaskWriteRegisterRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getAddress());
        buffer.writeShort(request.getAndMask());
        buffer.writeShort(request.getOrMask());

        return buffer;
    }

    public ByteBuf encodeReadWriteMultipleRegisters(ReadWriteMultipleRegistersRequest request, ByteBuf buffer) {
        buffer.writeByte(request.getFunctionCode().getCode());
        buffer.writeShort(request.getReadAddress());
        buffer.writeShort(request.getReadQuantity());
        buffer.writeShort(request.getWriteAddress());
        buffer.writeShort(request.getWriteQuantity());

        int byteCount = request.getWriteQuantity() * 2;
        buffer.writeByte(byteCount);

        buffer.writeBytes(request.getValues(), byteCount);

        return buffer;
    }

} public class MaskWriteRegisterRequest extends SimpleModbusRequest {

    private final int address;
    private final int andMask;
    private final int orMask;

    /**
     * @param address 0x0000 to 0xFFFF (0 to 65535)
     * @param andMask 0x0000 to 0xFFFF (0 to 65535)
     * @param orMask  0x0000 to 0xFFFF (0 to 65535)
     */
    public MaskWriteRegisterRequest(int address, int andMask, int orMask) {
        super(FunctionCode.MaskWriteRegister);

        this.address = address;
        this.andMask = andMask;
        this.orMask = orMask;
    }

    public int getAddress() {
        return address;
    }

    public int getAndMask() {
        return andMask;
    }

    public int getOrMask() {
        return orMask;
    }

} public class ReadCoilsRequest extends SimpleModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x07D0 (1 to 2000)
     */
    public ReadCoilsRequest(int address, int quantity) {
        super(FunctionCode.ReadCoils);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

} public class ReadDiscreteInputsRequest extends SimpleModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x07D0 (1 to 2000)
     */
    public ReadDiscreteInputsRequest(int address, int quantity) {
        super(FunctionCode.ReadDiscreteInputs);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

} public class ReadHoldingRegistersRequest extends SimpleModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x007D (1 to 125)
     */
    public ReadHoldingRegistersRequest(int address, int quantity) {
        super(FunctionCode.ReadHoldingRegisters);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

} public class ReadInputRegistersRequest extends SimpleModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x007D (1 to 125)
     */
    public ReadInputRegistersRequest(int address, int quantity) {
        super(FunctionCode.ReadInputRegisters);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

} public class WriteMultipleCoilsRequest extends ByteBufModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x07B0 (1 to 2000)
     * @param values   buffer of at least N bytes, where N = (quantity + 7) / 8
     */
    public WriteMultipleCoilsRequest(int address, int quantity, byte[] values) {
        this(address, quantity, Unpooled.wrappedBuffer(values));
    }

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x07B0 (1 to 2000)
     * @param values   buffer of at least N bytes, where N = (quantity + 7) / 8
     */
    public WriteMultipleCoilsRequest(int address, int quantity, ByteBuffer values) {
        this(address, quantity, Unpooled.wrappedBuffer(values));
    }

    /**
     * Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
     *
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x07B0 (1 to 2000)
     * @param values   buffer of at least N bytes, where N = (quantity + 7) / 8
     */
    public WriteMultipleCoilsRequest(int address, int quantity, ByteBuf values) {
        super(values, FunctionCode.WriteMultipleCoils);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

    public ByteBuf getValues() {
        return super.content();
    }

} public class WriteMultipleRegistersRequest extends ByteBufModbusRequest {

    private final int address;
    private final int quantity;

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x007B (1 to 123)
     * @param values   buffer of at least N bytes, where N = quantity * 2
     */
    public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) {
        this(address, quantity, Unpooled.wrappedBuffer(values));
    }

    /**
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x007B (1 to 123)
     * @param values   buffer of at least N bytes, where N = quantity * 2
     */
    public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) {
        this(address, quantity, Unpooled.wrappedBuffer(values));
    }

    /**
     * Create a request using a {@link ByteBuf}. The buffer will have its reference count decremented after encoding.
     *
     * @param address  0x0000 to 0xFFFF (0 to 65535)
     * @param quantity 0x0001 to 0x007B (1 to 123)
     * @param values   buffer of at least N bytes, where N = quantity * 2
     */
    public WriteMultipleRegistersRequest(int address, int quantity, ByteBuf values) {
        super(values, FunctionCode.WriteMultipleRegisters);

        this.address = address;
        this.quantity = quantity;
    }

    public int getAddress() {
        return address;
    }

    public int getQuantity() {
        return quantity;
    }

    public ByteBuf getValues() {
        return super.content();
    }

} public class WriteSingleCoilRequest extends SimpleModbusRequest {

    private final int address;
    private final int value;

    /**
     * @param address 0x0000 to 0xFFFF (0 to 65535)
     * @param value   true or false (0xFF00 or 0x0000)
     */
    public WriteSingleCoilRequest(int address, boolean value) {
        super(FunctionCode.WriteSingleCoil);

        this.address = address;
        this.value = value ? 0xFF00 : 0x0000;
    }

    public int getAddress() {
        return address;
    }

    public int getValue() {
        return value;
    }

} public class WriteSingleRegisterRequest extends SimpleModbusRequest {

    private final int address;
    private final int value;

    /**
     * @param address 0x0000 to 0xFFFF (0 to 65535)
     * @param value   0x0000 to 0xFFFF (0 to 65535)
     */
    public WriteSingleRegisterRequest(int address, int value) {
        super(FunctionCode.WriteSingleRegister);

        this.address = address;
        this.value = value;
    }

    public int getAddress() {
        return address;
    }

    public int getValue() {
        return value;
    }

}
import static org.testng.Assert.assertEquals;
import com.digitalpetri.modbus.codec.ModbusRequestDecoder;
import com.digitalpetri.modbus.codec.ModbusRequestEncoder;
import com.digitalpetri.modbus.requests.MaskWriteRegisterRequest;
import com.digitalpetri.modbus.requests.ReadCoilsRequest;
import com.digitalpetri.modbus.requests.ReadDiscreteInputsRequest;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.requests.ReadInputRegistersRequest;
import com.digitalpetri.modbus.requests.WriteMultipleCoilsRequest;
import com.digitalpetri.modbus.requests.WriteMultipleRegistersRequest;
import com.digitalpetri.modbus.requests.WriteSingleCoilRequest;
import com.digitalpetri.modbus.requests.WriteSingleRegisterRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
 * Copyright 2016 Kevin Herron
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



public class ModbusRequestSerializationTest {

    private final ModbusRequestEncoder encoder = new ModbusRequestEncoder();
    private final ModbusRequestDecoder decoder = new ModbusRequestDecoder();

    @DataProvider
    private Object[][] getAddressAndQuantity() {
        return new Object[][]{
                {0, 1},
                {0, 125},
                {0, 2000},
                {65535, 1},
                {65535, 125},
                {65535, 2000}
        };
    }

    @DataProvider
    private Object[][] getAddressAndRegisterValue() {
        return new Object[][]{
                {0, 1},
                {0, 125},
                {0, 2000},
                {0, 65535},
                {65535, 1},
                {65535, 125},
                {65535, 2000},
                {65535, 65535}
        };
    }

    @DataProvider
    private Object[][] getAddressAndQuantityAndValues() {
        return new Object[][]{
                {0, 1, new byte[]{0x01}},
                {0, 2, new byte[]{0x02}},
                {0, 3, new byte[]{0x04}},
                {0, 4, new byte[]{0x08}},
                {0, 5, new byte[]{0x10}},
                {0, 6, new byte[]{0x20}},
                {0, 7, new byte[]{0x40}},
                {0, 8, new byte[]{(byte) 0x80}},
                {0, 9, new byte[]{0x01, 0x01}},
                {0, 10, new byte[]{0x01, 0x02}},
                {0, 11, new byte[]{0x01, 0x04}},
                {0, 12, new byte[]{0x01, 0x08}},
                {0, 13, new byte[]{0x01, 0x10}},
                {0, 14, new byte[]{0x01, 0x20}},
                {0, 15, new byte[]{0x01, 0x40}},
                {0, 16, new byte[]{0x01, (byte) 0x80}},
                {0, 17, new byte[]{0x02, 0x01, 0x01}}
        };
    }

    @Test(dataProvider = "getAddressAndQuantity")
    public void testReadCoilsRequest(int address, int quantity) {
        ReadCoilsRequest request = new ReadCoilsRequest(address, quantity);

        ByteBuf encoded = encoder.encode(request, Unpooled.buffer());
        ReadCoilsRequest decoded = (ReadCoilsRequest) decoder.decode(encoded);

        assertEquals(request.getFunctionCode(), decoded.getFunctionCode());
        assertEquals(request.getAddress(), decoded.getAddress());
        assertEquals(request.getQuantity(), decoded.getQuantity());
    }

    @Test(dataProvider = "getAddressAndQuantity")
    public void testReadDiscreteInputsRequest(int address, int quantity) {
        ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(address, quantity);

        ByteBuf encoded = encoder.encode(request, Unpooled.buffer());
        ReadDiscreteInputsRequest decoded = (ReadDiscreteInputsRequest) decoder.decode(encoded);

        assertEquals(request.getFunctionCode(), decoded.getFunctionCode());
        assertEquals(request.getAddress(), decoded.getAddress());
        assertEquals(request.getQuantity(), decoded.getQuantity());
    }

    @Test(dataProvider = "getAddressAndQuantity")
    public void testReadHoldingRegistersRequest(int address, int quantity) {
        ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(address, quantity);

        ByteBuf encoded = encoder.encode(request, Unpooled.buffer());
        ReadHoldingRegistersRequest decoded = (ReadHoldingRegistersRequest) decoder.decode(encoded);

        assertEquals(request.getFunctionCode(), decoded.getFunctionCode());
        assertEquals(request.getAddress(), decoded.getAddress());
        assertEquals(request.getQuantity(), decoded.getQuantity());
    }

    @Test(dataProvider = "getAddressAndQuantity")
    public void testReadInputRegistersRequest(int address, int quantity) {
        ReadInputRegistersRequest request = new ReadInputRegistersRequest(address, quantity);