zaber.motion.gateway.Serialization Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of motion-library Show documentation
Show all versions of motion-library Show documentation
A library that aims to provide easy-to-use API for communication with Zaber devices using Zaber ASCII Protocol.
package zaber.motion.gateway;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class Serialization {
public static final int SIZE_TYPE_SIZE = 4;
private Serialization() {
}
public static byte[] serialize(List messages) {
int totalLength = SIZE_TYPE_SIZE;
for (byte[] message : messages) {
totalLength += message.length + SIZE_TYPE_SIZE;
}
ByteBuffer buffer = ByteBuffer.allocate(totalLength);
byte[] size = getSizeAsByteArrayLE(totalLength);
buffer.put(size, 0, SIZE_TYPE_SIZE);
for (byte[] message : messages) {
int msgSize = message.length;
byte[] msgSizeConverted = getSizeAsByteArrayLE(msgSize);
buffer.put(msgSizeConverted, 0, SIZE_TYPE_SIZE);
buffer.put(message, 0, msgSize);
}
return buffer.array();
}
@SuppressWarnings("checkstyle:magicnumber")
public static List deserialize(byte[] bytes) {
int offset = SIZE_TYPE_SIZE;
List messages = new ArrayList<>();
while (offset < bytes.length) {
int messageSize = getSizeFromByteArrayLE(bytes, offset);
offset += SIZE_TYPE_SIZE;
messages.add(Arrays.copyOfRange(bytes, offset, offset + messageSize));
offset += messageSize;
}
return messages;
}
@SuppressWarnings("checkstyle:magicnumber")
public static byte[] getSizeAsByteArrayLE(int size) {
return new byte[] {
(byte) (size & 0xff),
(byte) ((size >> 8) & 0xff),
(byte) ((size >> 16) & 0xff),
(byte) ((size >> 24) & 0xff)
};
}
@SuppressWarnings("checkstyle:magicnumber")
public static int getSizeFromByteArrayLE(byte[] array, int offset) {
return (array[offset] & 0xff)
| ((array[offset + 1] & 0xff) << 8)
| ((array[offset + 2] & 0xff) << 16)
| ((array[offset + 3] & 0xff) << 24);
}
}