Merge branch 'master' into story68

-updated port and starboard boat checks
-added gps method to check if on correct side of a line
-updated pos check method to make boats round marks with the new tech

# Conflicts:
#	racevisionGame/src/main/java/mock/app/ConnectionAcceptor.java
#	racevisionGame/src/main/java/mock/app/Event.java
#	racevisionGame/src/main/java/mock/model/commandFactory/TackGybeCommand.java
#	racevisionGame/src/main/java/mock/model/commandFactory/VMGCommand.java
This commit is contained in:
hba56
2017-08-12 03:24:20 +12:00
94 changed files with 5962 additions and 1849 deletions
@@ -52,10 +52,10 @@ public class ConnectionAcceptor implements Runnable {
*/
public ConnectionAcceptor(LatestMessages latestMessages) throws IOException {
this.latestMessages =latestMessages;
this.latestMessages = latestMessages;
this.serverSocket = new ServerSocket(serverPort);
CheckClientConnection checkClientConnection = new CheckClientConnection(mockOutputList);
new Thread(checkClientConnection).start();
new Thread(checkClientConnection, "ConnectionAcceptor()->CheckClientConnection thread").start();
}
public String getAddress() throws UnknownHostException {
@@ -76,20 +76,30 @@ public class ConnectionAcceptor implements Runnable {
*/
@Override
public void run() {
while(true){//should be connections not filled up
while(mockOutputList.remainingCapacity() > 0) {
try {
System.out.println("Waiting for a connection...");//TEMP DEBUG REMOVE
Socket mockSocket = serverSocket.accept();
//TODO at this point we need to assign the connection a boat source ID, if they requested to participate.
DataOutputStream outToVisualiser = new DataOutputStream(mockSocket.getOutputStream());
MockOutput mockOutput = new MockOutput(latestMessages, outToVisualiser);
this.controllerServer = new ControllerServer(mockSocket, rl);
new Thread(mockOutput).start();
new Thread(controllerServer).start();
System.out.println("I'm in connectionAcceptor");
ControllerServer controllerServer = new ControllerServer(mockSocket, this.rl); //TODO probably pass assigned boat source ID into ControllerServer.
new Thread(mockOutput, "ConnectionAcceptor.run()->MockOutput thread" + mockOutput).start();
new Thread(controllerServer, "ConnectionAcceptor.run()->ControllerServer thread" + controllerServer).start();
mockOutputList.add(mockOutput);
System.out.println(String.format("%d number of Visualisers Connected.", mockOutputList.size()));
System.out.println(String.format("%d number of Visualisers Connected.", mockOutputList.size()));//TEMP
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();//TODO handle this properly
}
}
@@ -118,7 +128,7 @@ public class ConnectionAcceptor implements Runnable {
double timeSinceLastHeartBeat = System.currentTimeMillis();
while(true) {
//System.out.println(mocks.size());//used to see current amount of visualisers connected.
ArrayBlockingQueue<MockOutput> m = new ArrayBlockingQueue(16, true, mocks);
ArrayBlockingQueue<MockOutput> m = new ArrayBlockingQueue<>(16, true, mocks);
for (MockOutput mo : m) {
try {
mo.sendHeartBeat();
@@ -35,7 +35,7 @@ public class Event {
private Polars boatPolars;
private ConnectionAcceptor mockOutput;
private ConnectionAcceptor connectionAcceptor;
private LatestMessages latestMessages;
/**
@@ -51,7 +51,7 @@ public class Event {
this.boatPolars = PolarParser.parse("mock/polars/acc_polars.csv");
this.latestMessages = new LatestMessages();
this.mockOutput = new ConnectionAcceptor(latestMessages);
this.connectionAcceptor = new ConnectionAcceptor(latestMessages);
}
catch (IOException e) {
e.printStackTrace();
@@ -67,11 +67,11 @@ public class Event {
}
public String getAddress() throws UnknownHostException {
return mockOutput.getAddress();
return connectionAcceptor.getAddress();
}
public int getPort() {
return mockOutput.getServerPort();
return connectionAcceptor.getServerPort();
}
/**
@@ -82,8 +82,7 @@ public class Event {
* @throws InvalidRegattaDataException Thrown if the regatta xml file cannot be parsed.
*/
public void start() throws InvalidRaceDataException, XMLReaderException, InvalidBoatDataException, InvalidRegattaDataException {
new Thread(mockOutput).start();
new Thread(connectionAcceptor, "Event.Start()->ConnectionAcceptor thread").start();
sendXMLs();
@@ -95,11 +94,9 @@ public class Event {
//Create and start race.
RaceLogic newRace = new RaceLogic(new MockRace(boatDataSource, raceDataSource, regattaDataSource, this.latestMessages, this.boatPolars, Constants.RaceTimeScale), this.latestMessages);
mockOutput.setRace(newRace);
connectionAcceptor.setRace(newRace);
new Thread(newRace, "Event.Start()->RaceLogic thread").start();
new Thread(newRace).start();
System.out.println("I'm in event");
}
/**
@@ -107,11 +104,11 @@ public class Event {
*/
private void sendXMLs() {
mockOutput.setRegattaXml(regattaXML);
connectionAcceptor.setRegattaXml(regattaXML);
mockOutput.setRaceXml(raceXML);
connectionAcceptor.setRaceXml(raceXML);
mockOutput.setBoatsXml(boatXML);
connectionAcceptor.setBoatsXml(boatXML);
}
/**
@@ -3,16 +3,16 @@ package mock.app;
import network.BinaryMessageEncoder;
import network.Exceptions.InvalidMessageException;
import network.MessageEncoders.RaceVisionByteEncoder;
import network.Messages.*;
import network.Messages.Enums.MessageType;
import network.Messages.Enums.XMLMessageType;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TCP server to send race information to connected clients.
@@ -54,8 +54,6 @@ public class MockOutput implements Runnable
private int heartbeatSequenceNum = 1;
private boolean stop = false; //whether or not hte thread keeps running
/**
* Ctor.
* @param latestMessages Latests Messages that the Mock is to send out
@@ -98,24 +96,25 @@ public class MockOutput implements Runnable
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
* @return The next heartbeat message.
*/
private Heartbeat createHeartbeatMessage() {
private HeartBeat createHeartbeatMessage() {
//Create the heartbeat message.
Heartbeat heartbeat = new Heartbeat(this.heartbeatSequenceNum);
HeartBeat heartBeat = new HeartBeat(this.heartbeatSequenceNum);
heartbeatSequenceNum++;
return heartbeat;
return heartBeat;
}
/**
* Serializes a heartbeat message into a packet to be sent, and returns the byte array.
* @param heartbeat The heartbeat message to serialize.
* @param heartBeat The heartbeat message to serialize.
* @return Byte array containing the next heartbeat message.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private byte[] parseHeartbeat(Heartbeat heartbeat) {
private byte[] parseHeartbeat(HeartBeat heartBeat) throws InvalidMessageException {
//Serializes the heartbeat message.
byte[] heartbeatMessage = RaceVisionByteEncoder.heartBeat(heartbeat);
byte[] heartbeatMessage = RaceVisionByteEncoder.encode(heartBeat);
//Places the serialized message in a packet.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
@@ -133,11 +132,12 @@ public class MockOutput implements Runnable
* Encodes/serialises a XMLMessage message, and returns it.
* @param xmlMessage The XMLMessage message to serialise.
* @return The XMLMessage message in a serialised form.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private synchronized byte[] parseXMLMessage(XMLMessage xmlMessage) {
private synchronized byte[] parseXMLMessage(XMLMessage xmlMessage) throws InvalidMessageException {
//Serialize the xml message.
byte[] encodedXML = RaceVisionByteEncoder.xmlMessage(xmlMessage);
byte[] encodedXML = RaceVisionByteEncoder.encode(xmlMessage);
//Place the message in a packet.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
@@ -158,12 +158,13 @@ public class MockOutput implements Runnable
* Encodes/serialises a BoatLocation message, and returns it.
* @param boatLocation The BoatLocation message to serialise.
* @return The BoatLocation message in a serialised form.
* @throws InvalidMessageException If the message cannot be encoded.
*/
private synchronized byte[] parseBoatLocation(BoatLocation boatLocation){
private synchronized byte[] parseBoatLocation(BoatLocation boatLocation) throws InvalidMessageException {
//Encodes the message.
byte[] encodedBoatLoc = RaceVisionByteEncoder.boatLocation(boatLocation);
byte[] encodedBoatLoc = RaceVisionByteEncoder.encode(boatLocation);
//Encodes the full message with header.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
@@ -182,11 +183,12 @@ public class MockOutput implements Runnable
* Encodes/serialises a RaceStatus message, and returns it.
* @param raceStatus The RaceStatus message to serialise.
* @return The RaceStatus message in a serialised form.
* @throws InvalidMessageException Thrown if the message cannot be encoded.
*/
private synchronized byte[] parseRaceStatus(RaceStatus raceStatus){
private synchronized byte[] parseRaceStatus(RaceStatus raceStatus) throws InvalidMessageException {
//Encodes the messages.
byte[] encodedRaceStatus = RaceVisionByteEncoder.raceStatus(raceStatus);
byte[] encodedRaceStatus = RaceVisionByteEncoder.encode(raceStatus);
//Encodes the full message with header.
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
@@ -209,7 +211,15 @@ public class MockOutput implements Runnable
public void sendHeartBeat() throws IOException {
//Sends a heartbeat every so often.
if (timeSinceHeartbeat() >= heartbeatPeriod) {
outToVisualiser.write(parseHeartbeat(createHeartbeatMessage()));
HeartBeat heartBeat = createHeartbeatMessage();
try {
outToVisualiser.write(parseHeartbeat(heartBeat));
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode HeartBeat: " + heartBeat, e);
}
lastHeartbeatTime = System.currentTimeMillis();
}
}
@@ -219,39 +229,47 @@ public class MockOutput implements Runnable
*/
public void run() {
//Wait until all of the xml files have been set.
while (!this.latestMessages.hasAllXMLMessages()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//If we get interrupted, exit the function.
Logger.getGlobal().log(Level.WARNING, "MockOutput.run().sleep(waitForXMLs) was interrupted on thread: " + Thread.currentThread(), e);
//Re-set the interrupt flag.
Thread.currentThread().interrupt();
return;
}
}
long previousFrameTime = System.currentTimeMillis();
boolean sentXMLs = false;
try {
while (!stop){
while (!Thread.interrupted()) {
//Wait until all of the xml files have been set.
if (!this.latestMessages.hasAllXMLMessages()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
try {
long currentFrameTime = System.currentTimeMillis();
long previousFrameTime = System.currentTimeMillis();
boolean sentXMLs = false;
//This is the time elapsed, in milliseconds, since the last server "frame".
long framePeriod = currentFrameTime - previousFrameTime;
//We only attempt to send packets every X milliseconds.
long minimumFramePeriod = 16;
if (framePeriod >= minimumFramePeriod) {
while(true) {
try {
//Send XML messages.
if (!sentXMLs) {
//Serialise them.
long currentFrameTime = System.currentTimeMillis();
//This is the time elapsed, in milliseconds, since the last server "frame".
long framePeriod = currentFrameTime - previousFrameTime;
//We only attempt to send packets every X milliseconds.
long minimumFramePeriod = 16;
if (framePeriod >= minimumFramePeriod) {
//Send XML messages.
if (!sentXMLs) {
//Serialise them.
try {
byte[] raceXMLBlob = parseXMLMessage(latestMessages.getRaceXMLMessage());
byte[] regattaXMLBlob = parseXMLMessage(latestMessages.getRegattaXMLMessage());
byte[] boatsXMLBlob = parseXMLMessage(latestMessages.getBoatXMLMessage());
@@ -261,55 +279,74 @@ public class MockOutput implements Runnable
outToVisualiser.write(regattaXMLBlob);
outToVisualiser.write(boatsXMLBlob);
sentXMLs = true;
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode XMLMessage: " + latestMessages.getRaceXMLMessage(), e);
continue; //Go to next iteration.
}
//Sends the RaceStatus message.
if (this.latestMessages.getRaceStatus() != null) {
}
//Sends the RaceStatus message.
if (this.latestMessages.getRaceStatus() != null) {
try {
byte[] raceStatusBlob = this.parseRaceStatus(this.latestMessages.getRaceStatus());
this.outToVisualiser.write(raceStatusBlob);
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode RaceStatus: " + latestMessages.getRaceStatus(), e);
}
}
//Send all of the BoatLocation messages.
for (int sourceID : this.latestMessages.getBoatLocationMap().keySet()) {
//Send all of the BoatLocation messages.
for (int sourceID : this.latestMessages.getBoatLocationMap().keySet()) {
//Get the message.
BoatLocation boatLocation = this.latestMessages.getBoatLocation(sourceID);
if (boatLocation != null) {
//Get the message.
BoatLocation boatLocation = this.latestMessages.getBoatLocation(sourceID);
if (boatLocation != null) {
try {
//Encode.
byte[] boatLocationBlob = this.parseBoatLocation(boatLocation);
//Write it.
this.outToVisualiser.write(boatLocationBlob);
} catch (InvalidMessageException e) {
Logger.getGlobal().log(Level.WARNING, "Could not encode BoatLocation: " + boatLocation, e);
}
}
previousFrameTime = currentFrameTime;
} else {
//Wait until the frame period will be large enough.
long timeToWait = minimumFramePeriod - framePeriod;
try {
Thread.sleep(timeToWait);
} catch (InterruptedException e) {
//If we get interrupted, exit the function.
e.printStackTrace();
//Re-set the interrupt flag.
Thread.currentThread().interrupt();
return;
}
}
} catch (SocketException e) {
break;
previousFrameTime = currentFrameTime;
} else {
//Wait until the frame period will be large enough.
long timeToWait = minimumFramePeriod - framePeriod;
try {
Thread.sleep(timeToWait);
} catch (InterruptedException e) {
//If we get interrupted, exit the function.
Logger.getGlobal().log(Level.WARNING, "MockOutput.run().sleep(framePeriod) was interrupted on thread: " + Thread.currentThread(), e);
//Re-set the interrupt flag.
Thread.currentThread().interrupt();
return;
}
}
} catch (SocketException e) {
break;
}
}
} catch (IOException e) {
@@ -317,8 +354,5 @@ public class MockOutput implements Runnable
}
}
public void stop(){
stop = true;
}
}
@@ -33,7 +33,7 @@ public class MockBoat extends Boat {
/**
* Stores whether the boat is on autoVMG or not
*/
private boolean autoVMG = true;
private boolean autoVMG = false;
@@ -649,4 +649,4 @@ public class MockRace extends Race {
public List<CompoundMark> getCompoundMarks() {
return compoundMarks;
}
}
}
@@ -2,9 +2,11 @@ package mock.model;
import network.Messages.BoatLocation;
import network.Messages.BoatStatus;
import network.Messages.Enums.BoatLocationDeviceEnum;
import network.Messages.LatestMessages;
import network.Messages.RaceStatus;
import network.Utils.AC35UnitConverter;
import shared.model.Bearing;
import shared.model.CompoundMark;
import shared.model.Constants;
import shared.model.Mark;
@@ -47,7 +49,9 @@ public class RaceServer {
mark.getPosition().getLatitude(),
mark.getPosition().getLongitude(),
this.boatLocationSequenceNumber,
0, 0,
BoatLocationDeviceEnum.Mark,
Bearing.fromDegrees(0),
0,
race.getRaceClock().getCurrentTimeMilli());
//Iterates the sequence number.
@@ -99,7 +103,8 @@ public class RaceServer {
boat.getCurrentPosition().getLatitude(),
boat.getCurrentPosition().getLongitude(),
this.boatLocationSequenceNumber,
boat.getBearing().degrees(),
BoatLocationDeviceEnum.RacingYacht,
boat.getBearing(),
boat.getCurrentSpeed(),
race.getRaceClock().getCurrentTimeMilli());
@@ -133,19 +138,17 @@ public class RaceServer {
}
//Convert wind direction and speed to ints. //TODO this conversion should be done inside the racestatus class.
int windDirectionInt = AC35UnitConverter.encodeHeading(race.getWindDirection().degrees());
int windSpeedInt = (int) (race.getWindSpeed() * Constants.KnotsToMMPerSecond);
//Create race status object, and send it.
RaceStatus raceStatus = new RaceStatus(
RaceStatus.currentMessageVersionNumber,
System.currentTimeMillis(),
race.getRaceId(),
race.getRaceStatusEnum().getValue(),
race.getRaceStatusEnum(),
race.getRaceClock().getStartingTimeMilli(),
windDirectionInt,
windSpeedInt,
race.getRaceType().getValue(),
race.getWindDirection(),
race.getWindSpeed(),
race.getRaceType(),
boatStatuses);
this.latestMessages.setRaceStatus(raceStatus);
@@ -2,8 +2,6 @@ package mock.model.commandFactory;
import mock.model.MockBoat;
import mock.model.MockRace;
import mock.model.VMG;
import shared.model.Bearing;
/**
* Created by David on 2/08/2017.
@@ -20,30 +18,18 @@ public class TackGybeCommand implements Command {
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
/*if(boat.getBearing().degrees()>180){
boat.setBearing(Bearing.fromDegrees(360 - race.getWindDirection().degrees()));
} else {
boat.setBearing(Bearing.fromDegrees(race.getWindDirection().degrees()));
boat.setAutoVMG(false);
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
VMG boatVMG = new VMG(boat.getCurrentSpeed(), boat.getBearing());
if(race.improvesVelocity(boatVMG, newVMG, boat.calculateBearingToNextMarker())){
boat.setVMG(newVMG);
}*/
/*double angle = Math.max(race.getWindDirection().degrees(), boat.getBearing().degrees()) - Math.min(race.getWindDirection().degrees(), boat.getBearing().degrees());
boat.setBearing(Bearing.fromDegrees(angle));*/
double boatAngle = boat.getBearing().degrees();
double windAngle =race.getWindDirection().degrees();
double differenceAngle = calcDistance(boatAngle, windAngle);
double angleA = windAngle + differenceAngle;
double angleB = windAngle - differenceAngle;
if(angleA % 360 == boatAngle){
boat.setBearing(Bearing.fromDegrees(angleB));
} else {
boat.setBearing(Bearing.fromDegrees(angleA));
}
}
public double calcDistance(double degreeA, double degreeB){
double phi = Math.abs(degreeB - degreeA) % 360;
double distance = phi > 180 ? 360 - phi : phi;
return distance;
}
}
@@ -18,12 +18,13 @@ public class VMGCommand implements Command {
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
if (boat.getAutoVMG()){
boat.setAutoVMG(false);
System.out.println("Auto VMG off!");
} else {
boat.setAutoVMG(true);
System.out.println("Auto VMG on!");
}
boat.setAutoVMG(true);
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
boat.setVMG(newVMG);*/
}
}
@@ -20,13 +20,17 @@ public class WindCommand implements Command {
@Override
public void execute() {
boat.setAutoVMG(false);
double wind = race.getWindDirection().degrees();
double heading = boat.getBearing().degrees();
double offset = 3.0;
offset *= direction;
if(wind - heading < 0) offset *= -1;
double headWindDelta = wind - heading;
if ((headWindDelta < 0) || (headWindDelta > 180)) offset *= -1;
boat.setBearing(Bearing.fromDegrees(heading + offset));
}