WIP. Probably need to cherry pick stuff out of here.
Added ClientConnection and server-side handshake. Added MessageSerialiser and Deserialiser. #story[1095]
This commit is contained in:
@@ -1,21 +1,22 @@
|
||||
package mock.app;
|
||||
|
||||
import mock.enums.ConnectionStateEnum;
|
||||
import mock.model.ClientConnection;
|
||||
import mock.model.SourceIdAllocator;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.Enums.XMLMessageType;
|
||||
import network.Messages.LatestMessages;
|
||||
import network.Messages.RaceSnapshot;
|
||||
import network.Messages.XMLMessage;
|
||||
import org.mockito.Mock;
|
||||
import visualiser.gameController.ControllerServer;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Array;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Connection acceptor for multiple clients
|
||||
@@ -31,10 +32,31 @@ public class ConnectionAcceptor implements Runnable {
|
||||
* Socket used to listen for clients on.
|
||||
*/
|
||||
private ServerSocket serverSocket;
|
||||
//mock outputs
|
||||
private ArrayBlockingQueue<MockOutput> mockOutputList = new ArrayBlockingQueue<>(16, true);
|
||||
//latest messages
|
||||
|
||||
|
||||
/**
|
||||
* List of client connections.
|
||||
*/
|
||||
private ArrayBlockingQueue<ClientConnection> clientConnections = new ArrayBlockingQueue<>(16, true);
|
||||
|
||||
/**
|
||||
* Snapshot of the race.
|
||||
*/
|
||||
private LatestMessages latestMessages;
|
||||
|
||||
/**
|
||||
* Collection of commands from clients for race to execute.
|
||||
*/
|
||||
private CompositeCommand compositeCommand;
|
||||
|
||||
/**
|
||||
* Used to allocate source IDs to clients.
|
||||
*/
|
||||
private SourceIdAllocator sourceIdAllocator;
|
||||
|
||||
|
||||
|
||||
|
||||
//Acknowledgement number for packets
|
||||
private int ackNumber = 0;
|
||||
//race xml sequence number
|
||||
@@ -47,14 +69,20 @@ public class ConnectionAcceptor implements Runnable {
|
||||
/**
|
||||
* Connection Acceptor Constructor
|
||||
* @param latestMessages Latest messages to be sent
|
||||
* @param compositeCommand Collection of commands for race to execute.
|
||||
* @param sourceIdAllocator Object used to allocate source IDs for clients.
|
||||
* @throws IOException if a server socket cannot be instantiated.
|
||||
*/
|
||||
public ConnectionAcceptor(LatestMessages latestMessages) throws IOException {
|
||||
public ConnectionAcceptor(LatestMessages latestMessages, CompositeCommand compositeCommand, SourceIdAllocator sourceIdAllocator) throws IOException {
|
||||
|
||||
this.latestMessages = latestMessages;
|
||||
this.compositeCommand = compositeCommand;
|
||||
this.sourceIdAllocator = sourceIdAllocator;
|
||||
|
||||
this.serverSocket = new ServerSocket(serverPort);
|
||||
CheckClientConnection checkClientConnection = new CheckClientConnection(mockOutputList);
|
||||
CheckClientConnection checkClientConnection = new CheckClientConnection(clientConnections);
|
||||
new Thread(checkClientConnection, "ConnectionAcceptor()->CheckClientConnection thread").start();
|
||||
|
||||
}
|
||||
|
||||
public String getAddress() throws UnknownHostException {
|
||||
@@ -71,28 +99,26 @@ public class ConnectionAcceptor implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while(mockOutputList.remainingCapacity() > 0) {
|
||||
while(clientConnections.remainingCapacity() > 0) {
|
||||
|
||||
try {
|
||||
|
||||
System.out.println("Waiting for a connection...");//TEMP DEBUG REMOVE
|
||||
|
||||
Socket mockSocket = serverSocket.accept();
|
||||
//TODO at this point we need to assign the connection a boat source ID, if they requested to participate.
|
||||
|
||||
DataOutputStream outToVisualiser = new DataOutputStream(mockSocket.getOutputStream());
|
||||
MockOutput mockOutput = new MockOutput(latestMessages, outToVisualiser);
|
||||
ControllerServer controllerServer = new ControllerServer(mockSocket); //TODO probably pass assigned boat source ID into ControllerServer.
|
||||
ClientConnection clientConnection = new ClientConnection(mockSocket, sourceIdAllocator, latestMessages, compositeCommand);
|
||||
|
||||
new Thread(mockOutput, "ConnectionAcceptor.run()->MockOutput thread" + mockOutput).start();
|
||||
new Thread(controllerServer, "ConnectionAcceptor.run()->ControllerServer thread" + controllerServer).start();
|
||||
clientConnections.add(clientConnection);
|
||||
|
||||
mockOutputList.add(mockOutput);
|
||||
new Thread(clientConnection, "ConnectionAcceptor.run()->ClientConnection thread " + clientConnection).start();
|
||||
|
||||
System.out.println(String.format("%d number of Visualisers Connected.", mockOutputList.size()));//TEMP
|
||||
|
||||
|
||||
Logger.getGlobal().log(Level.INFO, String.format("%d number of Visualisers Connected.", clientConnections.size()));
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();//TODO handle this properly
|
||||
Logger.getGlobal().log(Level.WARNING, "Got an IOException while a client was attempting to connect.", e);
|
||||
|
||||
}
|
||||
|
||||
@@ -104,14 +130,14 @@ public class ConnectionAcceptor implements Runnable {
|
||||
*/
|
||||
class CheckClientConnection implements Runnable{
|
||||
|
||||
private ArrayBlockingQueue<MockOutput> mocks;
|
||||
private ArrayBlockingQueue<ClientConnection> connections;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param mocks Mocks "connected"
|
||||
* @param connections Clients "connected"
|
||||
*/
|
||||
public CheckClientConnection(ArrayBlockingQueue<MockOutput> mocks){
|
||||
this.mocks = mocks;
|
||||
public CheckClientConnection(ArrayBlockingQueue<ClientConnection> connections){
|
||||
this.connections = connections;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,21 +145,27 @@ public class ConnectionAcceptor implements Runnable {
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
double timeSinceLastHeartBeat = System.currentTimeMillis();
|
||||
|
||||
while(true) {
|
||||
//System.out.println(mocks.size());//used to see current amount of visualisers connected.
|
||||
ArrayBlockingQueue<MockOutput> m = new ArrayBlockingQueue<>(16, true, mocks);
|
||||
for (MockOutput mo : m) {
|
||||
try {
|
||||
mo.sendHeartBeat();
|
||||
} catch (IOException e) {
|
||||
mocks.remove(mo);
|
||||
//System.out.println(connections.size());//used to see current amount of visualisers connected.
|
||||
ArrayBlockingQueue<ClientConnection> clientConnections = new ArrayBlockingQueue<>(16, true, connections);
|
||||
|
||||
for (ClientConnection client : clientConnections) {
|
||||
if (!client.isAlive()) {
|
||||
connections.remove(client);
|
||||
|
||||
Logger.getGlobal().log(Level.WARNING, "CheckClientConnection is removing the dead connection: " + client);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Logger.getGlobal().log(Level.WARNING, "CheckClientConnection was interrupted while sleeping.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package mock.app;
|
||||
|
||||
import mock.dataInput.PolarParser;
|
||||
import mock.exceptions.EventConstructionException;
|
||||
import mock.model.MockRace;
|
||||
import mock.model.Polars;
|
||||
import mock.model.RaceLogic;
|
||||
import mock.model.SourceIdAllocator;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.LatestMessages;
|
||||
import network.Messages.RaceSnapshot;
|
||||
import shared.dataInput.*;
|
||||
import shared.enums.XMLFileType;
|
||||
import shared.exceptions.InvalidBoatDataException;
|
||||
@@ -19,14 +23,18 @@ import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* A Race Event, this holds all of the race's information as well as handling the connection to its clients.
|
||||
*/
|
||||
public class Event {
|
||||
private static Event theEvent = new Event();
|
||||
|
||||
/**
|
||||
* Contents of the various xml files.
|
||||
*/
|
||||
private String raceXML;
|
||||
private String regattaXML;
|
||||
private String boatXML;
|
||||
@@ -35,36 +43,75 @@ public class Event {
|
||||
|
||||
private Polars boatPolars;
|
||||
|
||||
/**
|
||||
* Data sources containing data from the xml files.
|
||||
*/
|
||||
RaceDataSource raceDataSource;
|
||||
BoatDataSource boatDataSource;
|
||||
RegattaDataSource regattaDataSource;
|
||||
|
||||
|
||||
private ConnectionAcceptor connectionAcceptor;
|
||||
private LatestMessages latestMessages;
|
||||
|
||||
private CompositeCommand compositeCommand;
|
||||
|
||||
/**
|
||||
* This is used to allocate source IDs.
|
||||
*/
|
||||
private SourceIdAllocator sourceIdAllocator;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs an event, using various XML files.
|
||||
* @throws EventConstructionException Thrown if we cannot create an Event for any reason.
|
||||
*/
|
||||
private Event() {
|
||||
public Event() throws EventConstructionException {
|
||||
|
||||
//Read XML files.
|
||||
try {
|
||||
this.raceXML = getRaceXMLAtCurrentTime(XMLReader.readXMLFileToString("mock/mockXML/raceTest.xml", StandardCharsets.UTF_8));
|
||||
this.boatXML = XMLReader.readXMLFileToString("mock/mockXML/boatsSinglePlayer.xml", StandardCharsets.UTF_8);
|
||||
this.regattaXML = XMLReader.readXMLFileToString("mock/mockXML/regattaTest.xml", StandardCharsets.UTF_8);
|
||||
this.xmlFileType = XMLFileType.Contents;
|
||||
|
||||
this.boatPolars = PolarParser.parse("mock/polars/acc_polars.csv");
|
||||
|
||||
this.latestMessages = new LatestMessages();
|
||||
this.connectionAcceptor = new ConnectionAcceptor(latestMessages);
|
||||
} catch (TransformerException | XMLReaderException e) {
|
||||
throw new EventConstructionException("Could not read XML files.", e);
|
||||
}
|
||||
catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (XMLReaderException e) {
|
||||
e.printStackTrace();
|
||||
} catch (TransformerException e) {
|
||||
e.printStackTrace();
|
||||
|
||||
this.xmlFileType = XMLFileType.Contents;
|
||||
|
||||
this.boatPolars = PolarParser.parse("mock/polars/acc_polars.csv");
|
||||
|
||||
|
||||
//Parse the XML files into data sources.
|
||||
try {
|
||||
this.raceDataSource = new RaceXMLReader(this.raceXML, this.xmlFileType);
|
||||
this.boatDataSource = new BoatXMLReader(this.boatXML, this.xmlFileType);
|
||||
this.regattaDataSource = new RegattaXMLReader(this.regattaXML, this.xmlFileType);
|
||||
|
||||
|
||||
} catch (XMLReaderException | InvalidRaceDataException | InvalidRegattaDataException | InvalidBoatDataException e) {
|
||||
throw new EventConstructionException("Could not parse XML files.", e);
|
||||
|
||||
}
|
||||
|
||||
//Create connection acceptor.
|
||||
this.sourceIdAllocator = new SourceIdAllocator(raceDataSource.getParticipants());
|
||||
this.compositeCommand = new CompositeCommand();
|
||||
this.latestMessages = new LatestMessages();
|
||||
|
||||
try {
|
||||
this.connectionAcceptor = new ConnectionAcceptor(latestMessages, compositeCommand, sourceIdAllocator);
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new EventConstructionException("Could not create ConnectionAcceptor.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Event getEvent() {
|
||||
return theEvent;
|
||||
}
|
||||
|
||||
|
||||
public String getAddress() throws UnknownHostException {
|
||||
return connectionAcceptor.getAddress();
|
||||
@@ -76,23 +123,16 @@ public class Event {
|
||||
|
||||
/**
|
||||
* Sends the initial race data and then begins race simulation.
|
||||
* @throws InvalidRaceDataException Thrown if the race xml file cannot be parsed.
|
||||
* @throws XMLReaderException Thrown if any of the xml files cannot be parsed.
|
||||
* @throws InvalidBoatDataException Thrown if the boat xml file cannot be parsed.
|
||||
* @throws InvalidRegattaDataException Thrown if the regatta xml file cannot be parsed.
|
||||
*/
|
||||
public void start() throws InvalidRaceDataException, XMLReaderException, InvalidBoatDataException, InvalidRegattaDataException {
|
||||
public void start() {
|
||||
new Thread(connectionAcceptor, "Event.Start()->ConnectionAcceptor thread").start();
|
||||
|
||||
sendXMLs();
|
||||
|
||||
//Parse the XML files into data sources.
|
||||
RaceDataSource raceDataSource = new RaceXMLReader(this.raceXML, this.xmlFileType);
|
||||
BoatDataSource boatDataSource = new BoatXMLReader(this.boatXML, this.xmlFileType);
|
||||
RegattaDataSource regattaDataSource = new RegattaXMLReader(this.regattaXML, this.xmlFileType);
|
||||
|
||||
|
||||
//Create and start race.
|
||||
RaceLogic newRace = new RaceLogic(new MockRace(boatDataSource, raceDataSource, regattaDataSource, this.latestMessages, this.boatPolars, Constants.RaceTimeScale), this.latestMessages);
|
||||
RaceLogic newRace = new RaceLogic(new MockRace(boatDataSource, raceDataSource, regattaDataSource, this.latestMessages, this.boatPolars, Constants.RaceTimeScale), this.latestMessages, this.compositeCommand);
|
||||
|
||||
new Thread(newRace, "Event.Start()->RaceLogic thread").start();
|
||||
}
|
||||
|
||||
@@ -2,37 +2,25 @@ package mock.app;
|
||||
|
||||
|
||||
|
||||
import network.BinaryMessageEncoder;
|
||||
import network.Exceptions.InvalidMessageException;
|
||||
import network.MessageEncoders.RaceVisionByteEncoder;
|
||||
import network.Messages.*;
|
||||
import network.Messages.Enums.MessageType;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* TCP server to send race information to connected clients.
|
||||
*/
|
||||
public class MockOutput implements Runnable
|
||||
{
|
||||
/**
|
||||
* Timestamp of the last sent heartbeat message.
|
||||
*/
|
||||
private long lastHeartbeatTime;
|
||||
public class MockOutput implements RunnableWithFramePeriod {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Period for the heartbeat - that is, how often we send it.
|
||||
* A queue to send messages to client.
|
||||
*/
|
||||
private double heartbeatPeriod = 5.0;
|
||||
|
||||
/**
|
||||
* Output stream which wraps around mockSocket outstream.
|
||||
*/
|
||||
private DataOutputStream outToVisualiser;
|
||||
private BlockingQueue<AC35Data> outgoingMessages;
|
||||
|
||||
|
||||
/**
|
||||
@@ -43,186 +31,20 @@ public class MockOutput implements Runnable
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Ack numbers used in messages.
|
||||
*/
|
||||
private int ackNumber = 1;
|
||||
|
||||
/**
|
||||
* Sequence number for heartbeat messages.
|
||||
*/
|
||||
private int heartbeatSequenceNum = 1;
|
||||
|
||||
|
||||
/**
|
||||
* Ctor.
|
||||
* @param latestMessages Latests Messages that the Mock is to send out
|
||||
* @param outToVisualiser DataStream to output to Visualisers
|
||||
* @throws IOException if server socket cannot be opened.
|
||||
* @param latestMessages Latest Messages that the Mock is to send out
|
||||
* @param outgoingMessages A queue to place outgoing messages on.
|
||||
*/
|
||||
public MockOutput(LatestMessages latestMessages, DataOutputStream outToVisualiser) throws IOException {
|
||||
|
||||
this.outToVisualiser = outToVisualiser;
|
||||
|
||||
this.lastHeartbeatTime = System.currentTimeMillis();
|
||||
|
||||
public MockOutput(LatestMessages latestMessages, BlockingQueue<AC35Data> outgoingMessages) {
|
||||
this.outgoingMessages = outgoingMessages;
|
||||
this.latestMessages = latestMessages;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Increments the ackNumber value, and returns it.
|
||||
* @return Incremented ackNumber.
|
||||
*/
|
||||
private int getNextAckNumber(){
|
||||
this.ackNumber++;
|
||||
|
||||
return this.ackNumber;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Calculates the time since last heartbeat message, in seconds.
|
||||
* @return Time since last heartbeat message, in seconds.
|
||||
*/
|
||||
private double timeSinceHeartbeat() {
|
||||
long now = System.currentTimeMillis();
|
||||
return (now - lastHeartbeatTime) / 1000.0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
|
||||
* @return The next heartbeat message.
|
||||
*/
|
||||
private HeartBeat createHeartbeatMessage() {
|
||||
|
||||
//Create the heartbeat message.
|
||||
HeartBeat heartBeat = new HeartBeat(this.heartbeatSequenceNum);
|
||||
heartbeatSequenceNum++;
|
||||
|
||||
return heartBeat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a heartbeat message into a packet to be sent, and returns the byte array.
|
||||
* @param heartBeat The heartbeat message to serialize.
|
||||
* @return Byte array containing the next heartbeat message.
|
||||
* @throws InvalidMessageException Thrown if the message cannot be encoded.
|
||||
*/
|
||||
private byte[] parseHeartbeat(HeartBeat heartBeat) throws InvalidMessageException {
|
||||
|
||||
//Serializes the heartbeat message.
|
||||
byte[] heartbeatMessage = RaceVisionByteEncoder.encode(heartBeat);
|
||||
|
||||
//Places the serialized message in a packet.
|
||||
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
|
||||
MessageType.HEARTBEAT,
|
||||
System.currentTimeMillis(),
|
||||
getNextAckNumber(),
|
||||
(short) heartbeatMessage.length,
|
||||
heartbeatMessage );
|
||||
|
||||
return binaryMessageEncoder.getFullMessage();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes/serialises a XMLMessage message, and returns it.
|
||||
* @param xmlMessage The XMLMessage message to serialise.
|
||||
* @return The XMLMessage message in a serialised form.
|
||||
* @throws InvalidMessageException Thrown if the message cannot be encoded.
|
||||
*/
|
||||
private synchronized byte[] parseXMLMessage(XMLMessage xmlMessage) throws InvalidMessageException {
|
||||
|
||||
//Serialize the xml message.
|
||||
byte[] encodedXML = RaceVisionByteEncoder.encode(xmlMessage);
|
||||
|
||||
//Place the message in a packet.
|
||||
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
|
||||
MessageType.XMLMESSAGE,
|
||||
System.currentTimeMillis(),
|
||||
xmlMessage.getAckNumber(), //We use the ack number from the xml message.
|
||||
(short) encodedXML.length,
|
||||
encodedXML );
|
||||
|
||||
|
||||
return binaryMessageEncoder.getFullMessage();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes/serialises a BoatLocation message, and returns it.
|
||||
* @param boatLocation The BoatLocation message to serialise.
|
||||
* @return The BoatLocation message in a serialised form.
|
||||
* @throws InvalidMessageException If the message cannot be encoded.
|
||||
*/
|
||||
private synchronized byte[] parseBoatLocation(BoatLocation boatLocation) throws InvalidMessageException {
|
||||
|
||||
|
||||
//Encodes the message.
|
||||
byte[] encodedBoatLoc = RaceVisionByteEncoder.encode(boatLocation);
|
||||
|
||||
//Encodes the full message with header.
|
||||
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
|
||||
MessageType.BOATLOCATION,
|
||||
System.currentTimeMillis(),
|
||||
getNextAckNumber(),
|
||||
(short) encodedBoatLoc.length,
|
||||
encodedBoatLoc );
|
||||
|
||||
|
||||
return binaryMessageEncoder.getFullMessage();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes/serialises a RaceStatus message, and returns it.
|
||||
* @param raceStatus The RaceStatus message to serialise.
|
||||
* @return The RaceStatus message in a serialised form.
|
||||
* @throws InvalidMessageException Thrown if the message cannot be encoded.
|
||||
*/
|
||||
private synchronized byte[] parseRaceStatus(RaceStatus raceStatus) throws InvalidMessageException {
|
||||
|
||||
//Encodes the messages.
|
||||
byte[] encodedRaceStatus = RaceVisionByteEncoder.encode(raceStatus);
|
||||
|
||||
//Encodes the full message with header.
|
||||
BinaryMessageEncoder binaryMessageEncoder = new BinaryMessageEncoder(
|
||||
MessageType.RACESTATUS,
|
||||
System.currentTimeMillis(),
|
||||
getNextAckNumber(),
|
||||
(short) encodedRaceStatus.length,
|
||||
encodedRaceStatus );
|
||||
|
||||
|
||||
return binaryMessageEncoder.getFullMessage();
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a heartbeat
|
||||
* @throws IOException if the socket is no longer open at both ends the heartbeat returns an error.
|
||||
*/
|
||||
public void sendHeartBeat() throws IOException {
|
||||
//Sends a heartbeat every so often.
|
||||
if (timeSinceHeartbeat() >= heartbeatPeriod) {
|
||||
|
||||
HeartBeat heartBeat = createHeartbeatMessage();
|
||||
|
||||
try {
|
||||
outToVisualiser.write(parseHeartbeat(heartBeat));
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not encode HeartBeat: " + heartBeat, e);
|
||||
}
|
||||
|
||||
lastHeartbeatTime = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sending loop of the Server
|
||||
@@ -251,107 +73,40 @@ public class MockOutput implements Runnable
|
||||
long previousFrameTime = System.currentTimeMillis();
|
||||
boolean sentXMLs = false;
|
||||
|
||||
try {
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
try {
|
||||
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
|
||||
//This is the time elapsed, in milliseconds, since the last server "frame".
|
||||
long framePeriod = currentFrameTime - previousFrameTime;
|
||||
|
||||
//We only attempt to send packets every X milliseconds.
|
||||
long minimumFramePeriod = 16;
|
||||
if (framePeriod >= minimumFramePeriod) {
|
||||
|
||||
//Send XML messages.
|
||||
if (!sentXMLs) {
|
||||
//Serialise them.
|
||||
|
||||
try {
|
||||
byte[] raceXMLBlob = parseXMLMessage(latestMessages.getRaceXMLMessage());
|
||||
byte[] regattaXMLBlob = parseXMLMessage(latestMessages.getRegattaXMLMessage());
|
||||
byte[] boatsXMLBlob = parseXMLMessage(latestMessages.getBoatXMLMessage());
|
||||
|
||||
//Send them.
|
||||
outToVisualiser.write(raceXMLBlob);
|
||||
outToVisualiser.write(regattaXMLBlob);
|
||||
outToVisualiser.write(boatsXMLBlob);
|
||||
sentXMLs = true;
|
||||
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not encode XMLMessage: " + latestMessages.getRaceXMLMessage(), e);
|
||||
continue; //Go to next iteration.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Sends the RaceStatus message.
|
||||
if (this.latestMessages.getRaceStatus() != null) {
|
||||
|
||||
try {
|
||||
byte[] raceStatusBlob = this.parseRaceStatus(this.latestMessages.getRaceStatus());
|
||||
|
||||
this.outToVisualiser.write(raceStatusBlob);
|
||||
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not encode RaceStatus: " + latestMessages.getRaceStatus(), e);
|
||||
}
|
||||
}
|
||||
|
||||
//Send all of the BoatLocation messages.
|
||||
for (int sourceID : this.latestMessages.getBoatLocationMap().keySet()) {
|
||||
|
||||
//Get the message.
|
||||
BoatLocation boatLocation = this.latestMessages.getBoatLocation(sourceID);
|
||||
if (boatLocation != null) {
|
||||
|
||||
|
||||
try {
|
||||
//Encode.
|
||||
byte[] boatLocationBlob = this.parseBoatLocation(boatLocation);
|
||||
while (!Thread.interrupted()) {
|
||||
|
||||
//Write it.
|
||||
this.outToVisualiser.write(boatLocationBlob);
|
||||
try {
|
||||
|
||||
} catch (InvalidMessageException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Could not encode BoatLocation: " + boatLocation, e);
|
||||
}
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
waitForFramePeriod(previousFrameTime, currentFrameTime, 16);
|
||||
previousFrameTime = currentFrameTime;
|
||||
|
||||
|
||||
//Send XML messages.
|
||||
if (!sentXMLs) {
|
||||
|
||||
}
|
||||
}
|
||||
outgoingMessages.put(latestMessages.getRaceXMLMessage());
|
||||
outgoingMessages.put(latestMessages.getRegattaXMLMessage());
|
||||
outgoingMessages.put(latestMessages.getBoatXMLMessage());
|
||||
|
||||
previousFrameTime = currentFrameTime;
|
||||
|
||||
|
||||
} else {
|
||||
//Wait until the frame period will be large enough.
|
||||
long timeToWait = minimumFramePeriod - framePeriod;
|
||||
|
||||
try {
|
||||
Thread.sleep(timeToWait);
|
||||
} catch (InterruptedException e) {
|
||||
//If we get interrupted, exit the function.
|
||||
Logger.getGlobal().log(Level.WARNING, "MockOutput.run().sleep(framePeriod) was interrupted on thread: " + Thread.currentThread(), e);
|
||||
//Re-set the interrupt flag.
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} catch (SocketException e) {
|
||||
break;
|
||||
sentXMLs = true;
|
||||
}
|
||||
|
||||
List<AC35Data> snapshot = latestMessages.getSnapshot();
|
||||
for (AC35Data message : snapshot) {
|
||||
outgoingMessages.put(message);
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "MockOutput.run() interrupted while putting message in queue.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package mock.enums;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The states in which a connection to a client may have.
|
||||
*/
|
||||
public enum ConnectionStateEnum {
|
||||
|
||||
UNKNOWN(0),
|
||||
|
||||
/**
|
||||
* We're waiting for the client to complete the joining handshake (see {@link network.Messages.RequestToJoin}.
|
||||
*/
|
||||
WAITING_FOR_HANDSHAKE(1),
|
||||
|
||||
/**
|
||||
* The client has completed the handshake, and is connected.
|
||||
*/
|
||||
CONNECTED(2),
|
||||
|
||||
/**
|
||||
* The client has timed out.
|
||||
*/
|
||||
TIMED_OUT(3);
|
||||
|
||||
|
||||
|
||||
|
||||
private byte value;
|
||||
|
||||
/**
|
||||
* Ctor. Creates a ConnectionStateEnum from a given primitive integer value, cast to a byte.
|
||||
* @param value Integer, which is cast to byte, to construct from.
|
||||
*/
|
||||
private ConnectionStateEnum(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 ConnectionStateEnum values.
|
||||
*/
|
||||
private static final Map<Byte, ConnectionStateEnum> byteToStatusMap = new HashMap<>();
|
||||
|
||||
|
||||
/*
|
||||
Static initialization block. Initializes the byteToStatusMap.
|
||||
*/
|
||||
static {
|
||||
for (ConnectionStateEnum type : ConnectionStateEnum.values()) {
|
||||
ConnectionStateEnum.byteToStatusMap.put(type.value, type);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the enumeration value which corresponds to a given byte value.
|
||||
* @param connectionState Byte value to convert to a ConnectionStateEnum value.
|
||||
* @return The ConnectionStateEnum value which corresponds to the given byte value.
|
||||
*/
|
||||
public static ConnectionStateEnum fromByte(byte connectionState) {
|
||||
//Gets the corresponding MessageType from the map.
|
||||
ConnectionStateEnum type = ConnectionStateEnum.byteToStatusMap.get(connectionState);
|
||||
|
||||
if (type == null) {
|
||||
//If the byte value wasn't found, return the UNKNOWN connectionState.
|
||||
return ConnectionStateEnum.UNKNOWN;
|
||||
} else {
|
||||
//Otherwise, return the connectionState.
|
||||
return type;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mock.exceptions;
|
||||
|
||||
/**
|
||||
* An exception thrown when we cannot create an {@link mock.app.Event}.
|
||||
*/
|
||||
public class EventConstructionException extends Exception {
|
||||
|
||||
/**
|
||||
* Constructs the exception with a given message.
|
||||
* @param message Message to store.
|
||||
*/
|
||||
public EventConstructionException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the exception with a given message and cause.
|
||||
* @param message Message to store.
|
||||
* @param cause Cause to store.
|
||||
*/
|
||||
public EventConstructionException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mock.exceptions;
|
||||
|
||||
/**
|
||||
* An exception thrown when we cannot allocate a source ID.
|
||||
*/
|
||||
public class SourceIDAllocationException extends Exception {
|
||||
|
||||
/**
|
||||
* Constructs the exception with a given message.
|
||||
* @param message Message to store.
|
||||
*/
|
||||
public SourceIDAllocationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the exception with a given message and cause.
|
||||
* @param message Message to store.
|
||||
* @param cause Cause to store.
|
||||
*/
|
||||
public SourceIDAllocationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package mock.model;
|
||||
|
||||
|
||||
import mock.app.MockOutput;
|
||||
import mock.enums.ConnectionStateEnum;
|
||||
import shared.exceptions.HandshakeException;
|
||||
import mock.exceptions.SourceIDAllocationException;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.*;
|
||||
import network.Messages.Enums.JoinAcceptanceEnum;
|
||||
import network.Messages.Enums.MessageType;
|
||||
import network.Messages.Enums.RequestToJoinEnum;
|
||||
import network.StreamRelated.MessageDeserialiser;
|
||||
import network.StreamRelated.MessageSerialiser;
|
||||
import visualiser.gameController.ControllerServer;
|
||||
|
||||
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 connection handshake, and creation of MockOutput and ControllerServer.
|
||||
*/
|
||||
public class ClientConnection implements Runnable {
|
||||
|
||||
/**
|
||||
* The socket for the client's connection.
|
||||
*/
|
||||
private Socket socket;
|
||||
|
||||
/**
|
||||
* Periodically sends HeartBeat messages to client.
|
||||
*/
|
||||
private HeartBeatService heartBeatService;
|
||||
|
||||
|
||||
/**
|
||||
* Used to allocate source ID to client, if they request to participate.
|
||||
*/
|
||||
private SourceIdAllocator sourceIdAllocator;
|
||||
|
||||
/**
|
||||
* Latest snapshot of the race, to send to client. Currently only used for XML messages.
|
||||
*/
|
||||
private LatestMessages latestMessages;
|
||||
|
||||
|
||||
/**
|
||||
* Collection of commands from client for race to execute.
|
||||
*/
|
||||
private CompositeCommand compositeCommand;
|
||||
|
||||
/**
|
||||
* Used to send the race snapshot to client.
|
||||
*/
|
||||
private MockOutput mockOutput;
|
||||
|
||||
/**
|
||||
* Used to receive client input, and turn it into commands.
|
||||
*/
|
||||
private ControllerServer controllerServer;
|
||||
|
||||
|
||||
/**
|
||||
* Used to write messages to socket.
|
||||
*/
|
||||
private MessageSerialiser messageSerialiser;
|
||||
|
||||
/**
|
||||
* Stores messages to write to socket.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> outputQueue;
|
||||
|
||||
/**
|
||||
* Used to read messages from socket.
|
||||
*/
|
||||
private MessageDeserialiser messageDeserialiser;
|
||||
|
||||
/**
|
||||
* Stores messages read from socket.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> inputQueue;
|
||||
|
||||
/**
|
||||
* The state of the connection to the client.
|
||||
*/
|
||||
private ConnectionStateEnum connectionState = ConnectionStateEnum.UNKNOWN;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a client connection, using a given socket.
|
||||
* @param socket The socket which connects to the client.
|
||||
* @param sourceIdAllocator Used to allocate a source ID for the client.
|
||||
* @param latestMessages Latest race snapshot to send to client.
|
||||
* @param compositeCommand Collection of commands for race to execute.
|
||||
* @throws IOException Thrown if there is a problem with the client socket.
|
||||
*/
|
||||
public ClientConnection(Socket socket, SourceIdAllocator sourceIdAllocator, LatestMessages latestMessages, CompositeCommand compositeCommand) throws IOException {
|
||||
this.socket = socket;
|
||||
this.sourceIdAllocator = sourceIdAllocator;
|
||||
this.latestMessages = latestMessages;
|
||||
this.compositeCommand = compositeCommand;
|
||||
|
||||
this.outputQueue = new LinkedBlockingQueue<>();
|
||||
this.inputQueue = new LinkedBlockingQueue<>();
|
||||
|
||||
|
||||
this.messageSerialiser = new MessageSerialiser(socket.getOutputStream(), outputQueue);
|
||||
this.messageDeserialiser = new MessageDeserialiser(socket.getInputStream(), inputQueue);
|
||||
|
||||
new Thread(messageSerialiser, "ClientConnection()->MessageSerialiser thread " + messageSerialiser).start();
|
||||
new Thread(messageDeserialiser, "ClientConnection()->MessageDeserialiser thread " + messageDeserialiser).start();
|
||||
|
||||
|
||||
this.heartBeatService = new HeartBeatService(outputQueue);
|
||||
new Thread(heartBeatService, "ClientConnection()->HeartBeatService thread " + heartBeatService).start();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
handshake();
|
||||
|
||||
} catch (HandshakeException | SourceIDAllocationException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "Client handshake failed.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Initiates the handshake with the client.
|
||||
* @throws HandshakeException Thrown if something goes wrong with the handshake.
|
||||
* @throws SourceIDAllocationException Thrown if we cannot allocate a sourceID.
|
||||
*/
|
||||
private void handshake() throws SourceIDAllocationException, HandshakeException {
|
||||
|
||||
//This function is a bit messy, and could probably be refactored a bit.
|
||||
|
||||
connectionState = ConnectionStateEnum.WAITING_FOR_HANDSHAKE;
|
||||
|
||||
|
||||
|
||||
RequestToJoin requestToJoin = waitForRequestToJoin();
|
||||
|
||||
int allocatedSourceID = 0;
|
||||
|
||||
//If they want to participate, give them a source ID number.
|
||||
if (requestToJoin.getRequestType() == RequestToJoinEnum.PARTICIPANT) {
|
||||
|
||||
allocatedSourceID = sourceIdAllocator.allocateSourceID();
|
||||
|
||||
this.controllerServer = new ControllerServer(compositeCommand, inputQueue, allocatedSourceID);
|
||||
new Thread(controllerServer, "ClientConnection.run()->ControllerServer thread" + controllerServer).start();
|
||||
|
||||
}
|
||||
|
||||
this.mockOutput = new MockOutput(latestMessages, outputQueue);
|
||||
new Thread(mockOutput, "ClientConnection.run()->MockOutput thread" + mockOutput).start();
|
||||
|
||||
sendJoinAcceptanceMessage(allocatedSourceID);
|
||||
|
||||
connectionState = ConnectionStateEnum.CONNECTED;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Waits until the client sends a {@link RequestToJoin} message, and returns it.
|
||||
* @return The {@link RequestToJoin} message.
|
||||
* @throws HandshakeException Thrown if we get interrupted while waiting.
|
||||
*/
|
||||
private RequestToJoin waitForRequestToJoin() throws HandshakeException {
|
||||
|
||||
try {
|
||||
|
||||
|
||||
while (connectionState == ConnectionStateEnum.WAITING_FOR_HANDSHAKE) {
|
||||
|
||||
AC35Data message = inputQueue.take();
|
||||
|
||||
//We need to wait until they actually send a join request.
|
||||
if (message.getType() == MessageType.REQUEST_TO_JOIN) {
|
||||
return (RequestToJoin) message;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " was interrupted while waiting on the incoming message queue.", e);
|
||||
|
||||
}
|
||||
|
||||
|
||||
throw new HandshakeException("Handshake was cancelled. Connection state is now: " + connectionState);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends the client a {@link JoinAcceptance} message, containing their assigned sourceID.
|
||||
* @param sourceID The sourceID to assign to client.
|
||||
* @throws HandshakeException Thrown if the thread is interrupted while placing message on the outgoing message queue.
|
||||
*/
|
||||
private void sendJoinAcceptanceMessage(int sourceID) throws HandshakeException {
|
||||
|
||||
//Send them the source ID.
|
||||
JoinAcceptance joinAcceptance = new JoinAcceptance(JoinAcceptanceEnum.JOIN_SUCCESSFUL, sourceID);
|
||||
|
||||
try {
|
||||
outputQueue.put(joinAcceptance);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " interrupted while placing JoinAcceptance message on outgoing message queue.", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether or not this connection is still alive.
|
||||
* This is based off whether the {@link MessageSerialiser} is still alive.
|
||||
* @return True if it is alive, false otherwise.
|
||||
*/
|
||||
public boolean isAlive() {
|
||||
return messageSerialiser.isRunning();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package mock.model;
|
||||
|
||||
import network.Messages.AC35Data;
|
||||
import network.Messages.HeartBeat;
|
||||
import shared.model.RunnableWithFramePeriod;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* This class is responsible for sending {@link HeartBeat} messages to queue.
|
||||
*/
|
||||
public class HeartBeatService implements RunnableWithFramePeriod {
|
||||
|
||||
/**
|
||||
* Timestamp of the last sent heartbeat message.
|
||||
*/
|
||||
private long lastHeartbeatTime;
|
||||
|
||||
/**
|
||||
* Period for the heartbeat - that is, how often we send it. Milliseconds.
|
||||
*/
|
||||
private long heartbeatPeriod = 5000;
|
||||
|
||||
|
||||
/**
|
||||
* The messages we're writing to the stream.
|
||||
*/
|
||||
private BlockingQueue<AC35Data> messagesToSend;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sequence number for heartbeat messages.
|
||||
*/
|
||||
private int heartbeatSequenceNum = 1;
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a new HeartBeatService to send heartBeat messages to a given outputStream.
|
||||
* @param messagesToSend The queue to send heartBeat messages to.
|
||||
*/
|
||||
public HeartBeatService(BlockingQueue<AC35Data> messagesToSend) {
|
||||
this.messagesToSend = messagesToSend;
|
||||
this.lastHeartbeatTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Increments the {@link #heartbeatSequenceNum} value, and returns it.
|
||||
* @return Incremented heat beat number.
|
||||
*/
|
||||
private int getNextHeartBeatNumber(){
|
||||
this.heartbeatSequenceNum++;
|
||||
|
||||
return this.heartbeatSequenceNum;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
|
||||
* @return The next heartbeat message.
|
||||
*/
|
||||
private HeartBeat createHeartbeatMessage() {
|
||||
|
||||
HeartBeat heartBeat = new HeartBeat(getNextHeartBeatNumber());
|
||||
|
||||
return heartBeat;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Puts a HeartBeat message on the message queue.
|
||||
* @throws InterruptedException Thrown if the thread is interrupted.
|
||||
*/
|
||||
private void sendHeartBeat() throws InterruptedException {
|
||||
|
||||
HeartBeat heartBeat = createHeartbeatMessage();
|
||||
|
||||
messagesToSend.put(heartBeat);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (!Thread.interrupted()) {
|
||||
long currentFrameTime = System.currentTimeMillis();
|
||||
waitForFramePeriod(lastHeartbeatTime, currentFrameTime, heartbeatPeriod);
|
||||
lastHeartbeatTime = currentFrameTime;
|
||||
|
||||
try {
|
||||
sendHeartBeat();
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Logger.getGlobal().log(Level.WARNING, "HeartBeatService: " + this + " sendHeartBeat() was interrupted on thread: " + Thread.currentThread(), e);
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import shared.dataInput.BoatDataSource;
|
||||
import shared.dataInput.RaceDataSource;
|
||||
import network.Messages.Enums.RaceStatusEnum;
|
||||
import shared.dataInput.RegattaDataSource;
|
||||
import shared.exceptions.BoatNotFoundException;
|
||||
import shared.model.*;
|
||||
import shared.model.Bearing;
|
||||
|
||||
@@ -411,6 +412,25 @@ public class MockRace extends Race {
|
||||
return boats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a boat by sourceID.
|
||||
* @param sourceID The source ID the boat.
|
||||
* @return The boat.
|
||||
* @throws BoatNotFoundException Thrown if there is not boat with the specified sourceID.
|
||||
*/
|
||||
public MockBoat getBoat(int sourceID) throws BoatNotFoundException {
|
||||
|
||||
for (MockBoat boat : boats) {
|
||||
|
||||
if (boat.getSourceID() == sourceID) {
|
||||
return boat;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
throw new BoatNotFoundException("Boat with sourceID: " + sourceID + " was not found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the wind direction randomly, while keeping it within [windLowerBound, windUpperBound].
|
||||
*/
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package mock.model;
|
||||
|
||||
import javafx.animation.AnimationTimer;
|
||||
import mock.model.commandFactory.CompositeCommand;
|
||||
import network.Messages.Enums.BoatStatusEnum;
|
||||
import network.Messages.Enums.RaceStatusEnum;
|
||||
import network.Messages.LatestMessages;
|
||||
import shared.model.Race;
|
||||
|
||||
|
||||
|
||||
public class RaceLogic implements Runnable {
|
||||
|
||||
/**
|
||||
* State of current race modified by this object
|
||||
*/
|
||||
@@ -16,14 +19,18 @@ public class RaceLogic implements Runnable {
|
||||
*/
|
||||
private RaceServer server;
|
||||
|
||||
private CompositeCommand commands;
|
||||
|
||||
/**
|
||||
* Initialises race loop with state and server message queue
|
||||
* @param race state of race to modify
|
||||
* @param messages to send to server
|
||||
* @param compositeCommand Commands from clients to execute.
|
||||
*/
|
||||
public RaceLogic(MockRace race, LatestMessages messages) {
|
||||
public RaceLogic(MockRace race, LatestMessages messages, CompositeCommand compositeCommand) {
|
||||
this.race = race;
|
||||
this.server = new RaceServer(race, messages);
|
||||
this.commands = compositeCommand;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,17 +63,13 @@ public class RaceLogic implements Runnable {
|
||||
//Provide boat's with an estimated time at next mark until the race starts.
|
||||
race.setBoatsTimeNextMark(race.getRaceClock().getCurrentTime());
|
||||
|
||||
//Parse the boat locations.
|
||||
server.parseBoatLocations();
|
||||
|
||||
//Parse the marks.
|
||||
server.parseMarks();
|
||||
//Parse the race snapshot.
|
||||
server.parseSnapshot();
|
||||
|
||||
// Change wind direction
|
||||
race.changeWindDirection();
|
||||
|
||||
//Parse the race status.
|
||||
server.parseRaceStatus();
|
||||
|
||||
|
||||
|
||||
if (race.getRaceStatusEnum() == RaceStatusEnum.STARTED) {
|
||||
@@ -109,6 +112,9 @@ public class RaceLogic implements Runnable {
|
||||
//Get the current time.
|
||||
currentTime = System.currentTimeMillis();
|
||||
|
||||
//Execute commands from clients.
|
||||
commands.execute(race);
|
||||
|
||||
//Update race time.
|
||||
race.updateRaceTime(currentTime);
|
||||
|
||||
@@ -123,7 +129,6 @@ public class RaceLogic implements Runnable {
|
||||
|
||||
//If it is still racing, update its position.
|
||||
if (boat.getStatus() == BoatStatusEnum.RACING) {
|
||||
|
||||
race.updatePosition(boat, framePeriod, race.getRaceClock().getDurationMilli());
|
||||
|
||||
}
|
||||
@@ -141,15 +146,8 @@ public class RaceLogic implements Runnable {
|
||||
// Change wind direction
|
||||
race.changeWindDirection();
|
||||
|
||||
//Parse the boat locations.
|
||||
server.parseBoatLocations();
|
||||
|
||||
//Parse the marks.
|
||||
server.parseMarks();
|
||||
|
||||
//Parse the race status.
|
||||
server.parseRaceStatus();
|
||||
|
||||
//Parse the race snapshot.
|
||||
server.parseSnapshot();
|
||||
|
||||
//Update the last frame time.
|
||||
this.lastFrameTime = currentTime;
|
||||
@@ -165,7 +163,7 @@ public class RaceLogic implements Runnable {
|
||||
@Override
|
||||
public void handle(long now) {
|
||||
|
||||
server.parseRaceStatus();
|
||||
server.parseSnapshot();
|
||||
|
||||
if (iters > 500) {
|
||||
stop();
|
||||
@@ -173,4 +171,5 @@ public class RaceLogic implements Runnable {
|
||||
iters++;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package mock.model;
|
||||
|
||||
import network.Messages.BoatLocation;
|
||||
import network.Messages.BoatStatus;
|
||||
import network.Messages.*;
|
||||
import network.Messages.Enums.BoatLocationDeviceEnum;
|
||||
import network.Messages.LatestMessages;
|
||||
import network.Messages.RaceStatus;
|
||||
import network.Utils.AC35UnitConverter;
|
||||
import shared.model.Bearing;
|
||||
import shared.model.CompoundMark;
|
||||
@@ -21,10 +18,6 @@ public class RaceServer {
|
||||
private MockRace race;
|
||||
private LatestMessages latestMessages;
|
||||
|
||||
/**
|
||||
* The sequence number of the latest RaceStatus message sent or received.
|
||||
*/
|
||||
private int raceStatusSequenceNumber = 1;
|
||||
|
||||
/**
|
||||
* The sequence number of the latest BoatLocation message sent or received.
|
||||
@@ -39,10 +32,31 @@ public class RaceServer {
|
||||
|
||||
|
||||
/**
|
||||
* Parses an individual marker boat, and sends it to mockOutput.
|
||||
* @param mark The marker boat to parse.
|
||||
* Parses the race to create a snapshot, and places it in latestMessages.
|
||||
*/
|
||||
private void parseIndividualMark(Mark mark) {
|
||||
public void parseSnapshot() {
|
||||
|
||||
List<AC35Data> snapshotMessages = new ArrayList<>();
|
||||
|
||||
//Parse the boat locations.
|
||||
snapshotMessages.addAll(parseBoatLocations());
|
||||
|
||||
//Parse the marks.
|
||||
snapshotMessages.addAll(parseMarks());
|
||||
|
||||
//Parse the race status.
|
||||
snapshotMessages.add(parseRaceStatus());
|
||||
|
||||
latestMessages.setSnapshot(snapshotMessages);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parses an individual marker boat, and returns it.
|
||||
* @param mark The marker boat to parse.
|
||||
* @return The BoatLocation message.
|
||||
*/
|
||||
private BoatLocation parseIndividualMark(Mark mark) {
|
||||
//Create message.
|
||||
BoatLocation boatLocation = new BoatLocation(
|
||||
mark.getSourceID(),
|
||||
@@ -57,13 +71,17 @@ public class RaceServer {
|
||||
//Iterates the sequence number.
|
||||
this.boatLocationSequenceNumber++;
|
||||
|
||||
this.latestMessages.setBoatLocation(boatLocation);
|
||||
return boatLocation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the compound marker boats through mock output.
|
||||
* Parse the compound marker boats, and returns a list of BoatLocation messages.
|
||||
* @return BoatLocation messages for each mark.
|
||||
*/
|
||||
public void parseMarks() {
|
||||
private List<BoatLocation> parseMarks() {
|
||||
|
||||
List<BoatLocation> markLocations = new ArrayList<>(race.getCompoundMarks().size());
|
||||
|
||||
for (CompoundMark compoundMark : race.getCompoundMarks()) {
|
||||
|
||||
//Get the individual marks from the compound mark.
|
||||
@@ -72,31 +90,40 @@ public class RaceServer {
|
||||
|
||||
//If they aren't null, parse them (some compound marks only have one mark).
|
||||
if (mark1 != null) {
|
||||
this.parseIndividualMark(mark1);
|
||||
markLocations.add(this.parseIndividualMark(mark1));
|
||||
}
|
||||
|
||||
if (mark2 != null) {
|
||||
this.parseIndividualMark(mark2);
|
||||
markLocations.add(this.parseIndividualMark(mark2));
|
||||
}
|
||||
}
|
||||
|
||||
return markLocations;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse the boats in the race, and send it to mockOutput.
|
||||
* Parse the boats in the race, and returns all of their BoatLocation messages.
|
||||
* @return List of BoatLocation messages, for each boat.
|
||||
*/
|
||||
public void parseBoatLocations() {
|
||||
private List<BoatLocation> parseBoatLocations() {
|
||||
|
||||
List<BoatLocation> boatLocations = new ArrayList<>(race.getBoats().size());
|
||||
|
||||
//Parse each boat.
|
||||
for (MockBoat boat : race.getBoats()) {
|
||||
this.parseIndividualBoatLocation(boat);
|
||||
boatLocations.add(this.parseIndividualBoatLocation(boat));
|
||||
}
|
||||
|
||||
return boatLocations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an individual boat, and sends it to mockOutput.
|
||||
* Parses an individual boat, and returns it.
|
||||
* @param boat The boat to parse.
|
||||
* @return The BoatLocation message.
|
||||
*/
|
||||
private void parseIndividualBoatLocation(MockBoat boat) {
|
||||
private BoatLocation parseIndividualBoatLocation(MockBoat boat) {
|
||||
|
||||
BoatLocation boatLocation = new BoatLocation(
|
||||
boat.getSourceID(),
|
||||
@@ -111,16 +138,17 @@ public class RaceServer {
|
||||
//Iterates the sequence number.
|
||||
this.boatLocationSequenceNumber++;
|
||||
|
||||
this.latestMessages.setBoatLocation(boatLocation);
|
||||
return boatLocation;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Parses the race status, and sends it to mockOutput.
|
||||
* Parses the race status, and returns it.
|
||||
* @return The race status message.
|
||||
*/
|
||||
public void parseRaceStatus() {
|
||||
private RaceStatus parseRaceStatus() {
|
||||
|
||||
//A race status message contains a list of boat statuses.
|
||||
List<BoatStatus> boatStatuses = new ArrayList<>();
|
||||
@@ -151,6 +179,6 @@ public class RaceServer {
|
||||
race.getRaceType(),
|
||||
boatStatuses);
|
||||
|
||||
this.latestMessages.setRaceStatus(raceStatus);
|
||||
return raceStatus;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package mock.model;
|
||||
|
||||
|
||||
import mock.exceptions.SourceIDAllocationException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This class is responsible for allocating boat source IDs for use in a race, upon request.
|
||||
*/
|
||||
public class SourceIdAllocator {
|
||||
|
||||
|
||||
/**
|
||||
* This list contains all unallocated source IDs.
|
||||
*/
|
||||
List<Integer> unallocatedIDs = new ArrayList<>();
|
||||
|
||||
|
||||
/**
|
||||
* This list contains all allocated source IDs.
|
||||
*/
|
||||
List<Integer> allocatedIDs = new ArrayList<>();
|
||||
|
||||
|
||||
/**
|
||||
* Creates a source ID allocator, using the given list of unallocated source IDs.
|
||||
* @param unallocatedIDs List of unallocated source IDs.
|
||||
*/
|
||||
public SourceIdAllocator(List<Integer> unallocatedIDs) {
|
||||
//We need to copy the list.
|
||||
this.unallocatedIDs.addAll(unallocatedIDs);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Allocates a source ID for a boat.
|
||||
* @return The allocated source ID.
|
||||
* @throws SourceIDAllocationException Thrown if we cannot allocate any more source IDs.
|
||||
*/
|
||||
public synchronized int allocateSourceID() throws SourceIDAllocationException {
|
||||
|
||||
if (!unallocatedIDs.isEmpty()) {
|
||||
|
||||
int sourceID = unallocatedIDs.remove(0);
|
||||
|
||||
allocatedIDs.add(sourceID);
|
||||
|
||||
return sourceID;
|
||||
|
||||
} else {
|
||||
throw new SourceIDAllocationException("Could not allocate a source ID.");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a source ID to the source ID allocator, so that it can be reused.
|
||||
* @param sourceID Source ID to return.
|
||||
*/
|
||||
public void returnSourceID(Integer sourceID) {
|
||||
|
||||
//We remove an Integer, not an int, so that we remove by value not by index.
|
||||
allocatedIDs.remove(sourceID);
|
||||
|
||||
unallocatedIDs.add(sourceID);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package mock.model.commandFactory;
|
||||
|
||||
import mock.model.MockRace;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Wraps multiple commands into a composite to execute queued commands during a frame.
|
||||
*/
|
||||
public class CompositeCommand implements Command {
|
||||
private Stack<Command> commands;
|
||||
|
||||
public CompositeCommand() {
|
||||
this.commands = new Stack<>();
|
||||
}
|
||||
|
||||
public void addCommand(Command command) {
|
||||
commands.push(command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(MockRace race) {
|
||||
while(!commands.isEmpty()) commands.pop().execute(race);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user