TraciSimulationController.java 14.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
package de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.tud.kom.p2psim.impl.topology.movement.vehicular.information.LocationUtils;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.information.Position;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.SimulationSetupExtractor;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleController;
13
14
15
16
17
18
19
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetwork;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkEdge;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.RoadNetworkRoute;
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.routing.BreathFirstSearchRoutingAlgorithm;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.RoutingAlgorithm;
20
import de.tudresden.sumo.cmd.Junction;
21
import de.tudresden.sumo.cmd.Lane;
22
23
24
import de.tudresden.sumo.cmd.Simulation;
import de.tudresden.sumo.cmd.Vehicle;
import de.tudresden.sumo.util.SumoCommand;
25
import de.tudresden.ws.container.SumoBoundingBox;
26
27
import de.tudresden.ws.container.SumoLink;
import de.tudresden.ws.container.SumoLinkList;
28
29
30
31
32
33
import de.tudresden.ws.container.SumoPosition2D;
import de.tudresden.ws.container.SumoStringList;
import it.polito.appeal.traci.SumoTraciConnection;

public class TraciSimulationController implements VehicleController, SimulationSetupExtractor {

34
	private static final Map<String, TraciSimulationController> CONTROLLER = new HashMap<>();
35

36
	private static final double CLUSTERING_DISTANCE = 50;
37

38
39
	private String _sumoExe;
	private String _configFile;
40

41
	private SumoTraciConnection _connection;
42

43
44
	private double _start = -1;
	private double _step = -1;
45

46
47
48
49
	private double _startX;
	private double _startY;
	private double _endX;
	private double _endY;
50

51
	private Map<Double, Map<String, Position>> _positonsByTimestamp = new HashMap<>();
52
	private int _futureInformation = 0;
53

54
	private boolean _initalized = false;
55

56
	private boolean _observedAreaSet;
57

58
	private Map<String, Double> _vehiclesOutOfRange = new HashMap<>();
59

60
61
62
63
	private RoadNetwork _roadNetwork;

	private RoutingAlgorithm _algorithm = new BreathFirstSearchRoutingAlgorithm();

64
65
66
67
68
69
	public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile) {
		if (!CONTROLLER.containsKey(pConfigFile)) {
			CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile));
		}
		return CONTROLLER.get(pConfigFile);
	}
70

71
72
73
74
	private TraciSimulationController(String pSumoExe, String pConfigFile) {
		_sumoExe = pSumoExe;
		_configFile = pConfigFile;
	}
75

76
77
78
	public static VehicleController getSimulationController() {
		return CONTROLLER.values().iterator().next();
	}
79

80
81
82
83
	@Override
	public synchronized void init() {
		if (!_initalized) {
			_connection = new SumoTraciConnection(_sumoExe, _configFile);
84

85
86
			try {
				_connection.runServer();
87

88
89
90
91
92
93
94
95
				for (int i = 0; i < _futureInformation; i++) {
					nextStep();
				}
			} catch (RuntimeException e) {
				throw e;
			} catch (Exception e) {
				e.printStackTrace();
			}
96

97
			Runnable shutdownHook = new Runnable() {
98

99
100
101
102
103
				@Override
				public void run() {
					_connection.close();
				}
			};
104

105
			Runtime.getRuntime().addShutdownHook(new Thread(shutdownHook));
106

107
108
109
			_initalized = true;
		}
	}
110

111
112
113
114
	@Override
	public Position getVehiclePosition(String pVehicleID) {
		return getVehiclePosition(_step, pVehicleID);
	}
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
	@Override
	public Position getVehiclePosition(double pStep, String pVehicleID) {
		Map<String, Position> map = _positonsByTimestamp.get(pStep);

		return map.get(pVehicleID);
	}

	@Override
	public List<Position> getAllIntersections(boolean pCluster) {
		List<Position> result = new ArrayList<>();

		SumoCommand intersectionCommand = Junction.getIDList();

		Object intersectionObject = requestObject(intersectionCommand);

		SumoStringList intersections = (SumoStringList) intersectionObject;

		for (String intersection : intersections) {
			SumoCommand positionCommand = Junction.getPosition(intersection);
			Object positionObject = requestObject(positionCommand);
			SumoPosition2D sumoPosition = (SumoPosition2D) positionObject;

			if (_observedAreaSet) {
				if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
					result.add(new Position(sumoPosition.x - _startX, sumoPosition.y - _startY, 0, 0));
				}
			} else {
				result.add(new Position(sumoPosition.x, sumoPosition.y, 0, 0));
			}
		}

		if (pCluster) {
			List<Position> tempResult = new ArrayList<>();

			outer:for (int i = 0; i < result.size(); i++) {
				Position position = result.get(i);

				for (int j = 0; j < tempResult.size(); j++) {
					Position addedPosition = tempResult.get(j);
					if (position != addedPosition && LocationUtils.calculateDistance(position, addedPosition) < CLUSTERING_DISTANCE / 1000.0) {
						continue outer;
					}
				}

				tempResult.add(position);
			}

			result = tempResult;
		}

		return result;
	}

	@Override
	public boolean nextStep() {
		try {
			_connection.do_timestep();

			try {
				int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());

				_step = temp / 1000.0 - _futureInformation;

				if (_start == -1) {
					_start = _step + _futureInformation;
				}

				double newStep = _step + _futureInformation;
				if (!_positonsByTimestamp.containsKey(newStep)) {
					Map<String, Position> vehiclePositions = new HashMap<>();
					_positonsByTimestamp.put(newStep, vehiclePositions);

					List<String> allVehicles = requestAllVehicles();
					for (String vehicle : allVehicles) {
						Position vehiclePosition = requestVehiclePosition(vehicle);
						if (vehiclePosition != null) {
							vehiclePositions.put(vehicle, vehiclePosition);
						}
					}
				}

				if (_positonsByTimestamp.containsKey(_step - 1)) {
					_positonsByTimestamp.remove(_step - 1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return true;
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private Position requestVehiclePosition(String pVehicleID) {
		if (_vehiclesOutOfRange.containsKey(pVehicleID)) {
			if (_vehiclesOutOfRange.get(pVehicleID) < _step) {
				return null;
			} else {
				_vehiclesOutOfRange.remove(pVehicleID);
			}
		}

		SumoCommand positionCommand = Vehicle.getPosition(pVehicleID);
		SumoCommand angleCommand = Vehicle.getAngle(pVehicleID);
		SumoCommand speedCommand = Vehicle.getSpeed(pVehicleID);

		Object positionObject = requestObject(positionCommand);
		Object angleObject = requestObject(angleCommand);
		Object speedObject = requestObject(speedCommand);

		SumoPosition2D sumoPosition = (SumoPosition2D) positionObject;
		double angle = (Double) angleObject;
		double speed = (Double) speedObject;

		if (_observedAreaSet) {
			if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
				return new Position(sumoPosition.x - _startX, sumoPosition.y - _startY, 0, angle, speed);
			} else {
				double diffX = _startX - sumoPosition.x;
				if (diffX < 0 || sumoPosition.x - _endX < diffX) {
					diffX = sumoPosition.x - _endX;
				}
				if (diffX < 0) {
					diffX = 0;
				}
				double diffY = _startY - sumoPosition.y;
				if (diffY < 0 || sumoPosition.y - _endY < diffY) {
					diffY = sumoPosition.y - _endY;
				}
				if (diffY < 0) {
					diffY = 0;
				}
				double diff = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));

				double timeTillNextJoin = diff / 50;

				//                _vehiclesOutOfRange.put(pVehicleID, _step + timeTillNextJoin);

				return null;
			}
		} else {
			return new Position(sumoPosition.x, sumoPosition.y, 0, angle);
		}
	}

	private List<String> requestAllVehicles() {
		SumoCommand idList = Vehicle.getIDList();
		Object object = requestObject(idList);
		SumoStringList list = (SumoStringList)object;

		List<String> result = new ArrayList<>();

		for (String vehicle : list) {
			result.add(vehicle);
		}

		return result;
	}

	@Override
	public List<String> getAllVehicles() {
		return getAllVehicles(_step);
	}

	@Override
	public List<String> getAllVehicles(double pStep) {
		Map<String, Position> map = _positonsByTimestamp.get(pStep);

		return new ArrayList<>(map.keySet());
	}

291
292
	@Override
	public RoadNetworkRoute getCurrentRoute(String pVehicleID) {
293
294
295
296
		SumoCommand routeCommand = Vehicle.getRoute(pVehicleID);
		Object object = requestObject(routeCommand);
		SumoStringList streetList = (SumoStringList) object;

297
298
299
		SumoCommand roadIDCommand = Vehicle.getRoadID(pVehicleID);
		String currentRoadID = (String) requestObject(roadIDCommand);

300
301
302
		obtainRoadNetwork();

		List<RoadNetworkEdge> streets = new ArrayList<>();
303
		boolean add = false;
304
		for (String street : streetList) {
305
306
307
308
309
310
311
312
313
314
315
316
317
			if (street.equals(currentRoadID)) {
				add = true;
			}
			if (add) {
				streets.add(_roadNetwork.getEdge(street));
			}
		}


		if (streets.size() == 0) {
			for (String street : streetList) {
				streets.add(_roadNetwork.getEdge(street));
			}
318
319
		}

320
		return new RoadNetworkRoute(streets);
321
322
323
324
325
326
327
328
329
330
331
332
333
334
	}

	public Object requestObject(SumoCommand routeCommand) {
		Object object = null;
		try {
			object = _connection.do_job_get(routeCommand);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

335
336
337
338
339
340
341
342
343
344
	public void execute(SumoCommand routeCommand) {
		try {
			_connection.do_job_set(routeCommand);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
	@Override
	public double getStep() {
		return _step;
	}

	@Override
	public double getStart() {
		return _start;
	}

	@Override
	public double getMaximumAvailablePrediction() {
		double max = Collections.max(_positonsByTimestamp.keySet());

		return max;
	}

	@Override
	public void setObservedArea(double pStartX, double pStartY, double pEndX, double pEndY) {
		_startX = pStartX;
		_startY = pStartY;
		_endX = pEndX;
		_endY = pEndY;

		_observedAreaSet = true;
	}

	@Override
	public double getScenarioWidth() {
		SumoCommand netBoundaryCommand = Simulation.getNetBoundary();

		try {
			SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
378
			return Math.max(netBoundary.x_max - netBoundary.x_min, 10);
379
380
381
382
383
384
385
386
387
388
389
390
		} catch (Exception e) {
			//Nothing to do
		}
		return -1;
	}

	@Override
	public double getScenarioHeight() {
		SumoCommand netBoundaryCommand = Simulation.getNetBoundary();

		try {
			SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
391
			return Math.max(netBoundary.y_max - netBoundary.y_min, 10);
392
393
394
395
396
		} catch (Exception e) {
			//Nothing to do
		}
		return -1;
	}
397

398
399
400
401
402
	public boolean providesRoadInformation() {
		return true;
	}

	public RoadNetworkEdge getVehicleDestination(String pVehicleID) {
403
		RoadNetworkRoute roadNetworkRoute = getCurrentRoute(pVehicleID);
404
405
406
407
408
409
410
411
412
413
414
415

		return roadNetworkRoute.getDestination();
	}

	public RoadNetwork getRoadNetwork() {
		obtainRoadNetwork();

		return _roadNetwork;
	}

	public RoadNetworkRoute findNewRoute(String pVehicle) throws NoAdditionalRouteAvailableException {
		List<RoadNetworkRoute> routes = new ArrayList<>();
416
		RoadNetworkRoute route = getCurrentRoute(pVehicle);
417
418
419
420
421
422
423
424
425
426
427
		routes.add(route);
		RoadNetworkRoute findRoute = _algorithm.findRoute(_roadNetwork, route.getStart(), route.getDestination(), routes);
		if (findRoute == null) {
			throw new NoAdditionalRouteAvailableException(route.getStart(), route.getDestination(), routes);
		}
		return findRoute;
	}

	public RoadNetworkRoute findNewRoute(String pVehicle, List<RoadNetworkEdge> pEdgesToAvoid, boolean pKeepDestination) throws NoAdditionalRouteAvailableException, NoExitAvailableException {
		if (pKeepDestination) {
			List<RoadNetworkRoute> routes = new ArrayList<>();
428
			RoadNetworkRoute route = getCurrentRoute(pVehicle);
429
430
431
432
433
434
435
436
			routes.add(route);

			RoadNetworkRoute findRoute = _algorithm.findRoute(_roadNetwork, route.getStart(), route.getDestination(), routes, pEdgesToAvoid);
			if (findRoute == null) {
				throw new NoAdditionalRouteAvailableException(route.getStart(), route.getDestination(), routes);
			}
			return findRoute;
		} else {
437
			RoadNetworkRoute route = getCurrentRoute(pVehicle);
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
			List<RoadNetworkEdge> routeList = route.getRoute();

			RoadNetworkEdge lastEdge = null;
			boolean search = false;
			outer:for (int i = routeList.size() - 1; i >= 0; i--) {
				if (search) {
					List<RoadNetworkEdge> accessibleEdges = routeList.get(i).getAccessibleEdges();
					if (accessibleEdges.size() > 1) {
						for (int j = 0; j < accessibleEdges.size(); j++) {
							if (!accessibleEdges.get(j).equals(lastEdge)) {
								List<RoadNetworkEdge> edges = new ArrayList<>();

								for (int k = 0; k <= i; k++) {
									edges.add(routeList.get(k));
								}
								edges.add(accessibleEdges.get(j));

								for (RoadNetworkEdge roadNetworkEdge : edges) {
									if (pEdgesToAvoid.contains(roadNetworkEdge)) {
										continue outer;
									}
								}

								return new RoadNetworkRoute(edges);
							}
						}
					}
				}
				search = true;
				lastEdge = routeList.get(i);
			}
			throw new NoExitAvailableException(route.getStart(), route.getDestination());
		}
	}

	public void rerouteVehicle(String pVehicle, RoadNetworkRoute pRoute) {
		SumoStringList routeEdges = new SumoStringList();
		for (RoadNetworkEdge edge : pRoute.getRoute()) {
			routeEdges.add(edge.getEdgeID());
		}
		execute(Vehicle.setRoute(pVehicle, routeEdges));
	}

	public void obtainRoadNetwork() {
		if (_roadNetwork == null) {
			SumoCommand laneIDCommand = Lane.getIDList();

			Map<String, RoadNetworkEdge> roadNetwork = new HashMap<>();

			SumoStringList laneIDStringList = (SumoStringList) requestObject(laneIDCommand);
			for (String laneID : laneIDStringList) {
				SumoCommand edgeIDCommand = Lane.getEdgeID(laneID);

				SumoLinkList linkStringList = (SumoLinkList) requestObject(Lane.getLinks(laneID));

				if (linkStringList.size() > 0) {
					String edgeID = (String) requestObject(edgeIDCommand);

					if (!roadNetwork.containsKey(edgeID)) {
						roadNetwork.put(edgeID, new RoadNetworkEdge(edgeID));
					}

					RoadNetworkEdge edge = roadNetwork.get(edgeID);

					for (SumoLink link : linkStringList) {
						String notInternalLane = link.notInternalLane;
						String connectedEdge = (String) requestObject(Lane.getEdgeID(notInternalLane));

						if (!roadNetwork.containsKey(connectedEdge)) {
							roadNetwork.put(connectedEdge, new RoadNetworkEdge(connectedEdge));
						}

						edge.addConnectedEdge(roadNetwork.get(connectedEdge));
					}
				}


			}
			_roadNetwork = new RoadNetwork(roadNetwork);
		}
	}

520
}