SUMO - Simulation of Urban MObility
TraCIServer.cpp
Go to the documentation of this file.
1 /****************************************************************************/
17 /****************************************************************************/
18 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
19 // Copyright (C) 2007-2016 DLR (http://www.dlr.de/) and contributors
20 /****************************************************************************/
21 //
22 // This file is part of SUMO.
23 // SUMO is free software: you can redistribute it and/or modify
24 // it under the terms of the GNU General Public License as published by
25 // the Free Software Foundation, either version 3 of the License, or
26 // (at your option) any later version.
27 //
28 /****************************************************************************/
29 
30 // ===========================================================================
31 // included modules
32 // ===========================================================================
33 #ifdef _MSC_VER
34 #include <windows_config.h>
35 #else
36 #include <config.h>
37 #endif
38 
39 #ifdef HAVE_VERSION_H
40 #include <version.h>
41 #endif
42 
43 #ifndef NO_TRACI
44 
45 #ifdef HAVE_PYTHON
46 #include <Python.h>
47 #endif
48 
49 #include <string>
50 #include <map>
51 #include <iostream>
52 #include <foreign/tcpip/socket.h>
53 #include <foreign/tcpip/storage.h>
54 #include <utils/common/SUMOTime.h>
62 #include <utils/shapes/Polygon.h>
63 #include <utils/xml/XMLSubSys.h>
64 #include <microsim/MSNet.h>
66 #include <microsim/MSVehicle.h>
67 #include <microsim/MSEdge.h>
69 #include <microsim/MSJunction.h>
70 #include <microsim/MSEdgeControl.h>
71 #include <microsim/MSLane.h>
72 #include <microsim/MSGlobals.h>
74 #include "TraCIConstants.h"
75 #include "TraCIServer.h"
78 #include "TraCIServerAPI_Lane.h"
81 #include "TraCIServerAPI_TLS.h"
82 #include "TraCIServerAPI_Vehicle.h"
84 #include "TraCIServerAPI_Route.h"
85 #include "TraCIServerAPI_POI.h"
86 #include "TraCIServerAPI_Polygon.h"
87 #include "TraCIServerAPI_Edge.h"
89 #include "TraCIServerAPI_Person.h"
90 
91 #ifdef CHECK_MEMORY_LEAKS
92 #include <foreign/nvwa/debug_new.h>
93 #endif // CHECK_MEMORY_LEAKS
94 
95 
96 // ===========================================================================
97 // static member definitions
98 // ===========================================================================
101 
102 
103 // ===========================================================================
104 // method definitions
105 // ===========================================================================
106 TraCIServer::TraCIServer(const SUMOTime begin, const int port)
107  : mySocket(0), myTargetTime(begin), myDoingSimStep(false), myAmEmbedded(port == 0), myLaneTree(0) {
108 
109  myVehicleStateChanges[MSNet::VEHICLE_STATE_BUILT] = std::vector<std::string>();
110  myVehicleStateChanges[MSNet::VEHICLE_STATE_DEPARTED] = std::vector<std::string>();
111  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_TELEPORT] = std::vector<std::string>();
112  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_TELEPORT] = std::vector<std::string>();
113  myVehicleStateChanges[MSNet::VEHICLE_STATE_ARRIVED] = std::vector<std::string>();
114  myVehicleStateChanges[MSNet::VEHICLE_STATE_NEWROUTE] = std::vector<std::string>();
115  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_PARKING] = std::vector<std::string>();
116  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_PARKING] = std::vector<std::string>();
117  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_STOP] = std::vector<std::string>();
118  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_STOP] = std::vector<std::string>();
120 
124 
146 
148 
149  myDoCloseConnection = false;
150 
151  // display warning if internal lanes are not used
153  WRITE_WARNING("Starting TraCI without using internal lanes!");
154  MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
155  MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
156  }
157 
158  if (!myAmEmbedded) {
159  try {
160  WRITE_MESSAGE("***Starting server on port " + toString(port) + " ***");
161  mySocket = new tcpip::Socket(port);
162  mySocket->accept();
163  // When got here, a client has connected
164  } catch (tcpip::SocketException& e) {
165  throw ProcessError(e.what());
166  }
167  }
168 }
169 
170 
173  if (mySocket != NULL) {
174  mySocket->close();
175  delete mySocket;
176  }
177  for (std::map<int, NamedRTree*>::const_iterator i = myObjects.begin(); i != myObjects.end(); ++i) {
178  delete(*i).second;
179  }
180  delete myLaneTree;
181 }
182 
183 
184 // ---------- Initialisation and Shutdown
185 void
186 TraCIServer::openSocket(const std::map<int, CmdExecutor>& execs) {
187  if (myInstance != 0) {
188  return;
189  }
190  if (!myDoCloseConnection && OptionsCont::getOptions().getInt("remote-port") != 0) {
191  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")),
192  OptionsCont::getOptions().getInt("remote-port"));
193  for (std::map<int, CmdExecutor>::const_iterator i = execs.begin(); i != execs.end(); ++i) {
194  myInstance->myExecutors[i->first] = i->second;
195  }
196  }
197 }
198 
199 
200 void
202  if (myInstance == 0) {
203  return;
204  }
205  if (myDoCloseConnection) {
208  }
209  delete myInstance;
210  myInstance = 0;
211  myDoCloseConnection = true;
212 }
213 
214 
215 bool
217  return myDoCloseConnection;
218 }
219 
220 
221 void
223  SUMOTime t) {
224  myVTDControlledVehicles[v->getID()] = v;
225  v->getInfluencer().setVTDControlled(l, pos, angle, edgeOffset, route, t);
226 }
227 
228 
229 void
231  for (std::map<std::string, MSVehicle*>::const_iterator i = myVTDControlledVehicles.begin(); i != myVTDControlledVehicles.end(); ++i) {
232  if (MSNet::getInstance()->getVehicleControl().getVehicle((*i).first) != 0) {
233  (*i).second->getInfluencer().postProcessVTD((*i).second);
234  } else {
235  WRITE_WARNING("Vehicle '" + (*i).first + "' was removed though being controlled by VTD");
236  }
237  }
238  myVTDControlledVehicles.clear();
239 }
240 
241 
242 // ---------- Initialisation and Shutdown
243 
244 
245 void
247  if (!myDoCloseConnection) {
248  myVehicleStateChanges[to].push_back(vehicle->getID());
249  }
250 }
251 
252 
253 void
255  if (myInstance == 0) {
256  return;
257  }
258  try {
259  if (myInstance->myAmEmbedded || step < myInstance->myTargetTime) {
260  return;
261  }
262  // Simulation should run until
263  // 1. end time reached or
264  // 2. got CMD_CLOSE or
265  // 3. Client closes socket connection
266  if (myInstance->myDoingSimStep) {
268  myInstance->myDoingSimStep = false;
269  }
270  while (!myDoCloseConnection) {
272  if (myInstance->myOutputStorage.size() > 0) {
273  // send out all answers as one storage
275  }
278  // Read a message
280  }
282  // dispatch each command
283  int cmd = myInstance->dispatchCommand();
284  if (cmd == CMD_SIMSTEP2) {
285  myInstance->myDoingSimStep = true;
286  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
287  (*i).second.clear();
288  }
289  return;
290  }
291  }
292  }
294  // send out all answers as one storage
296  }
297  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
298  (*i).second.clear();
299  }
300  } catch (std::invalid_argument& e) {
301  throw ProcessError(e.what());
302  } catch (TraCIException& e) {
303  throw ProcessError(e.what());
304  } catch (tcpip::SocketException& e) {
305  throw ProcessError(e.what());
306  }
307 }
308 
309 
310 
311 
312 #ifdef HAVE_PYTHON
313 // ===========================================================================
314 // python functions (traciemb module)
315 // ===========================================================================
316 static PyObject*
317 traciemb_execute(PyObject* /* self */, PyObject* args) {
318  const char* msg;
319  int size;
320  if (!PyArg_ParseTuple(args, "s#", &msg, &size)) {
321  return NULL;
322  }
323  std::string result = TraCIServer::execute(std::string(msg, size));
324  return Py_BuildValue("s#", result.c_str(), result.size());
325 }
326 
327 static PyMethodDef EmbMethods[] = {
328  {
329  "execute", traciemb_execute, METH_VARARGS,
330  "Execute the given TraCI command and return the result."
331  },
332  {NULL, NULL, 0, NULL}
333 };
334 
335 
336 std::string
337 TraCIServer::execute(std::string cmd) {
338  try {
339  if (myInstance == 0) {
340  if (!myDoCloseConnection) {
341  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")));
342  } else {
343  return "";
344  }
345  }
348  for (std::string::iterator i = cmd.begin(); i != cmd.end(); ++i) {
350  }
352  return std::string(myInstance->myOutputStorage.begin(), myInstance->myOutputStorage.end());
353  } catch (std::invalid_argument& e) {
354  throw ProcessError(e.what());
355  } catch (TraCIException& e) {
356  throw ProcessError(e.what());
357  } catch (tcpip::SocketException& e) {
358  throw ProcessError(e.what());
359  }
360 }
361 
362 
363 void
364 TraCIServer::runEmbedded(std::string pyFile) {
365  PyObject* pName, *pModule;
366  Py_Initialize();
367  Py_InitModule("traciemb", EmbMethods);
368  if (pyFile.length() > 3 && !pyFile.compare(pyFile.length() - 3, 3, ".py")) {
369  PyObject* sys_path, *path;
370  char pathstr[] = "path";
371  sys_path = PySys_GetObject(pathstr);
372  if (sys_path == NULL || !PyList_Check(sys_path)) {
373  throw ProcessError("Could not access python sys.path!");
374  }
375  path = PyString_FromString(FileHelpers::getFilePath(pyFile).c_str());
376  PyList_Insert(sys_path, 0, path);
377  Py_DECREF(path);
378  FILE* pFile = fopen(pyFile.c_str(), "r");
379  if (pFile == NULL) {
380  throw ProcessError("Failed to load \"" + pyFile + "\"!");
381  }
382  PyRun_SimpleFile(pFile, pyFile.c_str());
383  fclose(pFile);
384  } else {
385  pName = PyString_FromString(pyFile.c_str());
386  /* Error checking of pName left out */
387  pModule = PyImport_Import(pName);
388  Py_DECREF(pName);
389  if (pModule == NULL) {
390  PyErr_Print();
391  throw ProcessError("Failed to load \"" + pyFile + "\"!");
392  }
393  }
394  Py_Finalize();
395 }
396 #endif
397 
398 
399 int
401  unsigned int commandStart = myInputStorage.position();
402  unsigned int commandLength = myInputStorage.readUnsignedByte();
403  if (commandLength == 0) {
404  commandLength = myInputStorage.readInt();
405  }
406 
407  int commandId = myInputStorage.readUnsignedByte();
408  bool success = false;
409  // dispatch commands
410  if (myExecutors.find(commandId) != myExecutors.end()) {
411  success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
412  } else {
413  switch (commandId) {
414  case CMD_GETVERSION:
415  success = commandGetVersion();
416  break;
417  case CMD_SIMSTEP2: {
418  SUMOTime nextT = myInputStorage.readInt();
419  success = true;
420  if (nextT != 0) {
421  myTargetTime = nextT;
422  } else {
424  }
425  if (myAmEmbedded) {
428  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
429  (*i).second.clear();
430  }
431  }
432  return commandId;
433  }
434  case CMD_CLOSE:
435  myDoCloseConnection = true;
436  success = true;
437  break;
453  success = addObjectVariableSubscription(commandId, false);
454  break;
470  success = addObjectVariableSubscription(commandId, true);
471  break;
472  default:
473  writeStatusCmd(commandId, RTYPE_NOTIMPLEMENTED, "Command not implemented in sumo");
474  }
475  }
476  if (!success) {
477  while (myInputStorage.valid_pos() && myInputStorage.position() < commandStart + commandLength) {
479  }
480  }
481  if (myInputStorage.position() != commandStart + commandLength) {
482  std::ostringstream msg;
483  msg << "Wrong position in requestMessage after dispatching command.";
484  msg << " Expected command length was " << commandLength;
485  msg << " but " << myInputStorage.position() - commandStart << " Bytes were read.";
486  writeStatusCmd(commandId, RTYPE_ERR, msg.str());
487  myDoCloseConnection = true;
488  }
489  return commandId;
490 }
491 
492 
493 // ---------- Server-internal command handling
494 bool
496  std::string sumoVersion = VERSION_STRING;
497  // Prepare response
498  tcpip::Storage answerTmp;
499  answerTmp.writeInt(TRACI_VERSION);
500  answerTmp.writeString(std::string("SUMO ") + sumoVersion);
501  // When we get here, the response is stored in answerTmp -> put into myOutputStorage
503  // command length
504  myOutputStorage.writeUnsignedByte(1 + 1 + static_cast<int>(answerTmp.size()));
505  // command type
507  // and the parameter dependant part
508  myOutputStorage.writeStorage(answerTmp);
509  return true;
510 }
511 
512 
513 void
517  int noActive = 0;
518  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
519  const Subscription& s = *i;
522  if ((s.endTime < t) || isArrivedVehicle) {
523  i = mySubscriptions.erase(i);
524  continue;
525  }
526  ++i;
527  if (s.beginTime > t) {
528  continue;
529  }
530  ++noActive;
531  }
532  myOutputStorage.writeInt(noActive);
533  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
534  const Subscription& s = *i;
535  if (s.beginTime > t) {
536  ++i;
537  continue;
538  }
539  tcpip::Storage into;
540  std::string errors;
541  bool ok = processSingleSubscription(s, into, errors);
543  if (ok) {
544  ++i;
545  } else {
546  i = mySubscriptions.erase(i);
547  }
548  }
549 }
550 
551 
552 void
553 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
554  writeStatusCmd(commandId, status, description, myOutputStorage);
555 }
556 
557 
558 void
559 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
560  if (status == RTYPE_ERR) {
561  WRITE_ERROR("Answered with error to command " + toHex(commandId, 2) + ": " + description);
562  } else if (status == RTYPE_NOTIMPLEMENTED) {
563  WRITE_ERROR("Requested command not implemented (" + toHex(commandId, 2) + "): " + description);
564  }
565  outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
566  outputStorage.writeUnsignedByte(commandId); // command type
567  outputStorage.writeUnsignedByte(status); // status
568  outputStorage.writeString(description); // description
569 }
570 
571 
572 bool
573 TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
574  writeStatusCmd(commandId, RTYPE_ERR, description, outputStorage);
575  return false;
576 }
577 
578 
579 void
581  tcpip::Storage writeInto;
582  std::string errors;
583  if (processSingleSubscription(s, writeInto, errors)) {
585  writeStatusCmd(s.commandId, RTYPE_ERR, "Subscription has ended.");
586  } else {
587  mySubscriptions.push_back(s);
589  }
590  } else {
591  writeStatusCmd(s.commandId, RTYPE_ERR, "Could not add subscription (" + errors + ").");
592  }
593  myOutputStorage.writeStorage(writeInto);
594 }
595 
596 
597 void
598 TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
599  bool found = false;
600  for (std::vector<Subscription>::iterator j = mySubscriptions.begin(); j != mySubscriptions.end();) {
601  if ((*j).id == id && (*j).commandId == commandId && (domain < 0 || (*j).contextDomain == domain)) {
602  j = mySubscriptions.erase(j);
603  found = true;
604  continue;
605  }
606  ++j;
607  }
608  // try unsubscribe
609  if (found) {
610  writeStatusCmd(commandId, RTYPE_OK, "");
611  } else {
612  writeStatusCmd(commandId, RTYPE_OK, "The subscription to remove was not found.");
613  }
614 }
615 
616 
617 bool
618 TraCIServer::findObjectShape(int domain, const std::string& id, PositionVector& shape) {
619  Position p;
620  switch (domain) {
623  shape.push_back(p);
624  return true;
625  }
626  break;
628  break;
630  break;
632  if (TraCIServerAPI_Lane::getShape(id, shape)) {
633  return true;
634  }
635  break;
638  shape.push_back(p);
639  return true;
640  }
641  break;
644  shape.push_back(p);
645  return true;
646  }
647  break;
649  break;
651  break;
653  if (TraCIServerAPI_POI::getPosition(id, p)) {
654  shape.push_back(p);
655  return true;
656  }
657  return false;
659  if (TraCIServerAPI_Polygon::getShape(id, shape)) {
660  return true;
661  }
662  break;
665  shape.push_back(p);
666  return true;
667  }
668  break;
670  if (TraCIServerAPI_Edge::getShape(id, shape)) {
671  return true;
672  }
673  break;
675  return false;
677  break;
678  default:
679  break;
680  }
681  return false;
682 }
683 
684 void
685 TraCIServer::collectObjectsInRange(int domain, const PositionVector& shape, SUMOReal range, std::set<std::string>& into) {
686  // build the look-up tree if not yet existing
687  if (myObjects.find(domain) == myObjects.end()) {
688  switch (domain) {
691  break;
700  break;
703  break;
706  break;
709  break;
710  default:
711  break;
712  }
713  }
714  const Boundary b = shape.getBoxBoundary().grow(range);
715  const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
716  const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
717  switch (domain) {
722  Named::StoringVisitor sv(into);
723  myObjects[domain]->Search(cmin, cmax, sv);
724  }
725  break;
729  TraCIServerAPI_Lane::StoringVisitor sv(into, shape, range, domain);
730  myLaneTree->Search(cmin, cmax, sv);
731  }
732  break;
733  default:
734  break;
735  }
736 }
737 
738 
739 bool
741  std::string& errors) {
742  bool ok = true;
743  tcpip::Storage outputStorage;
744  const int getCommandId = s.contextVars ? s.contextDomain : s.commandId - 0x30;
745  std::set<std::string> objIDs;
746  if (s.contextVars) {
747  PositionVector shape;
748  if (!findObjectShape(s.commandId, s.id, shape)) {
749  return false;
750  }
751  collectObjectsInRange(s.contextDomain, shape, s.range, objIDs);
752  } else {
753  objIDs.insert(s.id);
754  }
755  const int numVars = s.contextVars && s.variables.size() == 1 && s.variables[0] == ID_LIST ? 0 : (int)s.variables.size();
756  for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
757  if (s.contextVars) {
758  outputStorage.writeString(*j);
759  }
760  if (numVars > 0) {
761  std::vector<std::vector<unsigned char> >::const_iterator k = s.parameters.begin();
762  for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i, ++k) {
763  tcpip::Storage message;
764  message.writeUnsignedByte(*i);
765  message.writeString(*j);
766  message.writePacket(*k);
767  tcpip::Storage tmpOutput;
768  if (myExecutors.find(getCommandId) != myExecutors.end()) {
769  ok &= myExecutors[getCommandId](*this, message, tmpOutput);
770  } else {
771  writeStatusCmd(s.commandId, RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
772  ok = false;
773  }
774  // copy response part
775  if (ok) {
776  int length = tmpOutput.readUnsignedByte();
777  while (--length > 0) {
778  tmpOutput.readUnsignedByte();
779  }
780  int lengthLength = 1;
781  length = tmpOutput.readUnsignedByte();
782  if (length == 0) {
783  lengthLength = 5;
784  length = tmpOutput.readInt();
785  }
786  //read responseType
787  tmpOutput.readUnsignedByte();
788  int variable = tmpOutput.readUnsignedByte();
789  std::string id = tmpOutput.readString();
790  outputStorage.writeUnsignedByte(variable);
791  outputStorage.writeUnsignedByte(RTYPE_OK);
792  length -= (lengthLength + 1 + 4 + (int)id.length());
793  while (--length > 0) {
794  outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
795  }
796  } else {
797  //read length
798  tmpOutput.readUnsignedByte();
799  //read cmd
800  tmpOutput.readUnsignedByte();
801  //read status
802  tmpOutput.readUnsignedByte();
803  std::string msg = tmpOutput.readString();
804  outputStorage.writeUnsignedByte(*i);
805  outputStorage.writeUnsignedByte(RTYPE_ERR);
806  outputStorage.writeUnsignedByte(TYPE_STRING);
807  outputStorage.writeString(msg);
808  errors = errors + msg;
809  }
810  }
811  }
812  }
813  unsigned int length = (1 + 4) + 1 + (4 + (int)(s.id.length())) + 1 + (int)outputStorage.size();
814  if (s.contextVars) {
815  length += 4;
816  }
817  writeInto.writeUnsignedByte(0); // command length -> extended
818  writeInto.writeInt(length);
819  writeInto.writeUnsignedByte(s.commandId + 0x10);
820  writeInto.writeString(s.id);
821  if (s.contextVars) {
822  writeInto.writeUnsignedByte(s.contextDomain);
823  }
824  writeInto.writeUnsignedByte(numVars);
825  if (s.contextVars) {
826  writeInto.writeInt((int)objIDs.size());
827  }
828  if (!s.contextVars || objIDs.size() != 0) {
829  writeInto.writeStorage(outputStorage);
830  }
831  return ok;
832 }
833 
834 
835 bool
836 TraCIServer::addObjectVariableSubscription(const int commandId, const bool hasContext) {
837  const SUMOTime beginTime = myInputStorage.readInt();
838  const SUMOTime endTime = myInputStorage.readInt();
839  const std::string id = myInputStorage.readString();
840  const int domain = hasContext ? myInputStorage.readUnsignedByte() : 0;
841  const SUMOReal range = hasContext ? myInputStorage.readDouble() : 0.;
842  const int num = myInputStorage.readUnsignedByte();
843  std::vector<int> variables;
844  std::vector<std::vector<unsigned char> > parameters;
845  for (int i = 0; i < num; ++i) {
846  const int varID = myInputStorage.readUnsignedByte();
847  variables.push_back(varID);
848  parameters.push_back(std::vector<unsigned char>());
849  for (int j = 0; j < myParameterSizes[varID]; j++) {
850  parameters.back().push_back(myInputStorage.readChar());
851  }
852  }
853  // check subscribe/unsubscribe
854  if (variables.size() == 0) {
855  removeSubscription(commandId, id, -1);
856  return true;
857  }
858  // process subscription
859  Subscription s(commandId, id, variables, parameters, beginTime, endTime, hasContext, domain, range);
861  return true;
862 }
863 
864 
865 void
867  if (tempMsg.size() < 254) {
868  outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
869  } else {
870  outputStorage.writeUnsignedByte(0); // command length -> extended
871  outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
872  }
873  outputStorage.writeStorage(tempMsg);
874 }
875 
876 
877 bool
879  if (inputStorage.readUnsignedByte() != TYPE_INTEGER) {
880  return false;
881  }
882  into = inputStorage.readInt();
883  return true;
884 }
885 
886 
887 bool
889  if (inputStorage.readUnsignedByte() != TYPE_DOUBLE) {
890  return false;
891  }
892  into = inputStorage.readDouble();
893  return true;
894 }
895 
896 
897 bool
898 TraCIServer::readTypeCheckingString(tcpip::Storage& inputStorage, std::string& into) {
899  if (inputStorage.readUnsignedByte() != TYPE_STRING) {
900  return false;
901  }
902  into = inputStorage.readString();
903  return true;
904 }
905 
906 
907 bool
908 TraCIServer::readTypeCheckingStringList(tcpip::Storage& inputStorage, std::vector<std::string>& into) {
909  if (inputStorage.readUnsignedByte() != TYPE_STRINGLIST) {
910  return false;
911  }
912  into = inputStorage.readStringList();
913  return true;
914 }
915 
916 
917 bool
919  if (inputStorage.readUnsignedByte() != TYPE_COLOR) {
920  return false;
921  }
922  unsigned char r = static_cast<unsigned char>(inputStorage.readUnsignedByte());
923  unsigned char g = static_cast<unsigned char>(inputStorage.readUnsignedByte());
924  unsigned char b = static_cast<unsigned char>(inputStorage.readUnsignedByte());
925  unsigned char a = static_cast<unsigned char>(inputStorage.readUnsignedByte());
926  into.set(r, g, b, a);
927  return true;
928 }
929 
930 
931 bool
933  if (inputStorage.readUnsignedByte() != POSITION_2D) {
934  return false;
935  }
936  SUMOReal x = inputStorage.readDouble();
937  SUMOReal y = inputStorage.readDouble();
938  into.set(x, y, 0);
939  return true;
940 }
941 
942 
943 bool
945  if (inputStorage.readUnsignedByte() != TYPE_BOUNDINGBOX) {
946  return false;
947  }
948  const SUMOReal xmin = inputStorage.readDouble();
949  const SUMOReal ymin = inputStorage.readDouble();
950  const SUMOReal xmax = inputStorage.readDouble();
951  const SUMOReal ymax = inputStorage.readDouble();
952  into.set(xmin, ymin, xmax, ymax);
953  return true;
954 }
955 
956 
957 bool
959  if (inputStorage.readUnsignedByte() != TYPE_BYTE) {
960  return false;
961  }
962  into = inputStorage.readByte();
963  return true;
964 }
965 
966 
967 bool
969  if (inputStorage.readUnsignedByte() != TYPE_UBYTE) {
970  return false;
971  }
972  into = inputStorage.readUnsignedByte();
973  return true;
974 }
975 
976 
977 bool
979  if (inputStorage.readUnsignedByte() != TYPE_POLYGON) {
980  return false;
981  }
982  into.clear();
983  unsigned int noEntries = inputStorage.readUnsignedByte();
984  PositionVector shape;
985  for (unsigned int i = 0; i < noEntries; ++i) {
986  SUMOReal x = inputStorage.readDouble();
987  SUMOReal y = inputStorage.readDouble();
988  into.push_back(Position(x, y));
989  }
990  return true;
991 }
992 
993 #endif
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa3: Get Lane Variable)
bool processSingleSubscription(const TraCIServer::Subscription &s, tcpip::Storage &writeInto, std::string &errors)
The vehicle has departed (was inserted into the network)
Definition: MSNet.h:530
bool myDoingSimStep
Whether a step is currently done.
Definition: TraCIServer.h:313
static MsgHandler * getWarningInstance()
Returns the instance to add warnings to.
Definition: MsgHandler.cpp:71
tcpip::Socket * mySocket
The socket on which server is listening on.
Definition: TraCIServer.h:300
#define CMD_SUBSCRIBE_VEHICLE_CONTEXT
#define CMD_SUBSCRIBE_LANE_VARIABLE
bool findObjectShape(int domain, const std::string &id, PositionVector &shape)
Representation of a vehicle in the micro simulation.
Definition: MSVehicle.h:80
long long int SUMOTime
Definition: SUMOTime.h:43
bool contextVars
Whether the subscription is a context subscription (variable subscription otherwise) ...
Definition: TraCIServer.h:361
#define CMD_GET_TL_VARIABLE
void collectObjectsInRange(int domain, const PositionVector &shape, SUMOReal range, std::set< std::string > &into)
#define CMD_SUBSCRIBE_JUNCTION_CONTEXT
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition: MSNet.cpp:755
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc3: Change Lane State)
#define CMD_GET_VEHICLE_VARIABLE
virtual ~TraCIServer()
Destructor.
#define CMD_SUBSCRIBE_SIM_CONTEXT
bool commandGetVersion()
Returns the TraCI-version.
#define CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT
#define CMD_CLOSE
virtual std::vector< std::string > readStringList()
#define POSITION_2D
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc4: Change Vehicle State)
std::vector< std::vector< unsigned char > > parameters
The parameters for the subscribed variables.
Definition: TraCIServer.h:355
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc7: Change PoI State)
bool receiveExact(Storage &)
Receive a complete TraCI message from Socket::socket_.
Definition: socket.cpp:493
#define CMD_GET_INDUCTIONLOOP_VARIABLE
bool readTypeCheckingColor(tcpip::Storage &inputStorage, RGBColor &into)
Reads the value type and a color, verifying the type.
static NamedRTree * getTree()
Returns a tree filled with junction instances.
static NamedRTree * getTree()
Returns a tree filled with polygon instances.
static void fill(RTREE &into)
Fills the given RTree with lane instances.
Definition: MSLane.cpp:812
SUMOReal ymin() const
Returns minimum y-coordinate.
Definition: Boundary.cpp:124
#define CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE
virtual unsigned int position() const
#define TYPE_UBYTE
#define RTYPE_OK
SUMOTime beginTime
The begin time of the subscription.
Definition: TraCIServer.h:357
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa9: Get Junction Variable)
#define CMD_GET_PERSON_VARIABLE
virtual double readDouble()
tcpip::Storage myOutputStorage
The storage to writeto.
Definition: TraCIServer.h:309
#define TYPE_POLYGON
void accept()
Wait for a incoming connection to port_.
Definition: socket.cpp:221
SUMOReal xmin() const
Returns minimum x-coordinate.
Definition: Boundary.cpp:112
StorageType::size_type size() const
Definition: storage.h:115
#define TRACI_VERSION
static bool getPosition(const std::string &id, Position &p)
Returns the named vehicle&#39;s position.
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xab: Get Simulation Variable)
bool readTypeCheckingInt(tcpip::Storage &inputStorage, int &into)
Reads the value type and an int, verifying the type.
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition: MSNet.cpp:160
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change Route State)
SUMOTime DELTA_T
Definition: SUMOTime.cpp:39
bool readTypeCheckingString(tcpip::Storage &inputStorage, std::string &into)
Reads the value type and a string, verifying the type.
#define TYPE_COLOR
#define TYPE_STRINGLIST
bool readTypeCheckingDouble(tcpip::Storage &inputStorage, double &into)
Reads the value type and a double, verifying the type.
virtual bool valid_pos()
#define CMD_SUBSCRIBE_POLYGON_CONTEXT
tcpip::Storage myInputStorage
The storage to read from.
Definition: TraCIServer.h:306
#define CMD_GET_POLYGON_VARIABLE
virtual void writePacket(unsigned char *packet, int length)
#define CMD_SUBSCRIBE_JUNCTION_VARIABLE
Representation of a subscription.
Definition: TraCIServer.h:330
std::vector< const MSEdge * > ConstMSEdgeVector
Definition: MSEdge.h:78
#define CMD_SUBSCRIBE_ROUTE_CONTEXT
bool readTypeCheckingPolygon(tcpip::Storage &inputStorage, PositionVector &into)
Reads the value type and a polygon, verifying the type.
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xca: Change Edge State)
virtual void writeUnsignedByte(int)
#define CMD_SET_EDGE_VARIABLE
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition: MSNet.h:255
bool writeErrorStatusCmd(int commandId, const std::string &description, tcpip::Storage &outputStorage)
Writes a status command to the given storage with status = RTYPE_ERR.
#define CMD_SUBSCRIBE_EDGE_VARIABLE
virtual unsigned char readChar()
SUMOReal xmax() const
Returns maximum x-coordinate.
Definition: Boundary.cpp:118
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition: MSNet.cpp:747
#define CMD_GET_ROUTE_VARIABLE
A class that stores a 2D geometrical boundary.
Definition: Boundary.h:48
#define CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT
virtual void writeInt(int)
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:200
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:69
#define TYPE_STRING
virtual int readUnsignedByte()
virtual void writeChar(unsigned char)
#define CMD_SUBSCRIBE_POI_VARIABLE
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa4: Get Vehicle Variable)
static bool getPosition(const std::string &id, Position &p)
Returns the named inductive loop&#39;s position.
static bool getPosition(const std::string &id, Position &p)
Returns the named persons&#39;s position.
static bool myDoCloseConnection
Whether the connection was set to be to close.
Definition: TraCIServer.h:297
void postProcessVTD()
The vehicles starts to stop.
Definition: MSNet.h:544
std::map< int, CmdExecutor > myExecutors
Map of commandIds -> their executors; applicable if the executor applies to the method footprint...
Definition: TraCIServer.h:319
#define CMD_SET_TL_VARIABLE
void set(SUMOReal xmin, SUMOReal ymin, SUMOReal xmax, SUMOReal ymax)
Sets the boundary to the given values.
Definition: Boundary.cpp:241
void vehicleStateChanged(const SUMOVehicle *const vehicle, MSNet::VehicleState to)
Called if a vehicle changes its state.
bool readTypeCheckingBoundary(tcpip::Storage &inputStorage, Boundary &into)
Reads the value type and a 2D bounding box, verifying the type.
static NamedRTree * getTree()
Returns a tree filled with PoI instances.
#define CMD_SUBSCRIBE_LANE_CONTEXT
#define CMD_SUBSCRIBE_SIM_VARIABLE
void removeSubscription(int commandId, const std::string &identity, int domain)
#define CMD_GET_VEHICLETYPE_VARIABLE
static void close()
request termination of connection
bool addObjectVariableSubscription(const int commandId, const bool hasContext)
void setVTDControlled(MSVehicle *v, MSLane *l, SUMOReal pos, SUMOReal angle, int edgeOffset, ConstMSEdgeVector route, SUMOTime t)
#define CMD_SET_ROUTE_VARIABLE
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xcb: Set Simulation Variable)
#define CMD_GETVERSION
#define CMD_GET_AREAL_DETECTOR_VARIABLE
void setVTDControlled(MSLane *l, SUMOReal pos, SUMOReal angle, int edgeOffset, const ConstMSEdgeVector &route, SUMOTime t)
Definition: MSVehicle.cpp:416
#define CMD_SUBSCRIBE_GUI_CONTEXT
Allows to store the object; used as context while traveling the rtree in TraCI.
The vehicle got a new route.
Definition: MSNet.h:538
The vehicle arrived at his destination (is deleted)
Definition: MSNet.h:536
StorageType::const_iterator end() const
Definition: storage.h:118
The vehicles starts to park.
Definition: MSNet.h:540
int commandId
commandIdArg The command id of the subscription
Definition: TraCIServer.h:349
std::vector< Subscription > mySubscriptions
The list of known, still valid subscriptions.
Definition: TraCIServer.h:370
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xce: Change Person State)
Representation of a vehicle.
Definition: SUMOVehicle.h:65
SUMOReal range
The range of the context.
Definition: TraCIServer.h:365
virtual int readInt()
A point in 2D or 3D with translation and scaling methods.
Definition: Position.h:46
std::string id
The id of the object that is subscribed.
Definition: TraCIServer.h:351
#define CMD_GET_POI_VARIABLE
void set(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
assigns new values
Definition: RGBColor.cpp:87
A list of positions.
std::vector< int > variables
The subscribed variables.
Definition: TraCIServer.h:353
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition: MSNet.h:308
#define CMD_SET_VEHICLETYPE_VARIABLE
#define CMD_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE
#define TYPE_BOUNDINGBOX
bool readTypeCheckingStringList(tcpip::Storage &inputStorage, std::vector< std::string > &into)
Reads the value type and a string list, verifying the type.
#define CMD_SUBSCRIBE_GUI_VARIABLE
#define CMD_GET_LANE_VARIABLE
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa5: Get Vehicle Type Variable)
#define CMD_SET_VEHICLE_VARIABLE
SUMOTime string2time(const std::string &r)
Definition: SUMOTime.cpp:46
void postProcessSimulationStep2()
Handles subscriptions to send after a simstep2 command.
The vehicle started to teleport.
Definition: MSNet.h:532
#define CMD_GET_SIM_VARIABLE
virtual std::string readString()
#define CMD_GET_EDGE_VARIABLE
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition: MSGlobals.h:69
#define CMD_SET_POI_VARIABLE
#define CMD_SUBSCRIBE_POLYGON_VARIABLE
static TraCIServer * myInstance
Singleton instance of the server.
Definition: TraCIServer.h:294
static bool getPosition(const std::string &id, Position &p)
Returns the named PoI&#39;s position.
TraCIServer(const SUMOTime begin, const int port=0)
Constructor.
#define CMD_SUBSCRIBE_TL_CONTEXT
The vehicle ends to park.
Definition: MSNet.h:542
#define CMD_SUBSCRIBE_EDGE_CONTEXT
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa0: Get Induction Loop Variable)
#define CMD_GET_JUNCTION_VARIABLE
#define CMD_SUBSCRIBE_PERSON_VARIABLE
bool readTypeCheckingUnsignedByte(tcpip::Storage &inputStorage, int &into)
Reads the value type and an unsigned byte, verifying the type.
std::string toString(const T &t, std::streamsize accuracy=OUTPUT_ACCURACY)
Definition: ToString.h:54
TraCI server used to control sumo by a remote TraCI client.
Definition: TraCIServer.h:73
virtual void writeStorage(tcpip::Storage &store)
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xae: Get Person Variable)
#define VAR_LEADER
#define CMD_SET_SIM_VARIABLE
#define CMD_SUBSCRIBE_AREAL_DETECTOR_VARIABLE
#define CMD_SUBSCRIBE_AREAL_DETECTOR_CONTEXT
#define CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE
void writeResponseWithLength(tcpip::Storage &outputStorage, tcpip::Storage &tempMsg)
#define VERSION_STRING
Definition: config.h:225
VehicleState
Definition of a vehicle state.
Definition: MSNet.h:526
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa7: Get PoI Variable)
const bool myAmEmbedded
Whether the server runs in embedded mode.
Definition: TraCIServer.h:316
bool readTypeCheckingPosition2D(tcpip::Storage &inputStorage, Position &into)
Reads the value type and a 2D position, verifying the type.
The vehicle was built, but has not yet departed.
Definition: MSNet.h:528
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
static void processCommandsUntilSimStep(SUMOTime step)
process all commands until a simulation step is wanted
LANE_RTREE_QUAL * myLaneTree
A storage of lanes.
Definition: TraCIServer.h:379
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc5: Change Vehicle Type State)
Allows to store the object; used as context while traveling the rtree in TraCI.
Definition: Named.h:97
#define CMD_SET_POLYGON_VARIABLE
static void openSocket(const std::map< int, CmdExecutor > &execs)
Initialises the server.
Boundary & grow(SUMOReal by)
extends the boundary by the given amount
Definition: Boundary.cpp:201
static bool getShape(const std::string &id, PositionVector &shape)
Returns the named edge&#39;s shape.
virtual void writeString(const std::string &s)
#define RTYPE_NOTIMPLEMENTED
Influencer & getInfluencer()
Returns the velocity/lane influencer.
Definition: MSVehicle.cpp:2826
#define CMD_GET_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE
virtual const char * what() const
Definition: socket.h:70
#define TYPE_DOUBLE
std::string toHex(const T i, std::streamsize numDigits=0)
Definition: ToString.h:64
static bool getPosition(const std::string &id, Position &p)
Returns the named junction&#39;s position.
#define CMD_SUBSCRIBE_VEHICLE_VARIABLE
#define CMD_SUBSCRIBE_PERSON_CONTEXT
void sendExact(const Storage &)
Definition: socket.cpp:394
#define TYPE_BYTE
#define CMD_SET_LANE_VARIABLE
void inform(std::string msg, bool addType=true)
adds a new error to the list
Definition: MsgHandler.cpp:89
void set(SUMOReal x, SUMOReal y)
Definition: Position.h:78
SUMOTime myTargetTime
The time step to reach until processing the next commands.
Definition: TraCIServer.h:303
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa6: Get Route Variable)
static NamedRTree * getTree()
Returns a tree filled with inductive loop instances.
The vehicle ends to stop.
Definition: MSNet.h:546
#define LANE_RTREE_QUAL
std::map< int, NamedRTree * > myObjects
A storage of objects.
Definition: TraCIServer.h:376
StorageType::const_iterator begin() const
Definition: storage.h:117
SUMOVehicle * getVehicle(const std::string &id) const
Returns the vehicle with the given id.
std::map< std::string, MSVehicle * > myVTDControlledVehicles
Definition: TraCIServer.h:324
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa8: Get Polygon Variable)
int dispatchCommand()
#define CMD_SUBSCRIBE_MULTI_ENTRY_EXIT_DETECTOR_CONTEXT
void visit(const TraCIServerAPI_Lane::StoringVisitor &cont) const
Callback for visiting the lane when traversing an RTree.
Definition: MSLane.h:797
#define CMD_SUBSCRIBE_TL_VARIABLE
#define SUMOReal
Definition: config.h:213
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc2: Change Traffic Lights State)
void writeStatusCmd(int commandId, int status, const std::string &description, tcpip::Storage &outputStorage)
Writes a status command to the given storage.
SUMOReal ymax() const
Returns maximum y-coordinate.
Definition: Boundary.cpp:130
static std::string getFilePath(const std::string &path)
Removes the file information from the given path.
Definition: FileHelpers.cpp:76
#define CMD_SET_PERSON_VARIABLE
void simulationStep()
Performs a single simulation step.
Definition: MSNet.cpp:420
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa1: Get MeMeDetector Variable)
int contextDomain
The domain ID of the context.
Definition: TraCIServer.h:363
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:201
#define RTYPE_ERR
void initialiseSubscription(const Subscription &s)
#define TYPE_INTEGER
#define CMD_SIMSTEP2
#define ID_LIST
#define CMD_SUBSCRIBE_POI_CONTEXT
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xaa: Get Edge Variable)
Boundary getBoxBoundary() const
Returns a boundary enclosing this list of lines.
Representation of a lane in the micro simulation.
Definition: MSLane.h:77
static bool wasClosed()
check whether close was requested
std::map< MSNet::VehicleState, std::vector< std::string > > myVehicleStateChanges
Changes in the states of simulated vehicles.
Definition: TraCIServer.h:373
The vehicle ended being teleported.
Definition: MSNet.h:534
virtual const std::string & getID() const =0
Get the vehicle&#39;s ID.
virtual int readByte()
static bool getShape(const std::string &id, PositionVector &shape)
Returns the named polygons&#39;s shape.
bool readTypeCheckingByte(tcpip::Storage &inputStorage, int &into)
Reads the value type and a byte, verifying the type.
void close()
Definition: socket.cpp:345
SUMOTime endTime
The end time of the subscription.
Definition: TraCIServer.h:359
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa2: Get Traffic Lights Variable)
#define CMD_SUBSCRIBE_ROUTE_VARIABLE
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc8: Change Polygon State)
static bool getShape(const std::string &id, PositionVector &shape)
Returns the named lane&#39;s shape.
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa1: Get AreaDetector Variable)
const std::string & getID() const
Returns the name of the vehicle.
std::map< int, int > myParameterSizes
Map of variable ids to the size of the parameter in bytes.
Definition: TraCIServer.h:322