Merge remote-tracking branch 'origin/master' into issue#20fix
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
package visualiser.Commands.ConnectionToServerCommands;
|
||||
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
|
||||
/**
|
||||
* Factory to create ConnectionToServer commands.
|
||||
*/
|
||||
public class ConnectionToServerCommandFactory {
|
||||
|
||||
/**
|
||||
* Generates a command to execute on server connection based on the type of {@link network.Messages.Enums.JoinAcceptanceEnum}.
|
||||
* @param message The message to turn into a command.
|
||||
* @param connectionToServer The connection for the command to operate on.
|
||||
* @return The command to execute the given action.
|
||||
* @throws CommandConstructionException Thrown if the command cannot be constructed.
|
||||
*/
|
||||
public static Command create(AC35Data message, ConnectionToServer connectionToServer) throws CommandConstructionException {
|
||||
|
||||
if (!(message instanceof JoinAcceptance)) {
|
||||
throw new CommandConstructionException("Message: " + message + " is not a JoinAcceptance message.");
|
||||
}
|
||||
|
||||
JoinAcceptance joinAcceptance = (JoinAcceptance) message;
|
||||
|
||||
|
||||
switch(joinAcceptance.getAcceptanceType()) {
|
||||
|
||||
case JOIN_SUCCESSFUL_PARTICIPANT: return new JoinSuccessParticipantCommand(joinAcceptance, connectionToServer);
|
||||
|
||||
case JOIN_SUCCESSFUL_SPECTATOR: return new JoinSuccessSpectatorCommand(joinAcceptance, connectionToServer);
|
||||
|
||||
case JOIN_FAILURE: return new JoinFailureCommand(joinAcceptance, connectionToServer);
|
||||
|
||||
case SERVER_FULL: return new ServerFullCommand(joinAcceptance, connectionToServer);
|
||||
|
||||
default: throw new CommandConstructionException("Could not create command for JoinAcceptance: " + joinAcceptance + ". Unknown JoinAcceptanceEnum.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package visualiser.Commands.ConnectionToServerCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.JoinAcceptanceEnum#JOIN_FAILURE} {@link JoinAcceptance} message is received.
|
||||
*/
|
||||
public class JoinFailureCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private JoinAcceptance joinAcceptance;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link JoinFailureCommand}, which operates on a given {@link ConnectionToServer}.
|
||||
* @param joinAcceptance The message to operate on.
|
||||
* @param connectionToServer The context to operate on.
|
||||
*/
|
||||
public JoinFailureCommand(JoinAcceptance joinAcceptance, ConnectionToServer connectionToServer) {
|
||||
this.joinAcceptance = joinAcceptance;
|
||||
this.connectionToServer = connectionToServer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
connectionToServer.setJoinAcceptance(joinAcceptance);
|
||||
|
||||
connectionToServer.setConnectionState(ConnectionToServerState.DECLINED);
|
||||
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package visualiser.Commands.ConnectionToServerCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AssignPlayerBoat;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.JoinAcceptanceEnum#JOIN_SUCCESSFUL_PARTICIPANT} {@link network.Messages.JoinAcceptance} message is received.
|
||||
*/
|
||||
public class JoinSuccessParticipantCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private JoinAcceptance joinAcceptance;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link JoinSuccessParticipantCommand}, which operates on a given {@link ConnectionToServer}.
|
||||
* @param joinAcceptance The message to operate on.
|
||||
* @param connectionToServer The context to operate on.
|
||||
*/
|
||||
public JoinSuccessParticipantCommand(JoinAcceptance joinAcceptance, ConnectionToServer connectionToServer) {
|
||||
this.joinAcceptance = joinAcceptance;
|
||||
this.connectionToServer = connectionToServer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
connectionToServer.setJoinAcceptance(joinAcceptance);
|
||||
|
||||
connectionToServer.setConnectionState(ConnectionToServerState.CONNECTED);
|
||||
|
||||
|
||||
AssignPlayerBoat assignPlayerBoat = new AssignPlayerBoat(joinAcceptance.getSourceID());
|
||||
try {
|
||||
connectionToServer.send(assignPlayerBoat);
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "JoinSuccessParticipantCommand: " + this + " was interrupted on thread: " + Thread.currentThread() + " while sending AssignPlayerBoat message.", e);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package visualiser.Commands.ConnectionToServerCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.JoinAcceptanceEnum#JOIN_SUCCESSFUL_PARTICIPANT} {@link JoinAcceptance} message is received.
|
||||
*/
|
||||
public class JoinSuccessSpectatorCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private JoinAcceptance joinAcceptance;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link JoinSuccessSpectatorCommand}, which operates on a given {@link ConnectionToServer}.
|
||||
* @param joinAcceptance The message to operate on.
|
||||
* @param connectionToServer The context to operate on.
|
||||
*/
|
||||
public JoinSuccessSpectatorCommand(JoinAcceptance joinAcceptance, ConnectionToServer connectionToServer) {
|
||||
this.joinAcceptance = joinAcceptance;
|
||||
this.connectionToServer = connectionToServer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
connectionToServer.setJoinAcceptance(joinAcceptance);
|
||||
|
||||
connectionToServer.setConnectionState(ConnectionToServerState.CONNECTED);
|
||||
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package visualiser.Commands.ConnectionToServerCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.JoinAcceptanceEnum#SERVER_FULL} {@link JoinAcceptance} message is received.
|
||||
*/
|
||||
public class ServerFullCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private JoinAcceptance joinAcceptance;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link ServerFullCommand}, which operates on a given {@link ConnectionToServer}.
|
||||
* @param joinAcceptance The message to operate on.
|
||||
* @param connectionToServer The context to operate on.
|
||||
*/
|
||||
public ServerFullCommand(JoinAcceptance joinAcceptance, ConnectionToServer connectionToServer) {
|
||||
this.joinAcceptance = joinAcceptance;
|
||||
this.connectionToServer = connectionToServer;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
connectionToServer.setJoinAcceptance(joinAcceptance);
|
||||
|
||||
connectionToServer.setConnectionState(ConnectionToServerState.DECLINED);
|
||||
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package visualiser.Commands.IncomingHeartBeatCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.HeartBeat;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.network.ConnectionToServer;
|
||||
import visualiser.network.IncomingHeartBeatService;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link HeartBeat} message is received.
|
||||
*/
|
||||
public class IncomingHeartBeatCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private HeartBeat heartBeat;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private IncomingHeartBeatService incomingHeartBeatService;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link IncomingHeartBeatCommand}, which operates on a given {@link IncomingHeartBeatService}.
|
||||
* @param heartBeat The message to operate on.
|
||||
* @param incomingHeartBeatService The context to operate on.
|
||||
*/
|
||||
public IncomingHeartBeatCommand(HeartBeat heartBeat, IncomingHeartBeatService incomingHeartBeatService) {
|
||||
this.heartBeat = heartBeat;
|
||||
this.incomingHeartBeatService = incomingHeartBeatService;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
incomingHeartBeatService.setLastHeartBeatSeqNum(heartBeat.getSequenceNumber());
|
||||
|
||||
incomingHeartBeatService.setLastHeartbeatTime(System.currentTimeMillis());
|
||||
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package visualiser.Commands.IncomingHeartBeatCommands;
|
||||
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.HeartBeat;
|
||||
import visualiser.network.IncomingHeartBeatService;
|
||||
|
||||
/**
|
||||
* Factory to create IncomingHeartBeatService commands.
|
||||
*/
|
||||
public class IncomingHeartBeatCommandFactory {
|
||||
|
||||
/**
|
||||
* Generates a command on an IncomingHeartBeatService.
|
||||
* @param message The message to turn into a command.
|
||||
* @param incomingHeartBeatService The context for the command to operate on.
|
||||
* @return The command to execute the given action.
|
||||
* @throws CommandConstructionException Thrown if the command cannot be constructed.
|
||||
*/
|
||||
public static Command create(AC35Data message, IncomingHeartBeatService incomingHeartBeatService) throws CommandConstructionException {
|
||||
|
||||
if (!(message instanceof HeartBeat)) {
|
||||
throw new CommandConstructionException("Message: " + message + " is not a HeartBeat message.");
|
||||
}
|
||||
|
||||
HeartBeat heartBeat = (HeartBeat) message;
|
||||
|
||||
return new IncomingHeartBeatCommand(heartBeat, incomingHeartBeatService);
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AssignPlayerBoat;
|
||||
import network.Messages.BoatLocation;
|
||||
import shared.exceptions.BoatNotFoundException;
|
||||
import shared.exceptions.MarkNotFoundException;
|
||||
import shared.model.GPSCoordinate;
|
||||
import shared.model.Mark;
|
||||
import visualiser.model.VisualiserBoat;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link AssignPlayerBoat} message is received.
|
||||
*/
|
||||
public class AssignPlayerBoatCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private AssignPlayerBoat assignPlayerBoat;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link AssignPlayerBoatCommand}, which operates on a given {@link VisualiserRaceState}.
|
||||
* @param assignPlayerBoat The message to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public AssignPlayerBoatCommand(AssignPlayerBoat assignPlayerBoat, VisualiserRaceState visualiserRace) {
|
||||
this.assignPlayerBoat = assignPlayerBoat;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
visualiserRace.setPlayerBoatID(assignPlayerBoat.getSourceID());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.BoatLocation;
|
||||
import network.Messages.Enums.BoatStatusEnum;
|
||||
import shared.exceptions.BoatNotFoundException;
|
||||
import shared.exceptions.MarkNotFoundException;
|
||||
import shared.model.GPSCoordinate;
|
||||
import shared.model.Mark;
|
||||
import visualiser.model.VisualiserBoat;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link BoatLocation} message is received.
|
||||
*/
|
||||
public class BoatLocationCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private BoatLocation boatLocation;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link BoatLocationCommand}, which operates on a given {@link VisualiserRaceState}.
|
||||
* @param boatLocation The message to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public BoatLocationCommand(BoatLocation boatLocation, VisualiserRaceState visualiserRace) {
|
||||
this.boatLocation = boatLocation;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
if (visualiserRace.isVisualiserBoat(boatLocation.getSourceID())) {
|
||||
updateBoatLocation();
|
||||
} else if (visualiserRace.isMark(boatLocation.getSourceID())) {
|
||||
updateMarkLocation();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the boat specified in the message.
|
||||
*/
|
||||
private void updateBoatLocation() {
|
||||
|
||||
try {
|
||||
VisualiserBoat boat = visualiserRace.getBoat(boatLocation.getSourceID());
|
||||
|
||||
//Get the new position.
|
||||
GPSCoordinate gpsCoordinate = new GPSCoordinate(
|
||||
boatLocation.getLatitude(),
|
||||
boatLocation.getLongitude());
|
||||
|
||||
boat.setCurrentPosition(gpsCoordinate);
|
||||
|
||||
//Bearing.
|
||||
boat.setBearing(boatLocation.getHeading());
|
||||
|
||||
|
||||
//Speed.
|
||||
boat.setCurrentSpeed(boatLocation.getBoatSpeedKnots());
|
||||
|
||||
|
||||
//Attempt to add a track point.
|
||||
attemptAddTrackPoint(boat);
|
||||
|
||||
|
||||
} catch (BoatNotFoundException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "BoatLocationCommand: " + this + " could not execute. Boat with sourceID: " + boatLocation.getSourceID() + " not found.", e);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to add a track point to the boat. Only works if the boat is currently racing.
|
||||
* @param boat The boat to add a track point to.
|
||||
*/
|
||||
private void attemptAddTrackPoint(VisualiserBoat boat) {
|
||||
if (boat.getStatus() == BoatStatusEnum.RACING) {
|
||||
boat.addTrackPoint(boat.getCurrentPosition(), visualiserRace.getRaceClock().getCurrentTime());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the marker boat specified in message.
|
||||
*/
|
||||
private void updateMarkLocation() {
|
||||
|
||||
try {
|
||||
Mark mark = visualiserRace.getMark(boatLocation.getSourceID());
|
||||
|
||||
GPSCoordinate gpsCoordinate = new GPSCoordinate(
|
||||
boatLocation.getLatitude(),
|
||||
boatLocation.getLongitude());
|
||||
|
||||
mark.setPosition(gpsCoordinate);
|
||||
} catch (MarkNotFoundException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "BoatLocationCommand: " + this + " could not execute. Mark with sourceID: " + boatLocation.getSourceID() + " not found.", e);
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.XMLMessage;
|
||||
import shared.dataInput.BoatDataSource;
|
||||
import shared.dataInput.BoatXMLReader;
|
||||
import shared.enums.XMLFileType;
|
||||
import shared.exceptions.InvalidBoatDataException;
|
||||
import shared.exceptions.XMLReaderException;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.XMLMessageType#BOAT} {@link XMLMessage} message is received.
|
||||
*/
|
||||
public class BoatsXMLMessageCommand implements Command {
|
||||
|
||||
/**
|
||||
* The data source to operate on.
|
||||
*/
|
||||
private BoatDataSource boatDataSource;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link BoatsXMLMessageCommand}, which operates on a given {@link VisualiserRaceEvent}.
|
||||
* @param boatDataSource The data source to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public BoatsXMLMessageCommand(BoatDataSource boatDataSource, VisualiserRaceState visualiserRace) {
|
||||
this.boatDataSource = boatDataSource;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
visualiserRace.setBoatDataSource(boatDataSource);
|
||||
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.BoatStatus;
|
||||
import network.Messages.Enums.BoatStatusEnum;
|
||||
import network.Messages.RaceStatus;
|
||||
import shared.exceptions.BoatNotFoundException;
|
||||
import shared.model.Leg;
|
||||
import visualiser.model.VisualiserBoat;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link RaceStatus} message is received.
|
||||
*/
|
||||
public class RaceStatusCommand implements Command {
|
||||
|
||||
/**
|
||||
* The message to operate on.
|
||||
*/
|
||||
private RaceStatus raceStatus;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link RaceStatusCommand}, which operates on a given {@link VisualiserRaceState}.
|
||||
* @param raceStatus The message to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public RaceStatusCommand(RaceStatus raceStatus, VisualiserRaceState visualiserRace) {
|
||||
this.raceStatus = raceStatus;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
//Race status enum.
|
||||
visualiserRace.setRaceStatusEnum(raceStatus.getRaceStatus());
|
||||
|
||||
//Wind.
|
||||
visualiserRace.setWind(
|
||||
raceStatus.getWindDirection(),
|
||||
raceStatus.getWindSpeed() );
|
||||
|
||||
//Current race time.
|
||||
visualiserRace.getRaceClock().setUTCTime(raceStatus.getCurrentTime());
|
||||
|
||||
|
||||
|
||||
for (BoatStatus boatStatus : raceStatus.getBoatStatuses()) {
|
||||
updateBoatStatus(boatStatus);
|
||||
}
|
||||
|
||||
|
||||
visualiserRace.updateBoatPositions(visualiserRace.getBoats());
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates a single boat's status using the boatStatus message.
|
||||
* @param boatStatus BoatStatus message to get data from.
|
||||
*/
|
||||
private void updateBoatStatus(BoatStatus boatStatus) {
|
||||
try {
|
||||
VisualiserBoat boat = visualiserRace.getBoat(boatStatus.getSourceID());
|
||||
|
||||
//Time at next mark.
|
||||
updateEstimatedTimeAtNextMark(boatStatus, boat);
|
||||
|
||||
|
||||
BoatStatusEnum newBoatStatusEnum = boatStatus.getBoatStatus();
|
||||
|
||||
//Time at last mark.
|
||||
initialiseTimeAtLastMark(boat, boat.getStatus(), newBoatStatusEnum);
|
||||
|
||||
//Status.
|
||||
boat.setStatus(newBoatStatusEnum);
|
||||
|
||||
|
||||
List<Leg> legs = visualiserRace.getLegs();
|
||||
|
||||
//Leg.
|
||||
updateLeg(boatStatus.getLegNumber(), boat, legs);
|
||||
|
||||
|
||||
//Set finish time if boat finished.
|
||||
attemptUpdateFinishTime(boatStatus, boat, legs);
|
||||
|
||||
|
||||
} catch (BoatNotFoundException e) {
|
||||
//Logger.getGlobal().log(Level.WARNING, "RaceStatusCommand.updateBoatStatus: " + this + " could not execute. Boat with sourceID: " + boatStatus.getSourceID() + " not found.", e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to update the finish time of the boat. Only works if the boat has actually finished the race.
|
||||
* @param boatStatus BoatStatus to read data from.
|
||||
* @param boat Boat to update.
|
||||
* @param legs Legs of the race.
|
||||
*/
|
||||
private void attemptUpdateFinishTime(BoatStatus boatStatus, VisualiserBoat boat, List<Leg> legs) {
|
||||
|
||||
if (boat.getStatus() == BoatStatusEnum.FINISHED || boatStatus.getLegNumber() == legs.size()) {
|
||||
boat.setTimeFinished(visualiserRace.getRaceClock().getCurrentTimeMilli());
|
||||
boat.setStatus(BoatStatusEnum.FINISHED);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Updates a boat's leg.
|
||||
* @param legNumber The new leg number.
|
||||
* @param boat The boat to update.
|
||||
* @param legs The legs in the race.
|
||||
*/
|
||||
private void updateLeg(int legNumber, VisualiserBoat boat, List<Leg> legs) {
|
||||
|
||||
if (legNumber >= 1 && legNumber < legs.size()) {
|
||||
if (boat.getCurrentLeg() != legs.get(legNumber)) {
|
||||
boatFinishedLeg(boat, legs.get(legNumber));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialises the time at last mark for a boat. Only changes if the boat's status is changing from non-racing to racing.
|
||||
* @param boat The boat to update.
|
||||
* @param currentBoatStatus The current status of the boat.
|
||||
* @param newBoatStatusEnum The new status of the boat, from the BoatStatus message.
|
||||
*/
|
||||
private void initialiseTimeAtLastMark(VisualiserBoat boat, BoatStatusEnum currentBoatStatus, BoatStatusEnum newBoatStatusEnum) {
|
||||
//If we are changing from non-racing to racing, we need to initialise boat with their time at last mark.
|
||||
if ((currentBoatStatus != BoatStatusEnum.RACING) && (newBoatStatusEnum == BoatStatusEnum.RACING)) {
|
||||
boat.setTimeAtLastMark(visualiserRace.getRaceClock().getCurrentTime());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the estimated time at next mark for a given boat.
|
||||
* @param boatStatus BoatStatus to read data from.
|
||||
* @param boat Boat to update.
|
||||
*/
|
||||
private void updateEstimatedTimeAtNextMark(BoatStatus boatStatus, VisualiserBoat boat) {
|
||||
boat.setEstimatedTimeAtNextMark(visualiserRace.getRaceClock().getLocalTime(boatStatus.getEstTimeAtNextMark()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Updates a boat's leg to a specified leg. Also records the order in which the boat passed the leg.
|
||||
* @param boat The boat to update.
|
||||
* @param leg The leg to use.
|
||||
*/
|
||||
private void boatFinishedLeg(VisualiserBoat boat, Leg leg) {
|
||||
|
||||
//Record order in which boat finished leg.
|
||||
visualiserRace.getLegCompletionOrder().get(boat.getCurrentLeg()).add(boat);
|
||||
|
||||
//Update boat.
|
||||
boat.setCurrentLeg(leg);
|
||||
boat.setTimeAtLastMark(visualiserRace.getRaceClock().getCurrentTime());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.XMLMessage;
|
||||
import shared.dataInput.RaceDataSource;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.XMLMessageType#BOAT} {@link XMLMessage} message is received.
|
||||
*/
|
||||
public class RaceXMLMessageCommand implements Command {
|
||||
|
||||
/**
|
||||
* The data source to operate on.
|
||||
*/
|
||||
private RaceDataSource raceDataSource;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link RaceXMLMessageCommand}, which operates on a given {@link VisualiserRaceEvent}.
|
||||
* @param raceDataSource The data source to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public RaceXMLMessageCommand(RaceDataSource raceDataSource, VisualiserRaceState visualiserRace) {
|
||||
this.raceDataSource = raceDataSource;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
visualiserRace.setRaceDataSource(raceDataSource);
|
||||
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.XMLMessage;
|
||||
import shared.dataInput.RegattaDataSource;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
|
||||
/**
|
||||
* Command created when a {@link network.Messages.Enums.XMLMessageType#BOAT} {@link XMLMessage} message is received.
|
||||
*/
|
||||
public class RegattaXMLMessageCommand implements Command {
|
||||
|
||||
/**
|
||||
* The data source to operate on.
|
||||
*/
|
||||
private RegattaDataSource regattaDataSource;
|
||||
|
||||
/**
|
||||
* The context to operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link RegattaXMLMessageCommand}, which operates on a given {@link VisualiserRaceEvent}.
|
||||
* @param regattaDataSource The data source to operate on.
|
||||
* @param visualiserRace The context to operate on.
|
||||
*/
|
||||
public RegattaXMLMessageCommand(RegattaDataSource regattaDataSource, VisualiserRaceState visualiserRace) {
|
||||
this.regattaDataSource = regattaDataSource;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
|
||||
visualiserRace.setRegattaDataSource(regattaDataSource);
|
||||
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.*;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
/**
|
||||
* Factory to create VisualiserRace commands.
|
||||
*/
|
||||
public class VisualiserRaceCommandFactory {
|
||||
|
||||
/**
|
||||
* Generates a command on an VisualiserRace.
|
||||
* @param message The message to turn into a command.
|
||||
* @param visualiserRace The context for the command to operate on.
|
||||
* @return The command to execute the given action.
|
||||
* @throws CommandConstructionException Thrown if the command cannot be constructed.
|
||||
*/
|
||||
public static Command create(AC35Data message, VisualiserRaceState visualiserRace) throws CommandConstructionException {
|
||||
|
||||
switch (message.getType()) {
|
||||
|
||||
case BOATLOCATION: return new BoatLocationCommand((BoatLocation) message, visualiserRace);
|
||||
|
||||
case RACESTATUS: return new RaceStatusCommand((RaceStatus) message, visualiserRace);
|
||||
|
||||
case XMLMESSAGE: return XMLMessageCommandFactory.create((XMLMessage) message, visualiserRace);
|
||||
|
||||
case ASSIGN_PLAYER_BOAT: return new AssignPlayerBoatCommand((AssignPlayerBoat) message, visualiserRace);
|
||||
|
||||
default: throw new CommandConstructionException("Could not create VisualiserRaceCommand. Unrecognised or unsupported MessageType: " + message.getType());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package visualiser.Commands.VisualiserRaceCommands;
|
||||
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.BoatLocation;
|
||||
import network.Messages.RaceStatus;
|
||||
import network.Messages.XMLMessage;
|
||||
import shared.dataInput.*;
|
||||
import shared.enums.XMLFileType;
|
||||
import shared.exceptions.InvalidBoatDataException;
|
||||
import shared.exceptions.InvalidRaceDataException;
|
||||
import shared.exceptions.InvalidRegattaDataException;
|
||||
import shared.exceptions.XMLReaderException;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
/**
|
||||
* Factory to create VisualiserRace commands, from XMLMessages.
|
||||
*/
|
||||
public class XMLMessageCommandFactory {
|
||||
|
||||
/**
|
||||
* Generates a command on an VisualiserRace.
|
||||
* @param message The message to turn into a command.
|
||||
* @param visualiserRace The context for the command to operate on.
|
||||
* @return The command to execute the given action.
|
||||
* @throws CommandConstructionException Thrown if the command cannot be constructed.
|
||||
*/
|
||||
public static Command create(XMLMessage message, VisualiserRaceState visualiserRace) throws CommandConstructionException {
|
||||
|
||||
try {
|
||||
|
||||
switch (message.getXmlMsgSubType()) {
|
||||
|
||||
case BOAT:
|
||||
BoatDataSource boatDataSource = new BoatXMLReader(message.getXmlMessage(), XMLFileType.Contents);
|
||||
return new BoatsXMLMessageCommand(boatDataSource, visualiserRace);
|
||||
|
||||
|
||||
case RACE:
|
||||
RaceDataSource raceDataSource = new RaceXMLReader(message.getXmlMessage(), XMLFileType.Contents);
|
||||
return new RaceXMLMessageCommand(raceDataSource, visualiserRace);
|
||||
|
||||
|
||||
case REGATTA:
|
||||
RegattaDataSource regattaDataSource = new RegattaXMLReader(message.getXmlMessage(), XMLFileType.Contents);
|
||||
return new RegattaXMLMessageCommand(regattaDataSource, visualiserRace);
|
||||
|
||||
|
||||
default:
|
||||
throw new CommandConstructionException("Could not create VisualiserRaceCommand/XMLCommand. Unrecognised or unsupported MessageType: " + message.getType());
|
||||
|
||||
}
|
||||
|
||||
} catch (XMLReaderException | InvalidBoatDataException | InvalidRegattaDataException | InvalidRaceDataException e) {
|
||||
throw new CommandConstructionException("Could not create VisualiserRaceCommand/XMLCommand. Could not parse XML message payload.", e);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package visualiser.Controllers;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.property.Property;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.image.ImageView;
|
||||
import javafx.scene.layout.Pane;
|
||||
@@ -12,7 +11,6 @@ import javafx.scene.layout.StackPane;
|
||||
import javafx.scene.shape.Circle;
|
||||
import shared.model.Bearing;
|
||||
import shared.model.Wind;
|
||||
import visualiser.model.VisualiserRace;
|
||||
|
||||
/**
|
||||
* Controller for the arrow.fxml view.
|
||||
|
||||
@@ -19,6 +19,7 @@ import java.net.URL;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
//TODO it appears this view/controller was replaced by Lobby.fxml. Remove?
|
||||
/**
|
||||
* Controls the connection that the VIsualiser can connect to.
|
||||
*/
|
||||
@@ -82,11 +83,6 @@ public class ConnectionController extends Controller {
|
||||
private ObservableList<RaceConnection> connections;
|
||||
|
||||
|
||||
/**
|
||||
* Represents whether the client is currently hosting a game already - this is to ensure they don't launch multiple servers.
|
||||
*/
|
||||
private boolean currentlyHostingGame = false;
|
||||
|
||||
|
||||
@Override
|
||||
public void initialize(URL location, ResourceBundle resources) {
|
||||
@@ -144,32 +140,5 @@ public class ConnectionController extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up a new host
|
||||
*/
|
||||
public void addLocal() {
|
||||
try {
|
||||
//We don't want to host more than one game.
|
||||
if (!currentlyHostingGame) {
|
||||
Event game = Event.getEvent();
|
||||
urlField.textProperty().set(game.getAddress());
|
||||
portField.textProperty().set(Integer.toString(game.getPort()));
|
||||
|
||||
game.start();
|
||||
addConnection();
|
||||
|
||||
currentlyHostingGame = true;
|
||||
}
|
||||
} catch (InvalidRaceDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (XMLReaderException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidBoatDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidRegattaDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import javafx.scene.control.*;
|
||||
import javafx.scene.layout.AnchorPane;
|
||||
import javafx.stage.Stage;
|
||||
import mock.app.Event;
|
||||
import mock.exceptions.EventConstructionException;
|
||||
import shared.exceptions.InvalidBoatDataException;
|
||||
import shared.exceptions.InvalidRaceDataException;
|
||||
import shared.exceptions.InvalidRegattaDataException;
|
||||
@@ -17,6 +18,8 @@ import java.net.Socket;
|
||||
import java.net.URL;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ResourceBundle;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Controller for Hosting a game.
|
||||
@@ -44,17 +47,12 @@ public class HostController extends Controller {
|
||||
*/
|
||||
public void hostGamePressed() throws IOException{
|
||||
try {
|
||||
Event game = Event.getEvent();
|
||||
Event game = new Event(false);
|
||||
game.start();
|
||||
connectSocket("localhost", 4942);
|
||||
} catch (InvalidRaceDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (XMLReaderException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidBoatDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidRegattaDataException e) {
|
||||
e.printStackTrace();
|
||||
} catch (EventConstructionException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "Could not create Event.", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +78,6 @@ public class HostController extends Controller {
|
||||
*/
|
||||
public void hostGame(){
|
||||
hostWrapper.setVisible(true);
|
||||
System.out.println("Reacted hostGame");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -58,7 +58,6 @@ public class LobbyController extends Controller {
|
||||
}
|
||||
else {
|
||||
joinGameBtn.setDisable(true);
|
||||
System.out.println(curr.statusProperty().getValue());
|
||||
}
|
||||
});
|
||||
joinGameBtn.setDisable(true);
|
||||
@@ -70,11 +69,6 @@ public class LobbyController extends Controller {
|
||||
public void refreshBtnPressed(){
|
||||
for(RaceConnection connection: connections) {
|
||||
connection.check();
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (lobbyTable.getSelectionModel().getSelectedItem().statusProperty().getValue().equals("Ready")) {
|
||||
|
||||
@@ -3,15 +3,15 @@ package visualiser.Controllers;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.layout.AnchorPane;
|
||||
import visualiser.app.VisualiserInput;
|
||||
import visualiser.gameController.ControllerClient;
|
||||
import visualiser.model.VisualiserBoat;
|
||||
import visualiser.model.VisualiserRace;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
|
||||
import java.net.Socket;
|
||||
import java.net.URL;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
|
||||
/**
|
||||
* Controller that everything is overlayed onto. This makes it so that changing scenes does not resize your stage.
|
||||
*/
|
||||
@@ -36,12 +36,11 @@ public class MainController extends Controller {
|
||||
|
||||
/**
|
||||
* Transitions from the StartController screen (displays pre-race information) to the RaceController (displays the actual race).
|
||||
* @param visualiserInput The object used to read packets from the race server.
|
||||
* @param visualiserRace The object modelling the race.
|
||||
* @param controllerClient Socket Client that manipulates the controller.
|
||||
*/
|
||||
public void beginRace(VisualiserInput visualiserInput, VisualiserRace visualiserRace, ControllerClient controllerClient) {
|
||||
raceController.startRace(visualiserInput, visualiserRace, controllerClient);
|
||||
public void beginRace(VisualiserRaceEvent visualiserRace, ControllerClient controllerClient) {
|
||||
raceController.startRace(visualiserRace, controllerClient);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,10 +102,15 @@ public class MainController extends Controller {
|
||||
AnchorPane.setLeftAnchor(startController.startWrapper(), 0.0);
|
||||
AnchorPane.setRightAnchor(startController.startWrapper(), 0.0);
|
||||
|
||||
AnchorPane.setTopAnchor(connectionController.startWrapper(), 0.0);
|
||||
AnchorPane.setBottomAnchor(connectionController.startWrapper(), 0.0);
|
||||
AnchorPane.setLeftAnchor(connectionController.startWrapper(), 0.0);
|
||||
AnchorPane.setRightAnchor(connectionController.startWrapper(), 0.0);
|
||||
AnchorPane.setTopAnchor(lobbyController.startWrapper(), 0.0);
|
||||
AnchorPane.setBottomAnchor(lobbyController.startWrapper(), 0.0);
|
||||
AnchorPane.setLeftAnchor(lobbyController.startWrapper(), 0.0);
|
||||
AnchorPane.setRightAnchor(lobbyController.startWrapper(), 0.0);
|
||||
|
||||
AnchorPane.setTopAnchor(hostController.startWrapper(), 0.0);
|
||||
AnchorPane.setBottomAnchor(hostController.startWrapper(), 0.0);
|
||||
AnchorPane.setLeftAnchor(hostController.startWrapper(), 0.0);
|
||||
AnchorPane.setRightAnchor(hostController.startWrapper(), 0.0);
|
||||
|
||||
AnchorPane.setTopAnchor(finishController.finishWrapper, 0.0);
|
||||
AnchorPane.setBottomAnchor(finishController.finishWrapper, 0.0);
|
||||
|
||||
@@ -4,7 +4,9 @@ package visualiser.Controllers;
|
||||
import javafx.animation.AnimationTimer;
|
||||
import javafx.application.Platform;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.collections.transformation.SortedList;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.chart.LineChart;
|
||||
import javafx.scene.control.*;
|
||||
@@ -17,35 +19,38 @@ import javafx.scene.layout.StackPane;
|
||||
import javafx.util.Callback;
|
||||
import network.Messages.Enums.RaceStatusEnum;
|
||||
import shared.model.Leg;
|
||||
import visualiser.app.VisualiserInput;
|
||||
import visualiser.gameController.ControllerClient;
|
||||
import visualiser.gameController.Keys.ControlKey;
|
||||
import visualiser.gameController.Keys.KeyFactory;
|
||||
import visualiser.model.*;
|
||||
import visualiser.network.ServerConnection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.ResourceBundle;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Controller used to display a running race.
|
||||
*/
|
||||
public class RaceController extends Controller {
|
||||
|
||||
/**
|
||||
* The object used to read packets from the connected server.
|
||||
*/
|
||||
private VisualiserInput visualiserInput;
|
||||
|
||||
/**
|
||||
* The race object which describes the currently occurring race.
|
||||
*/
|
||||
private VisualiserRace visualiserRace;
|
||||
private VisualiserRaceEvent visualiserRace;
|
||||
|
||||
|
||||
/**
|
||||
* An additional observable list of boats. This is used by the table view, to allow it to sort boats without effecting the race's own list of boats.
|
||||
* Service for sending keystrokes to server
|
||||
*/
|
||||
private ObservableList<VisualiserBoat> tableBoatList;
|
||||
private ControllerClient controllerClient;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The canvas that draws the race.
|
||||
@@ -62,10 +67,6 @@ public class RaceController extends Controller {
|
||||
*/
|
||||
@FXML private ArrowController arrowController;
|
||||
|
||||
/**
|
||||
* Service for sending keystrokes to server
|
||||
*/
|
||||
private ControllerClient controllerClient;
|
||||
|
||||
|
||||
@FXML private GridPane canvasBase;
|
||||
@@ -115,8 +116,9 @@ public class RaceController extends Controller {
|
||||
controllerClient.sendKey(controlKey);
|
||||
controlKey.onAction(); // Change key state if applicable
|
||||
event.consume();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Logger.getGlobal().log(Level.WARNING, "RaceController was interrupted on thread: " + Thread.currentThread() + "while sending: " + controlKey, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -159,7 +161,7 @@ public class RaceController extends Controller {
|
||||
* Initialises the frame rate functionality. This allows for toggling the frame rate, and connect the fps label to the race's fps property.
|
||||
* @param visualiserRace The race to connect the fps label to.
|
||||
*/
|
||||
private void initialiseFps(VisualiserRace visualiserRace) {
|
||||
private void initialiseFps(VisualiserRaceEvent visualiserRace) {
|
||||
|
||||
//On/off toggle.
|
||||
initialiseFpsToggle();
|
||||
@@ -189,9 +191,9 @@ public class RaceController extends Controller {
|
||||
* Initialises the fps label to update when the race fps changes.
|
||||
* @param visualiserRace The race to monitor the frame rate of.
|
||||
*/
|
||||
private void initialiseFpsLabel(VisualiserRace visualiserRace) {
|
||||
private void initialiseFpsLabel(VisualiserRaceEvent visualiserRace) {
|
||||
|
||||
visualiserRace.fpsProperty().addListener((observable, oldValue, newValue) -> {
|
||||
visualiserRace.getFrameRateProperty().addListener((observable, oldValue, newValue) -> {
|
||||
Platform.runLater(() -> this.FPS.setText("FPS: " + newValue.toString()));
|
||||
});
|
||||
|
||||
@@ -203,14 +205,21 @@ public class RaceController extends Controller {
|
||||
* Initialises the information table view to listen to a given race.
|
||||
* @param race Race to listen to.
|
||||
*/
|
||||
public void initialiseInfoTable(VisualiserRace race) {
|
||||
public void initialiseInfoTable(VisualiserRaceEvent race) {
|
||||
|
||||
//Copy list of boats.
|
||||
this.tableBoatList = FXCollections.observableArrayList(race.getBoats());
|
||||
ObservableList<VisualiserBoat> boats = FXCollections.observableArrayList(race.getVisualiserRaceState().getBoats());
|
||||
SortedList<VisualiserBoat> sortedBoats = new SortedList<>(boats);
|
||||
sortedBoats.comparatorProperty().bind(boatInfoTable.comparatorProperty());
|
||||
|
||||
//Update copy when original changes.
|
||||
race.getVisualiserRaceState().getBoats().addListener((ListChangeListener.Change<? extends VisualiserBoat> c) -> Platform.runLater(() -> {
|
||||
boats.setAll(race.getVisualiserRaceState().getBoats());
|
||||
}));
|
||||
|
||||
|
||||
//Set up table.
|
||||
boatInfoTable.setItems(this.tableBoatList);
|
||||
boatInfoTable.setItems(sortedBoats);
|
||||
|
||||
|
||||
//Set up each column.
|
||||
@@ -290,12 +299,12 @@ public class RaceController extends Controller {
|
||||
|
||||
|
||||
/**
|
||||
* Initialises the {@link Sparkline}, and listens to a specified {@link VisualiserRace}.
|
||||
* Initialises the {@link Sparkline}, and listens to a specified {@link VisualiserRaceEvent}.
|
||||
* @param race The race to listen to.
|
||||
*/
|
||||
private void initialiseSparkline(VisualiserRace race) {
|
||||
private void initialiseSparkline(VisualiserRaceEvent race) {
|
||||
//The race.getBoats() we are passing in is sorted by position in race inside the race class.
|
||||
this.sparkline = new Sparkline(this.visualiserRace, this.sparklineChart);
|
||||
this.sparkline = new Sparkline(this.visualiserRace.getVisualiserRaceState(), this.sparklineChart);
|
||||
}
|
||||
|
||||
|
||||
@@ -303,7 +312,7 @@ public class RaceController extends Controller {
|
||||
* Initialises the {@link ResizableRaceCanvas}, provides the race to read data from.
|
||||
* @param race Race to read data from.
|
||||
*/
|
||||
private void initialiseRaceCanvas(VisualiserRace race) {
|
||||
private void initialiseRaceCanvas(VisualiserRaceEvent race) {
|
||||
|
||||
//Create canvas.
|
||||
raceCanvas = new ResizableRaceCanvas(race);
|
||||
@@ -326,18 +335,18 @@ public class RaceController extends Controller {
|
||||
* Intialises the race time zone label with the race's time zone.
|
||||
* @param race The race to get time zone from.
|
||||
*/
|
||||
private void initialiseRaceTimezoneLabel(VisualiserRace race) {
|
||||
timeZone.setText(race.getRaceClock().getTimeZone());
|
||||
private void initialiseRaceTimezoneLabel(VisualiserRaceEvent race) {
|
||||
timeZone.setText(race.getVisualiserRaceState().getRaceClock().getTimeZone());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialises the race clock to listen to the specified race.
|
||||
* @param race The race to listen to.
|
||||
*/
|
||||
private void initialiseRaceClock(VisualiserRace race) {
|
||||
private void initialiseRaceClock(VisualiserRaceEvent race) {
|
||||
|
||||
//RaceClock.duration isn't necessarily being changed in the javaFX thread, so we need to runlater the update.
|
||||
race.getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
|
||||
race.getVisualiserRaceState().getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
|
||||
Platform.runLater(() -> {
|
||||
timer.setText(newValue);
|
||||
});
|
||||
@@ -348,13 +357,11 @@ public class RaceController extends Controller {
|
||||
|
||||
/**
|
||||
* Displays a specified race.
|
||||
* @param visualiserInput Object used to read packets from server.
|
||||
* @param visualiserRace Object modelling the race.
|
||||
* @param controllerClient Socket Client that manipulates the controller.
|
||||
*/
|
||||
public void startRace(VisualiserInput visualiserInput, VisualiserRace visualiserRace, ControllerClient controllerClient) {
|
||||
public void startRace(VisualiserRaceEvent visualiserRace, ControllerClient controllerClient) {
|
||||
|
||||
this.visualiserInput = visualiserInput;
|
||||
this.visualiserRace = visualiserRace;
|
||||
this.controllerClient = controllerClient;
|
||||
|
||||
@@ -372,7 +379,7 @@ public class RaceController extends Controller {
|
||||
* Transition from the race view to the finish view.
|
||||
* @param boats boats there are in the race.
|
||||
*/
|
||||
public void finishRace(ObservableList<VisualiserBoat> boats){
|
||||
public void finishRace(ObservableList<VisualiserBoat> boats) {
|
||||
race.setVisible(false);
|
||||
parent.enterFinish(boats);
|
||||
}
|
||||
@@ -382,8 +389,8 @@ public class RaceController extends Controller {
|
||||
* Initialises the arrow controller with data from the race to observe.
|
||||
* @param race The race to observe.
|
||||
*/
|
||||
private void initialiseArrow(VisualiserRace race) {
|
||||
arrowController.setWindProperty(race.windProperty());
|
||||
private void initialiseArrow(VisualiserRaceEvent race) {
|
||||
arrowController.setWindProperty(race.getVisualiserRaceState().windProperty());
|
||||
}
|
||||
|
||||
|
||||
@@ -396,7 +403,7 @@ public class RaceController extends Controller {
|
||||
public void handle(long arg0) {
|
||||
|
||||
//Get the current race status.
|
||||
RaceStatusEnum raceStatus = visualiserRace.getRaceStatusEnum();
|
||||
RaceStatusEnum raceStatus = visualiserRace.getVisualiserRaceState().getRaceStatusEnum();
|
||||
|
||||
|
||||
//If the race has finished, go to finish view.
|
||||
@@ -405,7 +412,7 @@ public class RaceController extends Controller {
|
||||
stop();
|
||||
|
||||
//Hide this, and display the finish controller.
|
||||
finishRace(visualiserRace.getBoats());
|
||||
finishRace(visualiserRace.getVisualiserRaceState().getBoats());
|
||||
|
||||
} else {
|
||||
//Otherwise, render the canvas.
|
||||
@@ -417,6 +424,15 @@ public class RaceController extends Controller {
|
||||
|
||||
}
|
||||
|
||||
//Return to main screen if we lose connection.
|
||||
if (!visualiserRace.getServerConnection().isAlive()) {
|
||||
race.setVisible(false);
|
||||
parent.enterTitle();
|
||||
//TODO currently this doesn't work correctly - the title screen remains visible after clicking join game
|
||||
//TODO we should display an error to the user
|
||||
//TODO also need to "reset" any state (race, connections, etc...).
|
||||
}
|
||||
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
@@ -9,8 +9,9 @@ import javafx.scene.control.TableColumn;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.scene.layout.AnchorPane;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.paint.Color;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.Enums.RaceStatusEnum;
|
||||
import network.Messages.Enums.RequestToJoinEnum;
|
||||
import network.Messages.LatestMessages;
|
||||
import shared.dataInput.*;
|
||||
import shared.enums.XMLFileType;
|
||||
@@ -18,20 +19,24 @@ import shared.exceptions.InvalidBoatDataException;
|
||||
import shared.exceptions.InvalidRaceDataException;
|
||||
import shared.exceptions.InvalidRegattaDataException;
|
||||
import shared.exceptions.XMLReaderException;
|
||||
import visualiser.app.VisualiserInput;
|
||||
import visualiser.gameController.ControllerClient;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
import visualiser.network.ServerConnection;
|
||||
import visualiser.model.VisualiserBoat;
|
||||
import visualiser.model.VisualiserRace;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Controller to for waiting for the race to start.
|
||||
*/
|
||||
public class StartController extends Controller implements Observer {
|
||||
public class StartController extends Controller {
|
||||
|
||||
@FXML private GridPane start;
|
||||
@FXML private AnchorPane startWrapper;
|
||||
@@ -66,33 +71,21 @@ public class StartController extends Controller implements Observer {
|
||||
@FXML private Label raceStatusLabel;
|
||||
|
||||
|
||||
/**
|
||||
* The race + connection to server.
|
||||
*/
|
||||
private VisualiserRaceEvent visualiserRaceEvent;
|
||||
|
||||
|
||||
/**
|
||||
* The object used to read packets from the connected server.
|
||||
* Writes BoatActions to outgoing message queue.
|
||||
*/
|
||||
private VisualiserInput visualiserInput;
|
||||
|
||||
/**
|
||||
* The race object which describes the currently occurring race.
|
||||
*/
|
||||
private VisualiserRace visualiserRace;
|
||||
|
||||
private ControllerClient controllerClient;
|
||||
|
||||
/**
|
||||
* An array of colors used to assign colors to each boat - passed in to the VisualiserRace constructor.
|
||||
*/
|
||||
List<Color> colors = new ArrayList<>(Arrays.asList(
|
||||
Color.BLUEVIOLET,
|
||||
Color.BLACK,
|
||||
Color.RED,
|
||||
Color.ORANGE,
|
||||
Color.DARKOLIVEGREEN,
|
||||
Color.LIMEGREEN,
|
||||
Color.PURPLE,
|
||||
Color.DARKGRAY,
|
||||
Color.YELLOW
|
||||
));
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -109,33 +102,17 @@ public class StartController extends Controller implements Observer {
|
||||
|
||||
/**
|
||||
* Starts the race.
|
||||
* Called once we have received all XML files from the server.
|
||||
* @param latestMessages The set of latest race messages to use for race.
|
||||
* @throws XMLReaderException Thrown if XML file cannot be parsed.
|
||||
* @throws InvalidRaceDataException Thrown if XML file cannot be parsed.
|
||||
* @throws InvalidBoatDataException Thrown if XML file cannot be parsed.
|
||||
* @throws InvalidRegattaDataException Thrown if XML file cannot be parsed.
|
||||
*/
|
||||
private void startRace(LatestMessages latestMessages) throws XMLReaderException, InvalidRaceDataException, InvalidBoatDataException, InvalidRegattaDataException {
|
||||
|
||||
//Create data sources from latest messages for the race.
|
||||
RaceDataSource raceDataSource = new RaceXMLReader(latestMessages.getRaceXMLMessage().getXmlMessage(), XMLFileType.Contents);
|
||||
BoatDataSource boatDataSource = new BoatXMLReader(latestMessages.getBoatXMLMessage().getXmlMessage(), XMLFileType.Contents);
|
||||
RegattaDataSource regattaDataSource = new RegattaXMLReader(latestMessages.getRegattaXMLMessage().getXmlMessage(), XMLFileType.Contents);
|
||||
|
||||
//Create race.
|
||||
this.visualiserRace = new VisualiserRace(boatDataSource, raceDataSource, regattaDataSource, latestMessages, this.colors);
|
||||
new Thread(this.visualiserRace).start();
|
||||
|
||||
private void startRace() {
|
||||
|
||||
//Initialise the boat table.
|
||||
initialiseBoatTable(this.visualiserRace);
|
||||
initialiseBoatTable(this.visualiserRaceEvent.getVisualiserRaceState());
|
||||
|
||||
//Initialise the race name.
|
||||
initialiseRaceName(this.visualiserRace);
|
||||
initialiseRaceName(this.visualiserRaceEvent.getVisualiserRaceState());
|
||||
|
||||
//Initialises the race clock.
|
||||
initialiseRaceClock(this.visualiserRace);
|
||||
initialiseRaceClock(this.visualiserRaceEvent.getVisualiserRaceState());
|
||||
|
||||
//Starts the race countdown timer.
|
||||
countdownTimer();
|
||||
@@ -153,7 +130,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the boat table that is to be shown on the pane.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseBoatTable(VisualiserRace visualiserRace) {
|
||||
private void initialiseBoatTable(VisualiserRaceState visualiserRace) {
|
||||
|
||||
//Get the boats.
|
||||
ObservableList<VisualiserBoat> boats = visualiserRace.getBoats();
|
||||
@@ -168,7 +145,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the race name which is shown on the pane.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseRaceName(VisualiserRace visualiserRace) {
|
||||
private void initialiseRaceName(VisualiserRaceState visualiserRace) {
|
||||
|
||||
raceTitleLabel.setText(visualiserRace.getRegattaName());
|
||||
|
||||
@@ -178,7 +155,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the race clock/timer labels for the start time, current time, and remaining time.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseRaceClock(VisualiserRace visualiserRace) {
|
||||
private void initialiseRaceClock(VisualiserRaceState visualiserRace) {
|
||||
|
||||
//Start time.
|
||||
initialiseRaceClockStartTime(visualiserRace);
|
||||
@@ -196,7 +173,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the race current time label.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseRaceClockStartTime(VisualiserRace visualiserRace) {
|
||||
private void initialiseRaceClockStartTime(VisualiserRaceState visualiserRace) {
|
||||
|
||||
raceStartLabel.setText(visualiserRace.getRaceClock().getStartingTimeString());
|
||||
|
||||
@@ -213,7 +190,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the race current time label.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseRaceClockCurrentTime(VisualiserRace visualiserRace) {
|
||||
private void initialiseRaceClockCurrentTime(VisualiserRaceState visualiserRace) {
|
||||
|
||||
visualiserRace.getRaceClock().currentTimeProperty().addListener((observable, oldValue, newValue) -> {
|
||||
Platform.runLater(() -> {
|
||||
@@ -227,7 +204,7 @@ public class StartController extends Controller implements Observer {
|
||||
* Initialises the race duration label.
|
||||
* @param visualiserRace The race to get data from.
|
||||
*/
|
||||
private void initialiseRaceClockDuration(VisualiserRace visualiserRace) {
|
||||
private void initialiseRaceClockDuration(VisualiserRaceState visualiserRace) {
|
||||
|
||||
visualiserRace.getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
|
||||
Platform.runLater(() -> {
|
||||
@@ -245,13 +222,13 @@ public class StartController extends Controller implements Observer {
|
||||
@Override
|
||||
public void handle(long arg0) {
|
||||
|
||||
//TODO instead of having an AnimationTimer checking the race status, we could provide a Property<RaceStatusEnum>, and connect a listener to that.
|
||||
//Get the current race status.
|
||||
RaceStatusEnum raceStatus = visualiserRace.getRaceStatusEnum();
|
||||
RaceStatusEnum raceStatus = visualiserRaceEvent.getVisualiserRaceState().getRaceStatusEnum();
|
||||
|
||||
//Display it.
|
||||
raceStatusLabel.setText("Race Status: " + raceStatus.name());
|
||||
|
||||
|
||||
//If the race has reached the preparatory phase, or has started...
|
||||
if (raceStatus == RaceStatusEnum.PREPARATORY || raceStatus == RaceStatusEnum.STARTED) {
|
||||
//Stop this timer.
|
||||
@@ -259,9 +236,10 @@ public class StartController extends Controller implements Observer {
|
||||
|
||||
//Hide this, and display the race controller.
|
||||
startWrapper.setVisible(false);
|
||||
start.setVisible(false);
|
||||
//start.setVisible(false);//TODO is this needed?
|
||||
|
||||
parent.beginRace(visualiserRaceEvent, controllerClient);
|
||||
|
||||
parent.beginRace(visualiserInput, visualiserRace, controllerClient);
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
@@ -269,57 +247,25 @@ public class StartController extends Controller implements Observer {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Function to handle changes in objects we observe.
|
||||
* We observe LatestMessages.
|
||||
* @param o The observed object.
|
||||
* @param arg The {@link Observable#notifyObservers(Object)} parameter.
|
||||
*/
|
||||
@Override
|
||||
public void update(Observable o, Object arg) {
|
||||
|
||||
//Check that we actually have LatestMessages.
|
||||
if (o instanceof LatestMessages) {
|
||||
LatestMessages latestMessages = (LatestMessages) o;
|
||||
|
||||
//If we've received all of the xml files, start the race. Only start it if it hasn't already been created.
|
||||
if (latestMessages.hasAllXMLMessages() && this.visualiserRace == null) {
|
||||
|
||||
//Need to handle it in the javafx thread.
|
||||
Platform.runLater(() -> {
|
||||
try {
|
||||
this.startRace(latestMessages);
|
||||
|
||||
} catch (XMLReaderException | InvalidBoatDataException | InvalidRaceDataException | InvalidRegattaDataException e) {
|
||||
//We currently don't handle this in meaningful way, as it should never occur.
|
||||
//If we reach this point it means that malformed XML files were sent.
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Show starting information for a race given a socket.
|
||||
* @param socket network source of information
|
||||
*/
|
||||
public void enterLobby(Socket socket) {
|
||||
startWrapper.setVisible(true);
|
||||
try {
|
||||
//Begin reading packets from the socket/server.
|
||||
this.visualiserInput = new VisualiserInput(socket);
|
||||
//Send controller input to server
|
||||
this.controllerClient = new ControllerClient(socket);
|
||||
//Store a reference to latestMessages so that we can observe it.
|
||||
LatestMessages latestMessages = this.visualiserInput.getLatestMessages();
|
||||
latestMessages.addObserver(this);
|
||||
new Thread(this.visualiserInput).start();
|
||||
|
||||
this.visualiserRaceEvent = new VisualiserRaceEvent(socket, RequestToJoinEnum.PARTICIPANT);
|
||||
|
||||
this.controllerClient = visualiserRaceEvent.getControllerClient();
|
||||
|
||||
|
||||
startWrapper.setVisible(true);
|
||||
|
||||
startRace();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
//TODO should probably let this propagate, so that we only enter this scene if everything works
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not connect to server.", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,363 +0,0 @@
|
||||
package visualiser.app;
|
||||
import network.BinaryMessageDecoder;
|
||||
import network.Exceptions.InvalidMessageException;
|
||||
import network.Messages.*;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static network.Utils.ByteConverter.bytesToShort;
|
||||
|
||||
/**
|
||||
* TCP client which receives packets/messages from a race data source
|
||||
* (e.g., mock source, official source), and exposes them to any observers.
|
||||
*/
|
||||
public class VisualiserInput implements Runnable {
|
||||
|
||||
/**
|
||||
* Timestamp of the last heartbeat.
|
||||
*/
|
||||
private long lastHeartbeatTime = -1;
|
||||
/**
|
||||
* Sequence number of the last heartbeat.
|
||||
*/
|
||||
private long lastHeartbeatSequenceNum = -1;
|
||||
|
||||
|
||||
/**
|
||||
* The socket that we have connected to.
|
||||
*/
|
||||
private Socket connectionSocket;
|
||||
|
||||
|
||||
/**
|
||||
* InputStream (from the socket).
|
||||
*/
|
||||
private DataInputStream inStream;
|
||||
|
||||
|
||||
/**
|
||||
* An object containing the set of latest messages to write to.
|
||||
* Every server frame, VisualiserInput reads messages from its inputStream, and write them to this.
|
||||
*/
|
||||
private LatestMessages latestMessages;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Ctor.
|
||||
* @param socket Socket from which we will receive race data.
|
||||
* @throws IOException If there is something wrong with the socket's input stream.
|
||||
*/
|
||||
public VisualiserInput(Socket socket) throws IOException {
|
||||
|
||||
this.connectionSocket = socket;
|
||||
|
||||
//We wrap a DataInputStream around the socket's InputStream because it has the stream.readFully(buffer) function, which is a blocking read until the buffer has been filled.
|
||||
this.inStream = new DataInputStream(connectionSocket.getInputStream());
|
||||
|
||||
this.latestMessages = new LatestMessages();
|
||||
|
||||
|
||||
this.lastHeartbeatTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the LatestMessages object, which can be queried for any received race related messages.
|
||||
* @return The LatestMessages object.
|
||||
*/
|
||||
public LatestMessages getLatestMessages() {
|
||||
return latestMessages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the time since last heartbeat, in milliseconds.
|
||||
* @return Time since last heartbeat, in milliseconds..
|
||||
*/
|
||||
private double timeSinceHeartbeat() {
|
||||
long now = System.currentTimeMillis();
|
||||
return (now - lastHeartbeatTime);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reads and returns the next message as an array of bytes from the socket. Use getNextMessage() to get the actual message object instead.
|
||||
* @return Encoded binary message bytes.
|
||||
* @throws IOException Thrown when an error occurs while reading from the socket.
|
||||
*/
|
||||
private byte[] getNextMessageBytes() throws IOException {
|
||||
inStream.mark(0);
|
||||
short CRCLength = 4;
|
||||
short headerLength = 15;
|
||||
|
||||
//Read the header of the next message.
|
||||
byte[] headerBytes = new byte[headerLength];
|
||||
inStream.readFully(headerBytes);
|
||||
|
||||
//Read the message body length.
|
||||
byte[] messageBodyLengthBytes = Arrays.copyOfRange(headerBytes, headerLength - 2, headerLength);
|
||||
short messageBodyLength = bytesToShort(messageBodyLengthBytes);
|
||||
|
||||
//Read the message body.
|
||||
byte[] messageBodyBytes = new byte[messageBodyLength];
|
||||
inStream.readFully(messageBodyBytes);
|
||||
|
||||
//Read the message CRC.
|
||||
byte[] messageCRCBytes = new byte[CRCLength];
|
||||
inStream.readFully(messageCRCBytes);
|
||||
|
||||
//Put the head + body + crc into one large array.
|
||||
ByteBuffer messageBytes = ByteBuffer.allocate(headerBytes.length + messageBodyBytes.length + messageCRCBytes.length);
|
||||
messageBytes.put(headerBytes);
|
||||
messageBytes.put(messageBodyBytes);
|
||||
messageBytes.put(messageCRCBytes);
|
||||
|
||||
return messageBytes.array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and returns the next message object from the socket.
|
||||
* @return The message object. Use instanceof for concrete type.
|
||||
* @throws IOException Thrown when an error occurs while reading from the socket.
|
||||
* @throws InvalidMessageException Thrown when the message is invalid in some way.
|
||||
*/
|
||||
private AC35Data getNextMessage() throws IOException, InvalidMessageException
|
||||
{
|
||||
//Get the next message from the socket as a block of bytes.
|
||||
byte[] messageBytes = this.getNextMessageBytes();
|
||||
|
||||
//Decode the binary message into an appropriate message object.
|
||||
BinaryMessageDecoder decoder = new BinaryMessageDecoder(messageBytes);
|
||||
|
||||
return decoder.decode();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Main loop which reads messages from the socket, and exposes them.
|
||||
*/
|
||||
public void run(){
|
||||
boolean receiverLoop = true;
|
||||
//receiver loop that gets the input
|
||||
while (receiverLoop) {
|
||||
|
||||
//If no heartbeat has been received in more the heartbeat period
|
||||
//then the connection will need to be restarted.
|
||||
//System.out.println("time since last heartbeat: " + timeSinceHeartbeat());//TEMP REMOVE
|
||||
long heartBeatPeriod = 10 * 1000;
|
||||
if (timeSinceHeartbeat() > heartBeatPeriod) {
|
||||
System.out.println("Connection has stopped, trying to reconnect.");
|
||||
|
||||
//Attempt to reconnect the socket.
|
||||
try {//This attempt doesn't really work. Under what circumstances would
|
||||
this.connectionSocket = new Socket(this.connectionSocket.getInetAddress(), this.connectionSocket.getPort());
|
||||
//this.connectionSocket.connect(this.connectionSocket.getRemoteSocketAddress());
|
||||
//Reset the heartbeat timer.
|
||||
this.lastHeartbeatTime = System.currentTimeMillis();
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.println("Unable to reconnect.");
|
||||
|
||||
//Wait 500ms. Ugly hack, should refactor.
|
||||
long waitPeriod = 500;
|
||||
long waitTimeStart = System.currentTimeMillis() + waitPeriod;
|
||||
|
||||
while (System.currentTimeMillis() < waitTimeStart){
|
||||
//Nothing. Busyloop.
|
||||
}
|
||||
|
||||
//Swallow the exception.
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Reads the next message.
|
||||
AC35Data message;
|
||||
try {
|
||||
message = this.getNextMessage();
|
||||
}
|
||||
catch (InvalidMessageException | IOException e) {
|
||||
//Prints exception to stderr, and iterate loop (that is, read the next message).
|
||||
System.err.println("Unable to read message: " + e.getMessage());
|
||||
try {
|
||||
inStream.reset();
|
||||
} catch (IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
//Continue to the next loop iteration/message.
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
//Checks which message is being received and does what is needed for that message.
|
||||
switch (message.getType()) {
|
||||
|
||||
//Heartbeat.
|
||||
case HEARTBEAT: {
|
||||
HeartBeat heartBeat = (HeartBeat) message;
|
||||
|
||||
//Check that the heartbeat number is greater than the previous value, and then set the last heartbeat time.
|
||||
if (heartBeat.getSequenceNumber() > this.lastHeartbeatSequenceNum) {
|
||||
lastHeartbeatTime = System.currentTimeMillis();
|
||||
lastHeartbeatSequenceNum = heartBeat.getSequenceNumber();
|
||||
//System.out.println("HeartBeat Message! " + lastHeartbeatSequenceNum);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//RaceStatus.
|
||||
case RACESTATUS: {
|
||||
RaceStatus raceStatus = (RaceStatus) message;
|
||||
|
||||
//System.out.println("Race Status Message");
|
||||
this.latestMessages.setRaceStatus(raceStatus);
|
||||
|
||||
for (BoatStatus boatStatus : raceStatus.getBoatStatuses()) {
|
||||
this.latestMessages.setBoatStatus(boatStatus);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//DisplayTextMessage.
|
||||
case DISPLAYTEXTMESSAGE: {
|
||||
//System.out.println("Display Text Message");
|
||||
//No decoder for this.
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//XMLMessage.
|
||||
case XMLMESSAGE: {
|
||||
XMLMessage xmlMessage = (XMLMessage) message;
|
||||
|
||||
//System.out.println("XML Message!");
|
||||
|
||||
this.latestMessages.setXMLMessage(xmlMessage);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//RaceStartStatus.
|
||||
case RACESTARTSTATUS: {
|
||||
|
||||
//System.out.println("Race Start Status Message");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//YachtEventCode.
|
||||
case YACHTEVENTCODE: {
|
||||
//YachtEventCode yachtEventCode = (YachtEventCode) message;
|
||||
|
||||
//System.out.println("Yacht Event Code!");
|
||||
//No decoder for this.
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//YachtActionCode.
|
||||
case YACHTACTIONCODE: {
|
||||
//YachtActionCode yachtActionCode = (YachtActionCode) message;
|
||||
|
||||
//System.out.println("Yacht Action Code!");
|
||||
// No decoder for this.
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//ChatterText.
|
||||
case CHATTERTEXT: {
|
||||
//ChatterText chatterText = (ChatterText) message;
|
||||
|
||||
//System.out.println("Chatter Text Message!");
|
||||
//No decoder for this.
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//BoatLocation.
|
||||
case BOATLOCATION: {
|
||||
BoatLocation boatLocation = (BoatLocation) message;
|
||||
|
||||
//System.out.println("Boat Location!");
|
||||
|
||||
BoatLocation existingBoatLocation = this.latestMessages.getBoatLocationMap().get(boatLocation.getSourceID());
|
||||
if (existingBoatLocation != null) {
|
||||
//If our boatlocation map already contains a boat location message for this boat, check that the new message is actually for a later timestamp (i.e., newer).
|
||||
if (boatLocation.getTime() > existingBoatLocation.getTime()) {
|
||||
//If it is, replace the old message.
|
||||
this.latestMessages.setBoatLocation(boatLocation);
|
||||
}
|
||||
} else {
|
||||
//If the map _doesn't_ already contain a message for this boat, insert the message.
|
||||
this.latestMessages.setBoatLocation(boatLocation);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//MarkRounding.
|
||||
case MARKROUNDING: {
|
||||
MarkRounding markRounding = (MarkRounding) message;
|
||||
|
||||
//System.out.println("Mark Rounding Message!");
|
||||
|
||||
MarkRounding existingMarkRounding = this.latestMessages.getMarkRoundingMap().get(markRounding.getSourceID());
|
||||
if (existingMarkRounding != null) {
|
||||
|
||||
//If our markRoundingMap already contains a mark rounding message for this boat, check that the new message is actually for a later timestamp (i.e., newer).
|
||||
if (markRounding.getTime() > existingMarkRounding.getTime()) {
|
||||
//If it is, replace the old message.
|
||||
this.latestMessages.setMarkRounding(markRounding);
|
||||
}
|
||||
|
||||
} else {
|
||||
//If the map _doesn't_ already contain a message for this boat, insert the message.
|
||||
this.latestMessages.setMarkRounding(markRounding);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//CourseWinds.
|
||||
case COURSEWIND: {
|
||||
|
||||
//System.out.println("Course Wind Message!");
|
||||
CourseWinds courseWinds = (CourseWinds) message;
|
||||
|
||||
this.latestMessages.setCourseWinds(courseWinds);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//AverageWind.
|
||||
case AVGWIND: {
|
||||
|
||||
//System.out.println("Average Wind Message!");
|
||||
AverageWind averageWind = (AverageWind) message;
|
||||
|
||||
this.latestMessages.setAverageWind(averageWind);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
//Unrecognised message.
|
||||
default: {
|
||||
System.out.println("Broken Message!");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package visualiser.enums;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The states in which a connection from a client to a server may have.
|
||||
*/
|
||||
public enum ConnectionToServerState {
|
||||
|
||||
UNKNOWN(0),
|
||||
|
||||
/**
|
||||
* We're waiting for the server to complete the joining handshake.
|
||||
* See {@link network.Messages.RequestToJoin} and {@link network.Messages.JoinAcceptance}.
|
||||
*/
|
||||
REQUEST_SENT(1),
|
||||
|
||||
/**
|
||||
* The client has receved a {@link network.Messages.JoinAcceptance} from the server.
|
||||
*/
|
||||
RESPONSE_RECEIVED(2),
|
||||
|
||||
/**
|
||||
* The server has completed the handshake, and is connected.
|
||||
* That is, the client sent a {@link network.Messages.RequestToJoin}, which was successful, and the server responded with a {@link network.Messages.JoinAcceptance}.
|
||||
*/
|
||||
CONNECTED(3),
|
||||
|
||||
/**
|
||||
* The server has timed out, or the connection has been interrupted.
|
||||
*/
|
||||
TIMED_OUT(4),
|
||||
|
||||
/**
|
||||
* The client's connection has been declined.
|
||||
*/
|
||||
DECLINED(5);
|
||||
|
||||
|
||||
|
||||
|
||||
private byte value;
|
||||
|
||||
/**
|
||||
* Ctor. Creates a ConnectionToServerState from a given primitive integer value, cast to a byte.
|
||||
* @param value Integer, which is cast to byte, to construct from.
|
||||
*/
|
||||
private ConnectionToServerState(int value) {
|
||||
this.value = (byte) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the primitive value of the enum.
|
||||
* @return Primitive value of the enum.
|
||||
*/
|
||||
public byte getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Stores a mapping between Byte values and ConnectionToServerState values.
|
||||
*/
|
||||
private static final Map<Byte, ConnectionToServerState> byteToStateMap = new HashMap<>();
|
||||
|
||||
|
||||
/*
|
||||
Static initialization block. Initializes the byteToStateMap.
|
||||
*/
|
||||
static {
|
||||
for (ConnectionToServerState type : ConnectionToServerState.values()) {
|
||||
ConnectionToServerState.byteToStateMap.put(type.value, type);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the enumeration value which corresponds to a given byte value.
|
||||
* @param connectionState Byte value to convert to a ConnectionToServerState value.
|
||||
* @return The ConnectionToServerState value which corresponds to the given byte value.
|
||||
*/
|
||||
public static ConnectionToServerState fromByte(byte connectionState) {
|
||||
//Gets the corresponding ConnectionToServerState from the map.
|
||||
ConnectionToServerState type = ConnectionToServerState.byteToStateMap.get(connectionState);
|
||||
|
||||
if (type == null) {
|
||||
//If the byte value wasn't found, return the UNKNOWN ConnectionToServerState.
|
||||
return ConnectionToServerState.UNKNOWN;
|
||||
} else {
|
||||
//Otherwise, return the ConnectionToServerState.
|
||||
return type;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package visualiser.gameController;
|
||||
import network.BinaryMessageEncoder;
|
||||
import network.Exceptions.InvalidMessageException;
|
||||
import network.MessageEncoders.RaceVisionByteEncoder;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.BoatAction;
|
||||
import network.Messages.Enums.BoatActionEnum;
|
||||
import network.Messages.Enums.MessageType;
|
||||
@@ -11,6 +12,9 @@ import visualiser.gameController.Keys.ControlKey;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -18,56 +22,32 @@ import java.util.logging.Logger;
|
||||
* Basic service for sending key presses to game server
|
||||
*/
|
||||
public class ControllerClient {
|
||||
/**
|
||||
* Socket to server
|
||||
*/
|
||||
Socket socket;
|
||||
|
||||
/**
|
||||
* Output stream wrapper for socket to server
|
||||
* Queue of messages to be sent to server.
|
||||
*/
|
||||
DataOutputStream outputStream;
|
||||
private BlockingQueue<AC35Data> outgoingMessages;
|
||||
|
||||
/**
|
||||
* Initialise controller client with live socket.
|
||||
* @param socket to server
|
||||
* @param outgoingMessages Queue to place messages on to send to server.
|
||||
*/
|
||||
public ControllerClient(Socket socket) {
|
||||
this.socket = socket;
|
||||
|
||||
try {
|
||||
this.outputStream = new DataOutputStream(socket.getOutputStream());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
public ControllerClient(BlockingQueue<AC35Data> outgoingMessages) {
|
||||
this.outgoingMessages = outgoingMessages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a keypress to server
|
||||
* @param key to send
|
||||
* @throws IOException if socket write fails
|
||||
* @throws InterruptedException If thread is interrupted while writing message to outgoing message queue.
|
||||
*/
|
||||
public void sendKey(ControlKey key) throws IOException {
|
||||
public void sendKey(ControlKey key) throws InterruptedException {
|
||||
BoatActionEnum protocolCode = key.getProtocolCode();
|
||||
if(protocolCode != BoatActionEnum.NOT_A_STATUS) {
|
||||
|
||||
BoatAction boatAction = new BoatAction(protocolCode);
|
||||
|
||||
//Encode BoatAction.
|
||||
try {
|
||||
byte[] encodedBoatAction = RaceVisionByteEncoder.encode(boatAction);
|
||||
|
||||
BinaryMessageEncoder binaryMessage = new BinaryMessageEncoder(MessageType.BOATACTION, System.currentTimeMillis(), 0,
|
||||
(short) encodedBoatAction.length, encodedBoatAction);
|
||||
|
||||
// System.out.println("Sending out key: " + protocolCode);
|
||||
outputStream.write(binaryMessage.getFullMessage());
|
||||
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not encode BoatAction: " + boatAction, e);
|
||||
|
||||
}
|
||||
|
||||
outgoingMessages.put(boatAction);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,88 +1,102 @@
|
||||
package visualiser.gameController;
|
||||
|
||||
import mock.model.RaceLogic;
|
||||
import network.BinaryMessageDecoder;
|
||||
import network.Exceptions.InvalidMessageException;
|
||||
import network.MessageDecoders.BoatActionDecoder;
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.MockRace;
|
||||
import mock.model.commandFactory.Command;
|
||||
import mock.model.commandFactory.CommandFactory;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.BoatAction;
|
||||
import network.Messages.Enums.BoatActionEnum;
|
||||
import network.Messages.Enums.MessageType;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.util.Observable;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Service for dispatching key press data to race from client
|
||||
*/
|
||||
public class ControllerServer extends Observable implements Runnable {
|
||||
/**
|
||||
* Socket to client
|
||||
*/
|
||||
private Socket socket;
|
||||
/**
|
||||
* Wrapper for input from client
|
||||
*/
|
||||
private DataInputStream inputStream;
|
||||
/**
|
||||
* Last received boat action
|
||||
*/
|
||||
private BoatActionEnum action;
|
||||
public class ControllerServer implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* Initialise server-side controller with live client socket
|
||||
* @param socket to client
|
||||
* @param race logic loop observing controls
|
||||
* Queue of incoming messages from client.
|
||||
*/
|
||||
public ControllerServer(Socket socket, RaceLogic race) {
|
||||
this.socket = socket;
|
||||
this.addObserver(race);
|
||||
try {
|
||||
this.inputStream = new DataInputStream(this.socket.getInputStream());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
private BlockingQueue<AC35Data> inputQueue;
|
||||
|
||||
|
||||
/**
|
||||
* Collection of commands from client for race to execute.
|
||||
*/
|
||||
private CompositeCommand compositeCommand;
|
||||
|
||||
/**
|
||||
* The context for each command.
|
||||
*/
|
||||
private MockRace raceState;
|
||||
|
||||
/**
|
||||
* This is the source ID associated with the client.
|
||||
*/
|
||||
private int clientSourceID;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Initialise server-side controller with live client socket.
|
||||
* @param compositeCommand Commands for the race to execute.
|
||||
* @param inputQueue The queue of messages to read from.
|
||||
* @param clientSourceID The source ID of the client's boat.
|
||||
* @param raceState The context for each command.
|
||||
*/
|
||||
public ControllerServer(CompositeCommand compositeCommand, BlockingQueue<AC35Data> inputQueue, int clientSourceID, MockRace raceState) {
|
||||
this.compositeCommand = compositeCommand;
|
||||
this.inputQueue = inputQueue;
|
||||
this.clientSourceID = clientSourceID;
|
||||
this.raceState = raceState;
|
||||
}
|
||||
|
||||
public BoatActionEnum getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Wait for controller key input from client and loop.
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
byte[] message = new byte[20];
|
||||
while(!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
if (inputStream.available() > 0) {
|
||||
|
||||
inputStream.read(message);
|
||||
AC35Data message = inputQueue.take();
|
||||
|
||||
BinaryMessageDecoder encodedMessage = new BinaryMessageDecoder(message);
|
||||
BoatActionDecoder boatActionDecoder = new BoatActionDecoder();
|
||||
if (message.getType() == MessageType.BOATACTION) {
|
||||
|
||||
BoatAction boatAction = (BoatAction) message;
|
||||
|
||||
|
||||
boatAction.setSourceID(clientSourceID);
|
||||
|
||||
try {
|
||||
boatActionDecoder.decode(encodedMessage.getMessageBody());
|
||||
BoatAction boatAction = boatActionDecoder.getMessage();
|
||||
action = boatAction.getBoatAction();
|
||||
Command command = CommandFactory.createCommand(raceState, boatAction);
|
||||
compositeCommand.addCommand(command);
|
||||
|
||||
// Notify observers of most recent action
|
||||
this.notifyObservers();
|
||||
this.setChanged();
|
||||
} catch (CommandConstructionException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "ControllerServer could not create a Command for BoatAction: " + boatAction + ".", e);
|
||||
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not decode BoatAction message.", e);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "ControllerServer Interrupted while waiting for message on incoming message queue.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,16 +22,14 @@ public class Ping implements Runnable {
|
||||
this.rc = rc;
|
||||
}
|
||||
|
||||
public boolean pingPort(){
|
||||
//TODO the connection needs to be moved to its own thread, so it doesn't block fx thread.
|
||||
public boolean pingPort() {
|
||||
InetSocketAddress i = new InetSocketAddress(hostname, port);
|
||||
try (Socket s = new Socket()){
|
||||
s.connect(i, 750);//TODO this should be at least a second or two, once moved to its own thread
|
||||
s.connect(i, 1500);
|
||||
s.shutdownInput();
|
||||
s.shutdownOutput();
|
||||
s.close();
|
||||
rc.statusProperty().set("Ready");
|
||||
//System.out.println(String.valueOf(s.isClosed()));
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
rc.statusProperty().set("Offline");
|
||||
|
||||
@@ -11,22 +11,22 @@ public class RaceMap {
|
||||
/**
|
||||
* The longitude of the left side of the map.
|
||||
*/
|
||||
private final double longLeft;
|
||||
private double longLeft;
|
||||
|
||||
/**
|
||||
* The longitude of the right side of the map.
|
||||
*/
|
||||
private final double longRight;
|
||||
private double longRight;
|
||||
|
||||
/**
|
||||
* The latitude of the top side of the map.
|
||||
*/
|
||||
private final double latTop;
|
||||
private double latTop;
|
||||
|
||||
/**
|
||||
* The latitude of the bottom side of the map.
|
||||
*/
|
||||
private final double latBottom;
|
||||
private double latBottom;
|
||||
|
||||
|
||||
/**
|
||||
@@ -143,4 +143,27 @@ public class RaceMap {
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the bottom right GPS coordinates of the RaceMap.
|
||||
* @param bottomRight New bottom right GPS coordinates.
|
||||
*/
|
||||
public void setGPSBotRight(GPSCoordinate bottomRight) {
|
||||
this.latBottom = bottomRight.getLatitude();
|
||||
this.longRight = bottomRight.getLongitude();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the top left GPS coordinates of the RaceMap.
|
||||
* @param topLeft New top left GPS coordinates.
|
||||
*/
|
||||
public void setGPSTopLeft(GPSCoordinate topLeft) {
|
||||
this.latTop = topLeft.getLatitude();
|
||||
this.longLeft = topLeft.getLongitude();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import shared.dataInput.RaceDataSource;
|
||||
import shared.enums.RoundingType;
|
||||
import shared.model.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
/**
|
||||
* The race we read data from and draw.
|
||||
*/
|
||||
private VisualiserRace visualiserRace;
|
||||
private VisualiserRaceEvent visualiserRace;
|
||||
|
||||
|
||||
private boolean annoName = true;
|
||||
@@ -47,15 +48,15 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a {@link ResizableRaceCanvas} using a given {@link VisualiserRace}.
|
||||
* Constructs a {@link ResizableRaceCanvas} using a given {@link VisualiserRaceEvent}.
|
||||
* @param visualiserRace The race that data is read from in order to be drawn.
|
||||
*/
|
||||
public ResizableRaceCanvas(VisualiserRace visualiserRace) {
|
||||
public ResizableRaceCanvas(VisualiserRaceEvent visualiserRace) {
|
||||
super();
|
||||
|
||||
this.visualiserRace = visualiserRace;
|
||||
|
||||
RaceDataSource raceData = visualiserRace.getRaceDataSource();
|
||||
RaceDataSource raceData = visualiserRace.getVisualiserRaceState().getRaceDataSource();
|
||||
|
||||
double lat1 = raceData.getMapTopLeft().getLatitude();
|
||||
double long1 = raceData.getMapTopLeft().getLongitude();
|
||||
@@ -269,8 +270,8 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
boat.getCountry(),
|
||||
boat.getCurrentSpeed(),
|
||||
this.map.convertGPS(boat.getCurrentPosition()),
|
||||
boat.getTimeToNextMarkFormatted(this.visualiserRace.getRaceClock().getCurrentTime()),
|
||||
boat.getTimeSinceLastMarkFormatted(this.visualiserRace.getRaceClock().getCurrentTime()) );
|
||||
boat.getTimeToNextMarkFormatted(this.visualiserRace.getVisualiserRaceState().getRaceClock().getCurrentTime()),
|
||||
boat.getTimeSinceLastMarkFormatted(this.visualiserRace.getVisualiserRaceState().getRaceClock().getCurrentTime()) );
|
||||
|
||||
}
|
||||
|
||||
@@ -282,7 +283,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
*/
|
||||
private void drawBoats() {
|
||||
|
||||
for (VisualiserBoat boat : visualiserRace.getBoats()) {
|
||||
for (VisualiserBoat boat : new ArrayList<>(visualiserRace.getVisualiserRaceState().getBoats())) {
|
||||
|
||||
//Draw the boat.
|
||||
drawBoat(boat);
|
||||
@@ -295,7 +296,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
|
||||
//If the race hasn't started, we set the time since last mark to the current time, to ensure we don't start counting until the race actually starts.
|
||||
if ((boat.getStatus() != BoatStatusEnum.RACING) && (boat.getStatus() == BoatStatusEnum.FINISHED)) {
|
||||
boat.setTimeAtLastMark(visualiserRace.getRaceClock().getCurrentTime());
|
||||
boat.setTimeAtLastMark(visualiserRace.getVisualiserRaceState().getRaceClock().getCurrentTime());
|
||||
}
|
||||
|
||||
//Draw boat label.
|
||||
@@ -316,36 +317,69 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
*/
|
||||
private void drawBoat(VisualiserBoat boat) {
|
||||
|
||||
//The position may be null if we haven't received any BoatLocation messages yet.
|
||||
if (boat.getCurrentPosition() != null) {
|
||||
|
||||
//Convert position to graph coordinate.
|
||||
GraphCoordinate pos = this.map.convertGPS(boat.getCurrentPosition());
|
||||
|
||||
//The x coordinates of each vertex of the boat.
|
||||
double[] x = {
|
||||
pos.getX() - 6,
|
||||
pos.getX(),
|
||||
pos.getX() + 6 };
|
||||
|
||||
//The y coordinates of each vertex of the boat.
|
||||
double[] y = {
|
||||
pos.getY() + 12,
|
||||
pos.getY() - 12,
|
||||
pos.getY() + 12 };
|
||||
|
||||
//The above shape is essentially a triangle 12px wide, and 24px long.
|
||||
|
||||
//Draw the boat.
|
||||
gc.setFill(boat.getColor());
|
||||
|
||||
gc.save();
|
||||
rotate(boat.getBearing().degrees(), pos.getX(), pos.getY());
|
||||
gc.fillPolygon(x, y, 3);
|
||||
gc.restore();
|
||||
|
||||
if (boat.isClientBoat()) {
|
||||
drawClientBoat(boat);
|
||||
}
|
||||
|
||||
//Convert position to graph coordinate.
|
||||
GraphCoordinate pos = this.map.convertGPS(boat.getCurrentPosition());
|
||||
|
||||
//The x coordinates of each vertex of the boat.
|
||||
double[] x = {
|
||||
pos.getX() - 6,
|
||||
pos.getX(),
|
||||
pos.getX() + 6 };
|
||||
|
||||
//The y coordinates of each vertex of the boat.
|
||||
double[] y = {
|
||||
pos.getY() + 12,
|
||||
pos.getY() - 12,
|
||||
pos.getY() + 12 };
|
||||
|
||||
//The above shape is essentially a triangle 12px wide, and 24px long.
|
||||
|
||||
//Draw the boat.
|
||||
gc.setFill(boat.getColor());
|
||||
|
||||
gc.save();
|
||||
rotate(boat.getBearing().degrees(), pos.getX(), pos.getY());
|
||||
gc.fillPolygon(x, y, 3);
|
||||
gc.restore();
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws extra decorations to show which boat has been assigned to the client.
|
||||
* @param boat The client's boat.
|
||||
*/
|
||||
private void drawClientBoat(VisualiserBoat boat) {
|
||||
|
||||
//Convert position to graph coordinate.
|
||||
GraphCoordinate pos = this.map.convertGPS(boat.getCurrentPosition());
|
||||
|
||||
//The x coordinates of each vertex of the boat.
|
||||
double[] x = {
|
||||
pos.getX() - 9,
|
||||
pos.getX(),
|
||||
pos.getX() + 9 };
|
||||
|
||||
//The y coordinates of each vertex of the boat.
|
||||
double[] y = {
|
||||
pos.getY() + 15,
|
||||
pos.getY() - 15,
|
||||
pos.getY() + 15 };
|
||||
|
||||
//The above shape is essentially a triangle 24px wide, and 48 long.
|
||||
|
||||
//Draw the boat.
|
||||
gc.setFill(Color.BLACK);
|
||||
|
||||
gc.save();
|
||||
rotate(boat.getBearing().degrees(), pos.getX(), pos.getY());
|
||||
gc.fillPolygon(x, y, 3);
|
||||
gc.restore();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -370,7 +404,8 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
* Draws all of the {@link Mark}s on the canvas.
|
||||
*/
|
||||
private void drawMarks() {
|
||||
for (Mark mark : this.visualiserRace.getMarks()) {
|
||||
|
||||
for (Mark mark : new ArrayList<>(visualiserRace.getVisualiserRaceState().getMarks())) {
|
||||
drawMark(mark);
|
||||
}
|
||||
}
|
||||
@@ -430,7 +465,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
|
||||
|
||||
//Calculate the screen coordinates of the boundary.
|
||||
List<GPSCoordinate> boundary = this.visualiserRace.getBoundary();
|
||||
List<GPSCoordinate> boundary = new ArrayList<>(visualiserRace.getVisualiserRaceState().getBoundary());
|
||||
double[] xpoints = new double[boundary.size()];
|
||||
double[] ypoints = new double[boundary.size()];
|
||||
|
||||
@@ -454,6 +489,10 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
*/
|
||||
public void drawRace() {
|
||||
|
||||
//Update RaceMap with new GPS values of race.
|
||||
this.map.setGPSTopLeft(visualiserRace.getVisualiserRaceState().getRaceDataSource().getMapTopLeft());
|
||||
this.map.setGPSBotRight(visualiserRace.getVisualiserRaceState().getRaceDataSource().getMapBottomRight());
|
||||
|
||||
gc.setLineWidth(2);
|
||||
|
||||
clear();
|
||||
@@ -478,7 +517,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
* draws a transparent line around the course that shows the paths boats must travel
|
||||
*/
|
||||
public void drawRaceLine(){
|
||||
List<Leg> legs = this.visualiserRace.getLegs();
|
||||
List<Leg> legs = this.visualiserRace.getVisualiserRaceState().getLegs();
|
||||
GPSCoordinate legStartPoint = legs.get(0).getStartCompoundMark().getAverageGPSCoordinate();
|
||||
GPSCoordinate nextStartPoint;
|
||||
for (int i = 0; i < legs.size() -1; i++) {
|
||||
@@ -492,6 +531,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
* draws the line leg by leg
|
||||
* @param legs the legs of a race
|
||||
* @param index the index of the current leg to use
|
||||
* @param legStartPoint The position the current leg.
|
||||
* @return the end point of the current leg that has been drawn
|
||||
*/
|
||||
private GPSCoordinate drawLineRounding(List<Leg> legs, int index, GPSCoordinate legStartPoint){
|
||||
@@ -625,7 +665,7 @@ public class ResizableRaceCanvas extends ResizableCanvas {
|
||||
gc.setFill(boat.getColor());
|
||||
|
||||
//Draw each TrackPoint.
|
||||
for (TrackPoint point : boat.getTrack()) {
|
||||
for (TrackPoint point : new ArrayList<>(boat.getTrack())) {
|
||||
|
||||
//Convert the GPSCoordinate to a screen coordinate.
|
||||
GraphCoordinate scaledCoordinate = this.map.convertGPS(point.getCoordinate());
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package visualiser.model;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.collections.transformation.SortedList;
|
||||
import javafx.scene.chart.LineChart;
|
||||
import javafx.scene.chart.NumberAxis;
|
||||
import javafx.scene.chart.XYChart;
|
||||
import javafx.scene.paint.Color;
|
||||
import shared.model.Leg;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
@@ -23,7 +28,7 @@ public class Sparkline {
|
||||
/**
|
||||
* The race to observe.
|
||||
*/
|
||||
private VisualiserRace race;
|
||||
private VisualiserRaceState race;
|
||||
|
||||
/**
|
||||
* The boats to observe.
|
||||
@@ -31,10 +36,10 @@ public class Sparkline {
|
||||
private ObservableList<VisualiserBoat> boats;
|
||||
|
||||
/**
|
||||
* The number of legs in the race.
|
||||
* Used to correctly scale the linechart.
|
||||
* Race legs to observe.
|
||||
* We need to observe legs as they may be added after the sparkline is created if race.xml is received after this is created.
|
||||
*/
|
||||
private Integer legNum;
|
||||
private ObservableList<Leg> legs;
|
||||
|
||||
|
||||
/**
|
||||
@@ -52,21 +57,31 @@ public class Sparkline {
|
||||
*/
|
||||
private NumberAxis yAxis;
|
||||
|
||||
/**
|
||||
* A map between a boat and its data series in the sparkline.
|
||||
* This is used so that we can remove a series when (or if) a boat is removed from the race.
|
||||
*/
|
||||
private Map<VisualiserBoat, XYChart.Series<Number, Number>> boatSeriesMap;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructor to set up initial sparkline (LineChart) object
|
||||
* @param race The race to listen to.
|
||||
* @param sparklineChart JavaFX LineChart for the sparkline.
|
||||
*/
|
||||
public Sparkline(VisualiserRace race, LineChart<Number,Number> sparklineChart) {
|
||||
public Sparkline(VisualiserRaceState race, LineChart<Number, Number> sparklineChart) {
|
||||
this.race = race;
|
||||
this.boats = race.getBoats();
|
||||
this.legNum = race.getLegCount();
|
||||
this.boats = new SortedList<>(race.getBoats());
|
||||
this.legs = race.getLegs();
|
||||
|
||||
this.sparklineChart = sparklineChart;
|
||||
this.yAxis = (NumberAxis) sparklineChart.getYAxis();
|
||||
this.xAxis = (NumberAxis) sparklineChart.getXAxis();
|
||||
|
||||
this.boatSeriesMap = new HashMap<>();
|
||||
|
||||
createSparkline();
|
||||
|
||||
}
|
||||
@@ -78,50 +93,45 @@ public class Sparkline {
|
||||
* Position numbers are displayed.
|
||||
*/
|
||||
private void createSparkline() {
|
||||
// NOTE: Y axis is in negatives to display correct positions
|
||||
|
||||
//For each boat...
|
||||
for (VisualiserBoat boat : this.boats) {
|
||||
//We need to dynamically update the sparkline when boats are added/removed.
|
||||
boats.addListener((ListChangeListener.Change<? extends VisualiserBoat> c) -> {
|
||||
|
||||
//Create data series for each boat.
|
||||
XYChart.Series<Number, Number> series = new XYChart.Series<>();
|
||||
Platform.runLater(() -> {
|
||||
|
||||
while (c.next()) {
|
||||
|
||||
if (c.wasAdded()) {
|
||||
for (VisualiserBoat boat : c.getAddedSubList()) {
|
||||
addBoatSeries(boat);
|
||||
}
|
||||
|
||||
} else if (c.wasRemoved()) {
|
||||
for (VisualiserBoat boat : c.getRemoved()) {
|
||||
removeBoatSeries(boat);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Update height of y axis.
|
||||
setYAxisLowerBound();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
//All boats start in "last" place.
|
||||
series.getData().add(new XYChart.Data<>(0, boats.size()));
|
||||
|
||||
//Listen for changes in the boat's leg - we only update the graph when it changes leg.
|
||||
boat.legProperty().addListener(
|
||||
(observable, oldValue, newValue) -> {
|
||||
|
||||
//Get the data to plot.
|
||||
List<VisualiserBoat> boatOrder = race.getLegCompletionOrder().get(oldValue);
|
||||
//Find boat position in list.
|
||||
int boatPosition = boatOrder.indexOf(boat) + 1;
|
||||
|
||||
//Get leg number.
|
||||
int legNumber = oldValue.getLegNumber() + 1;
|
||||
|
||||
|
||||
//Create new data point for boat's position at the new leg.
|
||||
XYChart.Data<Number, Number> dataPoint = new XYChart.Data<>(legNumber, boatPosition);
|
||||
|
||||
//Add to series.
|
||||
Platform.runLater(() -> series.getData().add(dataPoint));
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
//Add to chart.
|
||||
sparklineChart.getData().add(series);
|
||||
|
||||
//Color using boat's color. We need to do this after adding the series to a chart, otherwise we get null pointer exceptions.
|
||||
series.getNode().setStyle("-fx-stroke: " + colourToHex(boat.getColor()) + ";");
|
||||
legs.addListener((ListChangeListener.Change<? extends Leg> c) -> {
|
||||
Platform.runLater(() -> xAxis.setUpperBound(race.getLegCount()));
|
||||
});
|
||||
|
||||
|
||||
//Initialise chart for existing boats.
|
||||
for (VisualiserBoat boat : boats) {
|
||||
addBoatSeries(boat);
|
||||
}
|
||||
|
||||
|
||||
sparklineChart.setCreateSymbols(false);
|
||||
|
||||
//Set x axis details
|
||||
@@ -130,20 +140,109 @@ public class Sparkline {
|
||||
xAxis.setTickLabelsVisible(false);
|
||||
xAxis.setMinorTickVisible(false);
|
||||
xAxis.setLowerBound(0);
|
||||
xAxis.setUpperBound(legNum + 2);
|
||||
xAxis.setUpperBound(race.getLegCount());
|
||||
xAxis.setTickUnit(1);
|
||||
|
||||
|
||||
//The y-axis uses negative values, with the minus sign hidden (e.g., boat in 1st has position -1, which becomes 1, boat in 6th has position -6, which becomes 6).
|
||||
//This is necessary to actually get the y-axis labelled correctly. Negative tick count doesn't work.
|
||||
//Set y axis details
|
||||
yAxis.setLowerBound(boats.size());
|
||||
yAxis.setUpperBound(1);
|
||||
yAxis.setAutoRanging(false);
|
||||
|
||||
yAxis.setTickUnit(1);
|
||||
yAxis.setMinorTickCount(0);
|
||||
|
||||
yAxis.setUpperBound(0);
|
||||
setYAxisLowerBound();
|
||||
|
||||
yAxis.setLabel("Position in Race");
|
||||
yAxis.setTickUnit(-1);//Negative tick reverses the y axis.
|
||||
|
||||
yAxis.setTickMarkVisible(true);
|
||||
yAxis.setTickLabelsVisible(true);
|
||||
yAxis.setTickMarkVisible(true);
|
||||
yAxis.setMinorTickVisible(true);
|
||||
yAxis.setMinorTickVisible(false);
|
||||
|
||||
|
||||
|
||||
//Hide minus number from displaying on axis.
|
||||
yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis) {
|
||||
@Override
|
||||
public String toString(Number value) {
|
||||
if ((value.intValue() == 0) || (value.intValue() < -boats.size())) {
|
||||
return "";
|
||||
|
||||
} else {
|
||||
return String.format("%d", -value.intValue());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the lower bound of the y-axis.
|
||||
*/
|
||||
private void setYAxisLowerBound() {
|
||||
yAxis.setLowerBound( -(boats.size() + 1));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Removes the data series for a given boat from the sparkline.
|
||||
* @param boat Boat to remove series for.
|
||||
*/
|
||||
private void removeBoatSeries(VisualiserBoat boat) {
|
||||
sparklineChart.getData().remove(boatSeriesMap.get(boat));
|
||||
boatSeriesMap.remove(boat);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a data series for a boat, and adds it to the sparkline.
|
||||
* @param boat Boat to add series for.
|
||||
*/
|
||||
private void addBoatSeries(VisualiserBoat boat) {
|
||||
|
||||
//Create data series for boat.
|
||||
XYChart.Series<Number, Number> series = new XYChart.Series<>();
|
||||
|
||||
|
||||
//All boats start in "last" place.
|
||||
series.getData().add(new XYChart.Data<>(0, -(boats.size())));
|
||||
|
||||
//Listen for changes in the boat's leg - we only update the graph when it changes leg.
|
||||
boat.legProperty().addListener(
|
||||
(observable, oldValue, newValue) -> {
|
||||
|
||||
//Get the data to plot.
|
||||
List<VisualiserBoat> boatOrder = race.getLegCompletionOrder().get(oldValue);
|
||||
//Find boat position in list.
|
||||
int boatPosition = -(boatOrder.indexOf(boat) + 1);
|
||||
|
||||
//Get leg number.
|
||||
int legNumber = oldValue.getLegNumber() + 1;
|
||||
|
||||
|
||||
//Create new data point for boat's position at the new leg.
|
||||
XYChart.Data<Number, Number> dataPoint = new XYChart.Data<>(legNumber, boatPosition);
|
||||
|
||||
//Add to series.
|
||||
Platform.runLater(() -> series.getData().add(dataPoint));
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
//Add to chart.
|
||||
sparklineChart.getData().add(series);
|
||||
|
||||
//Color using boat's color. We need to do this after adding the series to a chart, otherwise we get null pointer exceptions.
|
||||
series.getNode().setStyle("-fx-stroke: " + colourToHex(boat.getColor()) + ";");
|
||||
|
||||
|
||||
boatSeriesMap.put(boat, series);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -57,6 +57,11 @@ public class VisualiserBoat extends Boat {
|
||||
*/
|
||||
private static final double wakeScale = 5;
|
||||
|
||||
/**
|
||||
* If true then this boat has been allocated to the client.
|
||||
*/
|
||||
private boolean isClientBoat = false;
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -169,28 +174,33 @@ public class VisualiserBoat extends Boat {
|
||||
*/
|
||||
public String getTimeToNextMarkFormatted(ZonedDateTime currentTime) {
|
||||
|
||||
//Calculate time delta.
|
||||
Duration timeUntil = Duration.between(currentTime, getEstimatedTimeAtNextMark());
|
||||
if ((getTimeAtLastMark() != null) && (currentTime != null)) {
|
||||
//Calculate time delta.
|
||||
Duration timeUntil = Duration.between(currentTime, getEstimatedTimeAtNextMark());
|
||||
|
||||
//Convert to seconds.
|
||||
long secondsUntil = timeUntil.getSeconds();
|
||||
//Convert to seconds.
|
||||
long secondsUntil = timeUntil.getSeconds();
|
||||
|
||||
//This means the estimated time is in the past, or not racing.
|
||||
if ((secondsUntil < 0) || (getStatus() != BoatStatusEnum.RACING)) {
|
||||
return " -";
|
||||
}
|
||||
//This means the estimated time is in the past, or not racing.
|
||||
if ((secondsUntil < 0) || (getStatus() != BoatStatusEnum.RACING)) {
|
||||
return " -";
|
||||
}
|
||||
|
||||
|
||||
if (secondsUntil <= 60) {
|
||||
//If less than 1 minute, display seconds only.
|
||||
return " " + secondsUntil + "s";
|
||||
if (secondsUntil <= 60) {
|
||||
//If less than 1 minute, display seconds only.
|
||||
return " " + secondsUntil + "s";
|
||||
|
||||
} else {
|
||||
//Otherwise display minutes and seconds.
|
||||
long seconds = secondsUntil % 60;
|
||||
long minutes = (secondsUntil - seconds) / 60;
|
||||
return String.format(" %dm %ds", minutes, seconds);
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
//Otherwise display minutes and seconds.
|
||||
long seconds = secondsUntil % 60;
|
||||
long minutes = (secondsUntil - seconds) / 60;
|
||||
return String.format(" %dm %ds", minutes, seconds);
|
||||
|
||||
return " -";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -203,7 +213,7 @@ public class VisualiserBoat extends Boat {
|
||||
*/
|
||||
public String getTimeSinceLastMarkFormatted(ZonedDateTime currentTime) {
|
||||
|
||||
if (getTimeAtLastMark() != null) {
|
||||
if ((getTimeAtLastMark() != null) && (currentTime != null)) {
|
||||
//Calculate time delta.
|
||||
Duration timeSince = Duration.between(getTimeAtLastMark(), currentTime);
|
||||
|
||||
@@ -214,4 +224,21 @@ public class VisualiserBoat extends Boat {
|
||||
return " -";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether or not this boat has been assigned to the client.
|
||||
* @return True if this is the client's boat.
|
||||
*/
|
||||
public boolean isClientBoat() {
|
||||
return isClientBoat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether or not this boat has been assigned to the client.
|
||||
* @param clientBoat True if this is the client's boat.
|
||||
*/
|
||||
public void setClientBoat(boolean clientBoat) {
|
||||
isClientBoat = clientBoat;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,469 +0,0 @@
|
||||
package visualiser.model;
|
||||
|
||||
import javafx.animation.AnimationTimer;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.scene.paint.Color;
|
||||
import network.Messages.BoatLocation;
|
||||
import network.Messages.BoatStatus;
|
||||
import network.Messages.Enums.BoatStatusEnum;
|
||||
import network.Messages.Enums.RaceStatusEnum;
|
||||
import network.Messages.LatestMessages;
|
||||
import network.Messages.RaceStatus;
|
||||
import shared.dataInput.BoatDataSource;
|
||||
import shared.dataInput.RaceDataSource;
|
||||
import shared.dataInput.RegattaDataSource;
|
||||
import shared.model.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The Class used to view the race streamed.
|
||||
* Has a course, boats, boundaries, etc...
|
||||
* Observes LatestMessages and updates its state based on new messages.
|
||||
*/
|
||||
public class VisualiserRace extends Race implements Runnable {
|
||||
|
||||
|
||||
/**
|
||||
* An observable list of boats in the race.
|
||||
*/
|
||||
private final ObservableList<VisualiserBoat> boats;
|
||||
|
||||
/**
|
||||
* An observable list of marker boats in the race.
|
||||
*/
|
||||
private ObservableList<Mark> boatMarkers;
|
||||
|
||||
|
||||
/**
|
||||
* Maps between a Leg to a list of boats, in the order that they finished the leg.
|
||||
* Used by the Sparkline to ensure it has correct information.
|
||||
*/
|
||||
private Map<Leg, List<VisualiserBoat>> legCompletionOrder = new HashMap<>();
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a race object with a given RaceDataSource, BoatDataSource, and RegattaDataSource and receives events from LatestMessages.
|
||||
* @param boatDataSource Data source for boat related data (yachts and marker boats).
|
||||
* @param raceDataSource Data source for race related data (participating boats, legs, etc...).
|
||||
* @param regattaDataSource Data source for race related data (course name, location, timezone, etc...).
|
||||
* @param latestMessages The LatestMessages to send events to.
|
||||
* @param colors A collection of colors used to assign a color to each boat.
|
||||
*/
|
||||
public VisualiserRace(BoatDataSource boatDataSource, RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, LatestMessages latestMessages, List<Color> colors) {
|
||||
|
||||
super(boatDataSource, raceDataSource, regattaDataSource, latestMessages);
|
||||
|
||||
|
||||
this.boats = FXCollections.observableArrayList(this.generateVisualiserBoats(boatDataSource.getBoats(), raceDataSource.getParticipants(), colors));
|
||||
|
||||
this.boatMarkers = FXCollections.observableArrayList(boatDataSource.getMarkerBoats().values());
|
||||
|
||||
|
||||
//Initialise the leg completion order map.
|
||||
for (Leg leg : this.legs) {
|
||||
this.legCompletionOrder.put(leg, new ArrayList<>(this.boats.size()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the race data source for this race to a new RaceDataSource.
|
||||
* Uses the boundary and legs specified by the new RaceDataSource.
|
||||
* @param raceDataSource The new RaceDataSource to use.
|
||||
*/
|
||||
public void setRaceDataSource(RaceDataSource raceDataSource) {
|
||||
this.raceDataSource = raceDataSource;
|
||||
|
||||
this.boundary = raceDataSource.getBoundary();
|
||||
|
||||
this.useLegsList(raceDataSource.getLegs());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the boat data source for this race to a new BoatDataSource.
|
||||
* Uses the marker boats specified by the new BoatDataSource.
|
||||
* @param boatDataSource The new BoatDataSource to use.
|
||||
*/
|
||||
public void setBoatDataSource(BoatDataSource boatDataSource) {
|
||||
this.boatDataSource = boatDataSource;
|
||||
|
||||
this.boatMarkers = FXCollections.observableArrayList(boatDataSource.getMarkerBoats().values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the regatta data source for this race to a new RegattaDataSource.
|
||||
* @param regattaDataSource The new RegattaDataSource to use.
|
||||
*/
|
||||
public void setRegattaDataSource(RegattaDataSource regattaDataSource) {
|
||||
this.regattaDataSource = regattaDataSource;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a list of {@link Mark} boats.
|
||||
* @return List of mark boats.
|
||||
*/
|
||||
public ObservableList<Mark> getMarks() {
|
||||
return boatMarkers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a list of VisualiserBoats given a list of Boats, and a list of participating boats.
|
||||
* @param boats The map of Boats describing boats that are potentially in the race. Maps boat sourceID to boat.
|
||||
* @param sourceIDs The list of boat sourceIDs describing which specific boats are actually participating.
|
||||
* @param colors The list of colors to be used for the boats.
|
||||
* @return A list of MockBoats that are participating in the race.
|
||||
*/
|
||||
private List<VisualiserBoat> generateVisualiserBoats(Map<Integer, Boat> boats, List<Integer> sourceIDs, List<Color> colors) {
|
||||
|
||||
List<VisualiserBoat> visualiserBoats = new ArrayList<>(sourceIDs.size());
|
||||
|
||||
//For each sourceID participating...
|
||||
int colorIndex = 0;
|
||||
for (int sourceID : sourceIDs) {
|
||||
|
||||
//Get the boat associated with the sourceID.
|
||||
Boat boat = boats.get(sourceID);
|
||||
|
||||
//Get a color for the boat.
|
||||
Color color = colors.get(colorIndex);
|
||||
|
||||
//Construct a VisualiserBoat using the Boat and Polars.
|
||||
VisualiserBoat visualiserBoat = new VisualiserBoat(boat, color);
|
||||
|
||||
visualiserBoats.add(visualiserBoat);
|
||||
|
||||
//Next color.
|
||||
colorIndex++;
|
||||
|
||||
}
|
||||
|
||||
return visualiserBoats;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialise the boats in the race.
|
||||
* This sets their current leg.
|
||||
*/
|
||||
@Override
|
||||
protected void initialiseBoats() {
|
||||
|
||||
Leg startingLeg = legs.get(0);
|
||||
|
||||
for (VisualiserBoat boat : boats) {
|
||||
|
||||
boat.setCurrentLeg(startingLeg);
|
||||
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates all of the racing boats based on messages received.
|
||||
* @param boats The list of racing boats.
|
||||
* @param boatLocationMap A map between boat sourceIDs and BoatLocation messages.
|
||||
* @param boatStatusMap A map between boat sourceIDs and BoatStatus messages.
|
||||
*/
|
||||
private void updateBoats(ObservableList<VisualiserBoat> boats, Map<Integer, BoatLocation> boatLocationMap, Map<Integer, BoatStatus> boatStatusMap) {
|
||||
|
||||
for (VisualiserBoat boat : boats) {
|
||||
BoatLocation boatLocation = boatLocationMap.get(boat.getSourceID());
|
||||
BoatStatus boatStatus = boatStatusMap.get(boat.getSourceID());
|
||||
updateBoat(boat, boatLocation, boatStatus);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates an individual racing boat based on messages received.
|
||||
* @param boat The boat to update.
|
||||
* @param boatLocation The BoatLocation message to use.
|
||||
* @param boatStatus The BoatStatus message to use.
|
||||
*/
|
||||
private void updateBoat(VisualiserBoat boat, BoatLocation boatLocation, BoatStatus boatStatus) {
|
||||
|
||||
if (boatLocation != null && boatStatus != null) {
|
||||
|
||||
//Get the new position.
|
||||
double latitude = boatLocation.getLatitude();
|
||||
double longitude = boatLocation.getLongitude();
|
||||
GPSCoordinate gpsCoordinate = new GPSCoordinate(latitude, longitude);
|
||||
|
||||
boat.setCurrentPosition(gpsCoordinate);
|
||||
|
||||
//Bearing.
|
||||
boat.setBearing(boatLocation.getHeading());
|
||||
|
||||
//Time until next mark.
|
||||
boat.setEstimatedTimeAtNextMark(raceClock.getLocalTime(boatStatus.getEstTimeAtNextMark()));
|
||||
|
||||
//Speed.
|
||||
boat.setCurrentSpeed(boatLocation.getBoatSpeedKnots());
|
||||
|
||||
|
||||
//Boat status.
|
||||
BoatStatusEnum newBoatStatusEnum = boatStatus.getBoatStatus();
|
||||
|
||||
//If we are changing from non-racing to racing, we need to initialise boat with their time at last mark.
|
||||
if ((boat.getStatus() != BoatStatusEnum.RACING) && (newBoatStatusEnum == BoatStatusEnum.RACING)) {
|
||||
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
|
||||
}
|
||||
|
||||
boat.setStatus(newBoatStatusEnum);
|
||||
|
||||
|
||||
//Leg.
|
||||
int legNumber = boatStatus.getLegNumber();
|
||||
|
||||
if (legNumber >= 1 && legNumber < legs.size()) {
|
||||
if (boat.getCurrentLeg() != legs.get(legNumber)) {
|
||||
boatFinishedLeg(boat, legs.get(legNumber));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Attempt to add a track point.
|
||||
if (newBoatStatusEnum == BoatStatusEnum.RACING) {
|
||||
boat.addTrackPoint(boat.getCurrentPosition(), raceClock.getCurrentTime());
|
||||
}
|
||||
|
||||
//Set finish time if boat finished.
|
||||
if (newBoatStatusEnum == BoatStatusEnum.FINISHED || legNumber == this.legs.size()) {
|
||||
boat.setTimeFinished(boatLocation.getTime());
|
||||
boat.setStatus(BoatStatusEnum.FINISHED);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates a boat's leg to a specified leg. Also records the order in which the boat passed the leg.
|
||||
* @param boat The boat to update.
|
||||
* @param leg The leg to use.
|
||||
*/
|
||||
private void boatFinishedLeg(VisualiserBoat boat, Leg leg) {
|
||||
|
||||
//Record order in which boat finished leg.
|
||||
this.legCompletionOrder.get(boat.getCurrentLeg()).add(boat);
|
||||
|
||||
//Update boat.
|
||||
boat.setCurrentLeg(leg);
|
||||
boat.setTimeAtLastMark(this.raceClock.getCurrentTime());
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates all of the marker boats based on messages received.
|
||||
* @param boatMarkers The list of marker boats.
|
||||
* @param boatLocationMap A map between boat sourceIDs and BoatLocation messages.
|
||||
* @param boatStatusMap A map between boat sourceIDs and BoatStatus messages.
|
||||
*/
|
||||
private void updateMarkers(ObservableList<Mark> boatMarkers, Map<Integer, BoatLocation> boatLocationMap, Map<Integer, BoatStatus> boatStatusMap) {
|
||||
|
||||
for (Mark mark : boatMarkers) {
|
||||
BoatLocation boatLocation = boatLocationMap.get(mark.getSourceID());
|
||||
updateMark(mark, boatLocation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an individual marker boat based on messages received.
|
||||
* @param mark The marker boat to be updated.
|
||||
* @param boatLocation The message describing the boat's new location.
|
||||
*/
|
||||
private void updateMark(Mark mark, BoatLocation boatLocation) {
|
||||
|
||||
if (boatLocation != null) {
|
||||
|
||||
//We only update the boat's position.
|
||||
double latitude = boatLocation.getLatitude();
|
||||
double longitude = boatLocation.getLongitude();
|
||||
GPSCoordinate gpsCoordinate = new GPSCoordinate(latitude, longitude);
|
||||
|
||||
mark.setPosition(gpsCoordinate);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates the race status (RaceStatusEnum, wind bearing, wind speed) based on received messages.
|
||||
* @param raceStatus The RaceStatus message received.
|
||||
*/
|
||||
private void updateRaceStatus(RaceStatus raceStatus) {
|
||||
|
||||
//Race status enum.
|
||||
this.raceStatusEnum = raceStatus.getRaceStatus();
|
||||
|
||||
//Wind.
|
||||
this.setWind(
|
||||
raceStatus.getWindDirection(),
|
||||
raceStatus.getWindSpeed() );
|
||||
|
||||
//Current race time.
|
||||
this.raceClock.setUTCTime(raceStatus.getCurrentTime());
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Runnable for the thread.
|
||||
*/
|
||||
public void run() {
|
||||
initialiseBoats();
|
||||
startRaceStream();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Starts the race.
|
||||
* This updates the race based on {@link #latestMessages}.
|
||||
*/
|
||||
private void startRaceStream() {
|
||||
|
||||
new AnimationTimer() {
|
||||
|
||||
long lastFrameTime = System.currentTimeMillis();
|
||||
|
||||
@Override
|
||||
public void handle(long arg0) {
|
||||
|
||||
//Calculate the frame period.
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
long framePeriod = currentFrameTime - lastFrameTime;
|
||||
|
||||
|
||||
//Update race status.
|
||||
updateRaceStatus(latestMessages.getRaceStatus());
|
||||
|
||||
|
||||
//Update racing boats.
|
||||
updateBoats(boats, latestMessages.getBoatLocationMap(), latestMessages.getBoatStatusMap());
|
||||
//And their positions (e.g., 5th).
|
||||
updateBoatPositions(boats);
|
||||
|
||||
|
||||
//Update marker boats.
|
||||
updateMarkers(boatMarkers, latestMessages.getBoatLocationMap(), latestMessages.getBoatStatusMap());
|
||||
|
||||
|
||||
|
||||
|
||||
if (getRaceStatusEnum() == RaceStatusEnum.FINISHED) {
|
||||
stop();
|
||||
}
|
||||
|
||||
lastFrameTime = currentFrameTime;
|
||||
|
||||
//Increment fps.
|
||||
incrementFps(framePeriod);
|
||||
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update position of boats in race (e.g, 5th), no position if on starting leg or DNF.
|
||||
* @param boats The list of boats to update.
|
||||
*/
|
||||
private void updateBoatPositions(ObservableList<VisualiserBoat> boats) {
|
||||
|
||||
//Sort boats.
|
||||
sortBoatsByPosition(boats);
|
||||
|
||||
//Assign new positions.
|
||||
for (int i = 0; i < boats.size(); i++) {
|
||||
VisualiserBoat boat = boats.get(i);
|
||||
|
||||
|
||||
if ((boat.getStatus() == BoatStatusEnum.DNF) || (boat.getStatus() == BoatStatusEnum.PRESTART) || (boat.getCurrentLeg().getLegNumber() < 0)) {
|
||||
|
||||
boat.setPosition("-");
|
||||
|
||||
} else {
|
||||
boat.setPosition(Integer.toString(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the list of boats by their position within the race.
|
||||
* @param boats The list of boats in the race.
|
||||
*/
|
||||
private void sortBoatsByPosition(ObservableList<VisualiserBoat> boats) {
|
||||
|
||||
FXCollections.sort(boats, (a, b) -> {
|
||||
//Get the difference in leg numbers.
|
||||
int legNumberDelta = b.getCurrentLeg().getLegNumber() - a.getCurrentLeg().getLegNumber();
|
||||
|
||||
//If they're on the same leg, we need to compare time to finish leg.
|
||||
if (legNumberDelta == 0) {
|
||||
return (int) Duration.between(b.getEstimatedTimeAtNextMark(), a.getEstimatedTimeAtNextMark()).toMillis();
|
||||
} else {
|
||||
return legNumberDelta;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the boats participating in the race.
|
||||
* @return ObservableList of boats participating in the race.
|
||||
*/
|
||||
public ObservableList<VisualiserBoat> getBoats() {
|
||||
return boats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the order in which boats completed each leg. Maps the leg to a list of boats, ordered by the order in which they finished the leg.
|
||||
* @return Leg completion order for each leg.
|
||||
*/
|
||||
public Map<Leg, List<VisualiserBoat>> getLegCompletionOrder() {
|
||||
return legCompletionOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes an estimated time an event will occur, and converts it to the
|
||||
* number of seconds before the event will occur.
|
||||
*
|
||||
* @param estTimeMillis The estimated time, in milliseconds.
|
||||
* @param currentTime The current time, in milliseconds.
|
||||
* @return int difference between time the race started and the estimated time
|
||||
*/
|
||||
private int convertEstTime(long estTimeMillis, long currentTime) {
|
||||
|
||||
//Calculate millisecond delta.
|
||||
long estElapsedMillis = estTimeMillis - currentTime;
|
||||
|
||||
//Convert milliseconds to seconds.
|
||||
int estElapsedSecs = Math.round(estElapsedMillis / 1000);
|
||||
|
||||
return estElapsedSecs;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package visualiser.model;
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.*;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
import visualiser.Commands.VisualiserRaceCommands.VisualiserRaceCommandFactory;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* The controller for race related messages, coming from the server to the client.
|
||||
*/
|
||||
public class VisualiserRaceController implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* Incoming messages from server.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> incomingMessages;
|
||||
|
||||
|
||||
/**
|
||||
* Commands are placed in here, and executed by visualiserRace.
|
||||
*/
|
||||
private CompositeCommand compositeRaceCommand;
|
||||
|
||||
|
||||
/**
|
||||
* The context that created commands operate on.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRace;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a visualiserInput to convert an incoming stream of messages into commands.
|
||||
* @param incomingMessages The incoming queue of messages.
|
||||
* @param visualiserRace The context to for commands to operate on.
|
||||
* @param compositeRaceCommand The composite command to place command in.
|
||||
*/
|
||||
public VisualiserRaceController(BlockingQueue<AC35Data> incomingMessages, VisualiserRaceState visualiserRace, CompositeCommand compositeRaceCommand) {
|
||||
this.incomingMessages = incomingMessages;
|
||||
this.compositeRaceCommand = compositeRaceCommand;
|
||||
this.visualiserRace = visualiserRace;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
AC35Data message = incomingMessages.take();
|
||||
|
||||
Command command = VisualiserRaceCommandFactory.create(message, visualiserRace);
|
||||
compositeRaceCommand.addCommand(command);
|
||||
|
||||
} catch (CommandConstructionException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "VisualiserRaceController could not create a command for incoming message.");
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "VisualiserRaceController was interrupted on thread: " + Thread.currentThread() + " while waiting for messages.");
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package visualiser.model;
|
||||
|
||||
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.Enums.RequestToJoinEnum;
|
||||
import shared.dataInput.EmptyBoatDataSource;
|
||||
import shared.dataInput.EmptyRaceDataSource;
|
||||
import shared.dataInput.EmptyRegattaDataSource;
|
||||
import visualiser.gameController.ControllerClient;
|
||||
import visualiser.network.ServerConnection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
|
||||
/**
|
||||
* This class holds a race, and a client's connection to it
|
||||
*/
|
||||
public class VisualiserRaceEvent {
|
||||
|
||||
/**
|
||||
* Our connection to the server.
|
||||
*/
|
||||
private ServerConnection serverConnection;
|
||||
/**
|
||||
* The thread serverConnection is running on.
|
||||
*/
|
||||
private Thread serverConnectionThread;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The race object which describes the currently occurring race.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRaceState;
|
||||
|
||||
|
||||
/**
|
||||
* The service for updating the {@link #visualiserRaceState}.
|
||||
*/
|
||||
private VisualiserRaceService visualiserRaceService;
|
||||
/**
|
||||
* The thread {@link #visualiserRaceService} is running on.
|
||||
*/
|
||||
private Thread visualiserRaceServiceThread;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a visualiser race event, with a given socket and request type.
|
||||
* @param socket The socket to connect to.
|
||||
* @param requestType The type of {@link network.Messages.RequestToJoin} to make.
|
||||
* @throws IOException Thrown if there is a problem with the socket.
|
||||
*/
|
||||
public VisualiserRaceEvent(Socket socket, RequestToJoinEnum requestType) throws IOException {
|
||||
|
||||
this.visualiserRaceState = new VisualiserRaceState(new EmptyRaceDataSource(), new EmptyRegattaDataSource(), new EmptyBoatDataSource());
|
||||
|
||||
|
||||
CompositeCommand raceCommands = new CompositeCommand();
|
||||
this.visualiserRaceService = new VisualiserRaceService(raceCommands, visualiserRaceState);
|
||||
|
||||
this.visualiserRaceServiceThread = new Thread(visualiserRaceService, "VisualiserRaceEvent()->VisualiserRaceService thread " + visualiserRaceService);
|
||||
this.visualiserRaceServiceThread.start();
|
||||
|
||||
|
||||
this.serverConnection = new ServerConnection(socket, visualiserRaceState, raceCommands, requestType);
|
||||
this.serverConnectionThread = new Thread(serverConnection, "StartController.enterLobby()->serverConnection thread " + serverConnection);
|
||||
this.serverConnectionThread.start();
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the state of the race.
|
||||
* @return The state of the race.
|
||||
*/
|
||||
public VisualiserRaceState getVisualiserRaceState() {
|
||||
return visualiserRaceState;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the controller client, which writes BoatAction messages to the outgoing queue.
|
||||
* @return The ControllerClient.
|
||||
*/
|
||||
public ControllerClient getControllerClient() {
|
||||
return serverConnection.getControllerClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the connection to server.
|
||||
* @return Connection to server.
|
||||
*/
|
||||
public ServerConnection getServerConnection() {
|
||||
return serverConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the framerate property of the race.
|
||||
* @return Framerate property of race.
|
||||
*/
|
||||
public IntegerProperty getFrameRateProperty() {
|
||||
return visualiserRaceService.getFrameRateProperty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Terminates the server connection and race service.
|
||||
*/
|
||||
public void terminate() {
|
||||
this.serverConnectionThread.interrupt();
|
||||
|
||||
this.visualiserRaceServiceThread.interrupt();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package visualiser.model;
|
||||
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import shared.model.FrameRateTracker;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
|
||||
|
||||
/**
|
||||
* Handles updating a {@link VisualiserRaceState} with incoming commands.
|
||||
*/
|
||||
public class VisualiserRaceService implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* The race state to update.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRaceState;
|
||||
|
||||
|
||||
/**
|
||||
* A composite commands to execute to update the race.
|
||||
*/
|
||||
private CompositeCommand raceCommands;
|
||||
|
||||
|
||||
/**
|
||||
* Used to track the framerate of the "simulation".
|
||||
*/
|
||||
private FrameRateTracker frameRateTracker;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a visualiser race which models a yacht race, and is modified by CompositeCommand.
|
||||
* @param raceCommands A composite commands to execute to update the race.
|
||||
* @param visualiserRaceState The race state to update.
|
||||
*/
|
||||
public VisualiserRaceService(CompositeCommand raceCommands, VisualiserRaceState visualiserRaceState) {
|
||||
this.raceCommands = raceCommands;
|
||||
this.visualiserRaceState = visualiserRaceState;
|
||||
|
||||
this.frameRateTracker = new FrameRateTracker();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the CompositeCommand executed by the race.
|
||||
* @return CompositeCommand executed by race.
|
||||
*/
|
||||
public CompositeCommand getRaceCommands() {
|
||||
return raceCommands;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
long previousFrameTime = System.currentTimeMillis();
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
|
||||
waitForFramePeriod(previousFrameTime, currentFrameTime, 16);
|
||||
|
||||
previousFrameTime = currentFrameTime;
|
||||
|
||||
|
||||
raceCommands.execute();
|
||||
|
||||
}
|
||||
|
||||
frameRateTracker.stop();
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the framerate property of the race.
|
||||
* @return Framerate property of race.
|
||||
*/
|
||||
public IntegerProperty getFrameRateProperty() {
|
||||
return frameRateTracker.fpsProperty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
package visualiser.model;
|
||||
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.scene.paint.Color;
|
||||
import network.Messages.Enums.BoatStatusEnum;
|
||||
import shared.dataInput.BoatDataSource;
|
||||
import shared.dataInput.RaceDataSource;
|
||||
import shared.dataInput.RegattaDataSource;
|
||||
import shared.exceptions.BoatNotFoundException;
|
||||
import shared.exceptions.MarkNotFoundException;
|
||||
import shared.model.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* This class contains all of the state of a race on the client (visualiser) side.
|
||||
*/
|
||||
public class VisualiserRaceState extends RaceState {
|
||||
|
||||
|
||||
/**
|
||||
* A list of boats in the race.
|
||||
*/
|
||||
private ObservableList<VisualiserBoat> boats;
|
||||
|
||||
/**
|
||||
* The source ID of the boat assigned to the player.
|
||||
* 0 if no boat has been assigned.
|
||||
*/
|
||||
private int playerBoatID;
|
||||
|
||||
|
||||
/**
|
||||
* Maps between a Leg to a list of boats, in the order that they finished the leg.
|
||||
* Used by the Sparkline to ensure it has correct information.
|
||||
* TODO BUG: if we receive a race.xml file during the race, then we need to add/remove legs to this, without losing information.
|
||||
*/
|
||||
private Map<Leg, List<VisualiserBoat>> legCompletionOrder;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An array of colors used to assign colors to each boat - passed in to the VisualiserRace constructor.
|
||||
*/
|
||||
private List<Color> unassignedColors = new ArrayList<>(Arrays.asList(
|
||||
Color.BLUEVIOLET,
|
||||
Color.BLACK,
|
||||
Color.RED,
|
||||
Color.ORANGE,
|
||||
Color.DARKOLIVEGREEN,
|
||||
Color.LIMEGREEN,
|
||||
Color.PURPLE,
|
||||
Color.DARKGRAY,
|
||||
Color.YELLOW
|
||||
//TODO may need to add more colors.
|
||||
));
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a visualiser race which models a yacht race.
|
||||
* @param raceDataSource The raceDataSource to initialise with.
|
||||
* @param regattaDataSource The regattaDataSource to initialise with.
|
||||
* @param boatDataSource The boatDataSource to initialise with.
|
||||
*/
|
||||
public VisualiserRaceState(RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, BoatDataSource boatDataSource) {
|
||||
|
||||
this.boats = FXCollections.observableArrayList();
|
||||
|
||||
this.playerBoatID = 0;
|
||||
|
||||
this.legCompletionOrder = new HashMap<>();
|
||||
|
||||
|
||||
setRaceDataSource(raceDataSource);
|
||||
setRegattaDataSource(regattaDataSource);
|
||||
setBoatDataSource(boatDataSource);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets the race data source for this race to a new RaceDataSource.
|
||||
* Uses the boundary and legs specified by the new RaceDataSource.
|
||||
* @param raceDataSource The new RaceDataSource to use.
|
||||
*/
|
||||
public void setRaceDataSource(RaceDataSource raceDataSource) {
|
||||
super.setRaceDataSource(raceDataSource);
|
||||
|
||||
if (getBoatDataSource() != null) {
|
||||
this.generateVisualiserBoats(this.boats, getBoatDataSource().getBoats(), raceDataSource.getParticipants(), unassignedColors);
|
||||
}
|
||||
|
||||
initialiseLegCompletionOrder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the boat data source for this race to a new BoatDataSource.
|
||||
* Uses the marker boats specified by the new BoatDataSource.
|
||||
* @param boatDataSource The new BoatDataSource to use.
|
||||
*/
|
||||
public void setBoatDataSource(BoatDataSource boatDataSource) {
|
||||
super.setBoatDataSource(boatDataSource);
|
||||
|
||||
if (getRaceDataSource() != null) {
|
||||
this.generateVisualiserBoats(this.boats, boatDataSource.getBoats(), getRaceDataSource().getParticipants(), unassignedColors);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the regatta data source for this race to a new RegattaDataSource.
|
||||
* @param regattaDataSource The new RegattaDataSource to use.
|
||||
*/
|
||||
public void setRegattaDataSource(RegattaDataSource regattaDataSource) {
|
||||
super.setRegattaDataSource(regattaDataSource);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialises the {@link #legCompletionOrder} map.
|
||||
*/
|
||||
public void initialiseLegCompletionOrder() {
|
||||
//Initialise the leg completion order map.
|
||||
for (Leg leg : getLegs()) {
|
||||
this.legCompletionOrder.put(leg, new ArrayList<>(this.boats.size()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates a list of VisualiserBoats given a list of Boats, and a list of participating boats.
|
||||
* This will add VisualiserBoats for newly participating sourceID, and remove VisualiserBoats for any participating sourceIDs that have been removed.
|
||||
*
|
||||
* @param existingBoats The visualiser boats that already exist in the race. This will be populated when we receive a new race.xml or boats.xml.
|
||||
* @param boats The map of {@link Boat}s describing boats that are potentially in the race. Maps boat sourceID to boat.
|
||||
* @param sourceIDs The list of boat sourceIDs describing which specific boats are actually participating.
|
||||
* @param colors The list of unassignedColors to be used for the boats.
|
||||
*/
|
||||
private void generateVisualiserBoats(ObservableList<VisualiserBoat> existingBoats, Map<Integer, Boat> boats, List<Integer> sourceIDs, List<Color> colors) {
|
||||
|
||||
//Remove any VisualiserBoats that are no longer participating.
|
||||
for (VisualiserBoat boat : new ArrayList<>(existingBoats)) {
|
||||
|
||||
//Boat no longer is participating.
|
||||
if (!sourceIDs.contains(boat.getSourceID())) {
|
||||
//Return their colors to the color list.
|
||||
colors.add(boat.getColor());
|
||||
|
||||
//Remove boat.
|
||||
existingBoats.remove(boat);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Get source IDs of already existing boats.
|
||||
List<Integer> existingBoatIDs = new ArrayList<>();
|
||||
for (VisualiserBoat boat : existingBoats) {
|
||||
existingBoatIDs.add(boat.getSourceID());
|
||||
}
|
||||
|
||||
//Get source IDs of only newly participating boats.
|
||||
List<Integer> newBoatIDs = new ArrayList<>(sourceIDs);
|
||||
newBoatIDs.removeAll(existingBoatIDs);
|
||||
|
||||
//Create VisualiserBoat for newly participating boats.
|
||||
for (Integer sourceID : newBoatIDs) {
|
||||
|
||||
if (boats.containsKey(sourceID)) {
|
||||
|
||||
VisualiserBoat boat = new VisualiserBoat(
|
||||
boats.get(sourceID),
|
||||
colors.remove(colors.size() - 1));//TODO potential bug: not enough colors for boats.
|
||||
|
||||
boat.setCurrentLeg(getLegs().get(0));
|
||||
|
||||
existingBoats.add(boat);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
setPlayerBoat();
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the boat the player has been assigned to as belonging to them.
|
||||
*/
|
||||
private void setPlayerBoat() {
|
||||
|
||||
if (getPlayerBoatID() != 0) {
|
||||
|
||||
for (VisualiserBoat boat : new ArrayList<>(getBoats())) {
|
||||
|
||||
if (boat.getSourceID() == getPlayerBoatID()) {
|
||||
boat.setClientBoat(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initialise the boats in the race.
|
||||
* This sets their current leg.
|
||||
*/
|
||||
@Override
|
||||
protected void initialiseBoats() {
|
||||
|
||||
Leg startingLeg = getLegs().get(0);
|
||||
|
||||
for (VisualiserBoat boat : boats) {
|
||||
|
||||
boat.setCurrentLeg(startingLeg);
|
||||
boat.setTimeAtLastMark(getRaceClock().getCurrentTime());
|
||||
boat.setCurrentPosition(new GPSCoordinate(0, 0));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Update position of boats in race (e.g, 5th), no position if on starting leg or DNF.
|
||||
* @param boats The list of boats to update.
|
||||
*/
|
||||
public void updateBoatPositions(List<VisualiserBoat> boats) {
|
||||
|
||||
//Sort boats.
|
||||
sortBoatsByPosition(boats);
|
||||
|
||||
//Assign new positions.
|
||||
for (int i = 0; i < boats.size(); i++) {
|
||||
VisualiserBoat boat = boats.get(i);
|
||||
|
||||
|
||||
if ((boat.getStatus() == BoatStatusEnum.DNF) || (boat.getStatus() == BoatStatusEnum.PRESTART) || (boat.getCurrentLeg().getLegNumber() < 0)) {
|
||||
|
||||
boat.setPosition("-");
|
||||
|
||||
} else {
|
||||
boat.setPosition(Integer.toString(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sorts the list of boats by their position within the race.
|
||||
* @param boats The list of boats in the race.
|
||||
*/
|
||||
private void sortBoatsByPosition(List<VisualiserBoat> boats) {
|
||||
|
||||
boats.sort((a, b) -> {
|
||||
//Get the difference in leg numbers.
|
||||
int legNumberDelta = b.getCurrentLeg().getLegNumber() - a.getCurrentLeg().getLegNumber();
|
||||
|
||||
//If they're on the same leg, we need to compare time to finish leg.
|
||||
if (legNumberDelta == 0) {
|
||||
|
||||
//These are potentially null until we receive our first RaceStatus containing BoatStatuses.
|
||||
if ((a.getEstimatedTimeAtNextMark() != null) && (b.getEstimatedTimeAtNextMark() != null)) {
|
||||
|
||||
return (int) Duration.between(
|
||||
b.getEstimatedTimeAtNextMark(),
|
||||
a.getEstimatedTimeAtNextMark() ).toMillis();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return legNumberDelta;
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the boats participating in the race.
|
||||
* @return List of boats participating in the race.
|
||||
*/
|
||||
public ObservableList<VisualiserBoat> getBoats() {
|
||||
return boats;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a boat by sourceID.
|
||||
* @param sourceID The source ID the boat.
|
||||
* @return The boat.
|
||||
* @throws BoatNotFoundException Thrown if there is no boat with the specified sourceID.
|
||||
*/
|
||||
public VisualiserBoat getBoat(int sourceID) throws BoatNotFoundException {
|
||||
|
||||
for (VisualiserBoat boat : boats) {
|
||||
|
||||
if (boat.getSourceID() == sourceID) {
|
||||
return boat;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
throw new BoatNotFoundException("Boat with sourceID: " + sourceID + " was not found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not there exists a {@link VisualiserBoat} with the given source ID.
|
||||
* @param sourceID SourceID of VisualiserBoat.
|
||||
* @return True if VisualiserBoat exists, false otherwise.
|
||||
*/
|
||||
public boolean isVisualiserBoat(int sourceID) {
|
||||
|
||||
try {
|
||||
getBoat(sourceID);
|
||||
return true;
|
||||
} catch (BoatNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a mark by sourceID.
|
||||
* @param sourceID The source ID the mark.
|
||||
* @return The mark.
|
||||
* @throws MarkNotFoundException Thrown if there is no mark with the specified sourceID.
|
||||
*/
|
||||
public Mark getMark(int sourceID) throws MarkNotFoundException {
|
||||
|
||||
for (Mark mark : getMarks()) {
|
||||
|
||||
if (mark.getSourceID() == sourceID) {
|
||||
return mark;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
throw new MarkNotFoundException("Mark with sourceID: " + sourceID + " was not found.");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether or not there exists a {@link Mark} with the given source ID.
|
||||
* @param sourceID SourceID of mark.
|
||||
* @return True if mark exists, false otherwise.
|
||||
*/
|
||||
public boolean isMark(int sourceID) {
|
||||
|
||||
try {
|
||||
getMark(sourceID);
|
||||
return true;
|
||||
} catch (MarkNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the order in which boats completed each leg. Maps the leg to a list of boats, ordered by the order in which they finished the leg.
|
||||
* @return Leg completion order for each leg.
|
||||
*/
|
||||
public Map<Leg, List<VisualiserBoat>> getLegCompletionOrder() {
|
||||
return legCompletionOrder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the source ID of the player's boat. 0 if not assigned.
|
||||
* @return Players boat source ID.
|
||||
*/
|
||||
public int getPlayerBoatID() {
|
||||
return playerBoatID;
|
||||
}
|
||||
|
||||
/**
|
||||
* sets the source ID of the player's boat. 0 if not assigned.
|
||||
* @param playerBoatID Players boat source ID.
|
||||
*/
|
||||
public void setPlayerBoatID(int playerBoatID) {
|
||||
this.playerBoatID = playerBoatID;
|
||||
setPlayerBoat();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package visualiser.network;
|
||||
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.Enums.RequestToJoinEnum;
|
||||
import network.Messages.JoinAcceptance;
|
||||
import network.Messages.RequestToJoin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* This class tracks the state of the connection to a server.
|
||||
*/
|
||||
public class ConnectionToServer implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* The state of the connection to the client.
|
||||
*/
|
||||
private ConnectionToServerState connectionState = ConnectionToServerState.UNKNOWN;
|
||||
|
||||
|
||||
/**
|
||||
* The type of join request to make to server.
|
||||
*/
|
||||
private RequestToJoinEnum requestType;
|
||||
|
||||
|
||||
/**
|
||||
* The queue to place outgoing messages on.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> outgoingMessages;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The {@link JoinAcceptance} message that has been received, if any.
|
||||
*/
|
||||
@Nullable
|
||||
private JoinAcceptance joinAcceptance;
|
||||
|
||||
|
||||
/**
|
||||
* The incoming commands to execute.
|
||||
*/
|
||||
private BlockingQueue<Command> incomingCommands;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a ConnectionToServer with a given state.
|
||||
* @param connectionState The state of the connection.
|
||||
* @param requestType The type of join request to make to server.
|
||||
* @param incomingCommands The queue of commands to execute.
|
||||
* @param outgoingMessages The queue to place outgoing messages on.
|
||||
*/
|
||||
public ConnectionToServer(ConnectionToServerState connectionState, RequestToJoinEnum requestType, BlockingQueue<Command> incomingCommands, BlockingQueue<AC35Data> outgoingMessages) {
|
||||
this.connectionState = connectionState;
|
||||
this.requestType = requestType;
|
||||
this.incomingCommands = incomingCommands;
|
||||
this.outgoingMessages = outgoingMessages;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the state of this connection.
|
||||
* @return The state of this connection.
|
||||
*/
|
||||
public ConnectionToServerState getConnectionState() {
|
||||
return connectionState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the state of this connection.
|
||||
* @param connectionState The new state of this connection.
|
||||
*/
|
||||
public void setConnectionState(ConnectionToServerState connectionState) {
|
||||
this.connectionState = connectionState;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the {@link JoinAcceptance} message received from the server, if any.
|
||||
* @return The JoinAcceptance message from server. Null if no response from server.
|
||||
*/
|
||||
@Nullable
|
||||
public JoinAcceptance getJoinAcceptance() {
|
||||
return joinAcceptance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link JoinAcceptance} message received from the server, if any.
|
||||
* @param joinAcceptance The new JoinAcceptance message from server.
|
||||
*/
|
||||
public void setJoinAcceptance(@NotNull JoinAcceptance joinAcceptance) {
|
||||
this.joinAcceptance = joinAcceptance;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
try {
|
||||
sendRequestToJoinMessage(requestType);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "ConnectionToServer: " + this + " was interrupted on thread: " + Thread.currentThread() + " while sending RequestToJoin.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
|
||||
}
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
Command command = incomingCommands.take();
|
||||
command.execute();
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "ConnectionToServer: " + this + " was interrupted on thread: " + Thread.currentThread() + " while reading command.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//If we get interrupted, we consider the connection to have timed-out.
|
||||
connectionState = ConnectionToServerState.TIMED_OUT;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sends the server a {@link RequestToJoin} message.
|
||||
* @param requestType The type of request to send
|
||||
* @throws InterruptedException Thrown if the thread is interrupted while placing message on the outgoing message queue.
|
||||
*/
|
||||
private void sendRequestToJoinMessage(RequestToJoinEnum requestType) throws InterruptedException {
|
||||
|
||||
//Send them the source ID.
|
||||
RequestToJoin requestToJoin = new RequestToJoin(requestType);
|
||||
|
||||
send(requestToJoin);
|
||||
|
||||
connectionState = ConnectionToServerState.REQUEST_SENT;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a given message to the server, via the {@link #outgoingMessages} queue.
|
||||
* @param message Message to send.
|
||||
* @throws InterruptedException Thrown if thread is interrupted while sending message.
|
||||
*/
|
||||
public void send(AC35Data message) throws InterruptedException {
|
||||
outgoingMessages.put(message);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the type of join request that was made.
|
||||
* @return Type of join request made.
|
||||
*/
|
||||
public RequestToJoinEnum getRequestType() {
|
||||
return requestType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package visualiser.network;
|
||||
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
import visualiser.Commands.ConnectionToServerCommands.ConnectionToServerCommandFactory;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* The controller for connection related messages, coming from the server to the client.
|
||||
*/
|
||||
public class ConnectionToServerController implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* The incoming queue of messages to act on.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> incomingMessages;
|
||||
|
||||
|
||||
/**
|
||||
* The connection we are acting on.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
|
||||
|
||||
/**
|
||||
* The queue to place commands on.
|
||||
*/
|
||||
private BlockingQueue<Command> outgoingCommands;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a {@link ConnectionToServer} controller with the given parameters.
|
||||
* This accepts connection related messages, converts them to commands, and passes them to an outgoing command queue.
|
||||
* @param incomingMessages The message queue to read from.
|
||||
* @param connectionToServer The ConnectionToServer (context) to act on.
|
||||
* @param outgoingCommands The queue to place outgoing commands on.
|
||||
*/
|
||||
public ConnectionToServerController(BlockingQueue<AC35Data> incomingMessages, ConnectionToServer connectionToServer, BlockingQueue<Command> outgoingCommands) {
|
||||
this.incomingMessages = incomingMessages;
|
||||
this.connectionToServer = connectionToServer;
|
||||
this.outgoingCommands = outgoingCommands;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
AC35Data message = incomingMessages.take();
|
||||
Command command = ConnectionToServerCommandFactory.create(message, connectionToServer);
|
||||
outgoingCommands.put(command);
|
||||
|
||||
} catch (CommandConstructionException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "ConnectionToServerController: " + this + " could not create command from message.", e);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "ConnectionToServerController: " + this + " was interrupted on thread: " + Thread.currentThread(), e);
|
||||
Thread.currentThread().interrupt();
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package visualiser.network;
|
||||
|
||||
import mock.exceptions.CommandConstructionException;
|
||||
import mock.model.commandFactory.Command;
|
||||
import network.Messages.AC35Data;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
import visualiser.Commands.IncomingHeartBeatCommands.IncomingHeartBeatCommandFactory;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* The controller for heartbeat related messages, coming from the server to the client.
|
||||
*/
|
||||
public class IncomingHeartBeatController implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* The incoming queue of messages to act on.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> incomingMessages;
|
||||
|
||||
|
||||
/**
|
||||
* The heart beat service we are acting on.
|
||||
*/
|
||||
private IncomingHeartBeatService incomingHeartBeatService;
|
||||
|
||||
|
||||
/**
|
||||
* The queue to place commands on.
|
||||
*/
|
||||
private BlockingQueue<Command> outgoingCommands;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a {@link IncomingHeartBeatService} controller with the given parameters.
|
||||
* This accepts connection related messages, converts them to commands, and passes them to an outgoing command queue.
|
||||
* @param incomingMessages The message queue to read from.
|
||||
* @param incomingHeartBeatService The IncomingHeartBeatService (context) to act on.
|
||||
* @param outgoingCommands The queue to place outgoing commands on.
|
||||
*/
|
||||
public IncomingHeartBeatController(BlockingQueue<AC35Data> incomingMessages, IncomingHeartBeatService incomingHeartBeatService, BlockingQueue<Command> outgoingCommands) {
|
||||
this.incomingMessages = incomingMessages;
|
||||
this.incomingHeartBeatService = incomingHeartBeatService;
|
||||
this.outgoingCommands = outgoingCommands;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
AC35Data message = incomingMessages.take();
|
||||
Command command = IncomingHeartBeatCommandFactory.create(message, incomingHeartBeatService);
|
||||
outgoingCommands.put(command);
|
||||
|
||||
} catch (CommandConstructionException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "IncomingHeartBeatController: " + this + " could not create command from message.", e);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "IncomingHeartBeatController: " + this + " was interrupted on thread: " + Thread.currentThread(), e);
|
||||
Thread.currentThread().interrupt();
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package visualiser.network;
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* Tracks the heart beat status of a connection.
|
||||
*/
|
||||
public class IncomingHeartBeatService implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
/**
|
||||
* Timestamp of the last sent heartbeat message.
|
||||
*/
|
||||
private long lastHeartbeatTime;
|
||||
|
||||
|
||||
/**
|
||||
* Sequence number for heartbeat messages.
|
||||
*/
|
||||
private long lastHeartBeatSeqNum;
|
||||
|
||||
|
||||
/**
|
||||
* The incoming commands to execute.
|
||||
*/
|
||||
private BlockingQueue<Command> incomingCommands;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates an {@link IncomingHeartBeatService} which executes commands from a given queue.
|
||||
* @param incomingCommands Queue to read and execute commands from.
|
||||
*/
|
||||
public IncomingHeartBeatService(BlockingQueue<Command> incomingCommands) {
|
||||
this.incomingCommands = incomingCommands;
|
||||
|
||||
this.lastHeartbeatTime = System.currentTimeMillis();
|
||||
this.lastHeartBeatSeqNum = -1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the last heart beat time to a given value.
|
||||
* @param lastHeartbeatTime Timestamp of heartbeat.
|
||||
*/
|
||||
public void setLastHeartbeatTime(long lastHeartbeatTime) {
|
||||
this.lastHeartbeatTime = lastHeartbeatTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the last heart beat sequence number to a given value.
|
||||
* @param lastHeartBeatSeqNum Sequence number of heartbeat.
|
||||
*/
|
||||
public void setLastHeartBeatSeqNum(long lastHeartBeatSeqNum) {
|
||||
this.lastHeartBeatSeqNum = lastHeartBeatSeqNum;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Calculates the time since last heartbeat, in milliseconds.
|
||||
*
|
||||
* @return Time since last heartbeat, in milliseconds..
|
||||
*/
|
||||
private long timeSinceHeartbeat() {
|
||||
long now = System.currentTimeMillis();
|
||||
return (now - lastHeartbeatTime);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether or not the heartBeat service considers the connection "alive".
|
||||
* Going 10,000ms without receiving a heartBeat means that the connection is "dead".
|
||||
* @return True if alive, false if dead.
|
||||
*/
|
||||
public boolean isAlive() {
|
||||
long heartBeatPeriod = 10000;
|
||||
|
||||
return (timeSinceHeartbeat() < heartBeatPeriod);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
Command command = incomingCommands.take();
|
||||
command.execute();
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.SEVERE, "IncomingHeartBeatService: " + this + " was interrupted on thread: " + Thread.currentThread() + " while reading command.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
package visualiser.network;
|
||||
|
||||
|
||||
import mock.model.commandFactory.Command;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.MessageRouters.MessageRouter;
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.Enums.MessageType;
|
||||
import network.Messages.Enums.RequestToJoinEnum;
|
||||
import network.Messages.LatestMessages;
|
||||
import network.StreamRelated.MessageDeserialiser;
|
||||
import network.StreamRelated.MessageSerialiser;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
import visualiser.model.VisualiserRaceEvent;
|
||||
import visualiser.model.VisualiserRaceController;
|
||||
import visualiser.enums.ConnectionToServerState;
|
||||
import visualiser.gameController.ControllerClient;
|
||||
import visualiser.model.VisualiserRaceState;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* This class handles the client-server connection handshake.
|
||||
*/
|
||||
public class ServerConnection implements RunnableWithFramePeriod {
|
||||
|
||||
/**
|
||||
* The socket for the connection to server.
|
||||
*/
|
||||
private Socket socket;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Used to send client input to server.
|
||||
*/
|
||||
private ControllerClient controllerClient;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Used to write messages to socket.
|
||||
*/
|
||||
private MessageSerialiser messageSerialiser;
|
||||
/**
|
||||
* The thread {@link #messageSerialiser} runs on.
|
||||
*/
|
||||
private Thread messageSerialiserThread;
|
||||
|
||||
/**
|
||||
* Used to read messages from socket.
|
||||
*/
|
||||
private MessageDeserialiser messageDeserialiser;
|
||||
/**
|
||||
* The thread {@link #messageDeserialiser} runs on.
|
||||
*/
|
||||
private Thread messageDeserialiserThread;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Router to route messages to correct queue.
|
||||
*/
|
||||
private MessageRouter messageRouter;
|
||||
/**
|
||||
* The thread {@link #messageRouter} runs on.
|
||||
*/
|
||||
private Thread messageRouterThread;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The state of the connection to the client.
|
||||
*/
|
||||
private ConnectionToServer connectionToServer;
|
||||
/**
|
||||
* The thread {@link #connectionToServer} runs on.
|
||||
*/
|
||||
private Thread connectionToServerThread;
|
||||
|
||||
/**
|
||||
* The controller which handles JoinAcceptance messages.
|
||||
*/
|
||||
private ConnectionToServerController connectionToServerController;
|
||||
/**
|
||||
* The thread {@link #connectionToServerController} runs on.
|
||||
*/
|
||||
private Thread connectionToServerControllerThread;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Tracks the heartBeat status of the connection.
|
||||
*/
|
||||
private IncomingHeartBeatService heartBeatService;
|
||||
/**
|
||||
* The thread {@link #heartBeatService} runs on.
|
||||
*/
|
||||
private Thread heartBeatServiceThread;
|
||||
|
||||
/**
|
||||
* Tracks the heartBeat status of the connection.
|
||||
*/
|
||||
private IncomingHeartBeatController heartBeatController;
|
||||
/**
|
||||
* The thread {@link #heartBeatController} runs on.
|
||||
*/
|
||||
private Thread heartBeatControllerThread;
|
||||
|
||||
|
||||
/**
|
||||
* This is the race we are modelling.
|
||||
*/
|
||||
private VisualiserRaceState visualiserRaceState;
|
||||
|
||||
/**
|
||||
* The CompositeCommand to place race commands in.
|
||||
*/
|
||||
private CompositeCommand raceCommands;
|
||||
|
||||
|
||||
/**
|
||||
* Used to convert incoming messages into a race snapshot.
|
||||
*/
|
||||
private VisualiserRaceController visualiserRaceController;
|
||||
/**
|
||||
* The thread {@link #visualiserRaceController} runs on.
|
||||
*/
|
||||
private Thread visualiserRaceControllerThread;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a server connection, using a given socket.
|
||||
* @param socket The socket which connects to the client.
|
||||
* @param visualiserRaceState The race for the {@link VisualiserRaceController} to send commands to.
|
||||
* @param raceCommands The CompositeCommand to place race commands in.
|
||||
* @param requestType The type of join request to make.
|
||||
* @throws IOException Thrown if there is a problem with the client socket.
|
||||
*/
|
||||
public ServerConnection(Socket socket, VisualiserRaceState visualiserRaceState, CompositeCommand raceCommands, RequestToJoinEnum requestType) throws IOException {
|
||||
this.socket = socket;
|
||||
this.visualiserRaceState = visualiserRaceState;
|
||||
this.raceCommands = raceCommands;
|
||||
|
||||
createMessageSerialiser(socket);
|
||||
createMessageDeserialiser(socket);
|
||||
|
||||
createRouter(messageDeserialiser.getMessagesRead());
|
||||
|
||||
createConnectionToServer(requestType);
|
||||
|
||||
|
||||
messageRouterThread.start();
|
||||
|
||||
|
||||
this.controllerClient = new ControllerClient(messageRouter.getIncomingMessageQueue());
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates this connection's {@link MessageRouter}, and gives it a queue to read from.
|
||||
* Does not start {@link #messageRouterThread}. Start it after setting up any initial routes.
|
||||
* @param inputQueue Queue for the MessageRouter to read from.
|
||||
*/
|
||||
private void createRouter(BlockingQueue<AC35Data> inputQueue) {
|
||||
this.messageRouter = new MessageRouter(inputQueue);
|
||||
|
||||
this.messageRouterThread = new Thread(messageRouter, "ServerConnection()->MessageRouter thread " + messageRouter);
|
||||
|
||||
//Unrouted messages get sent back to the router. Kind of ugly, but we do this to ensure that no messages are lost while initializing (e.g., XML message being received before setting up the route for it).
|
||||
messageRouter.addDefaultRoute(messageRouter.getIncomingMessageQueue());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the {@link #connectionToServer} and {@link #connectionToServerController}, and starts their threads.
|
||||
* @param requestType The type of join request to make to server.
|
||||
*/
|
||||
private void createConnectionToServer(RequestToJoinEnum requestType) {
|
||||
|
||||
//ConnectionToServer executes these commands.
|
||||
BlockingQueue<Command> commands = new LinkedBlockingQueue<>();
|
||||
this.connectionToServer = new ConnectionToServer(ConnectionToServerState.UNKNOWN, requestType, commands, messageRouter.getIncomingMessageQueue());
|
||||
|
||||
//ConnectionToServerController receives messages, and places commands on the above command queue.
|
||||
BlockingQueue<AC35Data> incomingJoinMessages = new LinkedBlockingQueue<>();
|
||||
this.connectionToServerController = new ConnectionToServerController(incomingJoinMessages, connectionToServer, commands);
|
||||
|
||||
//Route JoinAcceptance messages to the controller, and RequestToJoin to the socket.
|
||||
this.messageRouter.addRoute(MessageType.JOIN_ACCEPTANCE, incomingJoinMessages);
|
||||
this.messageRouter.addRoute(MessageType.REQUEST_TO_JOIN, messageSerialiser.getMessagesToSend());
|
||||
|
||||
|
||||
//Start the above on new threads.
|
||||
this.connectionToServerThread = new Thread(connectionToServer, "ServerConnection()->ConnectionToServer thread " + connectionToServer);
|
||||
this.connectionToServerThread.start();
|
||||
|
||||
this.connectionToServerControllerThread = new Thread(connectionToServerController,"ServerConnection()->ConnectionToServerController thread " + connectionToServerController);
|
||||
this.connectionToServerControllerThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes connection message related routes from the router.
|
||||
* This is called after the client-server connection is properly established, so that any future (erroneous) connection messages get ignored.
|
||||
*/
|
||||
private void removeConnectionRoutes() {
|
||||
this.messageRouter.removeRoute(MessageType.JOIN_ACCEPTANCE);
|
||||
this.messageRouter.removeRoute(MessageType.REQUEST_TO_JOIN);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the {@link #messageSerialiser} and starts its thread.
|
||||
* @param socket The socket to write to.
|
||||
* @throws IOException Thrown if we cannot get an outputStream from the socket
|
||||
*/
|
||||
private void createMessageSerialiser(Socket socket) throws IOException {
|
||||
BlockingQueue<AC35Data> outputQueue = new LinkedBlockingQueue<>();
|
||||
this.messageSerialiser = new MessageSerialiser(socket.getOutputStream(), outputQueue);
|
||||
|
||||
this.messageSerialiserThread = new Thread(messageSerialiser, "ServerConnection()->MessageSerialiser thread " + messageSerialiser);
|
||||
this.messageSerialiserThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the {@link #messageDeserialiser} and starts its thread.
|
||||
* @param socket The socket to read from.
|
||||
* @throws IOException Thrown if we cannot get an inputStream from the socket
|
||||
*/
|
||||
private void createMessageDeserialiser(Socket socket) throws IOException {
|
||||
BlockingQueue<AC35Data> inputQueue = new LinkedBlockingQueue<>();
|
||||
this.messageDeserialiser = new MessageDeserialiser(socket.getInputStream(), inputQueue);
|
||||
|
||||
this.messageDeserialiserThread = new Thread(messageDeserialiser, "ServerConnection()->MessageDeserialiser thread " + messageDeserialiser);
|
||||
this.messageDeserialiserThread.start();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the {@link #heartBeatService} and {@link #heartBeatController} and starts their threads.
|
||||
*/
|
||||
private void createHeartBeatService() {
|
||||
|
||||
//IncomingHeartBeatService executes these commands.
|
||||
BlockingQueue<Command> commands = new LinkedBlockingQueue<>();
|
||||
this.heartBeatService = new IncomingHeartBeatService(commands);
|
||||
|
||||
//IncomingHeartBeatController receives messages, and places commands on the above command queue.
|
||||
BlockingQueue<AC35Data> incomingHeartBeatMessages = new LinkedBlockingQueue<>();
|
||||
this.heartBeatController = new IncomingHeartBeatController(incomingHeartBeatMessages, heartBeatService, commands);
|
||||
|
||||
//Route HeartBeat messages to the controller.
|
||||
this.messageRouter.addRoute(MessageType.HEARTBEAT, incomingHeartBeatMessages);
|
||||
|
||||
|
||||
//Start the above on new threads.
|
||||
this.heartBeatServiceThread = new Thread(heartBeatService, "ServerConnection()->IncomingHeartBeatService thread " + connectionToServer);
|
||||
this.heartBeatServiceThread.start();
|
||||
|
||||
this.heartBeatControllerThread = new Thread(heartBeatController,"ServerConnection()->IncomingHeartBeatController thread " + connectionToServerController);
|
||||
this.heartBeatControllerThread.start();
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the {@link #visualiserRaceController} and starts its thread.
|
||||
*/
|
||||
private void createVisualiserRaceController() {
|
||||
|
||||
|
||||
//VisualiserRaceController receives messages, and places commands on the race's command queue.
|
||||
BlockingQueue<AC35Data> incomingMessages = new LinkedBlockingQueue<>();
|
||||
this.visualiserRaceController = new VisualiserRaceController(incomingMessages, visualiserRaceState, raceCommands);
|
||||
|
||||
|
||||
//Routes.
|
||||
this.messageRouter.addRoute(MessageType.BOATLOCATION, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.RACESTATUS, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.RACESTARTSTATUS, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.AVGWIND, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.COURSEWIND, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.CHATTERTEXT, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.DISPLAYTEXTMESSAGE, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.YACHTACTIONCODE, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.YACHTEVENTCODE, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.MARKROUNDING, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.XMLMESSAGE, incomingMessages);
|
||||
this.messageRouter.addRoute(MessageType.ASSIGN_PLAYER_BOAT, incomingMessages);
|
||||
this.messageRouter.removeDefaultRoute(); //We no longer want to keep un-routed messages.
|
||||
|
||||
|
||||
//Start the above on a new thread.
|
||||
|
||||
this.visualiserRaceControllerThread = new Thread(visualiserRaceController, "ServerConnection()->VisualiserRaceController thread " + visualiserRaceController);
|
||||
this.visualiserRaceControllerThread.start();
|
||||
|
||||
}
|
||||
|
||||
|
||||
//TODO create input controller here. RaceController should query for it, if it exists.
|
||||
private void createPlayerInputController() {
|
||||
|
||||
this.messageRouter.addRoute(MessageType.BOATACTION, messageSerialiser.getMessagesToSend());
|
||||
//TODO routes
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
//Monitor the connection state.
|
||||
|
||||
long previousFrameTime = System.currentTimeMillis();
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
waitForFramePeriod(previousFrameTime, currentFrameTime, 100);
|
||||
previousFrameTime = currentFrameTime;
|
||||
|
||||
|
||||
ConnectionToServerState state = connectionToServer.getConnectionState();
|
||||
|
||||
switch (state) {
|
||||
|
||||
case CONNECTED:
|
||||
connected();
|
||||
break;
|
||||
|
||||
case DECLINED:
|
||||
declined();
|
||||
break;
|
||||
|
||||
case TIMED_OUT:
|
||||
timedOut();
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Called when the {@link #connectionToServer} state changes to {@link ConnectionToServerState#CONNECTED}.
|
||||
*/
|
||||
private void connected() {
|
||||
|
||||
createHeartBeatService();
|
||||
|
||||
createVisualiserRaceController();
|
||||
|
||||
if (connectionToServer.getRequestType() == RequestToJoinEnum.PARTICIPANT) {
|
||||
createPlayerInputController();
|
||||
}
|
||||
|
||||
|
||||
//We no longer want connection messages to be accepted.
|
||||
removeConnectionRoutes();
|
||||
|
||||
|
||||
//We interrupt as this thread's run() isn't needed anymore.
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the {@link #connectionToServer} state changes to {@link ConnectionToServerState#DECLINED}.
|
||||
*/
|
||||
private void declined() {
|
||||
Logger.getGlobal().log(Level.WARNING, "Server handshake failed. Connection was declined.");
|
||||
|
||||
terminate();
|
||||
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the {@link #connectionToServer} state changes to {@link ConnectionToServerState#TIMED_OUT}.
|
||||
*/
|
||||
private void timedOut() {
|
||||
Logger.getGlobal().log(Level.WARNING, "Server handshake failed. Connection timed out.");
|
||||
|
||||
terminate();
|
||||
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether or not this connection is still alive.
|
||||
* This is based off whether the {@link #messageDeserialiser}, {@link #messageSerialiser}, and {@link #heartBeatService} are alive.
|
||||
* @return True if it is alive, false otherwise.
|
||||
*/
|
||||
public boolean isAlive() {
|
||||
return messageDeserialiser.isRunning() && messageSerialiser.isRunning() && heartBeatService.isAlive();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the controller client, which writes BoatAction messages to the outgoing queue.
|
||||
* @return The ControllerClient.
|
||||
*/
|
||||
public ControllerClient getControllerClient() {
|
||||
return controllerClient;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Terminates the connection and any running threads.
|
||||
*/
|
||||
public void terminate() {
|
||||
|
||||
if (this.messageRouterThread != null) {
|
||||
this.messageRouterThread.interrupt();
|
||||
}
|
||||
|
||||
|
||||
if (this.messageSerialiserThread != null) {
|
||||
this.messageSerialiserThread.interrupt();
|
||||
}
|
||||
if (this.messageDeserialiserThread != null) {
|
||||
this.messageDeserialiserThread.interrupt();
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (this.connectionToServerThread != null) {
|
||||
this.connectionToServerThread.interrupt();
|
||||
}
|
||||
if (this.connectionToServerControllerThread != null) {
|
||||
this.connectionToServerControllerThread.interrupt();
|
||||
}
|
||||
|
||||
|
||||
if (this.heartBeatServiceThread != null) {
|
||||
this.heartBeatServiceThread.interrupt();
|
||||
}
|
||||
if (this.heartBeatControllerThread != null) {
|
||||
this.heartBeatControllerThread.interrupt();
|
||||
}
|
||||
|
||||
|
||||
if (this.visualiserRaceControllerThread != null) {
|
||||
this.visualiserRaceControllerThread.interrupt();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//TODO input controller?
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user