package seng302.Networking.MessageDecoders; import seng302.Networking.Utils.CourseWind; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; /** * Created by hba56 on 23/04/17. */ public class CourseWindDecoder { byte messageVersionNumber; byte byteWindID; byte loopCount; ArrayList loopMessages = new ArrayList(); public CourseWindDecoder(byte[] encodedCourseWind) { final int lengthInBytesOfMessages = 20; messageVersionNumber = encodedCourseWind[0]; byteWindID = encodedCourseWind[1]; loopCount = encodedCourseWind[2]; byte[] loopMessagesBytes = Arrays.copyOfRange(encodedCourseWind, 3, lengthInBytesOfMessages*loopCount+3); int messageLoopIndex = 0; for (int i=0; i < loopCount; i++) { byte[] messageBytes = Arrays.copyOfRange(loopMessagesBytes, messageLoopIndex, messageLoopIndex+20); ArrayList test = new ArrayList(); byte[] windId = Arrays.copyOfRange(messageBytes, 0, 1); byte[] time = Arrays.copyOfRange(messageBytes, 1, 7); byte[] raceID = Arrays.copyOfRange(messageBytes, 7, 11); byte[] windDirection = Arrays.copyOfRange(messageBytes, 11, 13); byte[] windSpeed = Arrays.copyOfRange(messageBytes, 13, 15); byte[] bestUpwindAngle = Arrays.copyOfRange(messageBytes, 15, 17); byte[] bestDownwindAngle = Arrays.copyOfRange(messageBytes, 17, 19); byte[] flags = Arrays.copyOfRange(messageBytes, 19, 20); CourseWind message = new CourseWind(windId[0], bytesToLong(time), bytesToInt(raceID), twoByteToInt(windDirection), twoByteToInt(windSpeed), twoByteToInt(bestUpwindAngle), twoByteToInt(bestDownwindAngle), flags[0]); loopMessages.add(message); messageLoopIndex += 20; } } private int twoByteToInt(byte[] bytesInt){ ByteBuffer byteBuffer = ByteBuffer.allocate(4); byteBuffer.order(ByteOrder.BIG_ENDIAN); byteBuffer.put((byte)0); byteBuffer.put((byte)0); byteBuffer.put(bytesInt); int num = byteBuffer.getInt(0); return num; } private int bytesToInt(byte[] bytesInt){ ByteBuffer wrapped = ByteBuffer.wrap(bytesInt); int num = wrapped.getInt(); return num; } private long bytesToLong(byte[] bytesLong){ ByteBuffer byteBuffer = ByteBuffer.allocate(8); byteBuffer.order(ByteOrder.BIG_ENDIAN); byteBuffer.put((byte)0); byteBuffer.put((byte)0); byteBuffer.put(bytesLong[0]); byteBuffer.put(bytesLong[1]); byteBuffer.put(bytesLong[2]); byteBuffer.put(bytesLong[3]); byteBuffer.put(bytesLong[4]); byteBuffer.put(bytesLong[5]); long longVal = byteBuffer.getLong(0); return longVal; } public ArrayList getLoopMessages() { return loopMessages; } }