SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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-2015 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  delete myInstance;
206  myInstance = 0;
207  myDoCloseConnection = true;
208 }
209 
210 
211 bool
213  return myDoCloseConnection;
214 }
215 
216 
217 void
219  SUMOTime t) {
220  myVTDControlledVehicles[v->getID()] = v;
221  v->getInfluencer().setVTDControlled(true, l, pos, edgeOffset, route, t);
222 }
223 
224 
225 void
227  for (std::map<std::string, MSVehicle*>::const_iterator i = myVTDControlledVehicles.begin(); i != myVTDControlledVehicles.end(); ++i) {
228  if (MSNet::getInstance()->getVehicleControl().getVehicle((*i).first) != 0) {
229  (*i).second->getInfluencer().postProcessVTD((*i).second);
230  } else {
231  WRITE_WARNING("Vehicle '" + (*i).first + "' was removed though being controlled by VTD");
232  }
233  }
234  myVTDControlledVehicles.clear();
235 }
236 
237 
238 // ---------- Initialisation and Shutdown
239 
240 
241 void
243  if (!myDoCloseConnection) {
244  myVehicleStateChanges[to].push_back(vehicle->getID());
245  }
246 }
247 
248 
249 void
251  if (myInstance == 0) {
252  return;
253  }
254  try {
255  if (myInstance->myAmEmbedded || step < myInstance->myTargetTime) {
256  return;
257  }
258  // Simulation should run until
259  // 1. end time reached or
260  // 2. got CMD_CLOSE or
261  // 3. Client closes socket connection
262  if (myInstance->myDoingSimStep) {
264  myInstance->myDoingSimStep = false;
265  }
266  while (!myDoCloseConnection) {
268  if (myInstance->myOutputStorage.size() > 0) {
269  // send out all answers as one storage
271  }
274  // Read a message
276  }
278  // dispatch each command
279  int cmd = myInstance->dispatchCommand();
280  if (cmd == CMD_SIMSTEP2) {
281  myInstance->myDoingSimStep = true;
282  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
283  (*i).second.clear();
284  }
285  return;
286  }
287  }
288  }
290  // send out all answers as one storage
292  }
293  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
294  (*i).second.clear();
295  }
296  } catch (std::invalid_argument& e) {
297  throw ProcessError(e.what());
298  } catch (TraCIException& e) {
299  throw ProcessError(e.what());
300  } catch (tcpip::SocketException& e) {
301  throw ProcessError(e.what());
302  }
303  if (myInstance != NULL) {
304  delete myInstance;
305  myInstance = 0;
306  myDoCloseConnection = true;
307  }
308 }
309 
310 
311 
312 
313 #ifdef HAVE_PYTHON
314 // ===========================================================================
315 // python functions (traciemb module)
316 // ===========================================================================
317 static PyObject*
318 traciemb_execute(PyObject* /* self */, PyObject* args) {
319  const char* msg;
320  int size;
321  if (!PyArg_ParseTuple(args, "s#", &msg, &size)) {
322  return NULL;
323  }
324  std::string result = TraCIServer::execute(std::string(msg, size));
325  return Py_BuildValue("s#", result.c_str(), result.size());
326 }
327 
328 static PyMethodDef EmbMethods[] = {
329  {
330  "execute", traciemb_execute, METH_VARARGS,
331  "Execute the given TraCI command and return the result."
332  },
333  {NULL, NULL, 0, NULL}
334 };
335 
336 
337 std::string
338 TraCIServer::execute(std::string cmd) {
339  try {
340  if (myInstance == 0) {
341  if (!myDoCloseConnection) {
342  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")));
343  } else {
344  return "";
345  }
346  }
349  for (std::string::iterator i = cmd.begin(); i != cmd.end(); ++i) {
351  }
353  return std::string(myInstance->myOutputStorage.begin(), myInstance->myOutputStorage.end());
354  } catch (std::invalid_argument& e) {
355  throw ProcessError(e.what());
356  } catch (TraCIException& e) {
357  throw ProcessError(e.what());
358  } catch (tcpip::SocketException& e) {
359  throw ProcessError(e.what());
360  }
361 }
362 
363 
364 void
365 TraCIServer::runEmbedded(std::string pyFile) {
366  PyObject* pName, *pModule;
367  Py_Initialize();
368  Py_InitModule("traciemb", EmbMethods);
369  if (pyFile.length() > 3 && !pyFile.compare(pyFile.length() - 3, 3, ".py")) {
370  PyObject* sys_path, *path;
371  char pathstr[] = "path";
372  sys_path = PySys_GetObject(pathstr);
373  if (sys_path == NULL || !PyList_Check(sys_path)) {
374  throw ProcessError("Could not access python sys.path!");
375  }
376  path = PyString_FromString(FileHelpers::getFilePath(pyFile).c_str());
377  PyList_Insert(sys_path, 0, path);
378  Py_DECREF(path);
379  FILE* pFile = fopen(pyFile.c_str(), "r");
380  if (pFile == NULL) {
381  throw ProcessError("Failed to load \"" + pyFile + "\"!");
382  }
383  PyRun_SimpleFile(pFile, pyFile.c_str());
384  fclose(pFile);
385  } else {
386  pName = PyString_FromString(pyFile.c_str());
387  /* Error checking of pName left out */
388  pModule = PyImport_Import(pName);
389  Py_DECREF(pName);
390  if (pModule == NULL) {
391  PyErr_Print();
392  throw ProcessError("Failed to load \"" + pyFile + "\"!");
393  }
394  }
395  Py_Finalize();
396 }
397 #endif
398 
399 
400 int
402  unsigned int commandStart = myInputStorage.position();
403  unsigned int commandLength = myInputStorage.readUnsignedByte();
404  if (commandLength == 0) {
405  commandLength = myInputStorage.readInt();
406  }
407 
408  int commandId = myInputStorage.readUnsignedByte();
409  bool success = false;
410  // dispatch commands
411  if (myExecutors.find(commandId) != myExecutors.end()) {
412  success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
413  } else {
414  switch (commandId) {
415  case CMD_GETVERSION:
416  success = commandGetVersion();
417  break;
418  case CMD_SIMSTEP2: {
419  SUMOTime nextT = myInputStorage.readInt();
420  success = true;
421  if (nextT != 0) {
422  myTargetTime = nextT;
423  } else {
425  }
426  if (myAmEmbedded) {
429  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
430  (*i).second.clear();
431  }
432  }
433  return commandId;
434  }
435  case CMD_CLOSE:
436  success = commandCloseConnection();
437  break;
452  success = addObjectVariableSubscription(commandId, false);
453  break;
468  success = addObjectVariableSubscription(commandId, true);
469  break;
470  default:
471  writeStatusCmd(commandId, RTYPE_NOTIMPLEMENTED, "Command not implemented in sumo");
472  }
473  }
474  if (!success) {
475  while (myInputStorage.valid_pos() && myInputStorage.position() < commandStart + commandLength) {
477  }
478  }
479  if (myInputStorage.position() != commandStart + commandLength) {
480  std::ostringstream msg;
481  msg << "Wrong position in requestMessage after dispatching command.";
482  msg << " Expected command length was " << commandLength;
483  msg << " but " << myInputStorage.position() - commandStart << " Bytes were read.";
484  writeStatusCmd(commandId, RTYPE_ERR, msg.str());
485  myDoCloseConnection = true;
486  }
487  return commandId;
488 }
489 
490 
491 // ---------- Server-internal command handling
492 bool
494  std::string sumoVersion = VERSION_STRING;
495  // Prepare response
496  tcpip::Storage answerTmp;
497  answerTmp.writeInt(TRACI_VERSION);
498  answerTmp.writeString(std::string("SUMO ") + sumoVersion);
499  // When we get here, the response is stored in answerTmp -> put into myOutputStorage
501  // command length
502  myOutputStorage.writeUnsignedByte(1 + 1 + static_cast<int>(answerTmp.size()));
503  // command type
505  // and the parameter dependant part
506  myOutputStorage.writeStorage(answerTmp);
507  return true;
508 }
509 
510 
511 bool
513  myDoCloseConnection = true;
514  // write answer
516  return true;
517 }
518 
519 
520 void
524  int noActive = 0;
525  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
526  const Subscription& s = *i;
529  if ((s.endTime < t) || isArrivedVehicle) {
530  i = mySubscriptions.erase(i);
531  continue;
532  }
533  ++i;
534  if (s.beginTime > t) {
535  continue;
536  }
537  ++noActive;
538  }
539  myOutputStorage.writeInt(noActive);
540  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
541  const Subscription& s = *i;
542  if (s.beginTime > t) {
543  ++i;
544  continue;
545  }
546  tcpip::Storage into;
547  std::string errors;
548  bool ok = processSingleSubscription(s, into, errors);
550  if (ok) {
551  ++i;
552  } else {
553  i = mySubscriptions.erase(i);
554  }
555  }
556 }
557 
558 
559 void
560 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
561  writeStatusCmd(commandId, status, description, myOutputStorage);
562 }
563 
564 
565 void
566 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
567  if (status == RTYPE_ERR) {
568  WRITE_ERROR("Answered with error to command " + toHex(commandId, 2) + ": " + description);
569  } else if (status == RTYPE_NOTIMPLEMENTED) {
570  WRITE_ERROR("Requested command not implemented (" + toHex(commandId, 2) + "): " + description);
571  }
572  outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
573  outputStorage.writeUnsignedByte(commandId); // command type
574  outputStorage.writeUnsignedByte(status); // status
575  outputStorage.writeString(description); // description
576 }
577 
578 
579 bool
580 TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
581  writeStatusCmd(commandId, RTYPE_ERR, description, outputStorage);
582  return false;
583 }
584 
585 
586 void
588  tcpip::Storage writeInto;
589  std::string errors;
590  if (processSingleSubscription(s, writeInto, errors)) {
592  writeStatusCmd(s.commandId, RTYPE_ERR, "Subscription has ended.");
593  } else {
594  mySubscriptions.push_back(s);
596  }
597  } else {
598  writeStatusCmd(s.commandId, RTYPE_ERR, "Could not add subscription (" + errors + ").");
599  }
600  myOutputStorage.writeStorage(writeInto);
601 }
602 
603 
604 void
605 TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
606  bool found = false;
607  for (std::vector<Subscription>::iterator j = mySubscriptions.begin(); j != mySubscriptions.end();) {
608  if ((*j).id == id && (*j).commandId == commandId && (domain < 0 || (*j).contextDomain == domain)) {
609  j = mySubscriptions.erase(j);
610  found = true;
611  continue;
612  }
613  ++j;
614  }
615  // try unsubscribe
616  if (found) {
617  writeStatusCmd(commandId, RTYPE_OK, "");
618  } else {
619  writeStatusCmd(commandId, RTYPE_OK, "The subscription to remove was not found.");
620  }
621 }
622 
623 
624 bool
625 TraCIServer::findObjectShape(int domain, const std::string& id, PositionVector& shape) {
626  Position p;
627  switch (domain) {
630  shape.push_back(p);
631  return true;
632  }
633  break;
635  break;
637  break;
639  if (TraCIServerAPI_Lane::getShape(id, shape)) {
640  return true;
641  }
642  break;
645  shape.push_back(p);
646  return true;
647  }
648  break;
651  shape.push_back(p);
652  return true;
653  }
654  break;
656  break;
658  break;
660  if (TraCIServerAPI_POI::getPosition(id, p)) {
661  shape.push_back(p);
662  return true;
663  }
664  return false;
666  if (TraCIServerAPI_Polygon::getShape(id, shape)) {
667  return true;
668  }
669  break;
672  shape.push_back(p);
673  return true;
674  }
675  break;
677  if (TraCIServerAPI_Edge::getShape(id, shape)) {
678  return true;
679  }
680  break;
682  return false;
684  break;
685  default:
686  break;
687  }
688  return false;
689 }
690 
691 void
692 TraCIServer::collectObjectsInRange(int domain, const PositionVector& shape, SUMOReal range, std::set<std::string>& into) {
693  // build the look-up tree if not yet existing
694  if (myObjects.find(domain) == myObjects.end()) {
695  switch (domain) {
698  break;
707  break;
710  break;
713  break;
716  break;
717  default:
718  break;
719  }
720  }
721  const Boundary b = shape.getBoxBoundary().grow(range);
722  const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
723  const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
724  switch (domain) {
729  Named::StoringVisitor sv(into);
730  myObjects[domain]->Search(cmin, cmax, sv);
731  }
732  break;
736  TraCIServerAPI_Lane::StoringVisitor sv(into, shape, range, domain);
737  myLaneTree->Search(cmin, cmax, sv);
738  }
739  break;
740  default:
741  break;
742  }
743 }
744 
745 
746 bool
748  std::string& errors) {
749  bool ok = true;
750  tcpip::Storage outputStorage;
751  const int getCommandId = s.contextVars ? s.contextDomain : s.commandId - 0x30;
752  std::set<std::string> objIDs;
753  if (s.contextVars) {
754  PositionVector shape;
755  if (!findObjectShape(s.commandId, s.id, shape)) {
756  return false;
757  }
758  collectObjectsInRange(s.contextDomain, shape, s.range, objIDs);
759  } else {
760  objIDs.insert(s.id);
761  }
762  const int numVars = s.contextVars && s.variables.size() == 1 && s.variables[0] == ID_LIST ? 0 : (int)s.variables.size();
763  for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
764  if (s.contextVars) {
765  outputStorage.writeString(*j);
766  }
767  if (numVars > 0) {
768  std::vector<std::vector<unsigned char> >::const_iterator k = s.parameters.begin();
769  for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i, ++k) {
770  tcpip::Storage message;
771  message.writeUnsignedByte(*i);
772  message.writeString(*j);
773  message.writePacket(*k);
774  tcpip::Storage tmpOutput;
775  if (myExecutors.find(getCommandId) != myExecutors.end()) {
776  ok &= myExecutors[getCommandId](*this, message, tmpOutput);
777  } else {
778  writeStatusCmd(s.commandId, RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
779  ok = false;
780  }
781  // copy response part
782  if (ok) {
783  int length = tmpOutput.readUnsignedByte();
784  while (--length > 0) {
785  tmpOutput.readUnsignedByte();
786  }
787  int lengthLength = 1;
788  length = tmpOutput.readUnsignedByte();
789  if (length == 0) {
790  lengthLength = 5;
791  length = tmpOutput.readInt();
792  }
793  //read responseType
794  tmpOutput.readUnsignedByte();
795  int variable = tmpOutput.readUnsignedByte();
796  std::string id = tmpOutput.readString();
797  outputStorage.writeUnsignedByte(variable);
798  outputStorage.writeUnsignedByte(RTYPE_OK);
799  length -= (lengthLength + 1 + 4 + (int)id.length());
800  while (--length > 0) {
801  outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
802  }
803  } else {
804  //read length
805  tmpOutput.readUnsignedByte();
806  //read cmd
807  tmpOutput.readUnsignedByte();
808  //read status
809  tmpOutput.readUnsignedByte();
810  std::string msg = tmpOutput.readString();
811  outputStorage.writeUnsignedByte(*i);
812  outputStorage.writeUnsignedByte(RTYPE_ERR);
813  outputStorage.writeUnsignedByte(TYPE_STRING);
814  outputStorage.writeString(msg);
815  errors = errors + msg;
816  }
817  }
818  }
819  }
820  unsigned int length = (1 + 4) + 1 + (4 + (int)(s.id.length())) + 1 + (int)outputStorage.size();
821  if (s.contextVars) {
822  length += 4;
823  }
824  writeInto.writeUnsignedByte(0); // command length -> extended
825  writeInto.writeInt(length);
826  writeInto.writeUnsignedByte(s.commandId + 0x10);
827  writeInto.writeString(s.id);
828  if (s.contextVars) {
829  writeInto.writeUnsignedByte(s.contextDomain);
830  }
831  writeInto.writeUnsignedByte(numVars);
832  if (s.contextVars) {
833  writeInto.writeInt((int)objIDs.size());
834  }
835  if (!s.contextVars || objIDs.size() != 0) {
836  writeInto.writeStorage(outputStorage);
837  }
838  return ok;
839 }
840 
841 
842 bool
843 TraCIServer::addObjectVariableSubscription(const int commandId, const bool hasContext) {
844  const SUMOTime beginTime = myInputStorage.readInt();
845  const SUMOTime endTime = myInputStorage.readInt();
846  const std::string id = myInputStorage.readString();
847  const int domain = hasContext ? myInputStorage.readUnsignedByte() : 0;
848  const SUMOReal range = hasContext ? myInputStorage.readDouble() : 0.;
849  const int num = myInputStorage.readUnsignedByte();
850  std::vector<int> variables;
851  std::vector<std::vector<unsigned char> > parameters;
852  for (int i = 0; i < num; ++i) {
853  const int varID = myInputStorage.readUnsignedByte();
854  variables.push_back(varID);
855  parameters.push_back(std::vector<unsigned char>());
856  for (int j = 0; j < myParameterSizes[varID]; j++) {
857  parameters.back().push_back(myInputStorage.readChar());
858  }
859  }
860  // check subscribe/unsubscribe
861  if (variables.size() == 0) {
862  removeSubscription(commandId, id, -1);
863  return true;
864  }
865  // process subscription
866  Subscription s(commandId, id, variables, parameters, beginTime, endTime, hasContext, domain, range);
868  return true;
869 }
870 
871 
872 void
874  if (tempMsg.size() < 254) {
875  outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
876  } else {
877  outputStorage.writeUnsignedByte(0); // command length -> extended
878  outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
879  }
880  outputStorage.writeStorage(tempMsg);
881 }
882 
883 
884 bool
886  if (inputStorage.readUnsignedByte() != TYPE_INTEGER) {
887  return false;
888  }
889  into = inputStorage.readInt();
890  return true;
891 }
892 
893 
894 bool
896  if (inputStorage.readUnsignedByte() != TYPE_DOUBLE) {
897  return false;
898  }
899  into = inputStorage.readDouble();
900  return true;
901 }
902 
903 
904 bool
905 TraCIServer::readTypeCheckingString(tcpip::Storage& inputStorage, std::string& into) {
906  if (inputStorage.readUnsignedByte() != TYPE_STRING) {
907  return false;
908  }
909  into = inputStorage.readString();
910  return true;
911 }
912 
913 
914 bool
915 TraCIServer::readTypeCheckingStringList(tcpip::Storage& inputStorage, std::vector<std::string>& into) {
916  if (inputStorage.readUnsignedByte() != TYPE_STRINGLIST) {
917  return false;
918  }
919  into = inputStorage.readStringList();
920  return true;
921 }
922 
923 
924 bool
926  if (inputStorage.readUnsignedByte() != TYPE_COLOR) {
927  return false;
928  }
929  unsigned char r = static_cast<unsigned char>(inputStorage.readUnsignedByte());
930  unsigned char g = static_cast<unsigned char>(inputStorage.readUnsignedByte());
931  unsigned char b = static_cast<unsigned char>(inputStorage.readUnsignedByte());
932  unsigned char a = static_cast<unsigned char>(inputStorage.readUnsignedByte());
933  into.set(r, g, b, a);
934  return true;
935 }
936 
937 
938 bool
940  if (inputStorage.readUnsignedByte() != POSITION_2D) {
941  return false;
942  }
943  SUMOReal x = inputStorage.readDouble();
944  SUMOReal y = inputStorage.readDouble();
945  into.set(x, y, 0);
946  return true;
947 }
948 
949 
950 bool
952  if (inputStorage.readUnsignedByte() != TYPE_BOUNDINGBOX) {
953  return false;
954  }
955  const SUMOReal xmin = inputStorage.readDouble();
956  const SUMOReal ymin = inputStorage.readDouble();
957  const SUMOReal xmax = inputStorage.readDouble();
958  const SUMOReal ymax = inputStorage.readDouble();
959  into.set(xmin, ymin, xmax, ymax);
960  return true;
961 }
962 
963 
964 bool
966  if (inputStorage.readUnsignedByte() != TYPE_BYTE) {
967  return false;
968  }
969  into = inputStorage.readByte();
970  return true;
971 }
972 
973 
974 bool
976  if (inputStorage.readUnsignedByte() != TYPE_UBYTE) {
977  return false;
978  }
979  into = inputStorage.readUnsignedByte();
980  return true;
981 }
982 
983 
984 bool
986  if (inputStorage.readUnsignedByte() != TYPE_POLYGON) {
987  return false;
988  }
989  into.clear();
990  unsigned int noEntries = inputStorage.readUnsignedByte();
991  PositionVector shape;
992  for (unsigned int i = 0; i < noEntries; ++i) {
993  SUMOReal x = inputStorage.readDouble();
994  SUMOReal y = inputStorage.readDouble();
995  into.push_back(Position(x, y));
996  }
997  return true;
998 }
999 
1000 #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:487
bool myDoingSimStep
Whether a step is currently done.
Definition: TraCIServer.h:320
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:307
#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
bool contextVars
Whether the subscription is a context subscription (variable subscription otherwise) ...
Definition: TraCIServer.h:368
#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:723
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:362
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:495
#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:892
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:364
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:316
#define TYPE_POLYGON
void accept()
Wait for a incoming connection to port_.
Definition: socket.cpp:223
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'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:159
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc6: Change Route State)
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:313
#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:337
std::vector< const MSEdge * > ConstMSEdgeVector
Definition: MSEdge.h:79
#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:235
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:715
#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:67
#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's position.
static bool getPosition(const std::string &id, Position &p)
Returns the named persons's position.
static bool myDoCloseConnection
Whether the connection was set to be to close.
Definition: TraCIServer.h:304
void postProcessVTD()
The vehicles starts to stop.
Definition: MSNet.h:501
std::map< int, CmdExecutor > myExecutors
Map of commandIds -> their executors; applicable if the executor applies to the method footprint...
Definition: TraCIServer.h:326
#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:240
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)
#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
#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:495
The vehicle arrived at his destination (is deleted)
Definition: MSNet.h:493
StorageType::const_iterator end() const
Definition: storage.h:118
The vehicles starts to park.
Definition: MSNet.h:497
int commandId
commandIdArg The command id of the subscription
Definition: TraCIServer.h:356
void setVTDControlled(bool c, MSLane *l, SUMOReal pos, int edgeOffset, const ConstMSEdgeVector &route, SUMOTime t)
Definition: MSVehicle.h:1004
std::vector< Subscription > mySubscriptions
The list of known, still valid subscriptions.
Definition: TraCIServer.h:377
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:372
virtual int readInt()
bool commandCloseConnection()
Indicates the connection as being closed.
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:358
#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:360
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition: MSNet.h:288
#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:48
void postProcessSimulationStep2()
Handles subscriptions to send after a simstep2 command.
The vehicle started to teleport.
Definition: MSNet.h:489
#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:71
#define CMD_SET_POI_VARIABLE
#define CMD_SUBSCRIBE_POLYGON_VARIABLE
static TraCIServer * myInstance
Singleton instance of the server.
Definition: TraCIServer.h:301
static bool getPosition(const std::string &id, Position &p)
Returns the named PoI's position.
TraCIServer(const SUMOTime begin, const int port=0)
Constructor.
#define CMD_SUBSCRIBE_TL_CONTEXT
The vehicle ends to park.
Definition: MSNet.h:499
#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:53
TraCI server used to control sumo by a remote TraCI client.
Definition: TraCIServer.h:74
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_VEHICLETYPE_VARIABLE
void writeResponseWithLength(tcpip::Storage &outputStorage, tcpip::Storage &tempMsg)
#define VERSION_STRING
Definition: config.h:230
VehicleState
Definition of a vehicle state.
Definition: MSNet.h:483
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:323
void setVTDControlled(MSVehicle *v, MSLane *l, SUMOReal pos, int edgeOffset, ConstMSEdgeVector route, SUMOTime t)
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:485
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:205
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:386
static bool processSet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a set value command (Command 0xc5: Change Vehicle Type State)
void push_back(const PositionVector &p)
Appends all positions from the given vector.
Allows to store the object; used as context while traveling the rtree in TraCI.
Definition: Named.h:92
#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:200
static bool getShape(const std::string &id, PositionVector &shape)
Returns the named edge's shape.
virtual void writeString(const std::string &s)
#define RTYPE_NOTIMPLEMENTED
Influencer & getInfluencer()
Returns the velocity/lane influencer.
Definition: MSVehicle.cpp:2510
#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:63
static bool getPosition(const std::string &id, Position &p)
Returns the named junction's position.
#define CMD_SUBSCRIBE_VEHICLE_VARIABLE
#define CMD_SUBSCRIBE_PERSON_CONTEXT
void sendExact(const Storage &)
Definition: socket.cpp:396
#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:310
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:503
int SUMOTime
Definition: SUMOTime.h:43
#define LANE_RTREE_QUAL
std::map< int, NamedRTree * > myObjects
A storage of objects.
Definition: TraCIServer.h:383
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:331
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:768
#define CMD_SUBSCRIBE_TL_VARIABLE
#define SUMOReal
Definition: config.h:218
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 DELTA_T
Definition: SUMOTime.h:50
#define CMD_SET_PERSON_VARIABLE
void simulationStep()
Performs a single simulation step.
Definition: MSNet.cpp:387
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:370
#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:380
The vehicle ended being teleported.
Definition: MSNet.h:491
virtual const std::string & getID() const =0
Get the vehicle's ID.
virtual int readByte()
static bool getShape(const std::string &id, PositionVector &shape)
Returns the named polygons's shape.
bool readTypeCheckingByte(tcpip::Storage &inputStorage, int &into)
Reads the value type and a byte, verifying the type.
void close()
Definition: socket.cpp:347
SUMOTime endTime
The end time of the subscription.
Definition: TraCIServer.h:366
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'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:329