Line data Source code
1 : /****************************************************************************/
2 : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3 : // Copyright (C) 2001-2025 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.h
15 : /// @author Axel Wegener
16 : /// @author Friedemann Wesner
17 : /// @author Christoph Sommer
18 : /// @author Tino Morenz
19 : /// @author Daniel Krajzewicz
20 : /// @author Thimor Bohn
21 : /// @author Sascha Krieg
22 : /// @author Michael Behrisch
23 : /// @author Leonhard Luecken
24 : /// @date 2007/10/24
25 : ///
26 : // TraCI server used to control sumo by a remote TraCI client
27 : /****************************************************************************/
28 : #pragma once
29 : #include <config.h>
30 :
31 : #include <map>
32 : #include <string>
33 : #include <set>
34 :
35 : #define BUILD_TCPIP
36 : #include <foreign/tcpip/socket.h>
37 : #include <foreign/tcpip/storage.h>
38 : #include <utils/common/NamedRTree.h>
39 : #include <utils/common/SUMOTime.h>
40 : #include <utils/common/ToString.h>
41 : #include <utils/geom/Boundary.h>
42 : #include <utils/geom/Position.h>
43 : #include <utils/geom/GeomHelper.h>
44 : #include <utils/options/OptionsCont.h>
45 : #include <microsim/MSNet.h>
46 : #include <microsim/traffic_lights/MSTrafficLightLogic.h>
47 : #include <libsumo/TraCIConstants.h>
48 : #include <libsumo/Subscription.h>
49 : #include <libsumo/TraCIDefs.h>
50 : #include "TraCIServerAPI_Lane.h"
51 :
52 :
53 : // ===========================================================================
54 : // class definitions
55 : // ===========================================================================
56 : /** @class TraCIServer
57 : * @brief TraCI server used to control sumo by a remote TraCI client
58 : */
59 : class TraCIServer final : public MSNet::VehicleStateListener, public libsumo::VariableWrapper, public MSNet::TransportableStateListener {
60 : public:
61 : /// @brief Definition of a method to be called for serving an associated commandID
62 : typedef bool(*CmdExecutor)(TraCIServer& server, tcpip::Storage& inputStorage, tcpip::Storage& outputStorage);
63 :
64 : SUMOTime getTargetTime() const {
65 : return myTargetTime;
66 : }
67 :
68 : static TraCIServer* getInstance() {
69 144307408 : return myInstance;
70 : }
71 :
72 : /// @name Initialisation and Shutdown
73 : /// @{
74 :
75 : /** @brief Initialises the server
76 : * @param[in] execs The (additional) command executors to use
77 : */
78 : static void openSocket(const std::map<int, CmdExecutor>& execs);
79 :
80 :
81 : /// @brief request termination of connection
82 : static void close();
83 :
84 :
85 : /** @brief check whether close was requested
86 : * @return Whether the connection was closed
87 : */
88 : static bool wasClosed();
89 : /// @}
90 :
91 :
92 : /// @brief process all commands until the next SUMO simulation step.
93 : /// It is guaranteed that t->getTargetTime() >= myStep after call
94 : /// (except the case that a load or close command is received)s
95 : int processCommands(const SUMOTime step, const bool afterMove = false);
96 :
97 : /** @brief Processes a get value command
98 : *
99 : * @param[in] commandID The id of the command to process
100 : * @param[in] inputStorage The storage to read the command parameters from
101 : * @param[out] outputStorage The storage to write the result to
102 : */
103 : bool processGet(const int commandID, tcpip::Storage& inputStorage, tcpip::Storage& outputStorage);
104 :
105 : /// @brief clean up subscriptions
106 : void cleanup();
107 :
108 :
109 : void vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& info = "");
110 :
111 : void transportableStateChanged(const MSTransportable* const transportable, MSNet::TransportableState to, const std::string& info = "");
112 :
113 : /// @name Writing Status Messages
114 : /// @{
115 :
116 : /** @brief Writes a status command to the given storage
117 : * @param[in] commandId The id of the command to respond to
118 : * @param[in] status The status to send
119 : * @param[in] description The status description (error message, for example)
120 : * @param[in, filled] outputStorage The storage to write the status into
121 : */
122 : void writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage);
123 :
124 :
125 : /** @brief Writes a status command to myOutputStorage
126 : * @param[in] commandId The id of the command to respond to
127 : * @param[in] status The status to send
128 : * @param[in] description The status description (error message, for example)
129 : */
130 : void writeStatusCmd(int commandId, int status, const std::string& description);
131 :
132 :
133 : /** @brief Writes a status command to the given storage with status = RTYPE_ERR
134 : * @param[in] commandId The id of the command to respond to
135 : * @param[in] description The status description (error message, for example)
136 : * @param[in, filled] outputStorage The storage to write the status into
137 : */
138 : bool writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage);
139 : /// @}
140 :
141 :
142 :
143 : const std::map<MSNet::VehicleState, std::vector<std::string> >& getVehicleStateChanges() const {
144 68049 : if (myCurrentSocket == mySockets.end()) {
145 : // Requested in context of a subscription update
146 16285 : return myVehicleStateChanges;
147 : } else {
148 : // Requested in the context of a custom query by active client
149 51764 : return myCurrentSocket->second->vehicleStateChanges;
150 : }
151 : }
152 :
153 : const std::map<MSNet::TransportableState, std::vector<std::string> >& getTransportableStateChanges() const {
154 60 : if (myCurrentSocket == mySockets.end()) {
155 : // Requested in context of a subscription update
156 12 : return myTransportableStateChanges;
157 : } else {
158 : // Requested in the context of a custom query by active client
159 48 : return myCurrentSocket->second->transportableStateChanges;
160 : }
161 : }
162 :
163 : void writeResponseWithLength(tcpip::Storage& outputStorage, tcpip::Storage& tempMsg);
164 :
165 : /// @brief updates myTargetTime and resets vehicle state changes after loading a simulation state
166 : /// @note Used in MSStateHandler to update the server's time after loading a state
167 : void stateLoaded(SUMOTime targetTime);
168 :
169 : std::vector<std::string>& getLoadArgs() {
170 13 : return myLoadArgs;
171 : }
172 :
173 : /// @name VariableWrapper interface
174 : /// @{
175 : void initWrapper(const int domainID, const int variable, const std::string& objID);
176 : bool wrapConnectionVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCIConnection>& value);
177 : bool wrapDouble(const std::string& objID, const int variable, const double value);
178 : bool wrapInt(const std::string& objID, const int variable, const int value);
179 : bool wrapString(const std::string& objID, const int variable, const std::string& value);
180 : bool wrapStringList(const std::string& objID, const int variable, const std::vector<std::string>& value);
181 : bool wrapDoubleList(const std::string& objID, const int variable, const std::vector<double>& value);
182 : bool wrapPosition(const std::string& objID, const int variable, const libsumo::TraCIPosition& value);
183 : bool wrapPositionVector(const std::string& objID, const int variable, const libsumo::TraCIPositionVector& value);
184 : bool wrapColor(const std::string& objID, const int variable, const libsumo::TraCIColor& value);
185 : bool wrapStringDoublePair(const std::string& objID, const int variable, const std::pair<std::string, double>& value);
186 : bool wrapStringDoublePairList(const std::string& objID, const int variable, const std::vector<std::pair<std::string, double> >& value);
187 : bool wrapStringPair(const std::string& objID, const int variable, const std::pair<std::string, std::string>& value);
188 : bool wrapIntPair(const std::string& objID, const int variable, const std::pair<int, int>& value);
189 : bool wrapStage(const std::string& objID, const int variable, const libsumo::TraCIStage& value);
190 : bool wrapReservationVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCIReservation>& value);
191 : bool wrapLogicVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCILogic>& value);
192 : bool wrapLinkVectorVector(const std::string& objID, const int variable, const std::vector<std::vector<libsumo::TraCILink> >& value);
193 : bool wrapSignalConstraintVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCISignalConstraint>& value);
194 : bool wrapJunctionFoeVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCIJunctionFoe>& value);
195 : bool wrapNextStopDataVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCINextStopData>& value);
196 : bool wrapVehicleDataVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCIVehicleData>& value);
197 : bool wrapBestLanesDataVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCIBestLanesData>& value);
198 : bool wrapNextTLSDataVector(const std::string& objID, const int variable, const std::vector<libsumo::TraCINextTLSData>& value);
199 : tcpip::Storage& getWrapperStorage();
200 : /// @}
201 :
202 :
203 : private:
204 : /** @brief Constructor
205 : * @param[in] port The port to listen to (to open)
206 : */
207 : TraCIServer(const SUMOTime begin, const int port, const int numClients);
208 :
209 :
210 : /// @brief Destructor
211 : virtual ~TraCIServer();
212 :
213 :
214 :
215 : struct SocketInfo {
216 : public:
217 : /// @brief constructor
218 : SocketInfo(tcpip::Socket* socket, SUMOTime t)
219 2721 : : targetTime(t), socket(socket) {}
220 : /// @brief destructor
221 2713 : ~SocketInfo() {
222 2713 : delete socket;
223 2713 : }
224 : /// @brief next point of action for the client
225 : SUMOTime targetTime;
226 : /// @brief whether a "half step" has been done, executing only the move
227 : bool executeMove = false;
228 : /// @brief Socket object for this client
229 : tcpip::Socket* socket;
230 : /// @brief container for vehicle state changes since last step taken by this client
231 : std::map<MSNet::VehicleState, std::vector<std::string> > vehicleStateChanges;
232 : /// @brief container for transportable state changes since last step taken by this client
233 : std::map<MSNet::TransportableState, std::vector<std::string> > transportableStateChanges;
234 : private:
235 : SocketInfo(const SocketInfo&);
236 : };
237 :
238 : /// @name Server-internal command handling
239 : /// @{
240 :
241 : /** @brief Returns the TraCI-version
242 : * @return Always true
243 : */
244 : bool commandGetVersion();
245 :
246 : /** @brief Handles subscriptions to send after a simstep2 command
247 : */
248 : void postProcessSimulationStep();
249 : /// @}
250 :
251 :
252 : /// @brief Reads the next command ID from the input storage
253 : /// @return the command ID
254 : /// @param[out] the version with reference parameters provides information on the command start position and length used in dispatchCommand for checking purposes
255 : int readCommandID(int& commandStart, int& commandLength);
256 :
257 : /// @brief Handles command, writes response to myOutputStorage
258 : int dispatchCommand();
259 :
260 : /// @brief Called once after connection of all clients for executing SET_ORDER (and possibly prior GET_VERSION) commands,
261 : /// that should be executed before simulation starts (in processCommandsUntilNextSimStep()).
262 : void checkClientOrdering();
263 :
264 : /// @brief checks for and processes reordering requests (relevant for multiple clients)
265 : void processReorderingRequests();
266 :
267 : /// @brief get the minimal next target time among all clients
268 : SUMOTime nextTargetTime() const;
269 :
270 : /// @brief send out subscription results (actually just the content of myOutputStorage) to clients which will act in this step (i.e. with client target time <= myTargetTime)
271 : void sendOutputToAll() const;
272 :
273 : /// @brief sends an empty response to a simstep command to the current client. (This applies to a situation where the TraCI step frequency is higher than the SUMO step frequency)
274 : void sendSingleSimStepResponse();
275 :
276 : /// @brief removes myCurrentSocket from mySockets and returns an iterator pointing to the next member according to the ordering
277 : std::map<int, SocketInfo*>::iterator removeCurrentSocket();
278 :
279 :
280 : private:
281 : /// @brief Singleton instance of the server
282 : static TraCIServer* myInstance;
283 :
284 : /// @brief Whether the connection was set to be to close
285 : static bool myDoCloseConnection;
286 :
287 : /// @brief The socket connections to the clients
288 : /// the first component (index) determines the client's order (lowest index's commands are processed first), @see CMD_SETORDER
289 : std::map<int, SocketInfo*> mySockets;
290 :
291 : /// @brief This stores the setOrder(int) requests of the clients.
292 : std::map<int, SocketInfo*> mySocketReorderRequests;
293 :
294 : /// @brief The currently active client socket
295 : std::map<int, SocketInfo*>::iterator myCurrentSocket;
296 :
297 : /// @brief The time step to reach until processing the next commands
298 : SUMOTime myTargetTime;
299 :
300 : /// @brief The storage to read from
301 : tcpip::Storage myInputStorage;
302 :
303 : /// @brief The storage to write to
304 : tcpip::Storage myOutputStorage;
305 :
306 : /// @brief A temporary storage to let the wrapper write to
307 : tcpip::Storage myWrapperStorage;
308 :
309 : /// @brief The last timestep's subscription results
310 : tcpip::Storage mySubscriptionCache;
311 :
312 : /// @brief Map of commandIds -> their executors; applicable if the executor applies to the method footprint
313 : std::map<int, CmdExecutor> myExecutors;
314 :
315 : /// @brief Set of variables which have parameters
316 : std::set<std::pair<int, int>> myParameterized;
317 :
318 : std::vector<std::string> myLoadArgs;
319 :
320 : /// @brief The list of known, still valid subscriptions
321 : std::vector<libsumo::Subscription> mySubscriptions;
322 :
323 : /// @brief The last modified context subscription (the one to add a filter to, see @addSubscriptionFilter(), currently only for vehicle to vehicle context)
324 : libsumo::Subscription* myLastContextSubscription;
325 :
326 : /// @brief Changes in the states of simulated vehicles
327 : /// @note
328 : /// Server cache myVehicleStateChanges is used for managing last steps subscription updates
329 : /// and for client information in case that myAmEmbedded==true, which implies a single client.
330 : /// For the potential multiclient case (myAmEmbedded==false), each socket in mySockets is associated
331 : /// with a proper vehicleStateChanges container mySockets[...].second->vehicleStateChanges
332 : /// Performance could be improved if for a single client, myVehicleStateChanges is used only.
333 : std::map<MSNet::VehicleState, std::vector<std::string> > myVehicleStateChanges;
334 :
335 : /// @brief Changes in the states of simulated transportables
336 : /// @note
337 : /// Server cache myTransportableStateChanges is used for managing last steps subscription updates
338 : /// and for client information in case that myAmEmbedded==true, which implies a single client.
339 : /// For the potential multiclient case (myAmEmbedded==false), each socket in mySockets is associated
340 : /// with a proper TransportableStateChanges container mySockets[...].second->TransportableStateChanges
341 : /// Performance could be improved if for a single client, myTransportableStateChanges is used only.
342 : std::map<MSNet::TransportableState, std::vector<std::string> > myTransportableStateChanges;
343 :
344 : private:
345 : bool addObjectVariableSubscription(const int commandId, const bool hasContext);
346 : void initialiseSubscription(libsumo::Subscription& s);
347 : void removeSubscription(int commandId, const std::string& identity, int domain);
348 : bool processSingleSubscription(const libsumo::Subscription& s, tcpip::Storage& writeInto,
349 : std::string& errors);
350 :
351 :
352 : bool addSubscriptionFilter();
353 : void removeFilters();
354 : void addSubscriptionFilterLanes(std::vector<int> lanes);
355 : void addSubscriptionFilterNoOpposite();
356 : void addSubscriptionFilterDownstreamDistance(double dist);
357 : void addSubscriptionFilterUpstreamDistance(double dist);
358 : void addSubscriptionFilterLeadFollow();
359 : // TODO: for libsumo, implement convenience definitions present in python client:
360 : // void addSubscriptionFilterCF();
361 : // void addSubscriptionFilterLC(int direction);
362 : void addSubscriptionFilterTurn(double dist);
363 : void addSubscriptionFilterVClass(SVCPermissions vClasses);
364 : void addSubscriptionFilterVType(std::set<std::string> vTypes);
365 : /** @brief Filter only vehicles within field of vision
366 : *
367 : * @param[in] openingAngle The opening angle of the circle sector
368 : */
369 : void addSubscriptionFilterFieldOfVision(double openingAngle);
370 : /** @brief Filter only vehicles within the given lateral distance
371 : *
372 : * @param[in] dist The lateral distance
373 : */
374 : void addSubscriptionFilterLateralDistance(double dist);
375 :
376 : /// @brief check whether a found objID refers to the central object of a context subscription
377 : bool centralObject(const libsumo::Subscription& s, const std::string& objID);
378 :
379 :
380 : private:
381 : /// @brief Invalidated assignment operator
382 : TraCIServer& operator=(const TraCIServer& s) = delete;
383 :
384 : };
|