Commit 1e657922 authored by Tobias Meuser's avatar Tobias Meuser
Browse files

Merged tm/vehicular-services into master-integration

parents 2a24c1a4 2c04ab95
......@@ -408,13 +408,10 @@
</dependency>
<!-- Traci as a Service -->
<!--
<dependency>
<groupId>maki</groupId>
<artifactId>simonstrator-traci</artifactId>
<version>0.2-SNAPSHOT</version>
</dependency>
-->
</dependencies>
</project>
......@@ -53,7 +53,7 @@ public enum PhyType {
* (LinkLayer might add retransmission behavior as in 802.11), 5MBit/s netto
* (802.11b) BW, 500us latency, 2,2kB MTU, Broadcast
*/
WIFI(NetInterfaceName.WIFI, 0.01, 5 * Rate.Mbit_s, 500 * Time.MICROSECOND,
WIFI(NetInterfaceName.WIFI, 0.01, 12 * Rate.Mbit_s, 500 * Time.MICROSECOND,
2334, true),
/**
* A wired connection based on a TopologyView
......
......@@ -92,8 +92,7 @@ public abstract class StatisticsFilter extends
if (values == null || values.isEmpty()) {
return null;
}
LinkedList<MetricValue> mvs = new LinkedList<MetricValue>(values);
return new StatisticsMetricValue(mvs);
return new StatisticsMetricValue(values);
}
/**
......@@ -104,11 +103,11 @@ public abstract class StatisticsFilter extends
*/
private class StatisticsMetricValue implements MetricValue<Double> {
private final List<MetricValue> inputs;
private final List<? extends MetricValue<?>> inputs;
private Double result = Double.NaN;
public StatisticsMetricValue(List<MetricValue> inputs) {
public StatisticsMetricValue(List<? extends MetricValue<?>> inputs) {
this.inputs = inputs;
}
......
......@@ -20,6 +20,7 @@
package de.tud.kom.p2psim.impl.analyzer.metric.output;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
......@@ -37,6 +38,9 @@ import de.tud.kom.p2psim.impl.util.db.metric.MetricDescription;
import de.tud.kom.p2psim.impl.util.oracle.GlobalOracle;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric.ActiveSpatialMetricListener;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric.SpatialMetricValue;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveMetric.ActiveMetricListener;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric.MetricValue;
......@@ -51,13 +55,14 @@ import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;
*/
public class MetricOutputDAO extends AbstractOutput {
protected long timeEnableDao = 0;
protected long timeStopDao = Long.MAX_VALUE;
protected Set<String> metricsToAggregate = new LinkedHashSet<>();
protected List<MetricDaoAdapter> daoAdapters = new LinkedList<>();
protected List<DaoAdapter> daoAdapters = new LinkedList<>();
/**
*
......@@ -65,7 +70,7 @@ public class MetricOutputDAO extends AbstractOutput {
*/
@XMLConfigurableConstructor({ "table" })
public MetricOutputDAO(String table) {
DAO.database = table;
DAO.setDatabase(table);
}
public void setAddress(String address) {
......@@ -77,11 +82,11 @@ public class MetricOutputDAO extends AbstractOutput {
}
public void setUser(String user) {
DAO.username = user;
DAO.setUsername(user);
}
public void setPassword(String password) {
DAO.password = password;
DAO.setPassword(password);
}
public void setTimeEnableDao(long timeEnableDao) {
......@@ -141,12 +146,18 @@ public class MetricOutputDAO extends AbstractOutput {
am.addActiveMetricListener(adapter);
daoAdapters.add(adapter);
}
if (metric instanceof ActiveSpatialMetric) {
ActiveSpatialMetric asm = (ActiveSpatialMetric) metric;
SpatialMetricDaoAdapter adapter = new SpatialMetricDaoAdapter(asm);
asm.addActiveSpatialMetricListener(adapter);
daoAdapters.add(adapter);
}
}
}
@Override
public void onStop() {
for (MetricDaoAdapter adapter : daoAdapters) {
for (DaoAdapter adapter : daoAdapters) {
adapter.onStop();
}
/*
......@@ -155,13 +166,17 @@ public class MetricOutputDAO extends AbstractOutput {
DAO.commitQueue();
}
private interface DaoAdapter {
void onStop();
}
/**
* This class helps in persisting a metric using the {@link MeasurementDAO}
*
* @author Bjoern Richerzhagen
* @version 1.0, 13.08.2012
*/
private class MetricDaoAdapter implements ActiveMetricListener {
private class MetricDaoAdapter implements ActiveMetricListener, DaoAdapter {
private final ActiveMetric metric;
......@@ -298,4 +313,148 @@ public class MetricOutputDAO extends AbstractOutput {
}
/**
* This class helps in persisting a spatial metric using the
* {@link MeasurementDAO}
*
* @author Tobias Meuser
* @version 1.0, 10.10.2018
*/
private class SpatialMetricDaoAdapter implements ActiveSpatialMetricListener, DaoAdapter {
private final MetricDescription md;
private final MeasurementDAO dao = new MeasurementDAO();
private final List<SimHost> hosts;
private final Map<String, List<SimHost>> hostsByGroup;
private final Map<String, DescriptiveStatistics> globalStatsByGroup;
private Map<GridKey, Double> values = new HashMap<>();
private long lastUpdate = -1;
private final double spatialResolution;
private ActiveSpatialMetric<?> metric;
public SpatialMetricDaoAdapter(ActiveSpatialMetric metric) {
this.metric = metric;
this.md = new MetricDescription(MetricOutputDAO.class.getName(), metric.getName(), metric.getDescription(),
metric.getUnit().toString());
this.hosts = GlobalOracle.getHosts();
this.hostsByGroup = new LinkedHashMap<>();
this.globalStatsByGroup = new LinkedHashMap<>();
for (SimHost simHost : hosts) {
String groupId = simHost.getProperties().getGroupID();
if (!this.hostsByGroup.containsKey(groupId)) {
this.hostsByGroup.put(groupId, new LinkedList<>());
this.globalStatsByGroup.put(groupId, new DescriptiveStatistics());
}
this.hostsByGroup.get(groupId).add(simHost);
}
spatialResolution = metric.getResolution();
}
@Override
public void onStop() {
store();
}
private void store() {
for (Entry<GridKey, Double> entry : values.entrySet()) {
dao.storeGlobalSpatialMeasurement(md, lastUpdate, entry.getValue(), entry.getKey().getX(),
entry.getKey().getY());
}
values.clear();
lastUpdate = Time.getCurrentTime();
}
@Override
public void onMetricUpdate(ActiveSpatialMetric<?> metric) {
long time = Time.getCurrentTime();
if (time < timeEnableDao || time > timeStopDao) {
return;
}
if (metric.isOverallMetric()) {
if (!metric.isAggregated() || Time.getCurrentTime() != lastUpdate) {
store();
}
// global
SpatialMetricValue mv = metric.getOverallMetric();
Object val = mv.getValue();
if (mv.isValid()) {
if (val instanceof Number) {
double vd = ((Number) val).doubleValue();
GridKey key = new GridKey((int) (mv.getLocation().getLongitudeOrX() / spatialResolution),
(int) (mv.getLocation().getLatitudeOrY() / spatialResolution));
if (!values.containsKey(key)) {
values.put(key, vd);
} else {
double storedValue = values.get(key);
if (storedValue < vd) {
values.put(key, vd);
}
}
}
}
} else {
for (SimHost host : hosts) {
SpatialMetricValue mv = metric.getPerHostMetric(host.getId());
if (mv != null) {
Object val = mv.getValue();
if (mv.isValid()) {
if (val instanceof Number) {
double vd = ((Number) val).doubleValue();
if (Double.isNaN(vd)) {
continue;
}
dao.storeSpatialMeasurement(md, host.getId().value(), time, vd,
(int) (mv.getLocation().getLongitudeOrX() / spatialResolution),
(int) (mv.getLocation().getLatitudeOrY() / spatialResolution));
}
}
}
}
}
}
}
private class GridKey {
private final int x;
private final int y;
public GridKey(int pX, int pY) {
x = pX;
y = pY;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int hashCode() {
return Integer.hashCode(x) << 16 + Integer.hashCode(y);
}
@Override
public boolean equals(Object pObj) {
if (pObj instanceof GridKey) {
return x == ((GridKey) pObj).x && y == ((GridKey) pObj).y;
}
return false;
}
}
}
/*
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de.tud.kom.p2psim.impl.analyzer.metric.spatial;
import java.util.ArrayList;
import java.util.List;
import de.tudarmstadt.maki.simonstrator.api.common.metric.AbstractMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric;
public abstract class AbstractSpatialMetric<T extends AbstractSpatialMetricValue<?>> extends AbstractMetric<T> implements Metric<T>, ActiveSpatialMetric<T> {
protected boolean aggregate = false;
public AbstractSpatialMetric(String pDescription, MetricUnit pUnit) {
super(pDescription, pUnit);
}
public AbstractSpatialMetric(String pName, String pDescription, MetricUnit pUnit) {
super(pName, pDescription, pUnit);
}
protected void setOverallMetric(T aggregate) {
super.setOverallMetric(aggregate);
}
@Override
public boolean isAggregated() {
return aggregate;
}
private List<ActiveSpatialMetricListener> _listeners = new ArrayList<>();
@Override
public void addActiveSpatialMetricListener(ActiveSpatialMetricListener pListener) {
_listeners.add(pListener);
}
@Override
public void notifyListeners() {
for (ActiveSpatialMetricListener activeSpatialMetricListener : _listeners) {
activeSpatialMetricListener.onMetricUpdate(this);
}
}
}
/*
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de.tud.kom.p2psim.impl.analyzer.metric.spatial;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric.SpatialMetricValue;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
public abstract class AbstractSpatialMetricValue<S extends Object> implements SpatialMetricValue<S> {
private S value;
private Location location;
private ActiveSpatialMetric<?> metric;
public AbstractSpatialMetricValue(ActiveSpatialMetric<?> pMetric) {
metric = pMetric;
}
public AbstractSpatialMetricValue(ActiveSpatialMetric<?> pMetric, S pValue) {
metric = pMetric;
value = pValue;
}
public void setValue(S pValue, Location pLocation) {
value = pValue;
location = pLocation;
metric.notifyListeners();
}
@Override
public S getValue() {
return value;
}
@Override
public Location getLocation() {
return location;
}
}
\ No newline at end of file
......@@ -143,7 +143,7 @@ public class DefaultMonitor implements MonitorComponent, EventHandler,
public void setTableName(String tableName) {
System.out.println("Table Name is set to: " + tableName);
if (tableName != null && !tableName.equals("")) {
DAO.database = tableName;
DAO.setDatabase(tableName);
}
}
......
......@@ -37,6 +37,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.sound.midi.Synthesizer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
......@@ -145,6 +146,8 @@ public class DefaultConfigurator implements Configurator {
private Map<String, String> variables = new LinkedHashMap<String, String>();
private boolean _parseOnly = false;
/**
* Create new configurator instance with the configuration data in the given
* XML file.
......@@ -199,6 +202,13 @@ public class DefaultConfigurator implements Configurator {
}
}
public Map<String, String> parseAllDefaults() throws ConfigurationException {
_parseOnly = true;
configureAll();
_parseOnly = false;
return getVariables();
}
/**
* Configure all components of the simulator. The single components are
* either registered via the <code>register(name, component)</code> method
......@@ -310,7 +320,6 @@ public class DefaultConfigurator implements Configurator {
* @return configured component
*/
public Object configureComponent(Element elem) {
String name = elem.getName();
if (Configurator.SPECIAL_IF_EQUAL_STR.equalsIgnoreCase(name)) {
processIfEqualStr(elem, new ToConfigureCallback() {
......@@ -347,6 +356,7 @@ public class DefaultConfigurator implements Configurator {
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Configure component " + name);
if (!_parseOnly) {
/*
* FIXED (BR) - if a component specifies a class-tag, do NOT reuse the
* old component for configuration. Instead, create a new component.
......@@ -388,6 +398,14 @@ public class DefaultConfigurator implements Configurator {
"Skip element " + name);
}
return component;
} else {
for (Iterator iter = elem.elementIterator(); iter.hasNext();) {
Element child = (Element) iter.next();
processChild(null, child, null);
}
return null;
}
}
private Object createComponent(Element elem, Set<String> consAttrs) {
......@@ -456,6 +474,7 @@ public class DefaultConfigurator implements Configurator {
Object subcomponent = configureComponent(child);
if (!_parseOnly) {
String prefix = SET_METHOD_PREFIX_TAG;
String methodName = getMethodName(prefix, child.getName());
Method[] methods = component.getClass().getMethods();
......@@ -494,6 +513,7 @@ public class DefaultConfigurator implements Configurator {
}
}
}
}
public void configureAttributes(Object component, Element elem) {
Set<String> set = Collections.emptySet();
......@@ -629,8 +649,9 @@ public class DefaultConfigurator implements Configurator {
}
param = lvals;
} else {
throw new IllegalArgumentException(
"Parameter type " + typeClass + " is not supported");
param = value;
// throw new IllegalArgumentException(
// "Parameter type " + typeClass + " is not supported");
}
return param;
}
......@@ -728,6 +749,9 @@ public class DefaultConfigurator implements Configurator {
if (staticMethod == null) {
Constructor[] cs = forName.getConstructors();
Constructor currentConstructor = null;
String[] usedArgs = null;
Object[] parameters = null;
for (Constructor<?> c : cs) {
XMLConfigurableConstructor a = c
......@@ -760,7 +784,7 @@ public class DefaultConfigurator implements Configurator {
break;
}
consArgs[i] = configureComponent(elem);
if (consArgs[i].getClass()
if (!consArgs[i].getClass()
.isAssignableFrom(types[i]))
throw new ConfigurationException(
"The type of the component configured for the parameter '"
......@@ -778,16 +802,23 @@ public class DefaultConfigurator implements Configurator {
}
if (!incompatible) {
component = c.newInstance(consArgs);
for (String consAttr : cArgs) {
consAttrs.add(consAttr.toLowerCase());
if (currentConstructor == null || parameters.length < consArgs.length) {
currentConstructor = c;
parameters = consArgs;
usedArgs = cArgs;
}
break;
}
}
}
if (currentConstructor != null) {
component = currentConstructor.newInstance(parameters);
for (String consAttr : usedArgs) {
consAttrs.add(consAttr.toLowerCase());
}
}
if (component == null)
component = forName.newInstance();
......@@ -880,6 +911,9 @@ public class DefaultConfigurator implements Configurator {
} else {
throw new IllegalStateException("Invalid bandwidth unit.");
}
} else if (value.matches("\\d+%") || value.matches("\\d+\\.\\d+%")) {
factor = 0.01;
number = value.substring(0, value.length() - 1);
}
// Size (Byte)
if (value.matches("\\d+(B|KB|MB)")) {
......
......@@ -32,6 +32,7 @@ import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.core.SchedulerComponent;
import de.tudarmstadt.maki.simonstrator.api.component.core.SimulationRuntimeAnalyzer;
import de.tudarmstadt.maki.simonstrator.api.component.core.TimeComponent;
/**
......@@ -57,7 +58,7 @@ SchedulerComponent, TimeComponent {
private long statusInterval = SCHEDULER_WAKEUP_INTERVAL_IN_VIRTUALTIME;
private static final int INITIAL_QUEUE_CAPACITY = 5000;
private static final int INITIAL_QUEUE_CAPACITY = 50000;
private long processedEventCounter;
......@@ -93,6 +94,9 @@ SchedulerComponent, TimeComponent {
protected static final int TYPE_END = 3;
private SimulationRuntimeAnalyzer _simulationRuntimeAnalyzer;
private boolean _simulationRuntimeAnalyzerInit;
/**
* Constructs a new scheduler instance using a calendar queue. If desired,
* status events about the progress of the simulation will be plotted.
......@@ -267,8 +271,14 @@ SchedulerComponent, TimeComponent {
processedEventCounter++;
currentTime = realEvent.getSimulationTime();
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
if (realEvent.schedulerType == TYPE_END)
......@@ -298,8 +308,15 @@ SchedulerComponent, TimeComponent {
assert (realEvent.simTime == Long.MIN_VALUE);
realEvent.simTime = currentTime;
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
}
......@@ -403,8 +420,14 @@ SchedulerComponent, TimeComponent {
}
currentTime = realEvent.getSimulationTime();
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
if (realEvent.schedulerType == TYPE_END) {
......@@ -612,4 +635,16 @@ SchedulerComponent, TimeComponent {
}
}
private SimulationRuntimeAnalyzer getSimulationRuntimeAnalyzer() {
return _simulationRuntimeAnalyzer;
}
private boolean hasSimulationRuntimeAnalyzer() {
if (!_simulationRuntimeAnalyzerInit) {
_simulationRuntimeAnalyzer = Monitor.getOrNull(SimulationRuntimeAnalyzer.class);
_simulationRuntimeAnalyzerInit = true;
}
return _simulationRuntimeAnalyzer != null;
}
}
......@@ -401,8 +401,7 @@ public class Simulator implements RandomGeneratorComponent, GlobalComponent {
if (randomGenerators.containsKey(source)) {
return randomGenerators.get(source);
} else {
long thisSeed = source.toString().hashCode() + 31
* seed;
long thisSeed = source.toString().hashCode() * seed + seed;
Monitor.log(Simulator.class, Level.INFO,
"Created a new Random Source for %s with seed %d", source,
thisSeed);
......@@ -487,7 +486,7 @@ public class Simulator implements RandomGeneratorComponent, GlobalComponent {
*/
@Deprecated
public void setDatabase(String database) {
DAO.database = database;
DAO.setDatabase(database);
}
/**
......
......@@ -142,13 +142,13 @@ public class RSUMovementModel implements MovementModel {
*/
protected void initializeModel() {
if (this.sumoExe != null) {
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
_controller.init();
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, 1);
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
} else {
_controller = new XMLSimulationController(null, sumoIntersections);
_controller.init();
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
}
......
......@@ -60,6 +60,8 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private static VehicleMovementModel MOVEMENT;
public static final int TIMESTEP_RATIO = 1;
private long timeBetweenMoveOperations;
private final List<SimLocationActuator> components;
......@@ -75,16 +77,11 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private final int width;
private final int height;
private double scenarioWidth = 0;
private double scenarioHeight = 0;
private final String sumoExe;
private final String sumoConfigFile;
private final String sumoTrace;
private String sumoIntersections;
private final long timestepConversion = Time.SECOND;
private boolean initialized = false;
private VehicleController _controller;
......@@ -92,6 +89,8 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private double _percentageOfKnownRoutes = 1;
private int _startTime;
/**
* Constructor for the movement model using the sumo TraCI API
* @param timeBetweenMoveOperations The time between two movement operations.
......@@ -117,6 +116,27 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
this.offsetY = Integer.parseInt(offsetY);
this.width = Integer.parseInt(width);
this.height = Integer.parseInt(height);
Thread current = Thread.currentThread();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
StackTraceElement[] stackTrace = current.getStackTrace();
System.out.println();
System.out.println();
for (int i = 0; i < stackTrace.length; i++) {
System.out.println(stackTrace[i]);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
});
// thread.start();
}
/**
......@@ -154,6 +174,10 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
_percentageOfKnownRoutes = pPercentageOfKnownRoutes;
}
public void setStartTime(long pStartTime) {
_startTime = (int) (pStartTime / timeBetweenMoveOperations);
}
public void setReuseComponents(boolean pReuseComponents) {
_reuseComponents = pReuseComponents;
......@@ -215,14 +239,15 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
protected void initializeModel() {
// Schedule first step
if (!initialized) {
Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);
Event.scheduleWithDelay(timeBetweenMoveOperations * TIMESTEP_RATIO, this, null, 0);
if (sumoExe != null) {
TraciSimulationController simulationController = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
TraciSimulationController simulationController = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, TIMESTEP_RATIO);
_controller = simulationController;
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_controller.init();
_controller.nextStep();
simulationController.setStartTime(_startTime);
_controller.init(timeBetweenMoveOperations);
_controller.nextStep(timeBetweenMoveOperations);
_extractor = simulationController;
} else {
......@@ -235,15 +260,12 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
_controller = simulationController;
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_controller.init();
_controller.nextStep();
_controller.init(timeBetweenMoveOperations);
_controller.nextStep(timeBetweenMoveOperations);
_extractor = simulationController;
}
scenarioWidth = _extractor.getScenarioWidth();
scenarioHeight = _extractor.getScenarioHeight();
System.out.println("Initialization: done.");
}
}
......@@ -260,10 +282,12 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
* simulation performance due to less recalculations in the network
* models.
*/
long currentTime = Time.getCurrentTime() / timestepConversion;
long currentTime = Time.getCurrentTime() / timeBetweenMoveOperations;
System.out.println("Performing movement for step " + currentTime);
while (_controller.getStep() - _controller.getStart() < currentTime) {
if (!_controller.nextStep()) {
if (!_controller.nextStep(timeBetweenMoveOperations)) {
return;
}
}
......@@ -316,7 +340,7 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
}
// Reschedule next step
Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);
Event.scheduleWithDelay(timeBetweenMoveOperations * TIMESTEP_RATIO, this, null, 0);
}
/**
......@@ -385,9 +409,11 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
idComponentMatcher.put(vehicle, simLocationActuator);
hostVehicleIDMatching.put(simLocationActuator.getHost().getId(), vehicle);
} else {
if (idComponentMatcher.size() != 0) {
throw new RuntimeException("Unable to assign new components. Please increase node amount" + (_reuseComponents?".":" or enable the reuse of components."));
}
}
}
return idComponentMatcher.get(vehicle);
}
......
......@@ -52,4 +52,8 @@ public class VehicleInformationContainer {
public RoadNetworkRoute getRoute() {
return _route;
}
public void setRoute(RoadNetworkRoute pRoute) {
_route = pRoute;
}
}
\ No newline at end of file
......@@ -12,6 +12,7 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import de.tud.kom.p2psim.api.simengine.SimulatorObserver;
......@@ -19,6 +20,7 @@ import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleInformationContainer;
import de.tud.kom.p2psim.impl.topology.util.PositionVector;
import de.tudarmstadt.maki.simonstrator.api.Randoms;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.EdgeController;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
......@@ -31,6 +33,8 @@ import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.Road
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.SerializableRoadNetwork;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoAdditionalRouteAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoExitAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.paths.VehiclePathTracker;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.paths.VehiclePathTrackerFactory;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.DijkstraAlgorithm;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.RoutingAlgorithm;
import de.tudresden.sumo.cmd.Edge;
......@@ -54,7 +58,9 @@ import it.polito.appeal.traci.SumoTraciConnection;
*
*/
public class TraciSimulationController implements VehicleController, SimulationSetupExtractor, EdgeController, SimulatorObserver {
private static final File TEMP_FILE = new File(new File(System.getProperty("java.io.tmpdir")), "road_network.tmp");
private static final File TEMP_FILE = new File(new File(System.getProperty("user.home") + "/.simonstrator"), "road_network.tmp");
private static final boolean TRAIN_PATH_PROBABILITIES = false;
private Random _random = Randoms.getRandom(getClass());
......@@ -75,6 +81,8 @@ public class TraciSimulationController implements VehicleController, SimulationS
private double _endX;
private double _endY;
private int _startTime = 0;
private Map<String, VehicleInformationContainer> _positons = new HashMap<>();
private boolean _initalized = false;
......@@ -87,16 +95,23 @@ public class TraciSimulationController implements VehicleController, SimulationS
private RoutingAlgorithm _algorithm = new DijkstraAlgorithm();
public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile) {
private int _timestepRatio;
public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile, int pTimestepRatio) {
if (!CONTROLLER.containsKey(pConfigFile)) {
CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile));
CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile, pTimestepRatio));
}
return CONTROLLER.get(pConfigFile);
}
private TraciSimulationController(String pSumoExe, String pConfigFile) {
private TraciSimulationController(String pSumoExe, String pConfigFile, int pTimestepRatio) {
_sumoExe = pSumoExe;
_configFile = pConfigFile;
_timestepRatio = pTimestepRatio;
}
public void setStartTime(int pStartTime) {
_startTime = pStartTime;
}
public static VehicleController getSimulationController() {
......@@ -104,7 +119,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
}
@Override
public synchronized void init() {
public synchronized void init(long pTimeScale) {
if (!_initalized) {
Random random = Randoms.getRandom("SUMO");
......@@ -115,6 +130,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
* prevent vehicles form teleporting (http://sumo.dlr.de/wiki/Simulation/Why_Vehicles_are_teleporting)
*/
_connection.addOption("time-to-teleport", Integer.toString(-1));
_connection.addOption("step-length", String.valueOf(pTimeScale / (double)Time.SECOND));
try {
_connection.runServer();
......@@ -127,6 +143,26 @@ public class TraciSimulationController implements VehicleController, SimulationS
Simulator.getInstance().addObserver(this);
_initalized = true;
for (int i = 0; i < _startTime; i++) {
System.out.println("Pre-Start Setup: " + i + " of " + _startTime + " steps done.");
if (TRAIN_PATH_PROBABILITIES) {
Map<String, VehicleInformationContainer> positions = nextStep();
for (Entry<String, VehicleInformationContainer> entry : positions.entrySet()) {
VehiclePathTrackerFactory.getVehiclePathTracker().setEdge(entry.getKey(), entry.getValue().getRoute().getStart(), i * pTimeScale);
}
} else {
try {
_connection.do_timestep();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
if (TRAIN_PATH_PROBABILITIES) {
VehiclePathTrackerFactory.getVehiclePathTracker().disableTracking();
}
}
}
......@@ -146,6 +182,13 @@ public class TraciSimulationController implements VehicleController, SimulationS
return _positons.get(pVehicleID).getPosition();
}
@Override
public double getVehicleLength(String pVehicleID) {
SumoCommand lengthCommand = Vehicle.getLength(pVehicleID);
Object requestObject = requestObject(lengthCommand);
return (Double) requestObject;
}
@Override
public double getVehicleHeading(String pVehicleID) {
return _positons.get(pVehicleID).getHeading();
......@@ -176,10 +219,10 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
result.add(new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY, 0));
result.add(new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY));
}
} else {
result.add(new PositionVector(sumoPosition.x, sumoPosition.y, 0));
result.add(new PositionVector(sumoPosition.x, sumoPosition.y));
}
}
......@@ -205,26 +248,13 @@ public class TraciSimulationController implements VehicleController, SimulationS
return result;
}
@Override
public boolean nextStep() {
if (Simulator.getEndTime() == Simulator.getCurrentTime()) {
return false;
}
private Map<String, VehicleInformationContainer> nextStep() {
try {
for (int i = 0; i < _timestepRatio; i++) {
_connection.do_timestep();
try {
synchronized (_positons) {
_positons.clear();
int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());
_step = temp / 1000.0;
if (_start == -1) {
_start = _step;
}
try {
Map<String, VehicleInformationContainer> vehiclePositions = new HashMap<>();
List<String> allVehicles = requestAllVehicles();
......@@ -240,20 +270,42 @@ public class TraciSimulationController implements VehicleController, SimulationS
vehiclePositions.put(vehicle, informationContainer);
}
}
_positons = vehiclePositions;
return vehiclePositions;
} catch (Exception e) {
throw new AssertionError(e);
}
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError(e);
}
}
return true;
} catch (RuntimeException e) {
throw e;
@Override
public boolean nextStep(long pTimeScale) {
if (Simulator.getEndTime() == Simulator.getCurrentTime()) {
return false;
}
Map<String, VehicleInformationContainer> vehiclePositions = nextStep();
try {
int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());
_step = temp / (pTimeScale / (double)Time.MILLISECOND);
if (_start == -1) {
_start = _step;
}
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError(e);
}
if (vehiclePositions != null) {
_positons = vehiclePositions;
return true;
} else {
_positons.clear();
return false;
}
}
private Location requestVehiclePosition(String pVehicleID) {
if (_vehiclesOutOfRange.containsKey(pVehicleID)) {
......@@ -272,7 +324,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
return new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY, 0);
return new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY);
} else {
double diffX = _startX - sumoPosition.x;
if (diffX < 0 || sumoPosition.x - _endX < diffX) {
......@@ -297,7 +349,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
return null;
}
} else {
return new PositionVector(sumoPosition.x, sumoPosition.y, 0);
return new PositionVector(sumoPosition.x, sumoPosition.y);
}
}
......@@ -314,7 +366,6 @@ public class TraciSimulationController implements VehicleController, SimulationS
Object angleObject = requestObject(angleCommand);
if (angleObject != null) {
return (Double) angleObject;
}
......@@ -408,7 +459,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
add = true;
}
if (add) {
streets.add(_roadNetwork.getEdge(street));
RoadNetworkEdge edge = _roadNetwork.getEdge(street);
streets.add(edge);
if (!edge.isUsable()) {
break;
}
}
}
......@@ -485,7 +540,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
try {
SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
if (_observedAreaSet) {
return Math.max(Math.min(netBoundary.x_max, _endX) - Math.max(netBoundary.x_min, _startX), 10);
} else {
return Math.max(netBoundary.x_max - netBoundary.x_min, 10);
}
} catch (Exception e) {
//Nothing to do
}
......@@ -498,7 +557,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
try {
SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
if (_observedAreaSet) {
return Math.max(Math.min(netBoundary.y_max, _endY) - Math.max(netBoundary.y_min, _startY), 10);
} else {
return Math.max(netBoundary.y_max - netBoundary.y_min, 10);
}
} catch (Exception e) {
//Nothing to do
}
......@@ -610,6 +673,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
routeEdges.add(edge.getEdgeID());
}
execute(Vehicle.setRoute(pVehicle, routeEdges));
_positons.get(pVehicle).setRoute(pRoute);
}
@Override
......@@ -707,12 +771,14 @@ public class TraciSimulationController implements VehicleController, SimulationS
_roadNetwork = new RoadNetwork(roadNetwork, this, true);
try {
if (TEMP_FILE.getParentFile().exists() || TEMP_FILE.getParentFile().mkdirs()) {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(TEMP_FILE));
outputStream.writeObject(new SerializableRoadNetwork(_roadNetwork));
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
//Nothing to do
e.printStackTrace();
......@@ -749,19 +815,19 @@ public class TraciSimulationController implements VehicleController, SimulationS
public List<Location> getLaneShape(String pLaneID) {
List<Location> positions = new ArrayList<>();
boolean set = true;
boolean set = false;
SumoCommand laneShapeCommand = Lane.getShape(pLaneID);
SumoGeometry geometry = (SumoGeometry)requestObject(laneShapeCommand);
for (SumoPosition2D location : geometry.coords) {
if (!isObservedAreaSet()) {
positions.add(new PositionVector(location.x, location.y));
set = true;
} else {
if (_startX <= location.x && location.x <= _endX && _startY <= location.y && location.y <= _endY) {
positions.add(new PositionVector(location.x - _startX, location.y - _startY));
} else {
set = true;
}
positions.add(new PositionVector(location.x - _startX, location.y - _startY));
}
}
......@@ -830,8 +896,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
length += (double) object;
}
if ((_roadNetwork.getEdge(pEdgeID).getLaneAmount()) != 0) {
return length / (_roadNetwork.getEdge(pEdgeID).getLaneAmount());
} else {
return 0.0;
}
}
@Override
......@@ -839,10 +908,12 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
List<RoadNetworkLane> lanes = _roadNetwork.getEdge(pEdgeID).getLanes();
if (lanes.size() > 0) {
List<Location> laneShape = getLaneShape(lanes.get(0).getLaneID());
for (RoadNetworkLane lane : lanes) {
List<Location> laneShape = getLaneShape(lane.getLaneID());
if (laneShape.size() > 1) {
return true;
}
}
}
return false;
}
......
......@@ -12,6 +12,7 @@ import javax.xml.parsers.SAXParserFactory;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleInformationContainer;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.csv.RoadSideUnitInformationHandler;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.VehicleController;
......@@ -49,7 +50,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
}
@Override
public void init() {
public void init(long timeBetweenMoveOperations) {
if (!_initalized) {
if (_vehicleDataPath != null) {
......@@ -57,7 +58,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
thread.start();
for (int i = 0; i < _futureInformation; i++) {
nextStep();
nextStep(Time.SECOND);
}
}
if (_roadSideUnitDataPath != null) {
......@@ -77,7 +78,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
}
@Override
public boolean nextStep() {
public boolean nextStep(long pTimeScale) {
_vehicleDataInformationHandler.readNext();
_step = _vehicleDataInformationHandler.getStep() - _futureInformation;
......@@ -171,6 +172,11 @@ public class XMLSimulationController implements VehicleController, SimulationSet
return -1;
}
@Override
public double getVehicleLength(String pVehicleID) {
throw new UnsupportedOperationException("This method is not supported for " + getClass().getSimpleName());
}
@Override
public RoadNetworkRoute getCurrentRoute(String pVehicleID) {
throw new UnsupportedOperationException("This method is not supported for " + getClass().getSimpleName());
......
......@@ -27,6 +27,7 @@ import de.tud.kom.p2psim.api.topology.placement.PlacementModel;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci.TraciSimulationController;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.xml.XMLSimulationController;
import de.tud.kom.p2psim.impl.topology.util.PositionVector;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;
......@@ -86,13 +87,13 @@ public class RSUPlacement implements PlacementModel {
*/
protected void initializeModel() {
if (this.sumoExe != null) {
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
_controller.init();
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, 1);
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
} else {
_controller = new XMLSimulationController(null, sumoIntersections);
_controller.init();
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
}
......
......@@ -22,11 +22,23 @@ package de.tud.kom.p2psim.impl.util.db.dao;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.commons.math3.analysis.function.Exp;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import de.tud.kom.p2psim.impl.util.db.metric.CustomMeasurement;
import de.tud.kom.p2psim.impl.util.db.metric.Experiment;
......@@ -45,6 +57,7 @@ import de.tud.kom.p2psim.impl.util.db.metric.Metric;
import de.tud.kom.p2psim.impl.util.db.metric.MetricDescription;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.web.WebConfigurationManager;
/**
* This class represents a simple access to persist objects with Hibernate. It
......@@ -175,6 +188,30 @@ public class DAO {
return currSession;
}
public static void setDatabase(String pDatabase) {
if (!WebConfigurationManager.isActive()) {
database = pDatabase;
} else {
database = WebConfigurationManager.getConfig().getOptions().getDatabase().getDatabase();
}
}
public static void setUsername(String pUsername) {
if (!WebConfigurationManager.isActive()) {
username = pUsername;
} else {
username = WebConfigurationManager.getConfig().getOptions().getDatabase().getUsername();
}
}
public static void setPassword(String pPassword) {
if (!WebConfigurationManager.isActive()) {
password = pPassword;
} else {
password = WebConfigurationManager.getConfig().getOptions().getDatabase().getPassword();
}
}
/**
* Gets the session
*
......@@ -282,6 +319,15 @@ public class DAO {
DAO.session.remove();
}
public static <T extends Object> List<T> retrieve(Class<T> pClass) {
begin();
Criteria criteria = getSession().createCriteria(pClass);
List<T> objects = criteria.list();
commit();
return objects;
}
/**
* Persist the given POJO directly to the DB. Should be make, if it exists
* relationships between tables.
......
Markdown is supported
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