Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
TraCIServer.cpp
Go to the documentation of this file.
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/****************************************************************************/
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>
51#include <utils/xml/XMLSubSys.h>
52#include <microsim/MSNet.h>
53#include <microsim/MSVehicle.h>
54#include <microsim/MSEdge.h>
57#include <microsim/MSJunction.h>
59#include <microsim/MSLane.h>
60#include <microsim/MSGlobals.h>
62#include <libsumo/Helper.h>
64#include <libsumo/libsumo.h>
67#include "TraCIServer.h"
70#include "TraCIServerAPI_Lane.h"
77#include "TraCIServerAPI_POI.h"
79#include "TraCIServerAPI_Edge.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// ===========================================================================
107
108
109// ===========================================================================
110// method definitions
111// ===========================================================================
112void
113TraCIServer::initWrapper(const int domainID, const int variable, const std::string& objID) {
118}
119
120
121bool
122TraCIServer::wrapConnectionVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIConnection>& value) {
123 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 8);
124 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
125 for (const libsumo::TraCIConnection& c : value) {
127 StoHelp::writeTypedString(myWrapperStorage, c.approachedInternal);
134 }
135 return true;
136}
137
138
139bool
140TraCIServer::wrapDouble(const std::string& /* objID */, const int /* variable */, const double value) {
143 return true;
144}
145
146
147bool
148TraCIServer::wrapInt(const std::string& /* objID */, const int /* variable */, const int value) {
151 return true;
152}
153
154
155bool
156TraCIServer::wrapString(const std::string& /* objID */, const int /* variable */, const std::string& value) {
159 return true;
160}
161
162
163bool
164TraCIServer::wrapStringList(const std::string& /* objID */, const int /* variable */, const std::vector<std::string>& value) {
167 return true;
168}
169
170
171bool
172TraCIServer::wrapDoubleList(const std::string& /* objID */, const int /* variable */, const std::vector<double>& value) {
175 return true;
176}
177
178
179bool
180TraCIServer::wrapPosition(const std::string& /* objID */, const int variable, const libsumo::TraCIPosition& value) {
181 const bool includeZ = variable == libsumo::VAR_POSITION3D;
185 if (includeZ) {
187 }
188 return true;
189}
190
191
192bool
193TraCIServer::wrapPositionVector(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIPositionVector& shape) {
195 if (shape.value.size() < 256) {
196 myWrapperStorage.writeUnsignedByte((int)shape.value.size());
197 } else {
199 myWrapperStorage.writeInt((int)shape.value.size());
200 }
201 for (const libsumo::TraCIPosition& pos : shape.value) {
204 }
205 return true;
206}
207
208
209bool
210TraCIServer::wrapColor(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIColor& value) {
216 return true;
217}
218
219
220bool
221TraCIServer::wrapStringDoublePair(const std::string& /* objID */, const int /* variable */, const std::pair<std::string, double>& value) {
225 return true;
226}
227
228
229bool
230TraCIServer::wrapStringDoublePairList(const std::string& /* objID */, const int /* variable */, const std::vector<std::pair<std::string, double> >& value) {
231 StoHelp::writeCompound(myWrapperStorage, (int)value.size());
232 for (const auto& p : value) {
235 }
236 return true;
237}
238
239
240bool
241TraCIServer::wrapStringPair(const std::string& /* objID */, const int /* variable */, const std::pair<std::string, std::string>& value) {
245 return true;
246}
247
248
249bool
250TraCIServer::wrapIntPair(const std::string& /* objID */, const int /* variable */, const std::pair<int, int>& value) {
254 return true;
255}
256
257
258bool
259TraCIServer::wrapStage(const std::string& /* objID */, const int /* variable */, const libsumo::TraCIStage& value) {
261 return true;
262}
263
264
265bool
266TraCIServer::wrapReservationVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIReservation>& value) {
267 StoHelp::writeCompound(myWrapperStorage, (int)value.size());
268 for (const libsumo::TraCIReservation& r : value) {
280 }
281 return true;
282}
283
284
285bool
286TraCIServer::wrapLogicVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCILogic>& value) {
287 StoHelp::writeCompound(myWrapperStorage, (int)value.size());
288 for (const libsumo::TraCILogic& logic : value) {
292 StoHelp::writeTypedInt(myWrapperStorage, logic.currentPhaseIndex);
293 StoHelp::writeCompound(myWrapperStorage, (int)logic.phases.size());
294 for (const std::shared_ptr<libsumo::TraCIPhase>& phase : logic.phases) {
300 StoHelp::writeCompound(myWrapperStorage, (int)phase->next.size());
301 for (int n : phase->next) {
303 }
305 }
306 StoHelp::writeCompound(myWrapperStorage, (int)logic.subParameter.size());
307 for (const auto& item : logic.subParameter) {
308 StoHelp::writeTypedStringList(myWrapperStorage, std::vector<std::string> {item.first, item.second});
309 }
310 }
311 return true;
312}
313
314
315bool
316TraCIServer::wrapLinkVectorVector(const std::string& /* objID */, const int /* variable */, const std::vector<std::vector<libsumo::TraCILink> >& value) {
317 int cnt = 1;
318 for (const std::vector<libsumo::TraCILink>& sublinks : value) {
319 cnt += (int)sublinks.size() + 1;
320 }
322 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
323 for (const std::vector<libsumo::TraCILink>& sublinks : value) {
325 for (const libsumo::TraCILink& link : sublinks) {
326 StoHelp::writeTypedStringList(myWrapperStorage, std::vector<std::string>({ link.fromLane, link.toLane, link.viaLane }));
327 }
328 }
329 return true;
330}
331
332
333bool
334TraCIServer::wrapSignalConstraintVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCISignalConstraint>& value) {
335 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 5);
336 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
337 for (const auto& c : value) {
339 }
340 return true;
341}
342
343
344bool
345TraCIServer::wrapJunctionFoeVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIJunctionFoe>& value) {
346 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 9);
347 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
348 for (const auto& c : value) {
358 }
359 return true;
360}
361
362
363bool
364TraCIServer::wrapNextStopDataVector(const std::string& /* objID */, const int variable, const std::vector<libsumo::TraCINextStopData>& value) {
365 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 4);
366 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
367 const bool full = variable == libsumo::VAR_NEXT_STOPS2;
368 for (const auto& s : value) {
369 const int legacyStopFlags = (s.stopFlags << 1) + (s.arrival >= 0 ? 1 : 0);
373 StoHelp::writeTypedInt(myWrapperStorage, full ? s.stopFlags : legacyStopFlags);
376 if (full) {
387 }
388 }
389 return true;
390}
391
392
393bool
394TraCIServer::wrapVehicleDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIVehicleData>& value) {
395 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 5);
396 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
397 for (const libsumo::TraCIVehicleData& vd : value) {
403 }
404 return true;
405}
406
407
408bool
409TraCIServer::wrapBestLanesDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCIBestLanesData>& value) {
410 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 6);
411 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
412 for (const libsumo::TraCIBestLanesData& bld : value) {
416 StoHelp::writeTypedByte(myWrapperStorage, bld.bestLaneOffset);
417 StoHelp::writeTypedUnsignedByte(myWrapperStorage, bld.allowsContinuation ? 1 : 0);
418 StoHelp::writeTypedStringList(myWrapperStorage, bld.continuationLanes);
419 }
420 return true;
421}
422
423
424bool
425TraCIServer::wrapNextTLSDataVector(const std::string& /* objID */, const int /* variable */, const std::vector<libsumo::TraCINextTLSData>& value) {
426 StoHelp::writeCompound(myWrapperStorage, 1 + (int)value.size() * 4);
427 StoHelp::writeTypedInt(myWrapperStorage, (int)value.size());
428 for (const libsumo::TraCINextTLSData& tlsd : value) {
433 }
434 return true;
435}
436
437
442
443
444
445TraCIServer::TraCIServer(const SUMOTime begin, const int port, const int numClients)
446 : 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 myVehicleStateChanges[MSNet::VehicleState::BUILT] = std::vector<std::string>();
451 myVehicleStateChanges[MSNet::VehicleState::DEPARTED] = std::vector<std::string>();
454 myVehicleStateChanges[MSNet::VehicleState::ARRIVED] = std::vector<std::string>();
455 myVehicleStateChanges[MSNet::VehicleState::NEWROUTE] = std::vector<std::string>();
457 myVehicleStateChanges[MSNet::VehicleState::MANEUVERING] = std::vector<std::string>();
459 myVehicleStateChanges[MSNet::VehicleState::STARTING_STOP] = std::vector<std::string>();
460 myVehicleStateChanges[MSNet::VehicleState::ENDING_STOP] = std::vector<std::string>();
461 myVehicleStateChanges[MSNet::VehicleState::COLLISION] = std::vector<std::string>();
462 myVehicleStateChanges[MSNet::VehicleState::EMERGENCYSTOP] = std::vector<std::string>();
463
468
472
491 //myExecutors[libsumo::CMD_SET_MEANDATA_VARIABLE] = &TraCIServerAPI_MeanData::processSet;
493
525 myParameterized.insert(std::make_pair(libsumo::CMD_SUBSCRIBE_VEHICLE_VARIABLE, libsumo::VAR_NEXT_STOPS)); // this is just a dummy to trigger an error
528 myParameterized.insert(std::make_pair(0, libsumo::VAR_PARAMETER));
529 myParameterized.insert(std::make_pair(0, libsumo::VAR_PARAMETER_WITH_KEY));
530
531 myDoCloseConnection = false;
532
533 // display warning if internal lanes are not used
534 // TODO this may be redundant to the warning in NLBuilder::build
536 WRITE_WARNING(TL("Starting TraCI without using internal lanes!"));
537 MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
538 MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
539 }
540
541 try {
542 WRITE_MESSAGEF(TL("***Starting server on port % ***"), toString(port));
543 tcpip::Socket serverSocket(port);
544 if (numClients > 1) {
545 WRITE_MESSAGEF(TL(" waiting for % clients..."), toString(numClients));
546 }
547 while ((int)mySockets.size() < numClients) {
548 int index = (int)mySockets.size() + libsumo::MAX_ORDER + 1;
549 mySockets[index] = new SocketInfo(serverSocket.accept(true), begin);
550 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::BUILT] = std::vector<std::string>();
551 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::DEPARTED] = std::vector<std::string>();
552 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_TELEPORT] = std::vector<std::string>();
553 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_TELEPORT] = std::vector<std::string>();
554 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ARRIVED] = std::vector<std::string>();
555 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::NEWROUTE] = std::vector<std::string>();
556 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_PARKING] = std::vector<std::string>();
557 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::MANEUVERING] = std::vector<std::string>();
558 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_PARKING] = std::vector<std::string>();
559 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::STARTING_STOP] = std::vector<std::string>();
560 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::ENDING_STOP] = std::vector<std::string>();
561 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::COLLISION] = std::vector<std::string>();
562 mySockets[index]->vehicleStateChanges[MSNet::VehicleState::EMERGENCYSTOP] = std::vector<std::string>();
563
564 mySockets[index]->transportableStateChanges[MSNet::TransportableState::PERSON_DEPARTED] = std::vector<std::string>();
565 mySockets[index]->transportableStateChanges[MSNet::TransportableState::PERSON_ARRIVED] = std::vector<std::string>();
566 mySockets[index]->transportableStateChanges[MSNet::TransportableState::CONTAINER_DEPARTED] = std::vector<std::string>();
567 mySockets[index]->transportableStateChanges[MSNet::TransportableState::CONTAINER_ARRIVED] = std::vector<std::string>();
568 if (numClients > 1) {
569 WRITE_MESSAGE(TL(" client connected"));
570 }
571 }
572 // When got here, all clients have connected
573 if (numClients > 1) {
575 }
576 // set myCurrentSocket != mySockets.end() to indicate that this is the first step in processCommands()
577 myCurrentSocket = mySockets.begin();
578 } catch (tcpip::SocketException& e) {
579 throw ProcessError(e.what());
580 }
581}
582
583
585 for (const auto& socket : mySockets) {
586 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}
590
591
592// ---------- Initialisation and Shutdown
593void
594TraCIServer::openSocket(const std::map<int, CmdExecutor>& execs) {
595 if (myInstance == nullptr && !myDoCloseConnection && (OptionsCont::getOptions().getInt("remote-port") != 0)) {
596 myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")),
597 OptionsCont::getOptions().getInt("remote-port"),
598 OptionsCont::getOptions().getInt("num-clients"));
599 for (std::map<int, CmdExecutor>::const_iterator i = execs.begin(); i != execs.end(); ++i) {
600 myInstance->myExecutors[i->first] = i->second;
601 }
602 }
603 if (myInstance != nullptr) {
604 // maybe net was deleted and built again
608 }
609}
610
611
612void
614 if (myInstance == nullptr) {
615 return;
616 }
617 delete myInstance;
618 myInstance = nullptr;
619 myDoCloseConnection = true;
620}
621
622
623bool
627
628
629// ---------- Initialisation and Shutdown
630
631
632void
633TraCIServer::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
634 if (!myDoCloseConnection) {
635 myVehicleStateChanges[to].push_back(vehicle->getID());
636 for (std::map<int, SocketInfo*>::iterator i = mySockets.begin(); i != mySockets.end(); ++i) {
637 i->second->vehicleStateChanges[to].push_back(vehicle->getID());
638 }
639 }
640}
641
642
643void
644TraCIServer::transportableStateChanged(const MSTransportable* const transportable, MSNet::TransportableState to, const std::string& /*info*/) {
645 if (!myDoCloseConnection) {
646 myTransportableStateChanges[to].push_back(transportable->getID());
647 for (std::map<int, SocketInfo*>::iterator i = mySockets.begin(); i != mySockets.end(); ++i) {
648 i->second->transportableStateChanges[to].push_back(transportable->getID());
649 }
650 }
651}
652
653
654void
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 myCurrentSocket = mySockets.begin();
662 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) {
669 myCurrentSocket->second->socket->receiveExact(myInputStorage);
670 int commandStart, commandLength;
671 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 bool initCommand = commandId == libsumo::CMD_SETORDER || commandId == libsumo::CMD_GETVERSION;
678 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 tcpip::Storage tmp;
688 // we don't know whether the command was set with extended
689 // length syntax or not so we hardcode the length here (#5037)
693
694 // Handle initialization command completely
696 myCurrentSocket->second->socket->sendExact(myOutputStorage);
698 } else {
699#ifdef DEBUG_MULTI_CLIENTS
700 std::cout << " Client " << myCurrentSocket->second->socket << " did not set order initially." << std::endl;
701#endif
702 throw ProcessError(TL("Execution order (libsumo::CMD_SETORDER) was not set for all TraCI clients in pre-execution phase."));
703 }
704 if (commandId == libsumo::CMD_SETORDER) {
705 // This is what we have waited for.
706 break;
707 }
708 }
710 }
711}
712
713
714void
716 // Process reordering requests
717 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 while (i != mySocketReorderRequests.end()) {
733 j = mySockets.begin();
734 while (j != mySockets.end()) {
735 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 mySockets[i->first] = i->second;
744 ++i;
745 }
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}
756
757
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 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 targetTime = MIN2(targetTime, i->second->targetTime);
773 }
774#ifdef DEBUG_MULTI_CLIENTS
775 std::cout << std::endl;
776#endif
777 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)
782void
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 while (i != mySockets.end()) {
789 if (i->second->targetTime <= MSNet::getInstance()->getCurrentTimeStep()) {
790 // this client will become active before the next SUMO step. Provide subscription results.
791 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}
802
803
804int
805TraCIServer::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
814 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
818 // Send out subscription results to clients which will act in this SUMO step (i.e. with client target time <= current sumo timestep end)
821 }
822
823 // determine minimal next target time among clients
825
826 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 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 myCurrentSocket = mySockets.begin();
844 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 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
858 continue;
859 }
860 finalCmd = 0;
861 while (finalCmd == 0) {
862 if (!myInputStorage.valid_pos()) {
863 // have read request completely, send response if adequate
864 if (myOutputStorage.size() > 0) {
865 // send response to previous query
866 myCurrentSocket->second->socket->sendExact(myOutputStorage);
868 }
869#ifdef DEBUG_MULTI_CLIENTS
870 std::cout << " resetting input storage and reading next command..." << std::endl;
871#endif
872 // Read next request
874 myCurrentSocket->second->socket->receiveExact(myInputStorage);
875 }
876
878 const int cmd = dispatchCommand();
880 finalCmd = cmd;
881 }
882 }
883 }
884 }
885 if (!myLoadArgs.empty()) {
886#ifdef DEBUG_MULTI_CLIENTS
887 std::cout << " Breaking loop to load new simulation." << std::endl;
888#endif
889 break;
890 } 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 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 myTargetTime = nextT;
904 }
905 // All clients are done with the current time step
906 // Reset myVehicleStateChanges and myTransportableStateChanges
907 for (auto& item : myVehicleStateChanges) {
908 item.second.clear();
909 }
910 for (auto& item : myTransportableStateChanges) {
911 item.second.clear();
912 }
913 return finalCmd;
914 } catch (std::invalid_argument& e) {
915 throw ProcessError(e.what());
916 } catch (libsumo::TraCIException& e) {
917 throw ProcessError(e.what());
918 } catch (tcpip::SocketException& e) {
919 throw ProcessError(e.what());
920 }
921}
922
923
924bool
925TraCIServer::processGet(const int commandID, tcpip::Storage& inputStorage, tcpip::Storage& outputStorage) {
926 const int variable = inputStorage.readUnsignedByte();
927 const std::string id = inputStorage.readString();
928 initWrapper(commandID + 0x10, variable, id);
929 try {
930 switch (commandID) {
932 if (!libsumo::InductionLoop::handleVariable(id, variable, this, &inputStorage)) {
933 throw libsumo::TraCIException("Get Induction Loop Variable: unsupported variable " + toHex(variable, 2) + " specified");
934 }
935 break;
937 if (!libsumo::MultiEntryExit::handleVariable(id, variable, this, &inputStorage)) {
938 throw libsumo::TraCIException("Get Multi Entry Exit Detector Variable: unsupported variable " + toHex(variable, 2) + " specified");
939 }
940 break;
942 if (!libsumo::TrafficLight::handleVariable(id, variable, this, &inputStorage)) {
943 switch (variable) {
945 StoHelp::readCompound(inputStorage, 3, "A compound object of size 3 is needed for swapping constraints.");
946 const std::string tripId = StoHelp::readTypedString(inputStorage, "The tripId must be given as a string.");
947 const std::string foeSignal = StoHelp::readTypedString(inputStorage, "The foeSignal id must be given as a string.");
948 const std::string foeId = StoHelp::readTypedString(inputStorage, "The foe tripId must be given as a string.");
949 wrapSignalConstraintVector(id, variable, libsumo::TrafficLight::swapConstraints(id, tripId, foeSignal, foeId));
950 break;
951 }
952 default:
953 throw libsumo::TraCIException("Get TLS Variable: unsupported variable " + toHex(variable, 2) + " specified");
954 }
955 }
956 break;
958 if (!libsumo::Lane::handleVariable(id, variable, this, &inputStorage)) {
959 throw libsumo::TraCIException("Get Lane Variable: unsupported variable " + toHex(variable, 2) + " specified");
960 }
961 break;
963 if (!libsumo::Vehicle::handleVariable(id, variable, this, &inputStorage)) {
964 throw libsumo::TraCIException("Get Vehicle Variable: unsupported variable " + toHex(variable, 2) + " specified");
965 }
966 break;
968 if (!libsumo::VehicleType::handleVariable(id, variable, this, &inputStorage)) {
969 throw libsumo::TraCIException("Get Vehicle Type Variable: unsupported variable " + toHex(variable, 2) + " specified");
970 }
971 break;
973 if (!libsumo::Route::handleVariable(id, variable, this, &inputStorage)) {
974 throw libsumo::TraCIException("Get Route Variable: unsupported variable " + toHex(variable, 2) + " specified");
975 }
976 break;
978 if (!libsumo::POI::handleVariable(id, variable, this, &inputStorage)) {
979 throw libsumo::TraCIException("Get PoI Variable: unsupported variable " + toHex(variable, 2) + " specified");
980 }
981 break;
983 if (!libsumo::Polygon::handleVariable(id, variable, this, &inputStorage)) {
984 throw libsumo::TraCIException("Get Polygon Variable: unsupported variable " + toHex(variable, 2) + " specified");
985 }
986 break;
988 if (!libsumo::Junction::handleVariable(id, variable, this, &inputStorage)) {
989 throw libsumo::TraCIException("Get Junction Variable: unsupported variable " + toHex(variable, 2) + " specified");
990 }
991 break;
993 if (!libsumo::Edge::handleVariable(id, variable, this, &inputStorage)) {
994 throw libsumo::TraCIException("Get Edge Variable: unsupported variable " + toHex(variable, 2) + " specified");
995 }
996 break;
998 if (!TraCIServerAPI_Simulation::processGet(*this, inputStorage, id, variable)) {
999 throw libsumo::TraCIException("Get Simulation Variable: unsupported variable " + toHex(variable, 2) + " specified");
1000 }
1001 break;
1003 if (!libsumo::LaneArea::handleVariable(id, variable, this, &inputStorage)) {
1004 throw libsumo::TraCIException("Get Lane Area Detector Variable: unsupported variable " + toHex(variable, 2) + " specified");
1005 }
1006 break;
1008 if (!libsumo::Person::handleVariable(id, variable, this, &inputStorage)) {
1009 throw libsumo::TraCIException("Get Person Variable: unsupported variable " + toHex(variable, 2) + " specified");
1010 }
1011 break;
1013 if (!libsumo::BusStop::handleVariable(id, variable, this, &inputStorage)) {
1014 throw libsumo::TraCIException("Get BusStop Variable: unsupported variable " + toHex(variable, 2) + " specified");
1015 }
1016 break;
1018 if (!libsumo::ParkingArea::handleVariable(id, variable, this, &inputStorage)) {
1019 throw libsumo::TraCIException("Get ParkingArea Variable: unsupported variable " + toHex(variable, 2) + " specified");
1020 }
1021 break;
1023 if (!libsumo::ChargingStation::handleVariable(id, variable, this, &inputStorage)) {
1024 throw libsumo::TraCIException("Get ChargingStation Variable: unsupported variable " + toHex(variable, 2) + " specified");
1025 }
1026 break;
1028 if (!libsumo::RouteProbe::handleVariable(id, variable, this, &inputStorage)) {
1029 throw libsumo::TraCIException("Get RouteProbe Variable: unsupported variable " + toHex(variable, 2) + " specified");
1030 }
1031 break;
1033 if (!libsumo::Calibrator::handleVariable(id, variable, this, &inputStorage)) {
1034 throw libsumo::TraCIException("Get Calibrator Variable: unsupported variable " + toHex(variable, 2) + " specified");
1035 }
1036 break;
1038 if (!libsumo::Rerouter::handleVariable(id, variable, this, &inputStorage)) {
1039 throw libsumo::TraCIException("Get Rerouter Variable: unsupported variable " + toHex(variable, 2) + " specified");
1040 }
1041 break;
1043 if (!libsumo::VariableSpeedSign::handleVariable(id, variable, this, &inputStorage)) {
1044 throw libsumo::TraCIException("Get VariableSpeedSign Variable: unsupported variable " + toHex(variable, 2) + " specified");
1045 }
1046 break;
1048 if (!libsumo::MeanData::handleVariable(id, variable, this, &inputStorage)) {
1049 throw libsumo::TraCIException("Get MeanData Variable: unsupported variable " + toHex(variable, 2) + " specified");
1050 }
1051 break;
1053 if (!libsumo::OverheadWire::handleVariable(id, variable, this, &inputStorage)) {
1054 throw libsumo::TraCIException("Get OverheadWire Variable: unsupported variable " + toHex(variable, 2) + " specified");
1055 }
1056 break;
1057 default:
1058 return false;
1059 }
1060 } catch (libsumo::TraCIException& e) {
1061 return writeErrorStatusCmd(commandID, e.what(), outputStorage);
1062 }
1063 writeStatusCmd(commandID, libsumo::RTYPE_OK, "", outputStorage);
1065 return true;
1066}
1067
1068
1069void
1071 mySubscriptions.clear();
1072 myLastContextSubscription = nullptr;
1073 myTargetTime = string2time(OptionsCont::getOptions().getString("begin"));
1075 myCurrentSocket->second->targetTime = myTargetTime;
1076 myCurrentSocket->second->executeMove = false;
1077 }
1081 for (auto& i : myVehicleStateChanges) {
1082 i.second.clear();
1083 }
1084 for (auto& i : myTransportableStateChanges) {
1085 i.second.clear();
1086 }
1087 myCurrentSocket = mySockets.begin();
1088}
1089
1090
1091std::map<int, TraCIServer::SocketInfo*>::iterator
1093#ifdef DEBUG_MULTI_CLIENTS
1094 std::cout << " Removing socket " << myCurrentSocket->second->socket
1095 << " (order " << myCurrentSocket->first << ")" << std::endl;
1096#endif
1097 delete myCurrentSocket->second;
1099 return myCurrentSocket;
1100}
1101
1102
1103int
1104TraCIServer::readCommandID(int& commandStart, int& commandLength) {
1105 commandStart = myInputStorage.position();
1106 commandLength = myInputStorage.readUnsignedByte();
1107 if (commandLength == 0) {
1108 commandLength = myInputStorage.readInt();
1109 }
1110#ifdef DEBUG_RAW_INPUT
1111 std::cout << " commandStart=" << commandStart << " commandLength=" << commandLength << " pos=" << myInputStorage.position() << " raw=";
1112 for (auto it = myInputStorage.begin(); it != myInputStorage.end(); ++it) {
1113 std::cout << (int)*it << " ";
1114 }
1115 std::cout << "\n";
1116#endif
1118}
1119
1120
1121int
1123 int commandStart, commandLength;
1124 int commandId = readCommandID(commandStart, commandLength);
1125#ifdef DEBUG_MULTI_CLIENTS
1126 std::cout << " dispatchCommand() called for client " << myCurrentSocket->second->socket
1127 << ", commandId = " << commandId << std::endl;
1128#endif
1129 bool success = false;
1130 // dispatch commands
1131 if (myExecutors.find(commandId) != myExecutors.end()) {
1132 success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
1133 } else if ((commandId >= libsumo::CMD_GET_INDUCTIONLOOP_VARIABLE && commandId <= libsumo::CMD_GET_BUSSTOP_VARIABLE)
1135 if (commandId == libsumo::CMD_GET_GUI_VARIABLE) {
1136 writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo");
1137 } else {
1138 success = processGet(commandId, myInputStorage, myOutputStorage);
1139 }
1140 } else {
1141 switch (commandId) {
1143 success = commandGetVersion();
1144 break;
1145 case libsumo::CMD_LOAD: {
1146 try {
1147 const std::vector<std::string> args = StoHelp::readTypedStringList(myInputStorage, "A load command needs a list of string arguments.");
1148#ifdef DEBUG_MULTI_CLIENTS
1149 std::cout << " commandId == libsumo::CMD_LOAD"
1150 << ", args = " << toString(args) << std::endl;
1151#endif
1152 myLoadArgs = args;
1153 success = true;
1155 // XXX: This only cares for the client that issued the load command.
1156 // Multiclient-load functionality is still to be implemented. Refs #3146.
1157 myCurrentSocket->second->socket->sendExact(myOutputStorage);
1158 myCurrentSocket = mySockets.end();
1160 } catch (libsumo::TraCIException& e) {
1162 }
1163 break;
1164 }
1166 myCurrentSocket->second->executeMove = true;
1168 success = true;
1170 break;
1171 case libsumo::CMD_SIMSTEP: {
1172 const double nextT = myInputStorage.readDouble();
1173 if (nextT == 0.) {
1174 myCurrentSocket->second->targetTime += DELTA_T;
1175 } else {
1176 myCurrentSocket->second->targetTime = TIME2STEPS(nextT);
1177 }
1178 myCurrentSocket->second->executeMove = false;
1179#ifdef DEBUG_MULTI_CLIENTS
1180 std::cout << " commandId == libsumo::CMD_SIMSTEP"
1181 << ", next target time for client is " << myCurrentSocket->second->targetTime << std::endl;
1182#endif
1183 if (myCurrentSocket->second->targetTime <= MSNet::getInstance()->getCurrentTimeStep()) {
1184 // This is not the last TraCI simstep in the current SUMO simstep -> send single simstep response.
1185 // @note: In the other case the simstep results are sent to all after the SUMO step was performed, see entry point for processCommands()
1187 }
1188 // Clear vehicleStateChanges and transportableStateChanges for this client
1189 // -> For subsequent TraCI stepping
1190 // that is performed within this SUMO step, no updates on vehicle states
1191 // belonging to the last SUMO simulation step will be received by this client.
1192 for (auto& item : myCurrentSocket->second->vehicleStateChanges) {
1193 item.second.clear();
1194 }
1195 for (auto& item : myCurrentSocket->second->transportableStateChanges) {
1196 item.second.clear();
1197 }
1199 return commandId;
1200 }
1201 case libsumo::CMD_CLOSE:
1203 myCurrentSocket->second->socket->sendExact(myOutputStorage);
1205 if (mySockets.size() == 1) {
1206 // Last client has closed connection
1207 myDoCloseConnection = true;
1208 }
1209 // remove current socket and increment to next socket in ordering
1211 success = true;
1212 break;
1213 case libsumo::CMD_SETORDER: {
1214 const int order = myInputStorage.readInt();
1215#ifdef DEBUG_MULTI_CLIENTS
1216 std::cout << " commandId == libsumo::CMD_SETORDER"
1217 << ", order index is " << order << std::endl;
1218#endif
1219 if (order > libsumo::MAX_ORDER) {
1220 return writeErrorStatusCmd(libsumo::CMD_SETORDER, "A set order command needs an int argument below " + toString(libsumo::MAX_ORDER) + ".", myOutputStorage);
1221 }
1222 if (mySockets.count(order) > 0 || mySocketReorderRequests.count(order) > 0) {
1223 return writeErrorStatusCmd(libsumo::CMD_SETORDER, "Order '" + toString(order) + "' is already taken.", myOutputStorage);
1224 }
1225 // memorize reorder request (will only take effect in the next step)
1227 success = true;
1229 break;
1230 }
1255 success = addObjectVariableSubscription(commandId, false);
1256 break;
1281 success = addObjectVariableSubscription(commandId, true);
1282 break;
1284 success = addSubscriptionFilter();
1285 break;
1287 writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo");
1288 break;
1289 default:
1290 writeStatusCmd(commandId, libsumo::RTYPE_NOTIMPLEMENTED, "Command not implemented in sumo");
1291 }
1292 }
1293 if (!success) {
1294 while (myInputStorage.valid_pos() && (int)myInputStorage.position() < commandStart + commandLength) {
1296 }
1297 }
1298 if ((int)myInputStorage.position() != commandStart + commandLength) {
1299 std::ostringstream msg;
1300 msg << "Wrong position in requestMessage after dispatching command " << commandId << ".";
1301 msg << " Expected command length was " << commandLength;
1302 msg << " but " << myInputStorage.position() - commandStart << " Bytes were read.";
1303 writeStatusCmd(commandId, libsumo::RTYPE_ERR, msg.str());
1304 myDoCloseConnection = true;
1305 }
1306 return commandId;
1307}
1308
1309
1310// ---------- Server-internal command handling
1311bool
1313 // Prepare response
1314 tcpip::Storage answerTmp;
1316 answerTmp.writeString("SUMO " VERSION_STRING);
1317 // When we get here, the response is stored in answerTmp -> put into myOutputStorage
1319 // command length
1320 myOutputStorage.writeUnsignedByte(1 + 1 + static_cast<int>(answerTmp.size()));
1321 // command type
1323 // and the parameter dependant part
1324 myOutputStorage.writeStorage(answerTmp);
1325 return true;
1326}
1327
1328
1329void
1332#ifdef DEBUG_MULTI_CLIENTS
1333 std::cout << " postProcessSimulationStep() at time=" << t << std::endl;
1334#endif
1336 int noActive = 0;
1337 for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
1338 const libsumo::Subscription& s = *i;
1340 && (MSNet::getInstance()->getVehicleControl().getVehicle(s.id) == nullptr
1342
1344 if ((s.endTime < t) || isArrivedVehicle || isArrivedPerson) {
1345 i = eraseSubscription(i);
1346 continue;
1347 }
1348 ++i;
1349 if (s.beginTime > t) {
1350 continue;
1351 }
1352 ++noActive;
1353 }
1355#ifdef DEBUG_SUBSCRIPTIONS
1356 std::cout << " Initial size of mySubscriptionCache is " << mySubscriptionCache.size()
1357 << "\n Nr. of active subscriptions = " << noActive << std::endl;
1358#endif
1359 mySubscriptionCache.writeInt(noActive);
1360#ifdef DEBUG_SUBSCRIPTIONS
1361 std::cout << " Size after writing an int is " << mySubscriptionCache.size() << std::endl;
1362#endif
1363 for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
1364 const libsumo::Subscription& s = *i;
1365 if (s.beginTime > t) {
1366 ++i;
1367 continue;
1368 }
1369 tcpip::Storage into;
1370 std::string errors;
1371 bool ok = processSingleSubscription(s, into, errors);
1372#ifdef DEBUG_SUBSCRIPTIONS
1373 std::cout << " Size of into-store for subscription " << s.id
1374 << ": " << into.size() << std::endl;
1375#endif
1377 if (ok) {
1378 ++i;
1379 } else {
1380 i = eraseSubscription(i);
1381 }
1382 }
1384#ifdef DEBUG_SUBSCRIPTIONS
1385 std::cout << " Size after writing subscriptions is " << mySubscriptionCache.size() << std::endl;
1386#endif
1387}
1388
1389
1390void
1392#ifdef DEBUG_MULTI_CLIENTS
1393 std::cout << " Sending cached simstep response to current client " << myCurrentSocket->second->socket
1394 << " (-> intermediate TraCI step)."
1395 << "\n Size of mySubscriptionCache is " << mySubscriptionCache.size()
1396 << std::endl;
1397#endif
1399
1400// NOTE: the commented code would send an empty response
1401// myOutputStorage.writeInt(0);
1402// myCurrentSocket->second->socket->sendExact(myOutputStorage);
1403// myOutputStorage.reset();
1405 // send results to active client
1406 myCurrentSocket->second->socket->sendExact(myOutputStorage);
1408}
1409
1410
1411void
1412TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
1413 writeStatusCmd(commandId, status, description, myOutputStorage);
1414}
1415
1416
1417void
1418TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
1419 if (status == libsumo::RTYPE_ERR) {
1420 WRITE_ERROR("Answered with error to command " + toHex(commandId, 2) + ": " + description);
1421 } else if (status == libsumo::RTYPE_NOTIMPLEMENTED) {
1422 WRITE_ERROR("Requested command not implemented (" + toHex(commandId, 2) + "): " + description);
1423 }
1424 outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
1425 outputStorage.writeUnsignedByte(commandId); // command type
1426 outputStorage.writeUnsignedByte(status); // status
1427 outputStorage.writeString(description); // description
1428}
1429
1430
1431bool
1432TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
1433 writeStatusCmd(commandId, libsumo::RTYPE_ERR, description, outputStorage);
1434 return false;
1435}
1436
1437
1438void
1440 tcpip::Storage writeInto;
1441 std::string errors;
1442 libsumo::Subscription* modifiedSubscription = nullptr;
1443 try {
1444 if (processSingleSubscription(s, writeInto, errors)) {
1446 writeStatusCmd(s.commandId, libsumo::RTYPE_ERR, "Subscription has ended.");
1447 } else {
1448 if (libsumo::Helper::needNewSubscription(s, mySubscriptions, modifiedSubscription)) {
1449 // Add new subscription to subscription cache (note: seems a bit inefficient)
1451 // copy new subscription into cache
1452 int noActive = 1 + (mySubscriptionCache.size() > 0 ? mySubscriptionCache.readInt() : 0);
1453 tcpip::Storage tmp;
1454 tmp.writeInt(noActive);
1455 while (mySubscriptionCache.valid_pos()) {
1457 }
1458 tmp.writeStorage(writeInto);
1461 }
1462 }
1464 }
1465 if (modifiedSubscription != nullptr && (
1466 modifiedSubscription->isVehicleToVehicleContextSubscription()
1467 || modifiedSubscription->isVehicleToPersonContextSubscription())) {
1468 // Set last modified vehicle context subscription active for filter modifications
1469 myLastContextSubscription = modifiedSubscription;
1470 } else {
1471 // adding other subscriptions deactivates the activation for filter addition
1472 myLastContextSubscription = nullptr;
1473 }
1474 } else {
1475 writeStatusCmd(s.commandId, libsumo::RTYPE_ERR, "Could not add subscription. " + errors);
1476 }
1477 } catch (libsumo::TraCIException& e) {
1479 }
1480 myOutputStorage.writeStorage(writeInto);
1481}
1482
1483
1484void
1485TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
1486 bool found = false;
1487 std::vector<libsumo::Subscription>::iterator j;
1488 for (j = mySubscriptions.begin(); j != mySubscriptions.end();) {
1489 if (j->id == id && j->commandId == commandId && j->contextDomain == domain) {
1490 j = eraseSubscription(j);
1491 found = true;
1492 continue;
1493 }
1494 ++j;
1495 }
1496 // try unsubscribe
1497 if (found) {
1498 writeStatusCmd(commandId, libsumo::RTYPE_OK, "");
1499 } else {
1500 writeStatusCmd(commandId, libsumo::RTYPE_ERR, "The subscription to remove was not found.");
1501 }
1502}
1503
1504
1505std::vector<libsumo::Subscription>::iterator
1506TraCIServer::eraseSubscription(std::vector<libsumo::Subscription>::iterator position) {
1508}
1509
1510
1511bool
1513 std::string& errors) {
1514 bool ok = true;
1515 tcpip::Storage outputStorage;
1516 const int getCommandId = s.contextDomain > 0 ? s.contextDomain : s.commandId - 0x30;
1517 std::set<std::string> objIDs;
1518 if (s.contextDomain > 0) {
1520 PositionVector shape;
1523 }
1525 } else {
1526 objIDs.insert(s.id);
1527 }
1528 const int numVars = s.contextDomain > 0 && s.variables.size() == 1 && s.variables[0] == libsumo::TRACI_ID_LIST ? 0 : (int)s.variables.size();
1529 int skipped = 0;
1530 for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
1531 if (s.contextDomain > 0) {
1532 //if (centralObject(s, *j)) {
1533 // skipped++;
1534 // continue;
1535 //}
1536 outputStorage.writeString(*j);
1537 }
1538 if (numVars > 0) {
1539 std::vector<std::shared_ptr<tcpip::Storage> >::const_iterator k = s.parameters.begin();
1540 for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i, ++k) {
1541 tcpip::Storage message;
1542 message.writeUnsignedByte(*i);
1543 message.writeString(*j);
1544 // TODO check why writeStorage fails here (probably some kind of invalid iterator)
1545 for (const auto& v :** k) {
1546 message.writeChar(v);
1547 }
1548 tcpip::Storage tmpOutput;
1549 try {
1550 if (myExecutors.find(getCommandId) != myExecutors.end()) {
1551 ok &= myExecutors[getCommandId](*this, message, tmpOutput);
1552 } else if (!processGet(getCommandId, message, tmpOutput)) {
1553 if (getCommandId == libsumo::CMD_GET_GUI_VARIABLE) {
1554 writeStatusCmd(s.commandId, libsumo::RTYPE_NOTIMPLEMENTED, "GUI is not running, command not implemented in command line sumo", tmpOutput);
1555 }
1556 ok = false;
1557 }
1558 } catch (const std::invalid_argument&) {
1559 writeStatusCmd(s.commandId, libsumo::RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
1560 ok = false;
1561 }
1562 // copy response part
1563 if (ok) {
1564 int length = tmpOutput.readUnsignedByte();
1565 while (--length > 0) {
1566 tmpOutput.readUnsignedByte();
1567 }
1568 int lengthLength = 1;
1569 length = tmpOutput.readUnsignedByte();
1570 if (length == 0) {
1571 lengthLength = 5;
1572 length = tmpOutput.readInt();
1573 }
1574 //read responseType
1575 tmpOutput.readUnsignedByte();
1576 int variable = tmpOutput.readUnsignedByte();
1577 std::string id = tmpOutput.readString();
1578 outputStorage.writeUnsignedByte(variable);
1579 outputStorage.writeUnsignedByte(libsumo::RTYPE_OK);
1580 length -= (lengthLength + 1 + 4 + (int)id.length());
1581 while (--length > 0) {
1582 outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
1583 }
1584 } else {
1585 //read length
1586 tmpOutput.readUnsignedByte();
1587 //read cmd
1588 tmpOutput.readUnsignedByte();
1589 //read status
1590 tmpOutput.readUnsignedByte();
1591 std::string msg = tmpOutput.readString();
1592 outputStorage.writeUnsignedByte(*i);
1595 outputStorage.writeString(msg);
1596 errors = errors + msg;
1597 }
1598 }
1599 }
1600 }
1601 int length = (1 + 4) + 1 + (4 + (int)s.id.length()) + 1 + (int)outputStorage.size();
1602 if (s.contextDomain > 0) {
1603 length += 1 + 4; // context domain and number of objects
1604 }
1605 // we always write extended command length here for backward compatibility
1606 writeInto.writeUnsignedByte(0); // command length -> extended
1607 writeInto.writeInt(length);
1608 writeInto.writeUnsignedByte(s.commandId + 0x10);
1609 writeInto.writeString(s.id);
1610 if (s.contextDomain > 0) {
1611 writeInto.writeUnsignedByte(s.contextDomain);
1612 }
1613 writeInto.writeUnsignedByte(numVars);
1614 if (s.contextDomain > 0) {
1615 writeInto.writeInt((int)objIDs.size() - skipped);
1616 }
1617 if (s.contextDomain == 0 || objIDs.size() != 0) {
1618 writeInto.writeStorage(outputStorage);
1619 }
1620 return ok;
1621}
1622
1623
1624bool
1625TraCIServer::addObjectVariableSubscription(const int commandId, const bool hasContext) {
1626 const double beginTime = myInputStorage.readDouble();
1627 const double endTime = myInputStorage.readDouble();
1628 const SUMOTime begin = beginTime == libsumo::INVALID_DOUBLE_VALUE ? 0 : TIME2STEPS(beginTime);
1629 const SUMOTime end = endTime == libsumo::INVALID_DOUBLE_VALUE || endTime > STEPS2TIME(SUMOTime_MAX) ? SUMOTime_MAX : TIME2STEPS(endTime);
1630 const std::string id = myInputStorage.readString();
1631 const int domain = hasContext ? myInputStorage.readUnsignedByte() : 0;
1632 double range = hasContext ? myInputStorage.readDouble() : 0.;
1633 if (commandId == libsumo::CMD_SUBSCRIBE_SIM_CONTEXT) {
1634 range = std::numeric_limits<double>::max();
1635 }
1636 const int num = myInputStorage.readUnsignedByte();
1637 std::vector<int> variables;
1638 std::vector<std::shared_ptr<tcpip::Storage> > parameters;
1639 for (int i = 0; i < num; ++i) {
1640 const int varID = myInputStorage.readUnsignedByte();
1641 variables.push_back(varID);
1642 parameters.push_back(std::make_shared<tcpip::Storage>());
1643 if ((myParameterized.count(std::make_pair(0, varID)) > 0) || (myParameterized.count(std::make_pair(commandId, varID)) > 0)) {
1644 if (!myInputStorage.valid_pos()) {
1645 writeStatusCmd(commandId, libsumo::RTYPE_ERR, "Missing parameter for subscription " + toHex(commandId, 2));
1646 return false;
1647 }
1648 int count = 1;
1649 while (count-- > 0) {
1650 const int parType = myInputStorage.readUnsignedByte();
1651 parameters.back()->writeUnsignedByte(parType);
1652 if (parType == libsumo::TYPE_DOUBLE) {
1653 parameters.back()->writeDouble(myInputStorage.readDouble());
1654 } else if (parType == libsumo::TYPE_INTEGER) {
1655 parameters.back()->writeInt(myInputStorage.readInt());
1656 } else if (parType == libsumo::TYPE_STRING) {
1657 parameters.back()->writeString(myInputStorage.readString());
1658 } else if (parType == libsumo::TYPE_BYTE) {
1659 parameters.back()->writeByte(myInputStorage.readByte());
1660 } else if (parType == libsumo::TYPE_UBYTE) {
1661 parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1662 } else if (parType == libsumo::POSITION_2D) {
1663 parameters.back()->writeDouble(myInputStorage.readDouble());
1664 parameters.back()->writeDouble(myInputStorage.readDouble());
1665 if (varID == libsumo::DISTANCE_REQUEST) {
1666 parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1667 break;
1668 }
1669 } else if (parType == libsumo::POSITION_3D) {
1670 parameters.back()->writeDouble(myInputStorage.readDouble());
1671 parameters.back()->writeDouble(myInputStorage.readDouble());
1672 parameters.back()->writeDouble(myInputStorage.readDouble());
1673 if (varID == libsumo::DISTANCE_REQUEST) {
1674 parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1675 break;
1676 }
1677 } else if (parType == libsumo::POSITION_ROADMAP) {
1678 parameters.back()->writeString(myInputStorage.readString());
1679 parameters.back()->writeDouble(myInputStorage.readDouble());
1680 parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1681 if (varID == libsumo::DISTANCE_REQUEST) {
1682 parameters.back()->writeUnsignedByte(myInputStorage.readUnsignedByte());
1683 break;
1684 }
1685 } else if (parType == libsumo::TYPE_COMPOUND) {
1686 count = myInputStorage.readInt();
1687 parameters.back()->writeInt(count);
1688 } else {
1689 writeStatusCmd(commandId, libsumo::RTYPE_ERR, "Invalid parameter for subscription " + toHex(commandId, 2));
1690 return false;
1691 }
1692 }
1693 }
1694 }
1695 // check subscribe/unsubscribe
1696 if (variables.empty()) {
1697 removeSubscription(commandId, id, domain);
1698 return true;
1699 }
1700 // process subscription
1701 libsumo::Subscription s(commandId, id, variables, parameters, begin, end, domain, range);
1703 return true;
1704}
1705
1706
1707
1708bool
1710 bool success = true;
1711 // Read filter type
1712 int filterType = myInputStorage.readUnsignedByte();
1713
1714 if (myLastContextSubscription == nullptr) {
1716 "No previous vehicle context subscription exists to apply filter type " + toHex(filterType, 2));
1717 return false;
1718 }
1719
1720 // dispatch according to filter type
1721 switch (filterType) {
1723 // Remove all filters
1724 removeFilters();
1725 break;
1727 // Read relative lanes to consider for context filter
1728 int nrLanes = (int)myInputStorage.readByte();
1729 std::vector<int> lanes;
1730 for (int i = 0; i < nrLanes; ++i) {
1731 lanes.push_back((int) myInputStorage.readByte());
1732 }
1734 }
1735 break;
1737 // Add no-opposite filter
1739 break;
1741 myInputStorage.readByte(); // read type double
1742 double dist = myInputStorage.readDouble();
1744 }
1745 break;
1747 myInputStorage.readByte(); // read type double
1748 double dist = myInputStorage.readDouble();
1750 }
1751 break;
1753 // Read relative lanes to consider for context filter
1755 }
1756 break;
1758 myInputStorage.readByte(); // read type double
1759 double dist = myInputStorage.readDouble();
1761 }
1762 break;
1764 myInputStorage.readByte(); // read type stringlist
1767 }
1768 break;
1770 myInputStorage.readByte(); // read type stringlist
1771 std::vector<std::string> vTypesVector = myInputStorage.readStringList();
1772 std::set<std::string> vTypesSet;
1773 vTypesSet.insert(vTypesVector.begin(), vTypesVector.end());
1774 addSubscriptionFilterVType(vTypesSet);
1775 }
1776 break;
1778 myInputStorage.readByte(); // read type double
1779 double angle = myInputStorage.readDouble();
1781 }
1782 break;
1784 myInputStorage.readByte(); // read type double
1785 double dist = myInputStorage.readDouble();
1787 }
1788 break;
1789 default:
1791 "'" + toString(filterType) + "' is no valid filter type code.");
1792 success = false;
1793 }
1794
1795 if (success) {
1796 // acknowledge filter addition
1798 }
1799
1800 return success;
1801}
1802
1803
1804void
1806#ifdef DEBUG_SUBSCRIPTION_FILTERS
1807 std::cout << "Removing filters" << std::endl;
1808#endif
1810}
1811
1812void
1814#ifdef DEBUG_SUBSCRIPTION_FILTERS
1815 std::cout << "Adding lane filter (lanes=" << toString(lanes) << ")" << std::endl;
1816#endif
1819}
1820
1821void
1823#ifdef DEBUG_SUBSCRIPTION_FILTERS
1824 std::cout << "Adding no opposite filter" << std::endl;
1825#endif
1827}
1828
1829void
1831#ifdef DEBUG_SUBSCRIPTION_FILTERS
1832 std::cout << "Adding downstream dist filter (dist=" << toString(dist) << ")" << std::endl;
1833#endif
1836}
1837
1838void
1840#ifdef DEBUG_SUBSCRIPTION_FILTERS
1841 std::cout << "Adding upstream dist filter (dist=" << toString(dist) << ")" << std::endl;
1842#endif
1845}
1846
1847void
1849#ifdef DEBUG_SUBSCRIPTION_FILTERS
1850 std::cout << "Adding Lead/Follow-maneuver filter" << std::endl;
1851#endif
1853}
1854
1855void
1857#ifdef DEBUG_SUBSCRIPTION_FILTERS
1858 std::cout << "Adding turn-maneuver filter" << std::endl;
1859#endif
1862}
1863
1864void
1866#ifdef DEBUG_SUBSCRIPTION_FILTERS
1867 std::cout << "Adding vClass filter (vClasses=" << toString(vClasses) << ")" << std::endl;
1868#endif
1871}
1872
1873void
1874TraCIServer::addSubscriptionFilterVType(std::set<std::string> vTypes) {
1875#ifdef DEBUG_SUBSCRIPTION_FILTERS
1876 std::cout << "Adding vType filter (vTypes=" << toString(vTypes) << ")" << std::endl;
1877#endif
1880}
1881
1882void
1884#ifdef DEBUG_SUBSCRIPTION_FILTERS
1885 std::cout << "Adding FieldOfVision filter (openingAngle=" << toString(openingAngle) << ")" << std::endl;
1886#endif
1889}
1890
1891void
1893#ifdef DEBUG_SUBSCRIPTION_FILTERS
1894 std::cout << "Adding lateral dist filter (dist=" << toString(dist) << ")" << std::endl;
1895#endif
1898}
1899
1900void
1902 if (tempMsg.size() < 254) {
1903 outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
1904 } else {
1905 outputStorage.writeUnsignedByte(0); // command length -> extended
1906 outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
1907 }
1908 outputStorage.writeStorage(tempMsg);
1909}
1910
1911
1912void
1914 myTargetTime = targetTime;
1915 for (auto& s : mySockets) {
1916 s.second->targetTime = targetTime;
1917 s.second->executeMove = false;
1918 for (auto& stateChange : s.second->vehicleStateChanges) {
1919 stateChange.second.clear();
1920 }
1921 for (auto& stateChange : s.second->transportableStateChanges) {
1922 stateChange.second.clear();
1923 }
1924 }
1925 mySubscriptions.clear();
1926 myLastContextSubscription = nullptr;
1928}
1929
1930
1931bool
1932TraCIServer::centralObject(const libsumo::Subscription& s, const std::string& objID) {
1933 return (s.id == objID && s.commandId + 32 == s.contextDomain);
1934}
1935
1936
1937/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_MESSAGE(msg)
Definition MsgHandler.h:300
#define WRITE_ERROR(msg)
Definition MsgHandler.h:307
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
SUMOTime DELTA_T
Definition SUMOTime.cpp:39
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
#define STEPS2TIME(x)
Definition SUMOTime.h:58
constexpr SUMOTime TIME2STEPS(double x)
Definition SUMOTime.h:60
#define SUMOTime_MAX
Definition SUMOTime.h:34
#define SIMTIME
Definition SUMOTime.h:70
SVCPermissions parseVehicleClasses(const std::string &allowedS)
Parses the given definition of allowed vehicle classes into the given containers Deprecated classes g...
long long int SVCPermissions
bitset where each bit declares whether a certain SVC may use this edge/lane
T MIN2(T a, T b)
Definition StdDefs.h:80
std::string toHex(const T i, std::streamsize numDigits=0)
Definition ToString.h:89
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
static bool gUseMesoSim
Definition MSGlobals.h:106
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
VehicleState
Definition of a vehicle state.
Definition MSNet.h:637
@ ENDING_PARKING
The vehicle ends to park.
@ STARTING_STOP
The vehicles starts to stop.
@ BUILT
The vehicle was built, but has not yet departed.
@ STARTING_PARKING
The vehicles starts to park.
@ NEWROUTE
The vehicle got a new route.
@ STARTING_TELEPORT
The vehicle started to teleport.
@ ENDING_STOP
The vehicle ends to stop.
@ ENDING_TELEPORT
The vehicle ended being teleported.
@ ARRIVED
The vehicle arrived at his destination (is deleted)
@ DEPARTED
The vehicle has departed (was inserted into the network)
@ COLLISION
The vehicle is involved in a collision.
@ EMERGENCYSTOP
The vehicle had to brake harder than permitted.
@ MANEUVERING
Vehicle maneuvering either entering or exiting a parking space.
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:201
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:335
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1385
void addTransportableStateListener(TransportableStateListener *listener)
Adds a transportable states listener.
Definition MSNet.cpp:1413
TransportableState
Definition of a transportable state.
Definition MSNet.h:714
@ CONTAINER_DEPARTED
The transportable container has departed (was inserted into the network)
@ PERSON_DEPARTED
The transportable person has departed (was inserted into the network)
@ PERSON_ARRIVED
The transportable person arrived at his destination (is deleted)
@ CONTAINER_ARRIVED
The transportable container arrived at his destination (is deleted)
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:403
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1317
MSTransportable * get(const std::string &id) const
Returns the named transportable, if existing.
SUMOVehicle * getVehicle(const std::string &id) const
Returns the vehicle with the given id.
virtual void inform(std::string msg, bool addType=true)
adds a new error to the list
static MsgHandler * getWarningInstance()
Returns the instance to add warnings to.
const std::string & getID() const
Returns the id.
Definition Named.h:73
static OptionsCont & getOptions()
Retrieves the options.
A list of positions.
Representation of a vehicle.
Definition SUMOVehicle.h:63
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change BusStop State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change Calibrator State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change ChargingStation State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xca: Change Edge State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc0: Set Induction Loop Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc9: Set Junction Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xcd: Set AreaDetector Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc3: Change Lane State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc1: Set MeMeDetector Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change OverheadWire State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc7: Change PoI State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change ParkingArea State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xce: Change Person State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc8: Change Polygon State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change Rerouter State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change Route State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change RouteProbe State)
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, const std::string &objID, const int variable)
Processes a get value command (Command 0xab: Get Simulation Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xcb: Set Simulation Variable)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc2: Change Traffic Lights State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change VariableSpeedSign State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc4: Change Vehicle State)
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc5: Change Vehicle Type State)
TraCI server used to control sumo by a remote TraCI client.
Definition TraCIServer.h:59
void addSubscriptionFilterDownstreamDistance(double dist)
static bool myDoCloseConnection
Whether the connection was set to be to close.
bool wrapStringDoublePair(const std::string &objID, const int variable, const std::pair< std::string, double > &value)
tcpip::Storage myWrapperStorage
A temporary storage to let the wrapper write to.
std::map< int, SocketInfo * > mySockets
The socket connections to the clients the first component (index) determines the client's order (lowe...
void addSubscriptionFilterLateralDistance(double dist)
Filter only vehicles within the given lateral distance.
void writeStatusCmd(int commandId, int status, const std::string &description, tcpip::Storage &outputStorage)
Writes a status command to the given storage.
static bool wasClosed()
check whether close was requested
void addSubscriptionFilterTurn(double dist)
bool wrapIntPair(const std::string &objID, const int variable, const std::pair< int, int > &value)
bool wrapReservationVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCIReservation > &value)
bool centralObject(const libsumo::Subscription &s, const std::string &objID)
check whether a found objID refers to the central object of a context subscription
bool wrapPositionVector(const std::string &objID, const int variable, const libsumo::TraCIPositionVector &value)
void addSubscriptionFilterVType(std::set< std::string > vTypes)
bool wrapInt(const std::string &objID, const int variable, const int value)
std::map< int, SocketInfo * >::iterator removeCurrentSocket()
removes myCurrentSocket from mySockets and returns an iterator pointing to the next member according ...
tcpip::Storage myOutputStorage
The storage to write to.
bool addObjectVariableSubscription(const int commandId, const bool hasContext)
void addSubscriptionFilterUpstreamDistance(double dist)
void stateLoaded(SUMOTime targetTime)
updates myTargetTime and resets vehicle state changes after loading a simulation state
void addSubscriptionFilterLeadFollow()
void addSubscriptionFilterNoOpposite()
tcpip::Storage & getWrapperStorage()
SUMOTime nextTargetTime() const
get the minimal next target time among all clients
std::map< MSNet::TransportableState, std::vector< std::string > > myTransportableStateChanges
Changes in the states of simulated transportables.
void removeSubscription(int commandId, const std::string &identity, int domain)
bool wrapStage(const std::string &objID, const int variable, const libsumo::TraCIStage &value)
bool wrapDouble(const std::string &objID, const int variable, const double value)
tcpip::Storage mySubscriptionCache
The last timestep's subscription results.
bool wrapColor(const std::string &objID, const int variable, const libsumo::TraCIColor &value)
bool wrapString(const std::string &objID, const int variable, const std::string &value)
int dispatchCommand()
Handles command, writes response to myOutputStorage.
bool wrapConnectionVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCIConnection > &value)
void initWrapper(const int domainID, const int variable, const std::string &objID)
bool writeErrorStatusCmd(int commandId, const std::string &description, tcpip::Storage &outputStorage)
Writes a status command to the given storage with status = RTYPE_ERR.
bool wrapDoubleList(const std::string &objID, const int variable, const std::vector< double > &value)
void checkClientOrdering()
Called once after connection of all clients for executing SET_ORDER (and possibly prior GET_VERSION) ...
void processReorderingRequests()
checks for and processes reordering requests (relevant for multiple clients)
void sendOutputToAll() const
send out subscription results (actually just the content of myOutputStorage) to clients which will ac...
bool wrapSignalConstraintVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCISignalConstraint > &value)
void cleanup()
clean up subscriptions
static void close()
request termination of connection
void postProcessSimulationStep()
Handles subscriptions to send after a simstep2 command.
bool commandGetVersion()
Returns the TraCI-version.
bool wrapPosition(const std::string &objID, const int variable, const libsumo::TraCIPosition &value)
static void openSocket(const std::map< int, CmdExecutor > &execs)
Initialises the server.
std::vector< std::string > myLoadArgs
void removeFilters()
void addSubscriptionFilterLanes(std::vector< int > lanes)
bool processGet(const int commandID, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command.
int processCommands(const SUMOTime step, const bool afterMove=false)
process all commands until the next SUMO simulation step. It is guaranteed that t->getTargetTime() >=...
SUMOTime myTargetTime
The time step to reach until processing the next commands.
virtual ~TraCIServer()
Destructor.
bool wrapNextStopDataVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCINextStopData > &value)
bool wrapStringPair(const std::string &objID, const int variable, const std::pair< std::string, std::string > &value)
std::map< MSNet::VehicleState, std::vector< std::string > > myVehicleStateChanges
Changes in the states of simulated vehicles.
int readCommandID(int &commandStart, int &commandLength)
Reads the next command ID from the input storage.
void sendSingleSimStepResponse()
sends an empty response to a simstep command to the current client. (This applies to a situation wher...
std::map< int, CmdExecutor > myExecutors
Map of commandIds -> their executors; applicable if the executor applies to the method footprint.
std::vector< libsumo::Subscription > mySubscriptions
The list of known, still valid subscriptions.
void vehicleStateChanged(const SUMOVehicle *const vehicle, MSNet::VehicleState to, const std::string &info="")
Called if a vehicle changes its state.
void writeResponseWithLength(tcpip::Storage &outputStorage, tcpip::Storage &tempMsg)
bool wrapStringDoublePairList(const std::string &objID, const int variable, const std::vector< std::pair< std::string, double > > &value)
TraCIServer(const SUMOTime begin, const int port, const int numClients)
Constructor.
tcpip::Storage myInputStorage
The storage to read from.
bool wrapLogicVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCILogic > &value)
bool wrapNextTLSDataVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCINextTLSData > &value)
libsumo::Subscription * myLastContextSubscription
The last modified context subscription (the one to add a filter to, see @addSubscriptionFilter(),...
std::map< int, SocketInfo * >::iterator myCurrentSocket
The currently active client socket.
bool wrapVehicleDataVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCIVehicleData > &value)
void addSubscriptionFilterVClass(SVCPermissions vClasses)
std::vector< libsumo::Subscription >::iterator eraseSubscription(std::vector< libsumo::Subscription >::iterator position)
static TraCIServer * myInstance
Singleton instance of the server.
std::map< int, SocketInfo * > mySocketReorderRequests
This stores the setOrder(int) requests of the clients.
bool addSubscriptionFilter()
std::set< std::pair< int, int > > myParameterized
Set of variables which have parameters.
void transportableStateChanged(const MSTransportable *const transportable, MSNet::TransportableState to, const std::string &info="")
Called if a transportable changes its state.
bool processSingleSubscription(const libsumo::Subscription &s, tcpip::Storage &writeInto, std::string &errors)
void initialiseSubscription(libsumo::Subscription &s)
void addSubscriptionFilterFieldOfVision(double openingAngle)
Filter only vehicles within field of vision.
bool wrapStringList(const std::string &objID, const int variable, const std::vector< std::string > &value)
bool wrapBestLanesDataVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCIBestLanesData > &value)
bool wrapLinkVectorVector(const std::string &objID, const int variable, const std::vector< std::vector< libsumo::TraCILink > > &value)
bool wrapJunctionFoeVector(const std::string &objID, const int variable, const std::vector< libsumo::TraCIJunctionFoe > &value)
static void findObjectShape(int domain, const std::string &id, PositionVector &shape)
Definition Helper.cpp:781
static void applySubscriptionFilters(const Subscription &s, std::set< std::string > &objIDs)
Filter the given ID-Set (which was obtained from an R-Tree search) according to the filters set by th...
Definition Helper.cpp:931
static void collectObjectIDsInRange(int domain, const PositionVector &shape, double range, std::set< std::string > &into)
Definition Helper.cpp:851
static std::vector< Subscription >::iterator eraseSubscription(std::vector< Subscription > &subscriptions, std::vector< Subscription >::iterator position, Subscription *&lastContextSubscription)
Definition Helper.cpp:223
static bool needNewSubscription(libsumo::Subscription &s, std::vector< Subscription > &subscriptions, libsumo::Subscription *&modifiedSubscription)
Definition Helper.cpp:198
static void writeConstraint(tcpip::Storage &content, const libsumo::TraCISignalConstraint &c)
static void writeTypedDouble(tcpip::Storage &content, double value)
static int readCompound(tcpip::Storage &ret, int expectedSize=-1, const std::string &error="")
static std::vector< std::string > readTypedStringList(tcpip::Storage &ret, const std::string &error="")
static void writeStage(tcpip::Storage &content, const libsumo::TraCIStage &stage)
static void writeTypedUnsignedByte(tcpip::Storage &content, int value)
static void writeCompound(tcpip::Storage &content, int size)
static std::string readTypedString(tcpip::Storage &ret, const std::string &error="")
static void writeTypedInt(tcpip::Storage &content, int value)
static void writeTypedStringList(tcpip::Storage &content, const std::vector< std::string > &value)
static void writeTypedByte(tcpip::Storage &content, int value)
static void writeTypedString(tcpip::Storage &content, const std::string &value)
Representation of a subscription.
double filterUpstreamDist
Upstream distance specified by the upstream distance filter.
int commandId
commandIdArg The command id of the subscription
std::set< std::string > filterVTypes
vTypes specified by the vTypes filter
double filterFieldOfVisionOpeningAngle
Opening angle (in deg) specified by the field of vision filter.
std::vector< int > filterLanes
lanes specified by the lanes filter
std::string id
The id of the object that is subscribed.
SUMOTime endTime
The end time of the subscription.
int contextDomain
The domain ID of the context.
double filterFoeDistToJunction
Foe distance to junction specified by the turn filter.
bool isVehicleToVehicleContextSubscription() const
SUMOTime beginTime
The begin time of the subscription.
std::vector< int > variables
The subscribed variables.
SVCPermissions filterVClasses
vClasses specified by the vClasses filter,
bool isVehicleToPersonContextSubscription() const
double filterDownstreamDist
Downstream distance specified by the downstream distance filter.
double filterLateralDist
Lateral distance specified by the lateral distance filter.
int activeFilters
Active filters for the subscription (bitset,.
double range
The range of the context.
std::vector< std::shared_ptr< tcpip::Storage > > parameters
The parameters for the subscribed variables.
An error which allows to continue.
Definition TraCIDefs.h:145
Socket * accept(const bool create=false)
Wait for a incoming connection to port_.
Definition socket.cpp:234
StorageType::const_iterator begin() const
Definition storage.h:121
virtual unsigned char readChar()
Definition storage.cpp:102
virtual std::string readString()
Definition storage.cpp:180
virtual void writeString(const std::string &s)
Definition storage.cpp:197
virtual unsigned int position() const
Definition storage.cpp:76
virtual void writeInt(int)
Definition storage.cpp:321
StorageType::const_iterator end() const
Definition storage.h:122
virtual void writeDouble(double)
Definition storage.cpp:354
virtual int readUnsignedByte()
Definition storage.cpp:155
virtual void writeStringList(const std::vector< std::string > &s)
Definition storage.cpp:247
virtual void writeChar(unsigned char)
Definition storage.cpp:116
virtual void writeUnsignedByte(int)
Definition storage.cpp:165
StorageType::size_type size() const
Definition storage.h:119
virtual bool valid_pos()
Definition storage.cpp:69
virtual void writeDoubleList(const std::vector< double > &s)
Definition storage.cpp:262
virtual void writeByte(int)
Definition storage.cpp:140
virtual void writeStorage(tcpip::Storage &store)
Definition storage.cpp:388
virtual int readByte()
Definition storage.cpp:128
virtual std::vector< std::string > readStringList()
Definition storage.cpp:211
virtual double readDouble()
Definition storage.cpp:362
virtual int readInt()
Definition storage.cpp:311
TRACI_CONST double INVALID_DOUBLE_VALUE
TRACI_CONST int TYPE_COLOR
TRACI_CONST int CMD_SUBSCRIBE_SIM_VARIABLE
TRACI_CONST int FILTER_TYPE_DOWNSTREAM_DIST
TRACI_CONST int VAR_EDGES
TRACI_CONST int CMD_LOAD
TRACI_CONST int CMD_SET_JUNCTION_VARIABLE
TRACI_CONST int POSITION_3D
TRACI_CONST int CMD_GET_CHARGINGSTATION_VARIABLE
TRACI_CONST int POSITION_ROADMAP
TRACI_CONST int CMD_SUBSCRIBE_EDGE_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE
TRACI_CONST int RTYPE_NOTIMPLEMENTED
TRACI_CONST int CMD_SUBSCRIBE_LANE_CONTEXT
TRACI_CONST int FILTER_TYPE_NOOPPOSITE
TRACI_CONST int CMD_SET_OVERHEADWIRE_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_BUSSTOP_VARIABLE
TRACI_CONST int TRACI_ID_LIST
TRACI_CONST int CMD_GET_PARKINGAREA_VARIABLE
TRACI_CONST int CMD_GET_POI_VARIABLE
TRACI_CONST int CMD_GET_TL_VARIABLE
TRACI_CONST int CMD_SET_EDGE_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_PARKINGAREA_VARIABLE
TRACI_CONST int TL_BLOCKING_VEHICLES
TRACI_CONST int VAR_SECURE_GAP
TRACI_CONST int CMD_SUBSCRIBE_JUNCTION_VARIABLE
TRACI_CONST int TL_CONSTRAINT_SWAP
TRACI_CONST int CMD_SUBSCRIBE_VEHICLE_CONTEXT
TRACI_CONST int VAR_EDGE_TRAVELTIME
TRACI_CONST int CMD_GET_REROUTER_VARIABLE
TRACI_CONST int LANE_CHANGES
TRACI_CONST int CMD_GET_VEHICLE_VARIABLE
TRACI_CONST int VAR_TAXI_RESERVATIONS
TRACI_CONST int CMD_SET_CALIBRATOR_VARIABLE
TRACI_CONST int CMD_GET_EDGE_VARIABLE
TRACI_CONST int CMD_GET_CALIBRATOR_VARIABLE
TRACI_CONST int MAX_ORDER
TRACI_CONST int VAR_FOLLOW_SPEED
TRACI_CONST int TL_PRIORITY_VEHICLES
TRACI_CONST int CMD_EXECUTEMOVE
TRACI_CONST int CMD_SUBSCRIBE_TL_CONTEXT
TRACI_CONST int FILTER_TYPE_FIELD_OF_VISION
TRACI_CONST int VAR_ANGLE
TRACI_CONST int TYPE_COMPOUND
TRACI_CONST int CMD_SUBSCRIBE_ROUTEPROBE_VARIABLE
TRACI_CONST int CMD_SET_REROUTER_VARIABLE
TRACI_CONST int VAR_EDGE_EFFORT
TRACI_CONST int CMD_SUBSCRIBE_MEANDATA_CONTEXT
TRACI_CONST int CMD_GET_PERSON_VARIABLE
TRACI_CONST int VAR_MEANDATA_VALUES
TRACI_CONST int CMD_SUBSCRIBE_REROUTER_CONTEXT
TRACI_CONST int CMD_SET_VARIABLESPEEDSIGN_VARIABLE
TRACI_CONST int TYPE_UBYTE
TRACI_CONST int CMD_SUBSCRIBE_GUI_VARIABLE
TRACI_CONST int VAR_STAGE
TRACI_CONST int CMD_SET_POI_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_ROUTE_CONTEXT
TRACI_CONST int CMD_GET_ROUTEPROBE_VARIABLE
TRACI_CONST int CMD_GET_LANEAREA_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_OVERHEADWIRE_VARIABLE
TRACI_CONST int VAR_PERSON_NUMBER
TRACI_CONST int CMD_SET_POLYGON_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_BUSSTOP_CONTEXT
TRACI_CONST int VAR_STOP_PARAMETER
TRACI_CONST int POSITION_2D
TRACI_CONST int CMD_GET_BUSSTOP_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_ROUTEPROBE_CONTEXT
TRACI_CONST int VAR_LEADER
TRACI_CONST int CMD_CLOSE
TRACI_CONST int TYPE_POLYGON
TRACI_CONST int CMD_GET_ROUTE_VARIABLE
TRACI_CONST int CMD_SET_ROUTE_VARIABLE
TRACI_CONST int CMD_SETORDER
TRACI_CONST int FILTER_TYPE_VTYPE
TRACI_CONST int TYPE_STRINGLIST
TRACI_CONST int VAR_TAXI_FLEET
TRACI_CONST int CMD_SET_SIM_VARIABLE
TRACI_CONST int TYPE_INTEGER
TRACI_CONST int CMD_ADD_SUBSCRIPTION_FILTER
TRACI_CONST int CMD_GET_MEANDATA_VARIABLE
TRACI_CONST int CMD_GET_JUNCTION_VARIABLE
TRACI_CONST int CMD_SET_VEHICLE_VARIABLE
TRACI_CONST int CMD_SET_GUI_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_ROUTE_VARIABLE
TRACI_CONST int TRACI_VERSION
TRACI_CONST int CMD_GET_VARIABLESPEEDSIGN_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_OVERHEADWIRE_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_CALIBRATOR_CONTEXT
TRACI_CONST int VAR_PARAMETER
TRACI_CONST int CMD_SET_VEHICLETYPE_VARIABLE
TRACI_CONST int CMD_SET_PERSON_VARIABLE
TRACI_CONST int CMD_GET_SIM_VARIABLE
TRACI_CONST int TL_CONSTRAINT_BYFOE
TRACI_CONST int CMD_SET_MULTIENTRYEXIT_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_POLYGON_VARIABLE
TRACI_CONST int VAR_STOP_SPEED
TRACI_CONST int CMD_SUBSCRIBE_PERSON_CONTEXT
TRACI_CONST int CMD_GET_VEHICLETYPE_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_CHARGINGSTATION_CONTEXT
TRACI_CONST int TL_CONSTRAINT
TRACI_CONST int CMD_SUBSCRIBE_POLYGON_CONTEXT
TRACI_CONST int CMD_SET_CHARGINGSTATION_VARIABLE
TRACI_CONST int CMD_SET_LANE_VARIABLE
TRACI_CONST int FILTER_TYPE_LEAD_FOLLOW
TRACI_CONST int CMD_SUBSCRIBE_GUI_CONTEXT
TRACI_CONST int VAR_MEANDATA_LANE
TRACI_CONST int CMD_SET_PARKINGAREA_VARIABLE
TRACI_CONST int CMD_GET_LANE_VARIABLE
TRACI_CONST int CMD_SET_LANEAREA_VARIABLE
TRACI_CONST int VAR_POSITION3D
TRACI_CONST int CMD_GET_GUI_VARIABLE
TRACI_CONST int VAR_PARAMETER_WITH_KEY
TRACI_CONST int FILTER_TYPE_UPSTREAM_DIST
TRACI_CONST int CMD_SUBSCRIBE_PARKINGAREA_CONTEXT
TRACI_CONST int TYPE_DOUBLELIST
TRACI_CONST int CMD_GET_POLYGON_VARIABLE
TRACI_CONST int VAR_NEXT_STOPS2
TRACI_CONST int FILTER_TYPE_TURN
TRACI_CONST int CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_REROUTER_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_VEHICLE_VARIABLE
TRACI_CONST int CMD_GET_MULTIENTRYEXIT_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_POI_VARIABLE
TRACI_CONST int TYPE_DOUBLE
TRACI_CONST int DISTANCE_REQUEST
@ SUBS_FILTER_LEAD_FOLLOW
@ SUBS_FILTER_UPSTREAM_DIST
@ SUBS_FILTER_VTYPE
@ SUBS_FILTER_NO_RTREE
@ SUBS_FILTER_LANES
@ SUBS_FILTER_NOOPPOSITE
@ SUBS_FILTER_DOWNSTREAM_DIST
@ SUBS_FILTER_LATERAL_DIST
@ SUBS_FILTER_TURN
@ SUBS_FILTER_VCLASS
@ SUBS_FILTER_NONE
@ SUBS_FILTER_FIELD_OF_VISION
TRACI_CONST int CMD_SUBSCRIBE_LANEAREA_VARIABLE
TRACI_CONST int TYPE_BYTE
TRACI_CONST int CMD_SUBSCRIBE_POI_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_CALIBRATOR_VARIABLE
TRACI_CONST int CMD_SET_INDUCTIONLOOP_VARIABLE
TRACI_CONST int CMD_SET_TL_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_SIM_CONTEXT
TRACI_CONST int FILTER_TYPE_VCLASS
TRACI_CONST int CMD_CHANGELANE
TRACI_CONST int CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_CHARGINGSTATION_VARIABLE
TRACI_CONST int CMD_GETVERSION
TRACI_CONST int RTYPE_ERR
TRACI_CONST int CMD_SIMSTEP
TRACI_CONST int FILTER_TYPE_NONE
TRACI_CONST int VAR_NEIGHBORS
TRACI_CONST int CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_LANE_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_PERSON_VARIABLE
TRACI_CONST int RTYPE_OK
TRACI_CONST int CMD_GET_INDUCTIONLOOP_VARIABLE
TRACI_CONST int CMD_SUBSCRIBE_TL_VARIABLE
TRACI_CONST int CMD_GET_OVERHEADWIRE_VARIABLE
TRACI_CONST int VAR_FOLLOWER
TRACI_CONST int CMD_SUBSCRIBE_LANEAREA_CONTEXT
TRACI_CONST int CMD_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT
TRACI_CONST int FILTER_TYPE_LANES
TRACI_CONST int CMD_SUBSCRIBE_JUNCTION_CONTEXT
TRACI_CONST int CMD_SET_ROUTEPROBE_VARIABLE
TRACI_CONST int VAR_FOES
TRACI_CONST int CMD_SET_BUSSTOP_VARIABLE
TRACI_CONST int SPLIT_TAXI_RESERVATIONS
TRACI_CONST int CMD_SUBSCRIBE_MEANDATA_VARIABLE
TRACI_CONST int FILTER_TYPE_LATERAL_DIST
TRACI_CONST int CMD_SUBSCRIBE_EDGE_VARIABLE
TRACI_CONST int TYPE_STRING
TRACI_CONST int TL_RIVAL_VEHICLES
TRACI_CONST int VAR_NEXT_STOPS
TRACI_CONST int CMD_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE
A 2D or 3D-position, for 2D positions z == INVALID_DOUBLE_VALUE.
Definition TraCIDefs.h:184
A list of positions.
Definition TraCIDefs.h:245
std::vector< TraCIPosition > value
Definition TraCIDefs.h:255
mirrors MSInductLoop::VehicleData
Definition TraCIDefs.h:525