com.github.xingshuangs.iot.protocol.s7.model.TPKT Maven / Gradle / Ivy
/*
* MIT License
*
* Copyright (c) 2021-2099 Oscura (xingshuang)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.xingshuangs.iot.protocol.s7.model;
import com.github.xingshuangs.iot.common.IObjectByteArray;
import com.github.xingshuangs.iot.common.buff.ByteReadBuff;
import com.github.xingshuangs.iot.common.buff.ByteWriteBuff;
import lombok.Getter;
/**
* TPKT协议
*
* @author xingshuang
*/
@Getter
public class TPKT implements IObjectByteArray {
public static final int BYTE_LENGTH = 4;
/**
* 版本号,常量0x03
* 字节大小:1
* 字节序数:0
*/
private byte version = 0x03;
/**
* 预留,默认值0x00
* 字节大小:1
* 字节序数:1
*/
private byte reserved = 0x00;
/**
* 长度,包括后面负载payload+版本号+预留+长度
* 字节大小:2
* 字节序数:2-3
*/
private int length = 0x0000;
public void setLength(int length) {
this.length = length;
}
@Override
public int byteArrayLength() {
return BYTE_LENGTH;
}
@Override
public byte[] toByteArray() {
return ByteWriteBuff.newInstance(BYTE_LENGTH)
.putByte(this.version)
.putByte(this.reserved)
.putShort(this.length)
.getData();
}
/**
* 字节数组数据解析
*
* @param data 字节数组数据
* @return TPKT
*/
public static TPKT fromBytes(final byte[] data) {
if (data.length < BYTE_LENGTH) {
throw new IndexOutOfBoundsException(String.format("During TPKT conversion, the length of byte data is less than %d", BYTE_LENGTH));
}
ByteReadBuff buff = new ByteReadBuff(data);
TPKT tpkt = new TPKT();
tpkt.version = buff.getByte();
tpkt.reserved = buff.getByte();
tpkt.length = buff.getUInt16();
return tpkt;
}
}