Commit 2eeadea7 authored by Stefan Schuhbaeck's avatar Stefan Schuhbaeck
Browse files

Merge branch 'traci_unsignedByte_overflow' into 'master'

Traci unsigned byte overflow

See merge request !116
parents fc9050b5 ddd8791a
Pipeline #212930 passed with stages
in 149 minutes and 39 seconds
......@@ -59,7 +59,7 @@ public class ClientHandler implements Runnable {
while (cmd != null) {
TraCIPacket response = cmdExecutor.execute(cmd);
logger.debugf("send packet with %d byte", response.size());
logger.debugf("send packet [%d byte]", response.size());
traCISocket.sendExact(response);
cmd = traCIPacketBuffer.nextCommand();
......
......@@ -34,10 +34,10 @@ public class Manager {
logger.infof("Start Server(%s) with Loglevel: %s", VadereServer.currentVersion.getVersionString(), logger.getLevel().toString());
AbstractVadereServer server;
if (ns.getBoolean("singleClient")) {
server = new VadereSingleClientServer(serverSocket, Paths.get(ns.getString("output-dir")), ns.getBoolean("guiMode"));
server = new VadereSingleClientServer(serverSocket, Paths.get(ns.getString("output-dir")), ns.getBoolean("guiMode"), ns.getBoolean("trace"));
} else {
ExecutorService pool = Executors.newFixedThreadPool(ns.getInt("clientNum"));
server = new VadereServer(serverSocket, pool, Paths.get(ns.getString("output-dir")), ns.getBoolean("guiMode"));
server = new VadereServer(serverSocket, pool, Paths.get(ns.getString("output-dir")), ns.getBoolean("guiMode"), ns.getBoolean("trace"));
}
server.run();
......@@ -99,6 +99,15 @@ public class Manager {
.dest("clientNum")
.help("Set number of clients to manager. Important: Each client has a separate simulation. No communication between clients");
parser.addArgument("--trace")
.required(false)
.action(Arguments.storeTrue())
.setDefault(false)
.type(Boolean.class)
.dest("trace")
.help("Activate additional TRACE information in low level components. Ensure correct --loglevel setting to see additional information");
parser.addArgument("--single-client")
.required(false)
.action(Arguments.storeTrue())
......
......@@ -161,10 +161,10 @@ public class RemoteManager implements RunnableFinishedListener {
public void startSimulation() {
if (currentSimulationRun == null)
throw new IllegalStateException("RemoteScenarioRun object must not be null");
throw new TraCIExceptionInternal("RemoteScenarioRun object must not be null");
if (currentSimulationThread != null && currentSimulationThread.isAlive())
throw new IllegalStateException("A simulation is already running. Stop current simulation before starting new one.");
throw new TraCIExceptionInternal("A simulation is already running. Stop current simulation before starting new one.");
simulationFinished = false;
currentSimulationThread = new Thread(currentSimulationRun);
......
......@@ -13,9 +13,9 @@ import java.util.concurrent.locks.ReentrantLock;
public class RemoteScenarioRun extends ScenarioRun implements RemoteRunListener {
private List<Subscription> subscriptions;
private final Object waitForLoopEnd;
private final ReentrantLock lock;
private List<Subscription> subscriptions;
private boolean lastSimulationStep;
......
......@@ -15,6 +15,33 @@ public class ServerView extends JFrame implements SingleScenarioFinishedListener
private static ServerView mainWindow;
private ServerView() throws HeadlessException {
ServerView.mainWindow = this;
setTitle("Vadere GUI - Server");
setBounds(100, 100, 1000, 600);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void close() {
EventQueue.invokeLater(() -> {
mainWindow.setVisible(false);
mainWindow.dispose();
});
}
public static void startServerGui(OnlineVisualization onlineVisualization) {
EventQueue.invokeLater(() -> {
ServerView frame = new ServerView();
frame.setVisible(true);
frame.setSize(1200, 800);
frame.add(onlineVisualization.getVisualizationPanel());
onlineVisualization.getMainPanel().setVisible(true);
});
}
@Override
public void preScenarioRun(Scenario scenario, int scenariosLeft) {
......@@ -45,32 +72,4 @@ public class ServerView extends JFrame implements SingleScenarioFinishedListener
}
private ServerView() throws HeadlessException {
ServerView.mainWindow = this;
setTitle("Vadere GUI - Server");
setBounds(100, 100, 1000, 600);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void close() {
EventQueue.invokeLater(() -> {
mainWindow.setVisible(false);
mainWindow.dispose();
});
}
public static void startServerGui(OnlineVisualization onlineVisualization) {
EventQueue.invokeLater(() -> {
ServerView frame = new ServerView();
frame.setVisible(true);
frame.setSize(1200, 800);
frame.add(onlineVisualization.getVisualizationPanel());
onlineVisualization.getMainPanel().setVisible(true);
});
}
}
......@@ -38,4 +38,8 @@ public class TraCIException extends RuntimeException {
+ "not supported in API: " + cmd.getTraCICmd().toString());
}
public String getMessageForClient() {
return getMessage();
}
}
package org.vadere.manager;
/**
* Use this Exception if the message produces has no mean for a TraCI client. The stacktrace is
* printed but the client gets a static response.
*/
public class TraCIExceptionInternal extends TraCIException {
private final static String CLIENT_MESSAGE = "Internal error occurred in TraCI server. See server logs for details";
public TraCIExceptionInternal(String message) {
super(message);
}
public TraCIExceptionInternal(String message, Object... arg) {
super(message, arg);
}
public TraCIExceptionInternal(String message, Throwable cause, Object... arg) {
super(message, cause, arg);
}
public TraCIExceptionInternal(String message, Throwable cause) {
super(message, cause);
}
@Override
public String getMessageForClient() {
return CLIENT_MESSAGE;
}
}
......@@ -3,6 +3,7 @@ package org.vadere.manager;
import org.vadere.manager.traci.reader.TraCIPacketBuffer;
import org.vadere.manager.traci.response.TraCIResponse;
import org.vadere.manager.traci.writer.TraCIPacket;
import org.vadere.util.logging.Logger;
import java.io.Closeable;
import java.io.DataInputStream;
......@@ -17,19 +18,27 @@ import java.nio.ByteBuffer;
public class TraCISocket implements Closeable {
private final static int TRACI_LEN_LENGTH = 4;
private static Logger logger = Logger.getLogger(TraCISocket.class);
private final Socket socket;
private final DataOutputStream outStream;
private final DataInputStream inStream;
private final boolean tracePackets;
private String host;
private int port;
public TraCISocket(Socket socket) throws IOException {
public TraCISocket(Socket socket, boolean tracePackets) throws IOException {
this.socket = socket;
this.host = this.socket.getInetAddress().toString();
this.port = this.socket.getPort();
this.outStream = new DataOutputStream(socket.getOutputStream());
this.inStream = new DataInputStream(socket.getInputStream());
this.tracePackets = tracePackets;
if (this.tracePackets)
logger.infof("TraCISocket is in TRACE-MODE. Ensure the correct Loglevel to see all Information.");
}
public TraCISocket(Socket socket) throws IOException {
this(socket, false);
}
public int getPort() {
......@@ -55,6 +64,8 @@ public class TraCISocket implements Closeable {
}
public void sendExact(final TraCIPacket packet) throws IOException {
if (tracePackets)
logger.tracef("send packet [%d byte]: %s", packet.size(), packet.asHexString());
send(packet.send());
}
......
......@@ -27,6 +27,25 @@ public class ConsoleReader implements Runnable {
addCommand("help", "Print this Help", this::cmd_help);
}
public static void main(String[] args) {
ConsoleReader r = new ConsoleReader();
r.addCommand("do-shit", "guess..",
args1 -> System.out.println("do-shit with " + Arrays.toString(args1)));
Thread thread = new Thread(r);
System.out.println("start..");
thread.start();
try {
thread.join();
System.out.println("joined");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void cmd_help(String[] args) {
if (!args[0].equals("help"))
System.out.println("Unknown command: " + args[0]);
......@@ -81,25 +100,6 @@ public class ConsoleReader implements Runnable {
running = false;
}
public static void main(String[] args) {
ConsoleReader r = new ConsoleReader();
r.addCommand("do-shit", "guess..",
args1 -> System.out.println("do-shit with " + Arrays.toString(args1)));
Thread thread = new Thread(r);
System.out.println("start..");
thread.start();
try {
thread.join();
System.out.println("joined");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
commandLoop();
......
......@@ -31,12 +31,6 @@ public class TestClient extends org.vadere.manager.client.AbstractTestClient imp
private String defaultScenario;
private boolean running;
public static void main(String[] args) throws IOException, InterruptedException {
TestClient testClient = new TestClient(9999, args);
testClient.run();
}
public TestClient(int port, String basePath, String defaultScenario) {
this.port = port;
this.running = false;
......@@ -44,6 +38,7 @@ public class TestClient extends org.vadere.manager.client.AbstractTestClient imp
this.defaultScenario = defaultScenario;
}
public TestClient(int port, String[] args) {
this.port = port;
this.running = false;
......@@ -61,6 +56,10 @@ public class TestClient extends org.vadere.manager.client.AbstractTestClient imp
}
}
public static void main(String[] args) throws IOException, InterruptedException {
TestClient testClient = new TestClient(9999, args);
testClient.run();
}
private void addCommands(ConsoleReader consoleReader) {
consoleReader.addCommand("ctr.getVersion", "", this::getVersion);
......
......@@ -7,20 +7,20 @@ import java.net.ServerSocket;
import java.nio.file.Path;
public abstract class AbstractVadereServer implements Runnable {
protected static Logger logger = Logger.getLogger(VadereServer.class);
public static int SUPPORTED_TRACI_VERSION = 20;
// public static int SUPPORTED_TRACI_VERSION = 1;
public static String SUPPORTED_TRACI_VERSION_STRING = "Vadere Simulator. Supports subset of commands based von TraCI Version " + SUPPORTED_TRACI_VERSION;
public static TraCIVersion currentVersion = TraCIVersion.V20_0_2;
protected static Logger logger = Logger.getLogger(VadereServer.class);
protected final ServerSocket serverSocket;
protected final Path baseDir;
protected final boolean guiSupport;
protected final boolean trace;
public AbstractVadereServer(ServerSocket serverSocket, Path baseDir, boolean guiSupport) {
public AbstractVadereServer(ServerSocket serverSocket, Path baseDir, boolean guiSupport, boolean trace) {
this.serverSocket = serverSocket;
this.baseDir = baseDir;
this.guiSupport = guiSupport;
this.trace = trace;
}
}
......@@ -15,8 +15,8 @@ public class VadereServer extends AbstractVadereServer {
private final ExecutorService handlerPool;
public VadereServer(ServerSocket serverSocket, ExecutorService handlerPool, Path baseDir, boolean guiSupport) {
super(serverSocket, baseDir, guiSupport);
public VadereServer(ServerSocket serverSocket, ExecutorService handlerPool, Path baseDir, boolean guiSupport, boolean trace) {
super(serverSocket, baseDir, guiSupport, trace);
this.handlerPool = handlerPool;
}
......@@ -31,7 +31,7 @@ public class VadereServer extends AbstractVadereServer {
while (true) {
Socket clientSocket = serverSocket.accept();
handlerPool.execute(new ClientHandler(serverSocket, new TraCISocket(clientSocket), baseDir, guiSupport));
handlerPool.execute(new ClientHandler(serverSocket, new TraCISocket(clientSocket, trace), baseDir, guiSupport));
}
} catch (IOException e) {
e.printStackTrace();
......
......@@ -15,8 +15,8 @@ import java.nio.file.Path;
public class VadereSingleClientServer extends AbstractVadereServer {
public VadereSingleClientServer(ServerSocket serverSocket, Path baseDir, boolean guiSupport) {
super(serverSocket, baseDir, guiSupport);
public VadereSingleClientServer(ServerSocket serverSocket, Path baseDir, boolean guiSupport, boolean trace) {
super(serverSocket, baseDir, guiSupport, trace);
}
@Override
......@@ -24,7 +24,7 @@ public class VadereSingleClientServer extends AbstractVadereServer {
try {
logger.infof("listening on port %d... (gui-mode: %s) Single Simulation", serverSocket.getLocalPort(), Boolean.toString(guiSupport));
Socket clientSocket = serverSocket.accept();
Thread t = new Thread(new ClientHandler(serverSocket, new TraCISocket(clientSocket), baseDir, guiSupport));
Thread t = new Thread(new ClientHandler(serverSocket, new TraCISocket(clientSocket, trace), baseDir, guiSupport));
t.start();
t.join();
......
......@@ -113,4 +113,8 @@ public enum TraCICmd {
return String.format("TraCICmd{%s: id=0x%02X, type=%s}", name(), id, type);
}
public String logShort() {
return String.format("{%s:0x%02X%s}", name(), id, type);
}
}
package org.vadere.manager.traci;
import org.vadere.manager.TraCIException;
public enum TraCIVersion {
V20_0_1(20, 0, 1),
V20_0_2(20, 0, 2); // allow cache transfer
......@@ -18,7 +20,7 @@ public enum TraCIVersion {
public static TraCIVersion valueOf(int ordinalId) {
if (ordinalId < 0 || ordinalId >= values().length)
throw new IllegalArgumentException("given ordinalId is outside of this Enum.");
throw new TraCIException("given ordinalId is outside of this Enum.");
return values()[ordinalId];
}
......
package org.vadere.manager.traci.commandHandler;
import org.vadere.manager.RemoteManager;
import org.vadere.manager.TraCIException;
import org.vadere.manager.traci.TraCICmd;
import org.vadere.manager.traci.commands.TraCICommand;
import org.vadere.manager.traci.commands.TraCISetCommand;
......@@ -45,10 +46,27 @@ public class CommandExecutor {
public TraCIPacket execute(TraCICommand cmd) {
TraCICmdHandler handler = cmdMap.get(cmd.getTraCICmd().id);
if (handler == null) {
logger.errorf("No CommandHandler found for command: %02X", cmd.getTraCICmd().id);
logger.errorf("No CommandHandler found for command: %s", cmd.getTraCICmd().logShort());
return TraCIPacket.create().add_Err_StatusResponse(cmd.getTraCICmd().id, "ID not found.");
}
TraCIPacket response;
try {
logger.debugf("execute cmd: %s", cmd.getTraCICmd().logShort());
cmd = handler.handel(cmd, remoteManager);
} catch (TraCIException e) {
logger.errorf("Error handling cmd: %s", cmd.getTraCICmd().logShort());
e.printStackTrace();
return TraCIPacket.createErr(cmd.getTraCICmd().id, e.getMessageForClient());
}
try {
logger.debugf("build response for: %s", cmd.getTraCICmd().logShort());
response = cmd.buildResponsePacket();
} catch (TraCIException e) {
logger.errorf("error building response for: %s", cmd.getTraCICmd().logShort());
e.printStackTrace();
return TraCIPacket.createErr(cmd.getTraCICmd().id, e.getMessageForClient());
}
return handler.handel(cmd, remoteManager).buildResponsePacket();
return response;
}
}
......@@ -31,8 +31,6 @@ import java.util.List;
*/
public abstract class CommandHandler<VAR extends Enum> {
private static Logger logger = Logger.getLogger(CommandHandler.class);
public static final String ELEMENT_ID_NOT_FOUND = "No element found with given object id ";
public static final String ELEMENT_ID_NOT_FREE = "There is already an element with the given object id ";
public static final String FILE_NOT_FOUND = "No file with given path ";
......@@ -40,8 +38,9 @@ public abstract class CommandHandler<VAR extends Enum> {
public static final String COULD_NOT_MAP_OBJECT_FROM_JSON = "Could not map object from given json ";
public static final String COULD_NOT_SERIALIZE_OBJECT = "Could not serialize object ";
public static final String NO_MAIN_MODEL = "Main Model is not present.";
protected HashMap<Pair<TraCICmd, VAR>, Method> handler;
private static Logger logger = Logger.getLogger(CommandHandler.class);
private final Method processNotImplemented;
protected HashMap<Pair<TraCICmd, VAR>, Method> handler;
public CommandHandler() {
handler = new HashMap<>();
......
......@@ -4,6 +4,7 @@ package org.vadere.manager.traci.commandHandler;
import org.vadere.manager.RemoteManager;
import org.vadere.manager.Subscription;
import org.vadere.manager.server.VadereServer;
import org.vadere.manager.traci.TraCICmd;
import org.vadere.manager.traci.TraCIVersion;
import org.vadere.manager.traci.commandHandler.annotation.ControlHandler;
import org.vadere.manager.traci.commandHandler.annotation.ControlHandlers;
......@@ -27,9 +28,8 @@ import java.lang.reflect.Method;
*/
public class ControlCommandHandler extends CommandHandler<ControlVar> {
private static Logger logger = Logger.getLogger(ControlCommandHandler.class);
public static ControlCommandHandler instance;
private static Logger logger = Logger.getLogger(ControlCommandHandler.class);
static {
instance = new ControlCommandHandler();
......@@ -74,15 +74,16 @@ public class ControlCommandHandler extends CommandHandler<ControlVar> {
public TraCICommand process_simStep(TraCICommand rawCmd, RemoteManager remoteManager) {
TraCISimStepCommand cmd = (TraCISimStepCommand) rawCmd;
logger.debugf("Simulate to: %f", cmd.getTargetTime());
// remoteManager.nextStep(cmd.getTargetTime());
logger.debugf("%s: Simulate until=%f", TraCICmd.SIM_STEP.name(), cmd.getTargetTime());
if (!remoteManager.nextStep(cmd.getTargetTime())) {
//simulation finished;
cmd.setResponse(TraCISimTimeResponse.simEndReached());
return cmd;
}
// execute all
logger.debug("execute subscriptions");
logger.debugf("%s: execute %d subscriptions",
TraCICmd.SIM_STEP.name(),
remoteManager.getSubscriptions().size());
remoteManager.getSubscriptions().forEach(sub -> sub.executeSubscription(remoteManager));
// remove subscriptions no longer valid
......
......@@ -172,7 +172,12 @@ public class PersonCommandHandler extends CommandHandler<PersonVar> {
.stream()
.map(p -> Integer.toString(p.getId()))
.collect(Collectors.toList());
logger.debugf("time: %f ID's: %s", state.getSimTimeInSec(), Arrays.toString(data.toArray(String[]::new)));
logger.debugf("%s.%s: t=%f pedIds(#%d)=%s",
TraCICmd.GET_PERSON_VALUE.logShort(),
PersonVar.ID_LIST.logShort(),
state.getSimTimeInSec(),
data.size(),
Arrays.toString(data.toArray(String[]::new)));
cmd.setResponse(responseOK(PersonVar.ID_LIST.type, data));
});
return cmd;
......@@ -233,7 +238,9 @@ public class PersonCommandHandler extends CommandHandler<PersonVar> {
if (checkIfPedestrianExists(ped, cmd)) {
cmd.setResponse(responseOK(PersonVar.POS_2D.type, ped.getPosition()));
logger.debugf("time: %f Pedestrian: %s Position: %s",
logger.tracef("%s.%s: t=%f pedId=%s pos2d=%s",
TraCICmd.GET_PERSON_VALUE.logShort(),
PersonVar.POS_2D.logShort(),
state.getSimTimeInSec(),
cmd.getElementIdentifier(),
ped.getPosition().toString());
......
......@@ -38,9 +38,8 @@ import java.util.stream.Collectors;
public class PolygonCommandHandler extends CommandHandler<PolygonVar> {
private static Logger logger = Logger.getLogger(PersonCommandHandler.class);
public static PolygonCommandHandler instance;
private static Logger logger = Logger.getLogger(PersonCommandHandler.class);
static {
instance = new PolygonCommandHandler();
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment