Line data Source code
1 : /****************************************************************************/
2 : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3 : // Copyright (C) 2007-2026 German Aerospace Center (DLR) and others.
4 : // This program and the accompanying materials are made available under the
5 : // terms of the Eclipse Public License 2.0 which is available at
6 : // https://www.eclipse.org/legal/epl-2.0/
7 : // This Source Code may also be made available under the following Secondary
8 : // Licenses when the conditions for such availability set forth in the Eclipse
9 : // Public License 2.0 are satisfied: GNU General Public License, version 2
10 : // or later which is available at
11 : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12 : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13 : /****************************************************************************/
14 : /// @file TraCIServer.cpp
15 : /// @author Axel Wegener
16 : /// @author Friedemann Wesner
17 : /// @author Christoph Sommer
18 : /// @author Jakob Erdmann
19 : /// @author Daniel Krajzewicz
20 : /// @author Thimor Bohn
21 : /// @author Tino Morenz
22 : /// @author Laura Bieker
23 : /// @author Michael Behrisch
24 : /// @author Mario Krumnow
25 : /// @author Leonhard Luecken
26 : /// @date 2007/10/24
27 : ///
28 : // TraCI server used to control sumo by a remote TraCI client (e.g., ns2)
29 : /****************************************************************************/
30 : #include <config.h>
31 :
32 : #ifdef HAVE_VERSION_H
33 : #include <version.h>
34 : #endif
35 :
36 : #include <string>
37 : #include <cmath>
38 : #include <map>
39 : #include <iostream>
40 : #include <algorithm>
41 : #include <foreign/tcpip/socket.h>
42 : #include <foreign/tcpip/storage.h>
43 : #include <utils/common/SUMOTime.h>
44 : #include <utils/router/DijkstraRouter.h>
45 : #include <utils/common/NamedObjectCont.h>
46 : #include <utils/common/RandHelper.h>
47 : #include <utils/common/MsgHandler.h>
48 : #include <utils/vehicle/SUMOVehicleParameter.h>
49 : #include <utils/shapes/PointOfInterest.h>
50 : #include <utils/shapes/ShapeContainer.h>
51 : #include <utils/xml/XMLSubSys.h>
52 : #include <microsim/MSNet.h>
53 : #include <microsim/MSVehicle.h>
54 : #include <microsim/MSEdge.h>
55 : #include <microsim/MSJunctionControl.h>
56 : #include <microsim/transportables/MSTransportableControl.h>
57 : #include <microsim/MSJunction.h>
58 : #include <microsim/MSEdgeControl.h>
59 : #include <microsim/MSLane.h>
60 : #include <microsim/MSGlobals.h>
61 : #include <microsim/traffic_lights/MSTLLogicControl.h>
62 : #include <libsumo/Helper.h>
63 : #include <libsumo/StorageHelper.h>
64 : #include <libsumo/libsumo.h>
65 : #include <libsumo/Subscription.h>
66 : #include <libsumo/TraCIConstants.h>
67 : #include "TraCIServer.h"
68 : #include "TraCIServerAPI_InductionLoop.h"
69 : #include "TraCIServerAPI_Junction.h"
70 : #include "TraCIServerAPI_Lane.h"
71 : #include "TraCIServerAPI_MultiEntryExit.h"
72 : #include "TraCIServerAPI_LaneArea.h"
73 : #include "TraCIServerAPI_TrafficLight.h"
74 : #include "TraCIServerAPI_Vehicle.h"
75 : #include "TraCIServerAPI_VehicleType.h"
76 : #include "TraCIServerAPI_Route.h"
77 : #include "TraCIServerAPI_POI.h"
78 : #include "TraCIServerAPI_Polygon.h"
79 : #include "TraCIServerAPI_Edge.h"
80 : #include "TraCIServerAPI_Simulation.h"
81 : #include "TraCIServerAPI_Person.h"
82 : #include "TraCIServerAPI_Calibrator.h"
83 : #include "TraCIServerAPI_BusStop.h"
84 : #include "TraCIServerAPI_ParkingArea.h"
85 : #include "TraCIServerAPI_ChargingStation.h"
86 : #include "TraCIServerAPI_RouteProbe.h"
87 : #include "TraCIServerAPI_Rerouter.h"
88 : #include "TraCIServerAPI_VariableSpeedSign.h"
89 : #include "TraCIServerAPI_MeanData.h"
90 : #include "TraCIServerAPI_OverheadWire.h"
91 :
92 :
93 : // ===========================================================================
94 : // debug constants
95 : // ===========================================================================
96 : //#define DEBUG_MULTI_CLIENTS
97 : //#define DEBUG_SUBSCRIPTIONS
98 : //#define DEBUG_SUBSCRIPTION_FILTERS
99 : //#define DEBUG_RAW_INPUT
100 :
101 :
102 : // ===========================================================================
103 : // static member definitions
104 : // ===========================================================================
105 : TraCIServer* TraCIServer::myInstance = nullptr;
106 : bool TraCIServer::myDoCloseConnection = false;
107 :
108 :
109 : // ===========================================================================
110 : // method definitions
111 : // ===========================================================================
112 : void
113 15473124 : TraCIServer::initWrapper(const int domainID, const int variable, const std::string& objID) {
114 15473124 : myWrapperStorage.reset();
115 15473124 : myWrapperStorage.writeUnsignedByte(domainID);
116 15473124 : myWrapperStorage.writeUnsignedByte(variable);
117 15473124 : myWrapperStorage.writeString(objID);
118 15473124 : }
119 :
120 :
121 : bool
122 51 : TraCIServer::wrapConnectionVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIConnection>& value) {
123 51 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 8);
124 51 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
125 139 : for (const libsumo::TraCIConnection& c : value) {
126 88 : StoHelp::writeTypedString(myWrapperStorage, c.approachedLane);
127 88 : StoHelp::writeTypedString(myWrapperStorage, c.approachedInternal);
128 88 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, c.hasPrio);
129 88 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, c.isOpen);
130 88 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, c.hasFoe);
131 88 : StoHelp::writeTypedString(myWrapperStorage, c.state);
132 88 : StoHelp::writeTypedString(myWrapperStorage, c.direction);
133 88 : StoHelp::writeTypedDouble(myWrapperStorage, c.length);
134 : }
135 51 : return true;
136 : }
137 :
138 :
139 : bool
140 5681648 : TraCIServer::wrapDouble(const std::string& /* objID */, const int /* variable */, const double value) {
141 5681648 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_DOUBLE);
142 5681648 : myWrapperStorage.writeDouble(value);
143 5681648 : return true;
144 : }
145 :
146 :
147 : bool
148 244230 : TraCIServer::wrapInt(const std::string& /* objID */, const int /* variable */, const int value) {
149 244230 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_INTEGER);
150 244230 : myWrapperStorage.writeInt(value);
151 244230 : return true;
152 : }
153 :
154 :
155 : bool
156 6651222 : TraCIServer::wrapString(const std::string& /* objID */, const int /* variable */, const std::string& value) {
157 6651222 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_STRING);
158 6651222 : myWrapperStorage.writeString(value);
159 6651222 : return true;
160 : }
161 :
162 :
163 : bool
164 253479 : TraCIServer::wrapStringList(const std::string& /* objID */, const int /* variable */, const std::vector<std::string>& value) {
165 253479 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_STRINGLIST);
166 253479 : myWrapperStorage.writeStringList(value);
167 253479 : return true;
168 : }
169 :
170 :
171 : bool
172 72 : TraCIServer::wrapDoubleList(const std::string& /* objID */, const int /* variable */, const std::vector<double>& value) {
173 72 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_DOUBLELIST);
174 72 : myWrapperStorage.writeDoubleList(value);
175 72 : return true;
176 : }
177 :
178 :
179 : bool
180 2466526 : TraCIServer::wrapPosition(const std::string& /* objID */, const int variable, const libsumo::TraCIPosition& value) {
181 : const bool includeZ = variable == libsumo::VAR_POSITION3D;
182 4931808 : myWrapperStorage.writeUnsignedByte(includeZ ? libsumo::POSITION_3D : libsumo::POSITION_2D);
183 2466526 : myWrapperStorage.writeDouble(value.x);
184 2466526 : myWrapperStorage.writeDouble(value.y);
185 2466526 : if (includeZ) {
186 1244 : myWrapperStorage.writeDouble(value.z);
187 : }
188 2466526 : return true;
189 : }
190 :
191 :
192 : bool
193 18124 : TraCIServer::wrapPositionVector(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIPositionVector& shape) {
194 18124 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_POLYGON);
195 18124 : if (shape.value.size() < 256) {
196 18121 : myWrapperStorage.writeUnsignedByte((int)shape.value.size());
197 : } else {
198 3 : myWrapperStorage.writeUnsignedByte(0);
199 3 : myWrapperStorage.writeInt((int)shape.value.size());
200 : }
201 62799 : for (const libsumo::TraCIPosition& pos : shape.value) {
202 44675 : myWrapperStorage.writeDouble(pos.x);
203 44675 : myWrapperStorage.writeDouble(pos.y);
204 : }
205 18124 : return true;
206 : }
207 :
208 :
209 : bool
210 729 : TraCIServer::wrapColor(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIColor& value) {
211 729 : myWrapperStorage.writeUnsignedByte(libsumo::TYPE_COLOR);
212 729 : myWrapperStorage.writeUnsignedByte(value.r);
213 729 : myWrapperStorage.writeUnsignedByte(value.g);
214 729 : myWrapperStorage.writeUnsignedByte(value.b);
215 729 : myWrapperStorage.writeUnsignedByte(value.a);
216 729 : return true;
217 : }
218 :
219 :
220 : bool
221 22603 : TraCIServer::wrapStringDoublePair(const std::string& /* objID */, const int /* variable */, const std::pair<std::string, double>& value) {
222 22603 : StoHelp::writeCompound(myWrapperStorage, 2);
223 22603 : StoHelp::writeTypedString(myWrapperStorage, value.first);
224 22603 : StoHelp::writeTypedDouble(myWrapperStorage, value.second);
225 22603 : return true;
226 : }
227 :
228 :
229 : bool
230 2926 : TraCIServer::wrapStringDoublePairList(const std::string& /* objID */, const int /* variable */, const std::vector<std::pair<std::string, double> >& value) {
231 2926 : StoHelp::writeCompound(myWrapperStorage, (int)value.size());
232 3870 : for (const auto& p : value) {
233 944 : myWrapperStorage.writeString(p.first);
234 944 : myWrapperStorage.writeDouble(p.second);
235 : }
236 2926 : return true;
237 : }
238 :
239 :
240 : bool
241 312 : TraCIServer::wrapStringPair(const std::string& /* objID */, const int /* variable */, const std::pair<std::string, std::string>& value) {
242 312 : StoHelp::writeCompound(myWrapperStorage, 2);
243 312 : StoHelp::writeTypedString(myWrapperStorage, value.first);
244 312 : StoHelp::writeTypedString(myWrapperStorage, value.second);
245 312 : return true;
246 : }
247 :
248 :
249 : bool
250 7113 : TraCIServer::wrapIntPair(const std::string& /* objID */, const int /* variable */, const std::pair<int, int>& value) {
251 7113 : StoHelp::writeCompound(myWrapperStorage, 2);
252 7113 : StoHelp::writeTypedInt(myWrapperStorage, value.first);
253 7113 : StoHelp::writeTypedInt(myWrapperStorage, value.second);
254 7113 : return true;
255 : }
256 :
257 :
258 : bool
259 441 : TraCIServer::wrapStage(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIStage& value) {
260 441 : StoHelp::writeStage(myWrapperStorage, value);
261 441 : return true;
262 : }
263 :
264 :
265 : bool
266 3086 : TraCIServer::wrapReservationVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIReservation>& value) {
267 3086 : StoHelp::writeCompound(myWrapperStorage, (int)value.size());
268 8305 : for (const libsumo::TraCIReservation& r : value) {
269 : StoHelp::writeCompound(myWrapperStorage, 10);
270 5219 : StoHelp::writeTypedString(myWrapperStorage, r.id);
271 5219 : StoHelp::writeTypedStringList(myWrapperStorage, r.persons);
272 5219 : StoHelp::writeTypedString(myWrapperStorage, r.group);
273 5219 : StoHelp::writeTypedString(myWrapperStorage, r.fromEdge);
274 5219 : StoHelp::writeTypedString(myWrapperStorage, r.toEdge);
275 5219 : StoHelp::writeTypedDouble(myWrapperStorage, r.departPos);
276 5219 : StoHelp::writeTypedDouble(myWrapperStorage, r.arrivalPos);
277 5219 : StoHelp::writeTypedDouble(myWrapperStorage, r.depart);
278 5219 : StoHelp::writeTypedDouble(myWrapperStorage, r.reservationTime);
279 5219 : StoHelp::writeTypedInt(myWrapperStorage, r.state);
280 : }
281 3086 : return true;
282 : }
283 :
284 :
285 : bool
286 68 : TraCIServer::wrapLogicVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCILogic>& value) {
287 68 : StoHelp::writeCompound(myWrapperStorage, (int)value.size());
288 177 : for (const libsumo::TraCILogic& logic : value) {
289 : StoHelp::writeCompound(myWrapperStorage, 5);
290 109 : StoHelp::writeTypedString(myWrapperStorage, logic.programID);
291 109 : StoHelp::writeTypedInt(myWrapperStorage, logic.type);
292 109 : StoHelp::writeTypedInt(myWrapperStorage, logic.currentPhaseIndex);
293 109 : StoHelp::writeCompound(myWrapperStorage, (int)logic.phases.size());
294 843 : for (const std::shared_ptr<libsumo::TraCIPhase>& phase : logic.phases) {
295 : StoHelp::writeCompound(myWrapperStorage, 6);
296 734 : StoHelp::writeTypedDouble(myWrapperStorage, phase->duration);
297 734 : StoHelp::writeTypedString(myWrapperStorage, phase->state);
298 734 : StoHelp::writeTypedDouble(myWrapperStorage, phase->minDur);
299 734 : StoHelp::writeTypedDouble(myWrapperStorage, phase->maxDur);
300 734 : StoHelp::writeCompound(myWrapperStorage, (int)phase->next.size());
301 866 : for (int n : phase->next) {
302 : StoHelp::writeTypedInt(myWrapperStorage, n);
303 : }
304 734 : StoHelp::writeTypedString(myWrapperStorage, phase->name);
305 : }
306 109 : StoHelp::writeCompound(myWrapperStorage, (int)logic.subParameter.size());
307 115 : for (const auto& item : logic.subParameter) {
308 24 : StoHelp::writeTypedStringList(myWrapperStorage, std::vector<std::string> {item.first, item.second});
309 : }
310 : }
311 68 : return true;
312 0 : }
313 :
314 :
315 : bool
316 36 : TraCIServer::wrapLinkVectorVector(const std::string& /* objID */, const int /* variable */, const std::vector<std::vector<libsumo::TraCILink> >& value) {
317 : int cnt = 1;
318 627 : for (const std::vector<libsumo::TraCILink>& sublinks : value) {
319 591 : cnt += (int)sublinks.size() + 1;
320 : }
321 36 : StoHelp::writeCompound(myWrapperStorage, cnt);
322 36 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
323 627 : for (const std::vector<libsumo::TraCILink>& sublinks : value) {
324 591 : StoHelp::writeTypedInt(myWrapperStorage, (int)sublinks.size());
325 1182 : for (const libsumo::TraCILink& link : sublinks) {
326 2955 : StoHelp::writeTypedStringList(myWrapperStorage, std::vector<std::string>({ link.fromLane, link.toLane, link.viaLane }));
327 : }
328 : }
329 36 : return true;
330 0 : }
331 :
332 :
333 : bool
334 813 : TraCIServer::wrapSignalConstraintVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCISignalConstraint>& value) {
335 813 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 5);
336 813 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
337 1479 : for (const auto& c : value) {
338 666 : StoHelp::writeConstraint(myWrapperStorage, c);
339 : }
340 813 : return true;
341 : }
342 :
343 :
344 : bool
345 96 : TraCIServer::wrapJunctionFoeVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIJunctionFoe>& value) {
346 96 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 9);
347 96 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
348 186 : for (const auto& c : value) {
349 90 : StoHelp::writeTypedString(myWrapperStorage, c.foeId);
350 90 : StoHelp::writeTypedDouble(myWrapperStorage, c.egoDist);
351 90 : StoHelp::writeTypedDouble(myWrapperStorage, c.foeDist);
352 90 : StoHelp::writeTypedDouble(myWrapperStorage, c.egoExitDist);
353 90 : StoHelp::writeTypedDouble(myWrapperStorage, c.foeExitDist);
354 90 : StoHelp::writeTypedString(myWrapperStorage, c.egoLane);
355 90 : StoHelp::writeTypedString(myWrapperStorage, c.foeLane);
356 90 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, c.egoResponse);
357 90 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, c.foeResponse);
358 : }
359 96 : return true;
360 : }
361 :
362 :
363 : bool
364 2474 : TraCIServer::wrapNextStopDataVector(const std::string& /* objID */, const int variable, const std::vector<libsumo::TraCINextStopData>& value) {
365 2474 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 4);
366 2474 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
367 : const bool full = variable == libsumo::VAR_NEXT_STOPS2;
368 8789 : for (const auto& s : value) {
369 6315 : const int legacyStopFlags = (s.stopFlags << 1) + (s.arrival >= 0 ? 1 : 0);
370 6315 : StoHelp::writeTypedString(myWrapperStorage, s.lane);
371 6315 : StoHelp::writeTypedDouble(myWrapperStorage, s.endPos);
372 6315 : StoHelp::writeTypedString(myWrapperStorage, s.stoppingPlaceID);
373 6315 : StoHelp::writeTypedInt(myWrapperStorage, full ? s.stopFlags : legacyStopFlags);
374 6315 : StoHelp::writeTypedDouble(myWrapperStorage, s.duration);
375 6315 : StoHelp::writeTypedDouble(myWrapperStorage, s.until);
376 6315 : if (full) {
377 6292 : StoHelp::writeTypedDouble(myWrapperStorage, s.startPos);
378 6292 : StoHelp::writeTypedDouble(myWrapperStorage, s.intendedArrival);
379 6292 : StoHelp::writeTypedDouble(myWrapperStorage, s.arrival);
380 6292 : StoHelp::writeTypedDouble(myWrapperStorage, s.depart);
381 6292 : StoHelp::writeTypedString(myWrapperStorage, s.split);
382 6292 : StoHelp::writeTypedString(myWrapperStorage, s.join);
383 6292 : StoHelp::writeTypedString(myWrapperStorage, s.actType);
384 6292 : StoHelp::writeTypedString(myWrapperStorage, s.tripId);
385 6292 : StoHelp::writeTypedString(myWrapperStorage, s.line);
386 6292 : StoHelp::writeTypedDouble(myWrapperStorage, s.speed);
387 : }
388 : }
389 2474 : return true;
390 : }
391 :
392 :
393 : bool
394 24856 : TraCIServer::wrapVehicleDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIVehicleData>& value) {
395 24856 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 5);
396 24856 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
397 29134 : for (const libsumo::TraCIVehicleData& vd : value) {
398 4278 : StoHelp::writeTypedString(myWrapperStorage, vd.id);
399 4278 : StoHelp::writeTypedDouble(myWrapperStorage, vd.length);
400 4278 : StoHelp::writeTypedDouble(myWrapperStorage, vd.entryTime);
401 4278 : StoHelp::writeTypedDouble(myWrapperStorage, vd.leaveTime);
402 4278 : StoHelp::writeTypedString(myWrapperStorage, vd.typeID);
403 : }
404 24856 : return true;
405 : }
406 :
407 :
408 : bool
409 56 : TraCIServer::wrapBestLanesDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIBestLanesData>& value) {
410 56 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 6);
411 56 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
412 105 : for (const libsumo::TraCIBestLanesData& bld : value) {
413 49 : StoHelp::writeTypedString(myWrapperStorage, bld.laneID);
414 49 : StoHelp::writeTypedDouble(myWrapperStorage, bld.length);
415 49 : StoHelp::writeTypedDouble(myWrapperStorage, bld.occupation);
416 49 : StoHelp::writeTypedByte(myWrapperStorage, bld.bestLaneOffset);
417 49 : StoHelp::writeTypedUnsignedByte(myWrapperStorage, bld.allowsContinuation ? 1 : 0);
418 49 : StoHelp::writeTypedStringList(myWrapperStorage, bld.continuationLanes);
419 : }
420 56 : return true;
421 : }
422 :
423 :
424 : bool
425 793 : TraCIServer::wrapNextTLSDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCINextTLSData>& value) {
426 793 : StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 4);
427 793 : StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
428 1495 : for (const libsumo::TraCINextTLSData& tlsd : value) {
429 702 : StoHelp::writeTypedString(myWrapperStorage, tlsd.id);
430 702 : StoHelp::writeTypedInt(myWrapperStorage, tlsd.tlIndex);
431 702 : StoHelp::writeTypedDouble(myWrapperStorage, tlsd.dist);
432 702 : StoHelp::writeTypedByte(myWrapperStorage, tlsd.state);
433 : }
434 793 : return true;
435 : }
436 :
437 :
438 : tcpip::Storage&
439 15564660 : TraCIServer::getWrapperStorage() {
440 15564660 : return myWrapperStorage;
441 : }
442 :
443 :
444 :
445 2774 : TraCIServer::TraCIServer(const SUMOTime begin, const int port, const int numClients)
446 2774 : : myTargetTime(begin), myLastContextSubscription(nullptr) {
447 : #ifdef DEBUG_MULTI_CLIENTS
448 : std::cout << "Creating new TraCIServer for " << numClients << " clients on port " << port << "." << std::endl;
449 : #endif
450 2774 : myVehicleStateChanges[MSNet::VehicleState::BUILT] = std::vector<std::string>();
451 2774 : myVehicleStateChanges[MSNet::VehicleState::DEPARTED] = std::vector<std::string>();
452 2774 : myVehicleStateChanges[MSNet::VehicleState::STARTING_TELEPORT] = std::vector<std::string>();
453 2774 : myVehicleStateChanges[MSNet::VehicleState::ENDING_TELEPORT] = std::vector<std::string>();
454 2774 : myVehicleStateChanges[MSNet::VehicleState::ARRIVED] = std::vector<std::string>();
455 2774 : myVehicleStateChanges[MSNet::VehicleState::NEWROUTE] = std::vector<std::string>();
456 2774 : myVehicleStateChanges[MSNet::VehicleState::STARTING_PARKING] = std::vector<std::string>();
457 2774 : myVehicleStateChanges[MSNet::VehicleState::MANEUVERING] = std::vector<std::string>();
458 2774 : myVehicleStateChanges[MSNet::VehicleState::ENDING_PARKING] = std::vector<std::string>();
459 2774 : myVehicleStateChanges[MSNet::VehicleState::STARTING_STOP] = std::vector<std::string>();
460 2774 : myVehicleStateChanges[MSNet::VehicleState::ENDING_STOP] = std::vector<std::string>();
461 2774 : myVehicleStateChanges[MSNet::VehicleState::COLLISION] = std::vector<std::string>();
462 2774 : myVehicleStateChanges[MSNet::VehicleState::EMERGENCYSTOP] = std::vector<std::string>();
463 :
464 2774 : myTransportableStateChanges[MSNet::TransportableState::PERSON_DEPARTED] = std::vector<std::string>();
465 2774 : myTransportableStateChanges[MSNet::TransportableState::PERSON_ARRIVED] = std::vector<std::string>();
466 2774 : myTransportableStateChanges[MSNet::TransportableState::CONTAINER_DEPARTED] = std::vector<std::string>();
467 2774 : myTransportableStateChanges[MSNet::TransportableState::CONTAINER_ARRIVED] = std::vector<std::string>();
468 :
469 2774 : myExecutors[libsumo::CMD_SET_INDUCTIONLOOP_VARIABLE] = &TraCIServerAPI_InductionLoop::processSet;
470 2774 : myExecutors[libsumo::CMD_SET_LANEAREA_VARIABLE] = &TraCIServerAPI_LaneArea::processSet;
471 2774 : myExecutors[libsumo::CMD_SET_MULTIENTRYEXIT_VARIABLE] = &TraCIServerAPI_MultiEntryExit::processSet;
472 :
473 2774 : myExecutors[libsumo::CMD_SET_TL_VARIABLE] = &TraCIServerAPI_TrafficLight::processSet;
474 2774 : myExecutors[libsumo::CMD_SET_LANE_VARIABLE] = &TraCIServerAPI_Lane::processSet;
475 2774 : myExecutors[libsumo::CMD_SET_VEHICLE_VARIABLE] = &TraCIServerAPI_Vehicle::processSet;
476 2774 : myExecutors[libsumo::CMD_SET_VEHICLETYPE_VARIABLE] = &TraCIServerAPI_VehicleType::processSet;
477 2774 : myExecutors[libsumo::CMD_SET_ROUTE_VARIABLE] = &TraCIServerAPI_Route::processSet;
478 2774 : myExecutors[libsumo::CMD_SET_POI_VARIABLE] = &TraCIServerAPI_POI::processSet;
479 2774 : myExecutors[libsumo::CMD_SET_POLYGON_VARIABLE] = &TraCIServerAPI_Polygon::processSet;
480 2774 : myExecutors[libsumo::CMD_SET_JUNCTION_VARIABLE] = &TraCIServerAPI_Junction::processSet;
481 2774 : myExecutors[libsumo::CMD_SET_EDGE_VARIABLE] = &TraCIServerAPI_Edge::processSet;
482 2774 : myExecutors[libsumo::CMD_SET_SIM_VARIABLE] = &TraCIServerAPI_Simulation::processSet;
483 2774 : myExecutors[libsumo::CMD_SET_PERSON_VARIABLE] = &TraCIServerAPI_Person::processSet;
484 2774 : myExecutors[libsumo::CMD_SET_CALIBRATOR_VARIABLE] = &TraCIServerAPI_Calibrator::processSet;
485 2774 : myExecutors[libsumo::CMD_SET_BUSSTOP_VARIABLE] = &TraCIServerAPI_BusStop::processSet;
486 2774 : myExecutors[libsumo::CMD_SET_PARKINGAREA_VARIABLE] = &TraCIServerAPI_ParkingArea::processSet;
487 2774 : myExecutors[libsumo::CMD_SET_CHARGINGSTATION_VARIABLE] = &TraCIServerAPI_ChargingStation::processSet;
488 2774 : myExecutors[libsumo::CMD_SET_ROUTEPROBE_VARIABLE] = &TraCIServerAPI_RouteProbe::processSet;
489 2774 : myExecutors[libsumo::CMD_SET_REROUTER_VARIABLE] = &TraCIServerAPI_Rerouter::processSet;
490 2774 : myExecutors[libsumo::CMD_SET_VARIABLESPEEDSIGN_VARIABLE] = &TraCIServerAPI_VariableSpeedSign::processSet;
491 : //myExecutors[libsumo::CMD_SET_MEANDATA_VARIABLE] = &TraCIServerAPI_MeanData::processSet;
492 2774 : myExecutors[libsumo::CMD_SET_OVERHEADWIRE_VARIABLE] = &TraCIServerAPI_OverheadWire::processSet;
493 :
494 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_MEANDATA_VARIABLE, libsumo::VAR_MEANDATA_LANE));
495 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_MEANDATA_VARIABLE, libsumo::VAR_MEANDATA_VALUES));
496 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_EDGE_VARIABLE, libsumo::VAR_EDGE_TRAVELTIME));
497 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_EDGE_VARIABLE, libsumo::VAR_EDGE_EFFORT));
498 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_EDGE_VARIABLE, libsumo::VAR_ANGLE));
499 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_LANE_VARIABLE, libsumo::VAR_ANGLE));
500 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_LANE_VARIABLE, libsumo::LANE_CHANGES));
501 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_LANE_VARIABLE, libsumo::VAR_FOES));
502 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE, libsumo::DISTANCE_REQUEST));
503 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE, libsumo::VAR_EDGES));
504 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE, libsumo::VAR_STAGE));
505 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE, libsumo::VAR_TAXI_RESERVATIONS));
506 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE, libsumo::SPLIT_TAXI_RESERVATIONS));
507 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::TL_BLOCKING_VEHICLES));
508 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::TL_RIVAL_VEHICLES));
509 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::TL_PRIORITY_VEHICLES));
510 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::TL_CONSTRAINT));
511 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::TL_CONSTRAINT_BYFOE));
512 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_TL_VARIABLE, libsumo::VAR_PERSON_NUMBER));
513 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::DISTANCE_REQUEST));
514 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_EDGE_TRAVELTIME));
515 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_EDGE_EFFORT));
516 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_FOLLOW_SPEED));
517 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_SECURE_GAP));
518 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_STOP_SPEED));
519 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_FOES));
520 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::CMD_CHANGELANE));
521 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_LEADER));
522 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_FOLLOWER));
523 5548 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_NEIGHBORS));
524 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_STOP_PARAMETER));
525 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_NEXT_STOPS)); // this is just a dummy to trigger an error
526 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_NEXT_STOPS2));
527 2774 : myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_TAXI_FLEET));
528 2774 : myParameterized.insert(std::make_pair(0, libsumo::VAR_PARAMETER));
529 2774 : myParameterized.insert(std::make_pair(0, libsumo::VAR_PARAMETER_WITH_KEY));
530 :
531 2774 : myDoCloseConnection = false;
532 :
533 : // display warning if internal lanes are not used
534 : // TODO this may be redundant to the warning in NLBuilder::build
535 2774 : if (!MSGlobals::gUsingInternalLanes && !MSGlobals::gUseMesoSim) {
536 2 : WRITE_WARNING(TL("Starting TraCI without using internal lanes!"));
537 2 : MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
538 16 : MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
539 : }
540 :
541 : try {
542 5548 : WRITE_MESSAGEF(TL("***Starting server on port % ***"), toString(port));
543 2774 : tcpip::Socket serverSocket(port);
544 2774 : if (numClients > 1) {
545 232 : WRITE_MESSAGEF(TL(" waiting for % clients..."), toString(numClients));
546 : }
547 5790 : while ((int)mySockets.size() < numClients) {
548 3022 : int index = (int)mySockets.size() + libsumo::MAX_ORDER + 1;
549 3022 : mySockets[index] = new SocketInfo(serverSocket.accept(true), begin);
550 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::BUILT] = std::vector<std::string>();
551 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::DEPARTED] = std::vector<std::string>();
552 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_TELEPORT] = std::vector<std::string>();
553 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_TELEPORT] = std::vector<std::string>();
554 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ARRIVED] = std::vector<std::string>();
555 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::NEWROUTE] = std::vector<std::string>();
556 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_PARKING] = std::vector<std::string>();
557 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::MANEUVERING] = std::vector<std::string>();
558 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_PARKING] = std::vector<std::string>();
559 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_STOP] = std::vector<std::string>();
560 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_STOP] = std::vector<std::string>();
561 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::COLLISION] = std::vector<std::string>();
562 3016 : mySockets[index]->vehicleStateChanges[MSNet::VehicleState::EMERGENCYSTOP] = std::vector<std::string>();
563 :
564 3016 : mySockets[index]->transportableStateChanges[MSNet::TransportableState::PERSON_DEPARTED] = std::vector<std::string>();
565 3016 : mySockets[index]->transportableStateChanges[MSNet::TransportableState::PERSON_ARRIVED] = std::vector<std::string>();
566 3016 : mySockets[index]->transportableStateChanges[MSNet::TransportableState::CONTAINER_DEPARTED] = std::vector<std::string>();
567 3016 : mySockets[index]->transportableStateChanges[MSNet::TransportableState::CONTAINER_ARRIVED] = std::vector<std::string>();
568 3016 : if (numClients > 1) {
569 728 : WRITE_MESSAGE(TL(" client connected"));
570 : }
571 : }
572 : // When got here, all clients have connected
573 2768 : if (numClients > 1) {
574 116 : checkClientOrdering();
575 : }
576 : // set myCurrentSocket != mySockets.end() to indicate that this is the first step in processCommands()
577 2762 : myCurrentSocket = mySockets.begin();
578 2786 : } catch (tcpip::SocketException& e) {
579 12 : throw ProcessError(e.what());
580 6 : }
581 2834 : }
582 :
583 :
584 5524 : TraCIServer::~TraCIServer() {
585 2873 : for (const auto& socket : mySockets) {
586 111 : delete socket.second;
587 : }
588 : // there is no point in calling cleanup() here, it does not free any pointers and will only modify members which get deleted anyway
589 8286 : }
590 :
591 :
592 : // ---------- Initialisation and Shutdown
593 : void
594 43536 : TraCIServer::openSocket(const std::map<int, CmdExecutor>& execs) {
595 127808 : if (myInstance == nullptr && !myDoCloseConnection && (OptionsCont::getOptions().getInt("remote-port") != 0)) {
596 8310 : myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")),
597 2774 : OptionsCont::getOptions().getInt("remote-port"),
598 11108 : OptionsCont::getOptions().getInt("num-clients"));
599 3036 : for (std::map<int, CmdExecutor>::const_iterator i = execs.begin(); i != execs.end(); ++i) {
600 274 : myInstance->myExecutors[i->first] = i->second;
601 : }
602 : }
603 43524 : if (myInstance != nullptr) {
604 : // maybe net was deleted and built again
605 2775 : MSNet::getInstance()->addVehicleStateListener(myInstance);
606 2775 : MSNet::getInstance()->addTransportableStateListener(myInstance);
607 2775 : myInstance->mySubscriptionCache.writeInt(0);
608 : }
609 43524 : }
610 :
611 :
612 : void
613 45254 : TraCIServer::close() {
614 45254 : if (myInstance == nullptr) {
615 : return;
616 : }
617 2762 : delete myInstance;
618 2762 : myInstance = nullptr;
619 2762 : myDoCloseConnection = true;
620 : }
621 :
622 :
623 : bool
624 129212768 : TraCIServer::wasClosed() {
625 129212768 : return myDoCloseConnection;
626 : }
627 :
628 :
629 : // ---------- Initialisation and Shutdown
630 :
631 :
632 : void
633 105918 : TraCIServer::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
634 105918 : if (!myDoCloseConnection) {
635 105918 : myVehicleStateChanges[to].push_back(vehicle->getID());
636 221314 : for (std::map<int, SocketInfo*>::iterator i = mySockets.begin(); i != mySockets.end(); ++i) {
637 115396 : i->second->vehicleStateChanges[to].push_back(vehicle->getID());
638 : }
639 : }
640 105918 : }
641 :
642 :
643 : void
644 1886 : TraCIServer::transportableStateChanged(const MSTransportable* const transportable, MSNet::TransportableState to, const std::string& /*info*/) {
645 1886 : if (!myDoCloseConnection) {
646 1868 : myTransportableStateChanges[to].push_back(transportable->getID());
647 3736 : for (std::map<int, SocketInfo*>::iterator i = mySockets.begin(); i != mySockets.end(); ++i) {
648 1868 : i->second->transportableStateChanges[to].push_back(transportable->getID());
649 : }
650 : }
651 1886 : }
652 :
653 :
654 : void
655 116 : TraCIServer::checkClientOrdering() {
656 : #ifdef DEBUG_MULTI_CLIENTS
657 : std::cout << "Checking client order requests." << std::endl;
658 : #endif
659 : // check for SET_ORDER commands queued by connected clients
660 : // In multiclient cas it is mandatory that SET_ORDER is sent as the first command (or directly after GET_VERSION)
661 116 : myCurrentSocket = mySockets.begin();
662 471 : while (myCurrentSocket != mySockets.end()) {
663 : #ifdef DEBUG_MULTI_CLIENTS
664 : std::cout << " Socket " << myCurrentSocket->second->socket << ":" << std::endl;
665 : #endif
666 : // bool clientUnordered = true;
667 : while (true) {
668 720 : myInputStorage.reset();
669 720 : myCurrentSocket->second->socket->receiveExact(myInputStorage);
670 : int commandStart, commandLength;
671 720 : int commandId = readCommandID(commandStart, commandLength);
672 : #ifdef DEBUG_MULTI_CLIENTS
673 : std::cout << " received command " << commandId << std::endl;
674 : #endif
675 : // Whether the received command is a permitted command for the initialization phase.
676 : // Currently, getVersion and setOrder are permitted.
677 720 : bool initCommand = commandId == libsumo::CMD_SETORDER || commandId == libsumo::CMD_GETVERSION;
678 720 : if (initCommand) {
679 : #ifdef DEBUG_MULTI_CLIENTS
680 : std::cout << " Init command. Sending response." << std::endl;
681 : #endif
682 : // reset input storage to initial state before reading the commandId
683 : // (ugly, but we can't just reset the store's iter_ from here)
684 : // Giving the commandId to dispatch command didn't work either
685 714 : tcpip::Storage tmp;
686 714 : tmp.writeStorage(myInputStorage);
687 714 : myInputStorage.reset();
688 : // we don't know whether the command was set with extended
689 : // length syntax or not so we hardcode the length here (#5037)
690 1073 : myInputStorage.writeUnsignedByte(commandId == libsumo::CMD_SETORDER ? 6 : 2);
691 714 : myInputStorage.writeUnsignedByte(commandId);
692 714 : myInputStorage.writeStorage(tmp);
693 :
694 : // Handle initialization command completely
695 714 : dispatchCommand();
696 714 : myCurrentSocket->second->socket->sendExact(myOutputStorage);
697 714 : myOutputStorage.reset();
698 714 : } else {
699 : #ifdef DEBUG_MULTI_CLIENTS
700 : std::cout << " Client " << myCurrentSocket->second->socket << " did not set order initially." << std::endl;
701 : #endif
702 12 : throw ProcessError(TL("Execution order (libsumo::CMD_SETORDER) was not set for all TraCI clients in pre-execution phase."));
703 : }
704 714 : if (commandId == libsumo::CMD_SETORDER) {
705 : // This is what we have waited for.
706 : break;
707 : }
708 359 : }
709 : ++myCurrentSocket;
710 : }
711 110 : }
712 :
713 :
714 : void
715 1700929 : TraCIServer::processReorderingRequests() {
716 : // Process reordering requests
717 1700929 : if (mySocketReorderRequests.size() > 0) {
718 : // process reordering requests
719 : std::map<int, SocketInfo*>::const_iterator i = mySocketReorderRequests.begin();
720 : std::map<int, SocketInfo*>::iterator j;
721 : #ifdef DEBUG_MULTI_CLIENTS
722 : std::cout << SIMTIME << " Current socket ordering:\n";
723 : for (j = mySockets.begin(); j != mySockets.end(); ++j) {
724 : std::cout << " " << j->first << ": " << j->second->socket << "\n";
725 : }
726 : std::cout << "Reordering requests:\n";
727 : for (i = mySocketReorderRequests.begin(); i != mySocketReorderRequests.end(); ++i) {
728 : std::cout << " Socket " << i->second->socket << " -> " << i->first << "\n";
729 : }
730 : i = mySocketReorderRequests.begin();
731 : #endif
732 472 : while (i != mySocketReorderRequests.end()) {
733 : j = mySockets.begin();
734 868 : while (j != mySockets.end()) {
735 868 : if (j->second->socket == i->second->socket) {
736 : break;
737 : } else {
738 : j++;
739 : }
740 : }
741 : assert(j != mySockets.end());
742 : mySockets.erase(j);
743 357 : mySockets[i->first] = i->second;
744 : ++i;
745 : }
746 : mySocketReorderRequests.clear();
747 : #ifdef DEBUG_MULTI_CLIENTS
748 : std::cout << "New socket ordering:\n";
749 : for (j = mySockets.begin(); j != mySockets.end(); ++j) {
750 : std::cout << " " << j->first << ": " << j->second->socket << "\n";
751 : }
752 : std::cout << std::endl;
753 : #endif
754 : }
755 1700929 : }
756 :
757 :
758 : SUMOTime
759 3366306 : TraCIServer::nextTargetTime() const {
760 : #ifdef DEBUG_MULTI_CLIENTS
761 : std::cout << "\n Determining new target time..." << std::endl;
762 : if (mySockets.size() == 0) {
763 : std::cout << " All clients have disconnected." << std::endl;
764 : }
765 : #endif
766 : std::map<int, SocketInfo*>::const_iterator i;
767 : SUMOTime targetTime = std::numeric_limits<SUMOTime>::max();
768 6885064 : for (i = mySockets.begin(); i != mySockets.end(); ++i) {
769 : #ifdef DEBUG_MULTI_CLIENTS
770 : std::cout << " target time for client " << i->second->socket << ": " << i->second->targetTime << "\n";
771 : #endif
772 3518758 : targetTime = MIN2(targetTime, i->second->targetTime);
773 : }
774 : #ifdef DEBUG_MULTI_CLIENTS
775 : std::cout << std::endl;
776 : #endif
777 3366306 : return targetTime;
778 : }
779 :
780 :
781 : // send out subscription results to clients which will act in this step (i.e. with client target time <= myTargetTime)
782 : void
783 1698101 : TraCIServer::sendOutputToAll() const {
784 : #ifdef DEBUG_MULTI_CLIENTS
785 : std::cout << "\n Sending subscription results to clients:\n";
786 : #endif
787 : std::map<int, SocketInfo*>::const_iterator i = mySockets.begin();
788 3443660 : while (i != mySockets.end()) {
789 1745559 : if (i->second->targetTime <= MSNet::getInstance()->getCurrentTimeStep()) {
790 : // this client will become active before the next SUMO step. Provide subscription results.
791 1663869 : i->second->socket->sendExact(myOutputStorage);
792 : #ifdef DEBUG_MULTI_CLIENTS
793 : std::cout << i->second->socket << "\n";
794 : #endif
795 : }
796 : ++i;
797 : }
798 : #ifdef DEBUG_MULTI_CLIENTS
799 : std::cout << std::endl;
800 : #endif
801 1698101 : }
802 :
803 :
804 : int
805 1700929 : TraCIServer::processCommands(const SUMOTime step, const bool afterMove) {
806 : #ifdef DEBUG_MULTI_CLIENTS
807 : std::cout << SIMTIME << " processCommands(step = " << step << "):\n" << std::endl;
808 : #endif
809 : try {
810 : int finalCmd = 0;
811 : const bool firstStep = myCurrentSocket != mySockets.end();
812 : // update client order if requested
813 1700929 : processReorderingRequests();
814 1700929 : if (!firstStep && !afterMove) {
815 : // This is the entry point after performing a SUMO step (block is skipped before first SUMO step since then no simulation results have to be sent)
816 : // update subscription results
817 1698154 : postProcessSimulationStep();
818 : // Send out subscription results to clients which will act in this SUMO step (i.e. with client target time <= current sumo timestep end)
819 1698101 : sendOutputToAll();
820 1698101 : myOutputStorage.reset();
821 : }
822 :
823 : // determine minimal next target time among clients
824 1700876 : myTargetTime = nextTargetTime();
825 :
826 1700876 : if (step < myTargetTime) {
827 : #ifdef DEBUG_MULTI_CLIENTS
828 : std::cout << " next target time is larger than next SUMO simstep (" << step << "). Returning from processCommands()." << std::endl;
829 : #endif
830 : return finalCmd;
831 : }
832 :
833 : // Simulation should run until
834 : // 1. end time reached or
835 : // 2. got libsumo::CMD_CLOSE or
836 : // 3. got libsumo::CMD_LOAD or
837 : // 4. Client closes socket connection
838 3305004 : while (!myDoCloseConnection && myTargetTime <= (MSNet::getInstance()->getCurrentTimeStep()) && finalCmd != libsumo::CMD_EXECUTEMOVE) {
839 : #ifdef DEBUG_MULTI_CLIENTS
840 : std::cout << " Next target time: " << myTargetTime << std::endl;
841 : #endif
842 : // Iterate over clients and process communication for the ones with target time == myTargetTime
843 1668146 : myCurrentSocket = mySockets.begin();
844 3441234 : while (myCurrentSocket != mySockets.end()) {
845 : #ifdef DEBUG_MULTI_CLIENTS
846 : std::cout << " current socket: " << myCurrentSocket->second->socket
847 : << " with target time=" << myCurrentSocket->second->targetTime
848 : << std::endl;
849 : #endif
850 :
851 1773140 : if (myCurrentSocket->second->targetTime > myTargetTime || (afterMove && !myCurrentSocket->second->executeMove)) {
852 : // this client must wait
853 : #ifdef DEBUG_MULTI_CLIENTS
854 : std::cout << " skipping client " << myCurrentSocket->second->socket
855 : << " with target time=" << myCurrentSocket->second->targetTime << std::endl;
856 : #endif
857 : myCurrentSocket++;
858 77940 : continue;
859 : }
860 : finalCmd = 0;
861 11712977 : while (finalCmd == 0) {
862 10017829 : if (!myInputStorage.valid_pos()) {
863 : // have read request completely, send response if adequate
864 10017829 : if (myOutputStorage.size() > 0) {
865 : // send response to previous query
866 8322635 : myCurrentSocket->second->socket->sendExact(myOutputStorage);
867 8322635 : myOutputStorage.reset();
868 : }
869 : #ifdef DEBUG_MULTI_CLIENTS
870 : std::cout << " resetting input storage and reading next command..." << std::endl;
871 : #endif
872 : // Read next request
873 10017829 : myInputStorage.reset();
874 10017829 : myCurrentSocket->second->socket->receiveExact(myInputStorage);
875 : }
876 :
877 20035554 : while (myInputStorage.valid_pos() && !myDoCloseConnection) {
878 10017777 : const int cmd = dispatchCommand();
879 10017777 : if (cmd == libsumo::CMD_SIMSTEP || cmd == libsumo::CMD_LOAD || cmd == libsumo::CMD_EXECUTEMOVE || cmd == libsumo::CMD_CLOSE) {
880 : finalCmd = cmd;
881 : }
882 : }
883 : }
884 : }
885 1668094 : if (!myLoadArgs.empty()) {
886 : #ifdef DEBUG_MULTI_CLIENTS
887 : std::cout << " Breaking loop to load new simulation." << std::endl;
888 : #endif
889 : break;
890 1668081 : } else if (myDoCloseConnection) {
891 : #ifdef DEBUG_MULTI_CLIENTS
892 : std::cout << " Breaking loop because last client closed connection." << std::endl;
893 : #endif
894 : break;
895 : }
896 1665430 : SUMOTime nextT = nextTargetTime();
897 : // minimal target time among clients should have been increased during the last loop through mySockets
898 : // XXX: The assert below is disabled since many tests do sth. like simulationStep(step). Such that for a first call step=0,
899 : // leading to targetTime==1000 (increased by DELTA_T in dispatchCommand()),
900 : // the next call is then usually simulationStep(step=1000) leading to no further increase
901 : // and thus a failing assertion here.
902 : //assert(myTargetTime < nextT || myDoCloseConnection);
903 1665430 : myTargetTime = nextT;
904 : }
905 : // All clients are done with the current time step
906 : // Reset myVehicleStateChanges and myTransportableStateChanges
907 22953308 : for (auto& item : myVehicleStateChanges) {
908 : item.second.clear();
909 : }
910 8197610 : for (auto& item : myTransportableStateChanges) {
911 : item.second.clear();
912 : }
913 : return finalCmd;
914 105 : } catch (std::invalid_argument& e) {
915 0 : throw ProcessError(e.what());
916 53 : } catch (libsumo::TraCIException& e) {
917 106 : throw ProcessError(e.what());
918 105 : } catch (tcpip::SocketException& e) {
919 104 : throw ProcessError(e.what());
920 52 : }
921 : }
922 :
923 :
924 : bool
925 15472464 : TraCIServer::processGet(const int commandID, tcpip::Storage& inputStorage, tcpip::Storage& outputStorage) {
926 15472464 : const int variable = inputStorage.readUnsignedByte();
927 15472464 : const std::string id = inputStorage.readString();
928 15472464 : initWrapper(commandID + 0x10, variable, id);
929 : try {
930 15472464 : switch (commandID) {
931 31719 : case libsumo::CMD_GET_INDUCTIONLOOP_VARIABLE:
932 31719 : if (!libsumo::InductionLoop::handleVariable(id, variable, this, &inputStorage)) {
933 8 : throw libsumo::TraCIException("Get Induction Loop Variable: unsupported variable " + toHex(variable, 2) + " specified");
934 : }
935 : break;
936 953 : case libsumo::CMD_GET_MULTIENTRYEXIT_VARIABLE:
937 953 : if (!libsumo::MultiEntryExit::handleVariable(id, variable, this, &inputStorage)) {
938 8 : throw libsumo::TraCIException("Get Multi Entry Exit Detector Variable: unsupported variable " + toHex(variable, 2) + " specified");
939 : }
940 : break;
941 77460 : case libsumo::CMD_GET_TL_VARIABLE:
942 77460 : if (!libsumo::TrafficLight::handleVariable(id, variable, this, &inputStorage)) {
943 74 : switch (variable) {
944 : case libsumo::TL_CONSTRAINT_SWAP: {
945 69 : StoHelp::readCompound(inputStorage, 3, "A compound object of size 3 is needed for swapping constraints.");
946 66 : const std::string tripId = StoHelp::readTypedString(inputStorage, "The tripId must be given as a string.");
947 66 : const std::string foeSignal = StoHelp::readTypedString(inputStorage, "The foeSignal id must be given as a string.");
948 66 : const std::string foeId = StoHelp::readTypedString(inputStorage, "The foe tripId must be given as a string.");
949 132 : wrapSignalConstraintVector(id, variable, libsumo::TrafficLight::swapConstraints(id, tripId, foeSignal, foeId));
950 : break;
951 : }
952 5 : default:
953 10 : throw libsumo::TraCIException("Get TLS Variable: unsupported variable " + toHex(variable, 2) + " specified");
954 : }
955 : }
956 : break;
957 19422 : case libsumo::CMD_GET_LANE_VARIABLE:
958 19422 : if (!libsumo::Lane::handleVariable(id, variable, this, &inputStorage)) {
959 10 : throw libsumo::TraCIException("Get Lane Variable: unsupported variable " + toHex(variable, 2) + " specified");
960 : }
961 : break;
962 9822830 : case libsumo::CMD_GET_VEHICLE_VARIABLE:
963 9822830 : if (!libsumo::Vehicle::handleVariable(id, variable, this, &inputStorage)) {
964 12 : throw libsumo::TraCIException("Get Vehicle Variable: unsupported variable " + toHex(variable, 2) + " specified");
965 : }
966 : break;
967 2230 : case libsumo::CMD_GET_VEHICLETYPE_VARIABLE:
968 2230 : if (!libsumo::VehicleType::handleVariable(id, variable, this, &inputStorage)) {
969 10 : throw libsumo::TraCIException("Get Vehicle Type Variable: unsupported variable " + toHex(variable, 2) + " specified");
970 : }
971 : break;
972 284 : case libsumo::CMD_GET_ROUTE_VARIABLE:
973 284 : if (!libsumo::Route::handleVariable(id, variable, this, &inputStorage)) {
974 10 : throw libsumo::TraCIException("Get Route Variable: unsupported variable " + toHex(variable, 2) + " specified");
975 : }
976 : break;
977 6363 : case libsumo::CMD_GET_POI_VARIABLE:
978 6363 : if (!libsumo::POI::handleVariable(id, variable, this, &inputStorage)) {
979 10 : throw libsumo::TraCIException("Get PoI Variable: unsupported variable " + toHex(variable, 2) + " specified");
980 : }
981 : break;
982 6669 : case libsumo::CMD_GET_POLYGON_VARIABLE:
983 6669 : if (!libsumo::Polygon::handleVariable(id, variable, this, &inputStorage)) {
984 10 : throw libsumo::TraCIException("Get Polygon Variable: unsupported variable " + toHex(variable, 2) + " specified");
985 : }
986 : break;
987 6201 : case libsumo::CMD_GET_JUNCTION_VARIABLE:
988 6201 : if (!libsumo::Junction::handleVariable(id, variable, this, &inputStorage)) {
989 10 : throw libsumo::TraCIException("Get Junction Variable: unsupported variable " + toHex(variable, 2) + " specified");
990 : }
991 : break;
992 14685 : case libsumo::CMD_GET_EDGE_VARIABLE:
993 14685 : if (!libsumo::Edge::handleVariable(id, variable, this, &inputStorage)) {
994 10 : throw libsumo::TraCIException("Get Edge Variable: unsupported variable " + toHex(variable, 2) + " specified");
995 : }
996 : break;
997 1666946 : case libsumo::CMD_GET_SIM_VARIABLE:
998 1666946 : if (!TraCIServerAPI_Simulation::processGet(*this, inputStorage, id, variable)) {
999 0 : throw libsumo::TraCIException("Get Simulation Variable: unsupported variable " + toHex(variable, 2) + " specified");
1000 : }
1001 : break;
1002 7150 : case libsumo::CMD_GET_LANEAREA_VARIABLE:
1003 7150 : if (!libsumo::LaneArea::handleVariable(id, variable, this, &inputStorage)) {
1004 8 : throw libsumo::TraCIException("Get Lane Area Detector Variable: unsupported variable " + toHex(variable, 2) + " specified");
1005 : }
1006 : break;
1007 3800879 : case libsumo::CMD_GET_PERSON_VARIABLE:
1008 3800879 : if (!libsumo::Person::handleVariable(id, variable, this, &inputStorage)) {
1009 10 : throw libsumo::TraCIException("Get Person Variable: unsupported variable " + toHex(variable, 2) + " specified");
1010 : }
1011 : break;
1012 525 : case libsumo::CMD_GET_BUSSTOP_VARIABLE:
1013 525 : if (!libsumo::BusStop::handleVariable(id, variable, this, &inputStorage)) {
1014 6 : throw libsumo::TraCIException("Get BusStop Variable: unsupported variable " + toHex(variable, 2) + " specified");
1015 : }
1016 : break;
1017 369 : case libsumo::CMD_GET_PARKINGAREA_VARIABLE:
1018 369 : if (!libsumo::ParkingArea::handleVariable(id, variable, this, &inputStorage)) {
1019 6 : throw libsumo::TraCIException("Get ParkingArea Variable: unsupported variable " + toHex(variable, 2) + " specified");
1020 : }
1021 : break;
1022 1414 : case libsumo::CMD_GET_CHARGINGSTATION_VARIABLE:
1023 1414 : if (!libsumo::ChargingStation::handleVariable(id, variable, this, &inputStorage)) {
1024 8 : throw libsumo::TraCIException("Get ChargingStation Variable: unsupported variable " + toHex(variable, 2) + " specified");
1025 : }
1026 : break;
1027 1771 : case libsumo::CMD_GET_ROUTEPROBE_VARIABLE:
1028 1771 : if (!libsumo::RouteProbe::handleVariable(id, variable, this, &inputStorage)) {
1029 6 : throw libsumo::TraCIException("Get RouteProbe Variable: unsupported variable " + toHex(variable, 2) + " specified");
1030 : }
1031 : break;
1032 306 : case libsumo::CMD_GET_CALIBRATOR_VARIABLE:
1033 306 : if (!libsumo::Calibrator::handleVariable(id, variable, this, &inputStorage)) {
1034 6 : throw libsumo::TraCIException("Get Calibrator Variable: unsupported variable " + toHex(variable, 2) + " specified");
1035 : }
1036 : break;
1037 132 : case libsumo::CMD_GET_REROUTER_VARIABLE:
1038 132 : if (!libsumo::Rerouter::handleVariable(id, variable, this, &inputStorage)) {
1039 6 : throw libsumo::TraCIException("Get Rerouter Variable: unsupported variable " + toHex(variable, 2) + " specified");
1040 : }
1041 : break;
1042 141 : case libsumo::CMD_GET_VARIABLESPEEDSIGN_VARIABLE:
1043 141 : if (!libsumo::VariableSpeedSign::handleVariable(id, variable, this, &inputStorage)) {
1044 6 : throw libsumo::TraCIException("Get VariableSpeedSign Variable: unsupported variable " + toHex(variable, 2) + " specified");
1045 : }
1046 : break;
1047 3670 : case libsumo::CMD_GET_MEANDATA_VARIABLE:
1048 3670 : if (!libsumo::MeanData::handleVariable(id, variable, this, &inputStorage)) {
1049 6 : throw libsumo::TraCIException("Get MeanData Variable: unsupported variable " + toHex(variable, 2) + " specified");
1050 : }
1051 : break;
1052 345 : case libsumo::CMD_GET_OVERHEADWIRE_VARIABLE:
1053 345 : if (!libsumo::OverheadWire::handleVariable(id, variable, this, &inputStorage)) {
1054 6 : throw libsumo::TraCIException("Get OverheadWire Variable: unsupported variable " + toHex(variable, 2) + " specified");
1055 : }
1056 : break;
1057 : default:
1058 : return false;
1059 : }
1060 697 : } catch (libsumo::TraCIException& e) {
1061 676 : return writeErrorStatusCmd(commandID, e.what(), outputStorage);
1062 676 : }
1063 15471788 : writeStatusCmd(commandID, libsumo::RTYPE_OK, "", outputStorage);
1064 15471767 : writeResponseWithLength(outputStorage, getWrapperStorage());
1065 : return true;
1066 : }
1067 :
1068 :
1069 : void
1070 2770 : TraCIServer::cleanup() {
1071 : mySubscriptions.clear();
1072 5540 : myTargetTime = string2time(OptionsCont::getOptions().getString("begin"));
1073 2889 : for (myCurrentSocket = mySockets.begin(); myCurrentSocket != mySockets.end(); ++myCurrentSocket) {
1074 119 : myCurrentSocket->second->targetTime = myTargetTime;
1075 119 : myCurrentSocket->second->executeMove = false;
1076 : }
1077 2770 : myOutputStorage.reset();
1078 2770 : myInputStorage.reset();
1079 2770 : mySubscriptionCache.reset();
1080 38780 : for (auto& i : myVehicleStateChanges) {
1081 : i.second.clear();
1082 : }
1083 13850 : for (auto& i : myTransportableStateChanges) {
1084 : i.second.clear();
1085 : }
1086 2770 : myCurrentSocket = mySockets.begin();
1087 2770 : }
1088 :
1089 :
1090 : std::map<int, TraCIServer::SocketInfo*>::iterator
1091 2893 : TraCIServer::removeCurrentSocket() {
1092 : #ifdef DEBUG_MULTI_CLIENTS
1093 : std::cout << " Removing socket " << myCurrentSocket->second->socket
1094 : << " (order " << myCurrentSocket->first << ")" << std::endl;
1095 : #endif
1096 2893 : delete myCurrentSocket->second;
1097 2893 : myCurrentSocket = mySockets.erase(myCurrentSocket);
1098 2893 : return myCurrentSocket;
1099 : }
1100 :
1101 :
1102 : int
1103 10019211 : TraCIServer::readCommandID(int& commandStart, int& commandLength) {
1104 10019211 : commandStart = myInputStorage.position();
1105 10019211 : commandLength = myInputStorage.readUnsignedByte();
1106 10019211 : if (commandLength == 0) {
1107 49937 : commandLength = myInputStorage.readInt();
1108 : }
1109 : #ifdef DEBUG_RAW_INPUT
1110 : std::cout << " commandStart=" << commandStart << " commandLength=" << commandLength << " pos=" << myInputStorage.position() << " raw=";
1111 : for (auto it = myInputStorage.begin(); it != myInputStorage.end(); ++it) {
1112 : std::cout << (int)*it << " ";
1113 : }
1114 : std::cout << "\n";
1115 : #endif
1116 10019211 : return myInputStorage.readUnsignedByte();
1117 : }
1118 :
1119 :
1120 : int
1121 10018491 : TraCIServer::dispatchCommand() {
1122 : int commandStart, commandLength;
1123 10018491 : int commandId = readCommandID(commandStart, commandLength);
1124 : #ifdef DEBUG_MULTI_CLIENTS
1125 : std::cout << " dispatchCommand() called for client " << myCurrentSocket->second->socket
1126 : << ", commandId = " << commandId << std::endl;
1127 : #endif
1128 : bool success = false;
1129 : // dispatch commands
1130 10018491 : if (myExecutors.find(commandId) != myExecutors.end()) {
1131 1333363 : success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
1132 8685128 : } else if ((commandId >= libsumo::CMD_GET_INDUCTIONLOOP_VARIABLE && commandId <= libsumo::CMD_GET_BUSSTOP_VARIABLE)
1133 8685128 : || (commandId >= libsumo::CMD_GET_PARKINGAREA_VARIABLE && commandId <= libsumo::CMD_GET_OVERHEADWIRE_VARIABLE)) {
1134 6977619 : if (commandId == libsumo::CMD_GET_GUI_VARIABLE) {
1135 198 : writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo");
1136 : } else {
1137 6977520 : success = processGet(commandId, myInputStorage, myOutputStorage);
1138 : }
1139 : } else {
1140 1707509 : switch (commandId) {
1141 2393 : case libsumo::CMD_GETVERSION:
1142 2393 : success = commandGetVersion();
1143 : break;
1144 : case libsumo::CMD_LOAD: {
1145 : try {
1146 13 : const std::vector<std::string> args = StoHelp::readTypedStringList(myInputStorage, "A load command needs a list of string arguments.");
1147 : #ifdef DEBUG_MULTI_CLIENTS
1148 : std::cout << " commandId == libsumo::CMD_LOAD"
1149 : << ", args = " << toString(args) << std::endl;
1150 : #endif
1151 13 : myLoadArgs = args;
1152 : success = true;
1153 26 : writeStatusCmd(libsumo::CMD_LOAD, libsumo::RTYPE_OK, "");
1154 : // XXX: This only cares for the client that issued the load command.
1155 : // Multiclient-load functionality is still to be implemented. Refs #3146.
1156 13 : myCurrentSocket->second->socket->sendExact(myOutputStorage);
1157 13 : myCurrentSocket = mySockets.end();
1158 13 : myOutputStorage.reset();
1159 13 : } catch (libsumo::TraCIException& e) {
1160 0 : return writeErrorStatusCmd(libsumo::CMD_LOAD, e.what(), myOutputStorage);
1161 0 : }
1162 : break;
1163 : }
1164 6 : case libsumo::CMD_EXECUTEMOVE:
1165 6 : myCurrentSocket->second->executeMove = true;
1166 : myCurrentSocket++;
1167 : success = true;
1168 12 : writeStatusCmd(libsumo::CMD_EXECUTEMOVE, libsumo::RTYPE_OK, "");
1169 : break;
1170 1692236 : case libsumo::CMD_SIMSTEP: {
1171 1692236 : const double nextT = myInputStorage.readDouble();
1172 1692236 : if (nextT == 0.) {
1173 1624809 : myCurrentSocket->second->targetTime += DELTA_T;
1174 : } else {
1175 67427 : myCurrentSocket->second->targetTime = TIME2STEPS(nextT);
1176 : }
1177 1692236 : myCurrentSocket->second->executeMove = false;
1178 : #ifdef DEBUG_MULTI_CLIENTS
1179 : std::cout << " commandId == libsumo::CMD_SIMSTEP"
1180 : << ", next target time for client is " << myCurrentSocket->second->targetTime << std::endl;
1181 : #endif
1182 1692236 : if (myCurrentSocket->second->targetTime <= MSNet::getInstance()->getCurrentTimeStep()) {
1183 : // This is not the last TraCI simstep in the current SUMO simstep -> send single simstep response.
1184 : // @note: In the other case the simstep results are sent to all after the SUMO step was performed, see entry point for processCommands()
1185 28314 : sendSingleSimStepResponse();
1186 : }
1187 : // Clear vehicleStateChanges and transportableStateChanges for this client
1188 : // -> For subsequent TraCI stepping
1189 : // that is performed within this SUMO step, no updates on vehicle states
1190 : // belonging to the last SUMO simulation step will be received by this client.
1191 23691304 : for (auto& item : myCurrentSocket->second->vehicleStateChanges) {
1192 : item.second.clear();
1193 : }
1194 8461180 : for (auto& item : myCurrentSocket->second->transportableStateChanges) {
1195 : item.second.clear();
1196 : }
1197 : myCurrentSocket++;
1198 1692236 : return commandId;
1199 : }
1200 : case libsumo::CMD_CLOSE:
1201 5786 : writeStatusCmd(libsumo::CMD_CLOSE, libsumo::RTYPE_OK, "");
1202 2893 : myCurrentSocket->second->socket->sendExact(myOutputStorage);
1203 2893 : myOutputStorage.reset();
1204 2893 : if (mySockets.size() == 1) {
1205 : // Last client has closed connection
1206 2651 : myDoCloseConnection = true;
1207 : }
1208 : // remove current socket and increment to next socket in ordering
1209 2893 : myCurrentSocket = removeCurrentSocket();
1210 : success = true;
1211 : break;
1212 361 : case libsumo::CMD_SETORDER: {
1213 361 : const int order = myInputStorage.readInt();
1214 : #ifdef DEBUG_MULTI_CLIENTS
1215 : std::cout << " commandId == libsumo::CMD_SETORDER"
1216 : << ", order index is " << order << std::endl;
1217 : #endif
1218 361 : if (order > libsumo::MAX_ORDER) {
1219 0 : return writeErrorStatusCmd(libsumo::CMD_SETORDER, "A set order command needs an int argument below " + toString(libsumo::MAX_ORDER) + ".", myOutputStorage);
1220 : }
1221 : if (mySockets.count(order) > 0 || mySocketReorderRequests.count(order) > 0) {
1222 0 : return writeErrorStatusCmd(libsumo::CMD_SETORDER, "Order '" + toString(order) + "' is already taken.", myOutputStorage);
1223 : }
1224 : // memorize reorder request (will only take effect in the next step)
1225 361 : mySocketReorderRequests[order] = myCurrentSocket->second;
1226 : success = true;
1227 361 : writeStatusCmd(libsumo::CMD_SETORDER, libsumo::RTYPE_OK, "");
1228 361 : break;
1229 : }
1230 5543 : case libsumo::CMD_SUBSCRIBE_BUSSTOP_VARIABLE:
1231 : case libsumo::CMD_SUBSCRIBE_CALIBRATOR_VARIABLE:
1232 : case libsumo::CMD_SUBSCRIBE_CHARGINGSTATION_VARIABLE:
1233 : case libsumo::CMD_SUBSCRIBE_EDGE_VARIABLE:
1234 : case libsumo::CMD_SUBSCRIBE_GUI_VARIABLE:
1235 : case libsumo::CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE:
1236 : case libsumo::CMD_SUBSCRIBE_JUNCTION_VARIABLE:
1237 : case libsumo::CMD_SUBSCRIBE_LANE_VARIABLE:
1238 : case libsumo::CMD_SUBSCRIBE_LANEAREA_VARIABLE:
1239 : case libsumo::CMD_SUBSCRIBE_MEANDATA_VARIABLE:
1240 : case libsumo::CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE:
1241 : case libsumo::CMD_SUBSCRIBE_OVERHEADWIRE_VARIABLE:
1242 : case libsumo::CMD_SUBSCRIBE_PARKINGAREA_VARIABLE:
1243 : case libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE:
1244 : case libsumo::CMD_SUBSCRIBE_POI_VARIABLE:
1245 : case libsumo::CMD_SUBSCRIBE_POLYGON_VARIABLE:
1246 : case libsumo::CMD_SUBSCRIBE_REROUTER_VARIABLE:
1247 : case libsumo::CMD_SUBSCRIBE_ROUTE_VARIABLE:
1248 : case libsumo::CMD_SUBSCRIBE_ROUTEPROBE_VARIABLE:
1249 : case libsumo::CMD_SUBSCRIBE_SIM_VARIABLE:
1250 : case libsumo::CMD_SUBSCRIBE_TL_VARIABLE:
1251 : case libsumo::CMD_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE:
1252 : case libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE:
1253 : case libsumo::CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE:
1254 5543 : success = addObjectVariableSubscription(commandId, false);
1255 : break;
1256 3492 : case libsumo::CMD_SUBSCRIBE_BUSSTOP_CONTEXT:
1257 : case libsumo::CMD_SUBSCRIBE_CALIBRATOR_CONTEXT:
1258 : case libsumo::CMD_SUBSCRIBE_CHARGINGSTATION_CONTEXT:
1259 : case libsumo::CMD_SUBSCRIBE_EDGE_CONTEXT:
1260 : case libsumo::CMD_SUBSCRIBE_GUI_CONTEXT:
1261 : case libsumo::CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT:
1262 : case libsumo::CMD_SUBSCRIBE_JUNCTION_CONTEXT:
1263 : case libsumo::CMD_SUBSCRIBE_LANE_CONTEXT:
1264 : case libsumo::CMD_SUBSCRIBE_LANEAREA_CONTEXT:
1265 : case libsumo::CMD_SUBSCRIBE_MEANDATA_CONTEXT:
1266 : case libsumo::CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT:
1267 : case libsumo::CMD_SUBSCRIBE_OVERHEADWIRE_CONTEXT:
1268 : case libsumo::CMD_SUBSCRIBE_PARKINGAREA_CONTEXT:
1269 : case libsumo::CMD_SUBSCRIBE_PERSON_CONTEXT:
1270 : case libsumo::CMD_SUBSCRIBE_POI_CONTEXT:
1271 : case libsumo::CMD_SUBSCRIBE_POLYGON_CONTEXT:
1272 : case libsumo::CMD_SUBSCRIBE_REROUTER_CONTEXT:
1273 : case libsumo::CMD_SUBSCRIBE_ROUTE_CONTEXT:
1274 : case libsumo::CMD_SUBSCRIBE_ROUTEPROBE_CONTEXT:
1275 : case libsumo::CMD_SUBSCRIBE_SIM_CONTEXT:
1276 : case libsumo::CMD_SUBSCRIBE_TL_CONTEXT:
1277 : case libsumo::CMD_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT:
1278 : case libsumo::CMD_SUBSCRIBE_VEHICLE_CONTEXT:
1279 : case libsumo::CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT:
1280 3492 : success = addObjectVariableSubscription(commandId, true);
1281 : break;
1282 570 : case libsumo::CMD_ADD_SUBSCRIPTION_FILTER:
1283 570 : success = addSubscriptionFilter();
1284 : break;
1285 : case libsumo::CMD_SET_GUI_VARIABLE:
1286 1 : writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo");
1287 1 : break;
1288 : default:
1289 2 : writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "Command not implemented in sumo");
1290 : }
1291 : }
1292 8322982 : if (!success) {
1293 2033 : while (myInputStorage.valid_pos() && (int)myInputStorage.position() < commandStart + commandLength) {
1294 1090 : myInputStorage.readChar();
1295 : }
1296 : }
1297 8326255 : if ((int)myInputStorage.position() != commandStart + commandLength) {
1298 0 : std::ostringstream msg;
1299 0 : msg << "Wrong position in requestMessage after dispatching command " << commandId << ".";
1300 0 : msg << " Expected command length was " << commandLength;
1301 0 : msg << " but " << myInputStorage.position() - commandStart << " Bytes were read.";
1302 0 : writeStatusCmd(commandId, libsumo::RTYPE_ERR, msg.str());
1303 0 : myDoCloseConnection = true;
1304 0 : }
1305 8326255 : return commandId;
1306 : }
1307 :
1308 :
1309 : // ---------- Server-internal command handling
1310 : bool
1311 2393 : TraCIServer::commandGetVersion() {
1312 : // Prepare response
1313 2393 : tcpip::Storage answerTmp;
1314 2393 : answerTmp.writeInt(libsumo::TRACI_VERSION);
1315 2393 : answerTmp.writeString("SUMO " VERSION_STRING);
1316 : // When we get here, the response is stored in answerTmp -> put into myOutputStorage
1317 2393 : writeStatusCmd(libsumo::CMD_GETVERSION, libsumo::RTYPE_OK, "");
1318 : // command length
1319 2393 : myOutputStorage.writeUnsignedByte(1 + 1 + static_cast<int>(answerTmp.size()));
1320 : // command type
1321 2393 : myOutputStorage.writeUnsignedByte(libsumo::CMD_GETVERSION);
1322 : // and the parameter dependant part
1323 2393 : myOutputStorage.writeStorage(answerTmp);
1324 2393 : return true;
1325 2393 : }
1326 :
1327 :
1328 : void
1329 1698154 : TraCIServer::postProcessSimulationStep() {
1330 1698154 : SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
1331 : #ifdef DEBUG_MULTI_CLIENTS
1332 : std::cout << " postProcessSimulationStep() at time=" << t << std::endl;
1333 : #endif
1334 3396308 : writeStatusCmd(libsumo::CMD_SIMSTEP, libsumo::RTYPE_OK, "");
1335 : int noActive = 0;
1336 5936140 : for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
1337 : const libsumo::Subscription& s = *i;
1338 4237986 : bool isArrivedVehicle = (s.commandId == libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE || s.commandId == libsumo::CMD_SUBSCRIBE_VEHICLE_CONTEXT)
1339 4237986 : && (find(myVehicleStateChanges[MSNet::VehicleState::ARRIVED].begin(), myVehicleStateChanges[MSNet::VehicleState::ARRIVED].end(), s.id) != myVehicleStateChanges[MSNet::VehicleState::ARRIVED].end());
1340 :
1341 4237986 : bool isArrivedPerson = (s.commandId == libsumo::CMD_SUBSCRIBE_PERSON_VARIABLE || s.commandId == libsumo::CMD_SUBSCRIBE_PERSON_CONTEXT) && MSNet::getInstance()->getPersonControl().get(s.id) == nullptr;
1342 4237986 : if ((s.endTime < t) || isArrivedVehicle || isArrivedPerson) {
1343 2065 : i = mySubscriptions.erase(i);
1344 2065 : continue;
1345 : }
1346 : ++i;
1347 4235921 : if (s.beginTime > t) {
1348 25 : continue;
1349 : }
1350 4235896 : ++noActive;
1351 : }
1352 1698154 : mySubscriptionCache.reset();
1353 : #ifdef DEBUG_SUBSCRIPTIONS
1354 : std::cout << " Initial size of mySubscriptionCache is " << mySubscriptionCache.size()
1355 : << "\n Nr. of active subscriptions = " << noActive << std::endl;
1356 : #endif
1357 1698154 : mySubscriptionCache.writeInt(noActive);
1358 : #ifdef DEBUG_SUBSCRIPTIONS
1359 : std::cout << " Size after writing an int is " << mySubscriptionCache.size() << std::endl;
1360 : #endif
1361 5934022 : for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
1362 : const libsumo::Subscription& s = *i;
1363 4235921 : if (s.beginTime > t) {
1364 : ++i;
1365 25 : continue;
1366 : }
1367 4235896 : tcpip::Storage into;
1368 : std::string errors;
1369 4235896 : bool ok = processSingleSubscription(s, into, errors);
1370 : #ifdef DEBUG_SUBSCRIPTIONS
1371 : std::cout << " Size of into-store for subscription " << s.id
1372 : << ": " << into.size() << std::endl;
1373 : #endif
1374 4235843 : mySubscriptionCache.writeStorage(into);
1375 4235843 : if (ok) {
1376 : ++i;
1377 : } else {
1378 0 : i = mySubscriptions.erase(i);
1379 : }
1380 4235896 : }
1381 1698101 : myOutputStorage.writeStorage(mySubscriptionCache);
1382 : #ifdef DEBUG_SUBSCRIPTIONS
1383 : std::cout << " Size after writing subscriptions is " << mySubscriptionCache.size() << std::endl;
1384 : #endif
1385 1698101 : }
1386 :
1387 :
1388 : void
1389 28314 : TraCIServer::sendSingleSimStepResponse() {
1390 : #ifdef DEBUG_MULTI_CLIENTS
1391 : std::cout << " Sending cached simstep response to current client " << myCurrentSocket->second->socket
1392 : << " (-> intermediate TraCI step)."
1393 : << "\n Size of mySubscriptionCache is " << mySubscriptionCache.size()
1394 : << std::endl;
1395 : #endif
1396 28314 : writeStatusCmd(libsumo::CMD_SIMSTEP, libsumo::RTYPE_OK, "");
1397 :
1398 : // NOTE: the commented code would send an empty response
1399 : // myOutputStorage.writeInt(0);
1400 : // myCurrentSocket->second->socket->sendExact(myOutputStorage);
1401 : // myOutputStorage.reset();
1402 28314 : myOutputStorage.writeStorage(mySubscriptionCache);
1403 : // send results to active client
1404 28314 : myCurrentSocket->second->socket->sendExact(myOutputStorage);
1405 28314 : myOutputStorage.reset();
1406 28314 : }
1407 :
1408 :
1409 : void
1410 1741840 : TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
1411 1741840 : writeStatusCmd(commandId, status, description, myOutputStorage);
1412 1741840 : }
1413 :
1414 :
1415 : void
1416 18548282 : TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
1417 18548282 : if (status == libsumo::RTYPE_ERR) {
1418 5847 : WRITE_ERROR("Answered with error to command " + toHex(commandId, 2) + ": " + description);
1419 18546333 : } else if (status == libsumo::RTYPE_NOTIMPLEMENTED) {
1420 366 : WRITE_ERROR("Requested command not implemented (" + toHex(commandId, 2) + "): " + description);
1421 : }
1422 18548282 : outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
1423 18548282 : outputStorage.writeUnsignedByte(commandId); // command type
1424 18548282 : outputStorage.writeUnsignedByte(status); // status
1425 18548282 : outputStorage.writeString(description); // description
1426 18548282 : }
1427 :
1428 :
1429 : bool
1430 924 : TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
1431 924 : writeStatusCmd(commandId, libsumo::RTYPE_ERR, description, outputStorage);
1432 924 : return false;
1433 : }
1434 :
1435 :
1436 : void
1437 7799 : TraCIServer::initialiseSubscription(libsumo::Subscription& s) {
1438 7799 : tcpip::Storage writeInto;
1439 : std::string errors;
1440 7799 : libsumo::Subscription* modifiedSubscription = nullptr;
1441 : try {
1442 7799 : if (processSingleSubscription(s, writeInto, errors)) {
1443 6784 : if (s.endTime < MSNet::getInstance()->getCurrentTimeStep()) {
1444 0 : writeStatusCmd(s.commandId, libsumo::RTYPE_ERR, "Subscription has ended.");
1445 : } else {
1446 6784 : if (libsumo::Helper::needNewSubscription(s, mySubscriptions, modifiedSubscription)) {
1447 : // Add new subscription to subscription cache (note: seems a bit inefficient)
1448 4383 : if (s.beginTime < MSNet::getInstance()->getCurrentTimeStep()) {
1449 : // copy new subscription into cache
1450 4337 : int noActive = 1 + (mySubscriptionCache.size() > 0 ? mySubscriptionCache.readInt() : 0);
1451 4337 : tcpip::Storage tmp;
1452 4337 : tmp.writeInt(noActive);
1453 28301150 : while (mySubscriptionCache.valid_pos()) {
1454 28296813 : tmp.writeByte(mySubscriptionCache.readByte());
1455 : }
1456 4337 : tmp.writeStorage(writeInto);
1457 4337 : mySubscriptionCache.reset();
1458 4337 : mySubscriptionCache.writeStorage(tmp);
1459 4337 : }
1460 : }
1461 13568 : writeStatusCmd(s.commandId, libsumo::RTYPE_OK, "");
1462 : }
1463 6784 : if (modifiedSubscription != nullptr && (
1464 : modifiedSubscription->isVehicleToVehicleContextSubscription()
1465 : || modifiedSubscription->isVehicleToPersonContextSubscription())) {
1466 : // Set last modified vehicle context subscription active for filter modifications
1467 211 : myLastContextSubscription = modifiedSubscription;
1468 : } else {
1469 : // adding other subscriptions deactivates the activation for filter addition
1470 6573 : myLastContextSubscription = nullptr;
1471 : }
1472 : } else {
1473 226 : writeStatusCmd(s.commandId, libsumo::RTYPE_ERR, "Could not add subscription. " + errors);
1474 : }
1475 902 : } catch (libsumo::TraCIException& e) {
1476 902 : writeStatusCmd(s.commandId, libsumo::RTYPE_ERR, e.what());
1477 902 : }
1478 7799 : myOutputStorage.writeStorage(writeInto);
1479 7799 : }
1480 :
1481 :
1482 : void
1483 1229 : TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
1484 : bool found = false;
1485 : std::vector<libsumo::Subscription>::iterator j;
1486 2502 : for (j = mySubscriptions.begin(); j != mySubscriptions.end();) {
1487 1273 : if (j->id == id && j->commandId == commandId && j->contextDomain == domain) {
1488 1229 : j = mySubscriptions.erase(j);
1489 1229 : if (j != mySubscriptions.end() && myLastContextSubscription == &(*j)) {
1490 : // Remove also reference for filter additions
1491 0 : myLastContextSubscription = nullptr;
1492 : }
1493 : found = true;
1494 1229 : continue;
1495 : }
1496 : ++j;
1497 : }
1498 : // try unsubscribe
1499 1229 : if (found) {
1500 2458 : writeStatusCmd(commandId, libsumo::RTYPE_OK, "");
1501 : } else {
1502 0 : writeStatusCmd(commandId, libsumo::RTYPE_ERR, "The subscription to remove was not found.");
1503 : }
1504 1229 : }
1505 :
1506 :
1507 : bool
1508 4243695 : TraCIServer::processSingleSubscription(const libsumo::Subscription& s, tcpip::Storage& writeInto,
1509 : std::string& errors) {
1510 : bool ok = true;
1511 4243695 : tcpip::Storage outputStorage;
1512 4243695 : const int getCommandId = s.contextDomain > 0 ? s.contextDomain : s.commandId - 0x30;
1513 : std::set<std::string> objIDs;
1514 4243695 : if (s.contextDomain > 0) {
1515 89504 : if ((s.activeFilters & libsumo::SUBS_FILTER_NO_RTREE) == 0) {
1516 87745 : PositionVector shape;
1517 87745 : libsumo::Helper::findObjectShape(s.commandId, s.id, shape);
1518 87745 : libsumo::Helper::collectObjectIDsInRange(s.contextDomain, shape, s.range, objIDs);
1519 87745 : }
1520 88602 : libsumo::Helper::applySubscriptionFilters(s, objIDs);
1521 : } else {
1522 4154191 : objIDs.insert(s.id);
1523 : }
1524 4242740 : const int numVars = s.contextDomain > 0 && s.variables.size() == 1 && s.variables[0] == libsumo::TRACI_ID_LIST ? 0 : (int)s.variables.size();
1525 : int skipped = 0;
1526 8597227 : for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
1527 4354487 : if (s.contextDomain > 0) {
1528 : //if (centralObject(s, *j)) {
1529 : // skipped++;
1530 : // continue;
1531 : //}
1532 200296 : outputStorage.writeString(*j);
1533 : }
1534 4354487 : if (numVars > 0) {
1535 : std::vector<std::shared_ptr<tcpip::Storage> >::const_iterator k = s.parameters.begin();
1536 12843368 : for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i, ++k) {
1537 8495559 : tcpip::Storage message;
1538 8495559 : message.writeUnsignedByte(*i);
1539 8495559 : message.writeString(*j);
1540 : // TODO check why writeStorage fails here (probably some kind of invalid iterator)
1541 8589087 : for (const auto& v :** k) {
1542 93528 : message.writeChar(v);
1543 : }
1544 8495559 : tcpip::Storage tmpOutput;
1545 : try {
1546 8495559 : if (myExecutors.find(getCommandId) != myExecutors.end()) {
1547 615 : ok &= myExecutors[getCommandId](*this, message, tmpOutput);
1548 8494944 : } else if (!processGet(getCommandId, message, tmpOutput)) {
1549 92 : if (getCommandId == libsumo::CMD_GET_GUI_VARIABLE) {
1550 0 : writeStatusCmd(s.commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo", tmpOutput);
1551 : }
1552 : ok = false;
1553 : }
1554 21 : } catch (const std::invalid_argument&) {
1555 21 : writeStatusCmd(s.commandId, libsumo::RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
1556 : ok = false;
1557 21 : }
1558 : // copy response part
1559 8495446 : if (ok) {
1560 8495446 : int length = tmpOutput.readUnsignedByte();
1561 59468122 : while (--length > 0) {
1562 50972676 : tmpOutput.readUnsignedByte();
1563 : }
1564 : int lengthLength = 1;
1565 8495446 : length = tmpOutput.readUnsignedByte();
1566 8495446 : if (length == 0) {
1567 : lengthLength = 5;
1568 45 : length = tmpOutput.readInt();
1569 : }
1570 : //read responseType
1571 8495446 : tmpOutput.readUnsignedByte();
1572 8495446 : int variable = tmpOutput.readUnsignedByte();
1573 8495446 : std::string id = tmpOutput.readString();
1574 8495446 : outputStorage.writeUnsignedByte(variable);
1575 8495446 : outputStorage.writeUnsignedByte(libsumo::RTYPE_OK);
1576 8495446 : length -= (lengthLength + 1 + 4 + (int)id.length());
1577 107581885 : while (--length > 0) {
1578 99086439 : outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
1579 : }
1580 : } else {
1581 : //read length
1582 113 : tmpOutput.readUnsignedByte();
1583 : //read cmd
1584 113 : tmpOutput.readUnsignedByte();
1585 : //read status
1586 113 : tmpOutput.readUnsignedByte();
1587 113 : std::string msg = tmpOutput.readString();
1588 113 : outputStorage.writeUnsignedByte(*i);
1589 113 : outputStorage.writeUnsignedByte(libsumo::RTYPE_ERR);
1590 113 : outputStorage.writeUnsignedByte(libsumo::TYPE_STRING);
1591 113 : outputStorage.writeString(msg);
1592 226 : errors = errors + msg;
1593 : }
1594 8495559 : }
1595 : }
1596 : }
1597 4242740 : int length = (1 + 4) + 1 + (4 + (int)s.id.length()) + 1 + (int)outputStorage.size();
1598 4242740 : if (s.contextDomain > 0) {
1599 88549 : length += 1 + 4; // context domain and number of objects
1600 : }
1601 : // we always write extended command length here for backward compatibility
1602 4242740 : writeInto.writeUnsignedByte(0); // command length -> extended
1603 4242740 : writeInto.writeInt(length);
1604 4242740 : writeInto.writeUnsignedByte(s.commandId + 0x10);
1605 4242740 : writeInto.writeString(s.id);
1606 4242740 : if (s.contextDomain > 0) {
1607 88549 : writeInto.writeUnsignedByte(s.contextDomain);
1608 : }
1609 4242740 : writeInto.writeUnsignedByte(numVars);
1610 4242740 : if (s.contextDomain > 0) {
1611 88549 : writeInto.writeInt((int)objIDs.size() - skipped);
1612 : }
1613 4242740 : if (s.contextDomain == 0 || objIDs.size() != 0) {
1614 4198847 : writeInto.writeStorage(outputStorage);
1615 : }
1616 4242740 : return ok;
1617 4243695 : }
1618 :
1619 :
1620 : bool
1621 9035 : TraCIServer::addObjectVariableSubscription(const int commandId, const bool hasContext) {
1622 9035 : const double beginTime = myInputStorage.readDouble();
1623 9035 : const double endTime = myInputStorage.readDouble();
1624 9035 : const SUMOTime begin = beginTime == libsumo::INVALID_DOUBLE_VALUE ? 0 : TIME2STEPS(beginTime);
1625 9035 : const SUMOTime end = endTime == libsumo::INVALID_DOUBLE_VALUE || endTime > STEPS2TIME(SUMOTime_MAX) ? SUMOTime_MAX : TIME2STEPS(endTime);
1626 9035 : const std::string id = myInputStorage.readString();
1627 9035 : const int domain = hasContext ? myInputStorage.readUnsignedByte() : 0;
1628 3492 : double range = hasContext ? myInputStorage.readDouble() : 0.;
1629 9035 : if (commandId == libsumo::CMD_SUBSCRIBE_SIM_CONTEXT) {
1630 : range = std::numeric_limits<double>::max();
1631 : }
1632 9035 : const int num = myInputStorage.readUnsignedByte();
1633 : std::vector<int> variables;
1634 : std::vector<std::shared_ptr<tcpip::Storage> > parameters;
1635 19670 : for (int i = 0; i < num; ++i) {
1636 10642 : const int varID = myInputStorage.readUnsignedByte();
1637 10642 : variables.push_back(varID);
1638 10642 : parameters.push_back(std::make_shared<tcpip::Storage>());
1639 10642 : if ((myParameterized.count(std::make_pair(0, varID)) > 0) || (myParameterized.count(std::make_pair(commandId, varID)) > 0)) {
1640 343 : if (!myInputStorage.valid_pos()) {
1641 14 : writeStatusCmd(commandId, libsumo::RTYPE_ERR, "Missing parameter for subscription " + toHex(commandId, 2));
1642 7 : return false;
1643 : }
1644 : int count = 1;
1645 730 : while (count-- > 0) {
1646 406 : const int parType = myInputStorage.readUnsignedByte();
1647 406 : parameters.back()->writeUnsignedByte(parType);
1648 : if (parType == libsumo::TYPE_DOUBLE) {
1649 109 : parameters.back()->writeDouble(myInputStorage.readDouble());
1650 : } else if (parType == libsumo::TYPE_INTEGER) {
1651 33 : parameters.back()->writeInt(myInputStorage.readInt());
1652 : } else if (parType == libsumo::TYPE_STRING) {
1653 422 : parameters.back()->writeString(myInputStorage.readString());
1654 : } else if (parType == libsumo::TYPE_BYTE) {
1655 6 : parameters.back()->writeByte(myInputStorage.readByte());
1656 : } else if (parType == libsumo::TYPE_UBYTE) {
1657 3 : parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1658 : } else if (parType == libsumo::POSITION_2D) {
1659 6 : parameters.back()->writeDouble(myInputStorage.readDouble());
1660 6 : parameters.back()->writeDouble(myInputStorage.readDouble());
1661 6 : if (varID == libsumo::DISTANCE_REQUEST) {
1662 6 : parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1663 : break;
1664 : }
1665 : } else if (parType == libsumo::POSITION_3D) {
1666 0 : parameters.back()->writeDouble(myInputStorage.readDouble());
1667 0 : parameters.back()->writeDouble(myInputStorage.readDouble());
1668 0 : parameters.back()->writeDouble(myInputStorage.readDouble());
1669 0 : if (varID == libsumo::DISTANCE_REQUEST) {
1670 0 : parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1671 : break;
1672 : }
1673 : } else if (parType == libsumo::POSITION_ROADMAP) {
1674 12 : parameters.back()->writeString(myInputStorage.readString());
1675 6 : parameters.back()->writeDouble(myInputStorage.readDouble());
1676 6 : parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1677 6 : if (varID == libsumo::DISTANCE_REQUEST) {
1678 6 : parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1679 : break;
1680 : }
1681 : } else if (parType == libsumo::TYPE_COMPOUND) {
1682 32 : count = myInputStorage.readInt();
1683 32 : parameters.back()->writeInt(count);
1684 : } else {
1685 0 : writeStatusCmd(commandId, libsumo::RTYPE_ERR, "Invalid parameter for subscription " + toHex(commandId, 2));
1686 0 : return false;
1687 : }
1688 : }
1689 : }
1690 : }
1691 : // check subscribe/unsubscribe
1692 9028 : if (variables.empty()) {
1693 1229 : removeSubscription(commandId, id, domain);
1694 : return true;
1695 : }
1696 : // process subscription
1697 7799 : libsumo::Subscription s(commandId, id, variables, parameters, begin, end, domain, range);
1698 7799 : initialiseSubscription(s);
1699 : return true;
1700 16834 : }
1701 :
1702 :
1703 :
1704 : bool
1705 570 : TraCIServer::addSubscriptionFilter() {
1706 : bool success = true;
1707 : // Read filter type
1708 570 : int filterType = myInputStorage.readUnsignedByte();
1709 :
1710 570 : if (myLastContextSubscription == nullptr) {
1711 3 : writeStatusCmd(libsumo::CMD_ADD_SUBSCRIPTION_FILTER, libsumo::RTYPE_ERR,
1712 3 : "No previous vehicle context subscription exists to apply filter type " + toHex(filterType, 2));
1713 3 : return false;
1714 : }
1715 :
1716 : // dispatch according to filter type
1717 567 : switch (filterType) {
1718 0 : case libsumo::FILTER_TYPE_NONE:
1719 : // Remove all filters
1720 0 : removeFilters();
1721 : break;
1722 133 : case libsumo::FILTER_TYPE_LANES: {
1723 : // Read relative lanes to consider for context filter
1724 133 : int nrLanes = (int)myInputStorage.readByte();
1725 : std::vector<int> lanes;
1726 358 : for (int i = 0; i < nrLanes; ++i) {
1727 225 : lanes.push_back((int) myInputStorage.readByte());
1728 : }
1729 133 : addSubscriptionFilterLanes(lanes);
1730 133 : }
1731 : break;
1732 43 : case libsumo::FILTER_TYPE_NOOPPOSITE:
1733 : // Add no-opposite filter
1734 43 : addSubscriptionFilterNoOpposite();
1735 : break;
1736 153 : case libsumo::FILTER_TYPE_DOWNSTREAM_DIST: {
1737 153 : myInputStorage.readByte(); // read type double
1738 153 : double dist = myInputStorage.readDouble();
1739 153 : addSubscriptionFilterDownstreamDistance(dist);
1740 : }
1741 : break;
1742 129 : case libsumo::FILTER_TYPE_UPSTREAM_DIST: {
1743 129 : myInputStorage.readByte(); // read type double
1744 129 : double dist = myInputStorage.readDouble();
1745 129 : addSubscriptionFilterUpstreamDistance(dist);
1746 : }
1747 : break;
1748 18 : case libsumo::FILTER_TYPE_LEAD_FOLLOW: {
1749 : // Read relative lanes to consider for context filter
1750 18 : addSubscriptionFilterLeadFollow();
1751 : }
1752 : break;
1753 25 : case libsumo::FILTER_TYPE_TURN: {
1754 25 : myInputStorage.readByte(); // read type double
1755 25 : double dist = myInputStorage.readDouble();
1756 25 : addSubscriptionFilterTurn(dist);
1757 : }
1758 : break;
1759 10 : case libsumo::FILTER_TYPE_VCLASS: {
1760 10 : myInputStorage.readByte(); // read type stringlist
1761 10 : SVCPermissions vClasses = parseVehicleClasses(myInputStorage.readStringList());
1762 10 : addSubscriptionFilterVClass(vClasses);
1763 : }
1764 : break;
1765 10 : case libsumo::FILTER_TYPE_VTYPE: {
1766 10 : myInputStorage.readByte(); // read type stringlist
1767 10 : std::vector<std::string> vTypesVector = myInputStorage.readStringList();
1768 : std::set<std::string> vTypesSet;
1769 : vTypesSet.insert(vTypesVector.begin(), vTypesVector.end());
1770 20 : addSubscriptionFilterVType(vTypesSet);
1771 10 : }
1772 : break;
1773 25 : case libsumo::FILTER_TYPE_FIELD_OF_VISION: {
1774 25 : myInputStorage.readByte(); // read type double
1775 25 : double angle = myInputStorage.readDouble();
1776 25 : addSubscriptionFilterFieldOfVision(angle);
1777 : }
1778 : break;
1779 21 : case libsumo::FILTER_TYPE_LATERAL_DIST: {
1780 21 : myInputStorage.readByte(); // read type double
1781 21 : double dist = myInputStorage.readDouble();
1782 21 : addSubscriptionFilterLateralDistance(dist);
1783 : }
1784 : break;
1785 0 : default:
1786 0 : writeStatusCmd(libsumo::CMD_ADD_SUBSCRIPTION_FILTER, libsumo::RTYPE_NOTIMPLEMENTED,
1787 0 : "'" + toString(filterType) + "' is no valid filter type code.");
1788 : success = false;
1789 : }
1790 :
1791 : if (success) {
1792 : // acknowledge filter addition
1793 1134 : writeStatusCmd(libsumo::CMD_ADD_SUBSCRIPTION_FILTER, libsumo::RTYPE_OK, "");
1794 : }
1795 :
1796 : return success;
1797 : }
1798 :
1799 :
1800 : void
1801 0 : TraCIServer::removeFilters() {
1802 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1803 : std::cout << "Removing filters" << std::endl;
1804 : #endif
1805 0 : myLastContextSubscription->activeFilters = libsumo::SUBS_FILTER_NONE;
1806 0 : }
1807 :
1808 : void
1809 133 : TraCIServer::addSubscriptionFilterLanes(std::vector<int> lanes) {
1810 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1811 : std::cout << "Adding lane filter (lanes=" << toString(lanes) << ")" << std::endl;
1812 : #endif
1813 133 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_LANES;
1814 133 : myLastContextSubscription->filterLanes = lanes;
1815 133 : }
1816 :
1817 : void
1818 43 : TraCIServer::addSubscriptionFilterNoOpposite() {
1819 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1820 : std::cout << "Adding no opposite filter" << std::endl;
1821 : #endif
1822 43 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_NOOPPOSITE;
1823 43 : }
1824 :
1825 : void
1826 153 : TraCIServer::addSubscriptionFilterDownstreamDistance(double dist) {
1827 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1828 : std::cout << "Adding downstream dist filter (dist=" << toString(dist) << ")" << std::endl;
1829 : #endif
1830 153 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_DOWNSTREAM_DIST;
1831 153 : myLastContextSubscription->filterDownstreamDist = dist;
1832 153 : }
1833 :
1834 : void
1835 129 : TraCIServer::addSubscriptionFilterUpstreamDistance(double dist) {
1836 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1837 : std::cout << "Adding upstream dist filter (dist=" << toString(dist) << ")" << std::endl;
1838 : #endif
1839 129 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_UPSTREAM_DIST;
1840 129 : myLastContextSubscription->filterUpstreamDist = dist;
1841 129 : }
1842 :
1843 : void
1844 18 : TraCIServer::addSubscriptionFilterLeadFollow() {
1845 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1846 : std::cout << "Adding Lead/Follow-maneuver filter" << std::endl;
1847 : #endif
1848 18 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_LEAD_FOLLOW;
1849 18 : }
1850 :
1851 : void
1852 25 : TraCIServer::addSubscriptionFilterTurn(double dist) {
1853 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1854 : std::cout << "Adding turn-maneuver filter" << std::endl;
1855 : #endif
1856 25 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_TURN;
1857 25 : myLastContextSubscription->filterFoeDistToJunction = dist;
1858 25 : }
1859 :
1860 : void
1861 10 : TraCIServer::addSubscriptionFilterVClass(SVCPermissions vClasses) {
1862 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1863 : std::cout << "Adding vClass filter (vClasses=" << toString(vClasses) << ")" << std::endl;
1864 : #endif
1865 10 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_VCLASS;
1866 10 : myLastContextSubscription->filterVClasses = vClasses;
1867 10 : }
1868 :
1869 : void
1870 10 : TraCIServer::addSubscriptionFilterVType(std::set<std::string> vTypes) {
1871 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1872 : std::cout << "Adding vType filter (vTypes=" << toString(vTypes) << ")" << std::endl;
1873 : #endif
1874 10 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_VTYPE;
1875 : myLastContextSubscription->filterVTypes = vTypes;
1876 10 : }
1877 :
1878 : void
1879 25 : TraCIServer::addSubscriptionFilterFieldOfVision(double openingAngle) {
1880 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1881 : std::cout << "Adding FieldOfVision filter (openingAngle=" << toString(openingAngle) << ")" << std::endl;
1882 : #endif
1883 25 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_FIELD_OF_VISION;
1884 25 : myLastContextSubscription->filterFieldOfVisionOpeningAngle = openingAngle;
1885 25 : }
1886 :
1887 : void
1888 21 : TraCIServer::addSubscriptionFilterLateralDistance(double dist) {
1889 : #ifdef DEBUG_SUBSCRIPTION_FILTERS
1890 : std::cout << "Adding lateral dist filter (dist=" << toString(dist) << ")" << std::endl;
1891 : #endif
1892 21 : myLastContextSubscription->activeFilters = myLastContextSubscription->activeFilters | libsumo::SUBS_FILTER_LATERAL_DIST;
1893 21 : myLastContextSubscription->filterLateralDist = dist;
1894 21 : }
1895 :
1896 : void
1897 15472427 : TraCIServer::writeResponseWithLength(tcpip::Storage& outputStorage, tcpip::Storage& tempMsg) {
1898 15472427 : if (tempMsg.size() < 254) {
1899 15439519 : outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
1900 : } else {
1901 32908 : outputStorage.writeUnsignedByte(0); // command length -> extended
1902 32908 : outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
1903 : }
1904 15472427 : outputStorage.writeStorage(tempMsg);
1905 15472427 : }
1906 :
1907 :
1908 : void
1909 111 : TraCIServer::stateLoaded(SUMOTime targetTime) {
1910 111 : myTargetTime = targetTime;
1911 222 : for (auto& s : mySockets) {
1912 111 : s.second->targetTime = targetTime;
1913 111 : s.second->executeMove = false;
1914 1554 : for (auto& stateChange : s.second->vehicleStateChanges) {
1915 : stateChange.second.clear();
1916 : }
1917 555 : for (auto& stateChange : s.second->transportableStateChanges) {
1918 : stateChange.second.clear();
1919 : }
1920 : }
1921 : mySubscriptions.clear();
1922 111 : mySubscriptionCache.reset();
1923 111 : }
1924 :
1925 :
1926 : bool
1927 0 : TraCIServer::centralObject(const libsumo::Subscription& s, const std::string& objID) {
1928 0 : return (s.id == objID && s.commandId + 32 == s.contextDomain);
1929 : }
1930 :
1931 :
1932 : /****************************************************************************/
|