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

com.iteaj.iot.modbus.ReadPayload Maven / Gradle / Ivy

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

import com.iteaj.iot.format.DataFormatConvert;
import com.iteaj.iot.utils.ByteUtil;

import java.nio.charset.Charset;

public class ReadPayload extends Payload{

    private int start;
    private DataFormatConvert convert;

    public ReadPayload(byte[] payload, int start, DataFormatConvert convert) {
        super(payload);
        this.start = start;
        this.convert = convert;
    }

    @Override
    public short readShort(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readShort(this.getPayload(), offset);
    }


    @Override
    public int readUShort(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readUShort(this.getPayload(), offset);
    }

    @Override
    public int readInt(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readInt(this.getPayload(), offset);
    }

    @Override
    public long readUInt(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readUInt(this.getPayload(), offset);
    }

    @Override
    public long readLong(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readLong(this.getPayload(), offset);
    }

    @Override
    public float readFloat(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readFloat(this.getPayload(), offset);
    }

    @Override
    public double readDouble(int start) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return convert.readDouble(this.getPayload(), offset);
    }

    @Override
    public String readString(int start, int num) {
        validatorStartAddress(start);
        int offset = (start - this.start) * 2;
        return ByteUtil.bytesToString(this.getPayload(), offset, offset + num * 2, Charset.forName("UTF-8"));
    }

    private void validatorStartAddress(int start) {
        if(start < this.start) {
            throw new IndexOutOfBoundsException("读取的寄存器地址不能小于["+this.start+"]");
        }
    }

    public DataFormatConvert getConvert() {
        return convert;
    }

    public void setConvert(DataFormatConvert convert) {
        this.convert = convert;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy