SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TraCIServer.cpp
Go to the documentation of this file.
1 /****************************************************************************/
16 /****************************************************************************/
17 // SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
18 // Copyright (C) 2001-2014 DLR (http://www.dlr.de/) and contributors
19 /****************************************************************************/
20 //
21 // This file is part of SUMO.
22 // SUMO is free software: you can redistribute it and/or modify
23 // it under the terms of the GNU General Public License as published by
24 // the Free Software Foundation, either version 3 of the License, or
25 // (at your option) any later version.
26 //
27 /****************************************************************************/
28 
29 // ===========================================================================
30 // included modules
31 // ===========================================================================
32 #ifdef _MSC_VER
33 #include <windows_config.h>
34 #else
35 #include <config.h>
36 #endif
37 
38 #ifdef HAVE_VERSION_H
39 #include <version.h>
40 #endif
41 
42 #ifndef NO_TRACI
43 
44 #ifdef HAVE_PYTHON
45 #include <Python.h>
46 #endif
47 
48 #include <string>
49 #include <map>
50 #include <iostream>
51 #include <foreign/tcpip/socket.h>
52 #include <foreign/tcpip/storage.h>
53 #include <utils/common/SUMOTime.h>
61 #include <utils/shapes/Polygon.h>
62 #include <utils/xml/XMLSubSys.h>
63 #include <microsim/MSNet.h>
65 #include <microsim/MSVehicle.h>
66 #include <microsim/MSEdge.h>
68 #include <microsim/MSJunction.h>
69 #include <microsim/MSEdgeControl.h>
70 #include <microsim/MSLane.h>
71 #include <microsim/MSGlobals.h>
73 #include "TraCIConstants.h"
74 #include "TraCIServer.h"
77 #include "TraCIServerAPI_Lane.h"
80 
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 
90 #ifdef CHECK_MEMORY_LEAKS
91 #include <foreign/nvwa/debug_new.h>
92 #endif // CHECK_MEMORY_LEAKS
93 
94 
95 // ===========================================================================
96 // static member definitions
97 // ===========================================================================
100 
101 
102 // ===========================================================================
103 // method definitions
104 // ===========================================================================
105 TraCIServer::TraCIServer(const SUMOTime begin, const int port)
106  : mySocket(0), myTargetTime(begin), myDoingSimStep(false), myAmEmbedded(port == 0), myLaneTree(0) {
107 
108  myVehicleStateChanges[MSNet::VEHICLE_STATE_BUILT] = std::vector<std::string>();
109  myVehicleStateChanges[MSNet::VEHICLE_STATE_DEPARTED] = std::vector<std::string>();
110  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_TELEPORT] = std::vector<std::string>();
111  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_TELEPORT] = std::vector<std::string>();
112  myVehicleStateChanges[MSNet::VEHICLE_STATE_ARRIVED] = std::vector<std::string>();
113  myVehicleStateChanges[MSNet::VEHICLE_STATE_NEWROUTE] = std::vector<std::string>();
114  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_PARKING] = std::vector<std::string>();
115  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_PARKING] = std::vector<std::string>();
116  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_STOP] = std::vector<std::string>();
117  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_STOP] = std::vector<std::string>();
119 
123 
143 
145 
146  myDoCloseConnection = false;
147 
148  // display warning if internal lanes are not used
150  WRITE_WARNING("Starting TraCI without using internal lanes!");
151  MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
152  MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
153  }
154 
155  if (!myAmEmbedded) {
156  try {
157  WRITE_MESSAGE("***Starting server on port " + toString(port) + " ***");
158  mySocket = new tcpip::Socket(port);
159  mySocket->accept();
160  // When got here, a client has connected
161  } catch (tcpip::SocketException& e) {
162  throw ProcessError(e.what());
163  }
164  }
165 }
166 
167 
170  if (mySocket != NULL) {
171  mySocket->close();
172  delete mySocket;
173  }
174  for (std::map<int, NamedRTree*>::const_iterator i = myObjects.begin(); i != myObjects.end(); ++i) {
175  delete(*i).second;
176  }
177  delete myLaneTree;
178 }
179 
180 
181 // ---------- Initialisation and Shutdown
182 void
183 TraCIServer::openSocket(const std::map<int, CmdExecutor>& execs) {
184  if (myInstance == 0) {
185  if (!myDoCloseConnection && OptionsCont::getOptions().getInt("remote-port") != 0) {
186  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")),
187  OptionsCont::getOptions().getInt("remote-port"));
188  for (std::map<int, CmdExecutor>::const_iterator i = execs.begin(); i != execs.end(); ++i) {
189  myInstance->myExecutors[i->first] = i->second;
190  }
191  }
192  }
193 }
194 
195 
196 void
198  if (myInstance != 0) {
199  delete myInstance;
200  myInstance = 0;
201  myDoCloseConnection = true;
202  }
203 }
204 
205 
206 bool
208  return myDoCloseConnection;
209 }
210 
211 
212 void
214  myVTDControlledVehicles[v->getID()] = v;
215  v->getInfluencer().setVTDControlled(true, l, pos, edgeOffset, route);
216 }
217 
218 void
220  for (std::map<std::string, MSVehicle*>::const_iterator i = myVTDControlledVehicles.begin(); i != myVTDControlledVehicles.end(); ++i) {
221  if (MSNet::getInstance()->getVehicleControl().getVehicle((*i).first) != 0) {
222  (*i).second->getInfluencer().postProcessVTD((*i).second);
223  } else {
224  WRITE_WARNING("Vehicle '" + (*i).first + "' was removed though being controlled by VTD");
225  }
226  }
227  myVTDControlledVehicles.clear();
228 }
229 
230 
231 bool
233  return true;
234 }
235 
236 
237 // ---------- Initialisation and Shutdown
238 
239 
240 void
242  if (!myDoCloseConnection) {
243  myVehicleStateChanges[to].push_back(vehicle->getID());
244  }
245 }
246 
247 
248 void
250  try {
251  if (myInstance == 0) {
252  if (!myDoCloseConnection && OptionsCont::getOptions().getInt("remote-port") != 0) {
253  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")),
254  OptionsCont::getOptions().getInt("remote-port"));
255  } else {
256  return;
257  }
258  }
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  if (myInstance != NULL) {
308  delete myInstance;
309  myInstance = 0;
310  myDoCloseConnection = true;
311  }
312 }
313 
314 
315 
316 
317 #ifdef HAVE_PYTHON
318 // ===========================================================================
319 // python functions (traciemb module)
320 // ===========================================================================
321 static PyObject*
322 traciemb_execute(PyObject* /* self */, PyObject* args) {
323  const char* msg;
324  int size;
325  if (!PyArg_ParseTuple(args, "s#", &msg, &size)) {
326  return NULL;
327  }
328  std::string result = TraCIServer::execute(std::string(msg, size));
329  return Py_BuildValue("s#", result.c_str(), result.size());
330 }
331 
332 static PyMethodDef EmbMethods[] = {
333  {
334  "execute", traciemb_execute, METH_VARARGS,
335  "Execute the given TraCI command and return the result."
336  },
337  {NULL, NULL, 0, NULL}
338 };
339 
340 
341 std::string
342 TraCIServer::execute(std::string cmd) {
343  try {
344  if (myInstance == 0) {
345  if (!myDoCloseConnection) {
346  myInstance = new TraCIServer(string2time(OptionsCont::getOptions().getString("begin")));
347  } else {
348  return "";
349  }
350  }
353  for (std::string::iterator i = cmd.begin(); i != cmd.end(); ++i) {
355  }
357  return std::string(myInstance->myOutputStorage.begin(), myInstance->myOutputStorage.end());
358  } catch (std::invalid_argument& e) {
359  throw ProcessError(e.what());
360  } catch (TraCIException& e) {
361  throw ProcessError(e.what());
362  } catch (tcpip::SocketException& e) {
363  throw ProcessError(e.what());
364  }
365 }
366 
367 
368 void
369 TraCIServer::runEmbedded(std::string pyFile) {
370  PyObject* pName, *pModule;
371  Py_Initialize();
372  Py_InitModule("traciemb", EmbMethods);
373  if (pyFile.length() > 3 && !pyFile.compare(pyFile.length() - 3, 3, ".py")) {
374  PyObject* sys_path, *path;
375  char pathstr[] = "path";
376  sys_path = PySys_GetObject(pathstr);
377  if (sys_path == NULL || !PyList_Check(sys_path)) {
378  throw ProcessError("Could not access python sys.path!");
379  }
380  path = PyString_FromString(FileHelpers::getFilePath(pyFile).c_str());
381  PyList_Insert(sys_path, 0, path);
382  Py_DECREF(path);
383  FILE* pFile = fopen(pyFile.c_str(), "r");
384  if (pFile == NULL) {
385  throw ProcessError("Failed to load \"" + pyFile + "\"!");
386  }
387  PyRun_SimpleFile(pFile, pyFile.c_str());
388  fclose(pFile);
389  } else {
390  pName = PyString_FromString(pyFile.c_str());
391  /* Error checking of pName left out */
392  pModule = PyImport_Import(pName);
393  Py_DECREF(pName);
394  if (pModule == NULL) {
395  PyErr_Print();
396  throw ProcessError("Failed to load \"" + pyFile + "\"!");
397  }
398  }
399  Py_Finalize();
400 }
401 #endif
402 
403 
404 int
406  unsigned int commandStart = myInputStorage.position();
407  unsigned int commandLength = myInputStorage.readUnsignedByte();
408  if (commandLength == 0) {
409  commandLength = myInputStorage.readInt();
410  }
411 
412  int commandId = myInputStorage.readUnsignedByte();
413  bool success = false;
414  // dispatch commands
415  if (myExecutors.find(commandId) != myExecutors.end()) {
416  success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
417  } else {
418  switch (commandId) {
419  case CMD_GETVERSION:
420  success = commandGetVersion();
421  break;
422  case CMD_SIMSTEP2: {
423  SUMOTime nextT = myInputStorage.readInt();
424  success = true;
425  if (nextT != 0) {
426  myTargetTime = nextT;
427  } else {
429  }
430  if (myAmEmbedded) {
433  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
434  (*i).second.clear();
435  }
436  }
437  return commandId;
438  }
439  case CMD_CLOSE:
440  success = commandCloseConnection();
441  break;
455  success = addObjectVariableSubscription(commandId, false);
456  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 bool
515  myDoCloseConnection = true;
516  // write answer
518  return true;
519 }
520 
521 
522 void
526  int noActive = 0;
527  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
528  const Subscription& s = *i;
531  if ((s.endTime < t) || isArrivedVehicle) {
532  i = mySubscriptions.erase(i);
533  continue;
534  }
535  ++i;
536  if (s.beginTime > t) {
537  continue;
538  }
539  ++noActive;
540  }
541  myOutputStorage.writeInt(noActive);
542  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
543  const Subscription& s = *i;
544  if (s.beginTime > t) {
545  ++i;
546  continue;
547  }
548  tcpip::Storage into;
549  std::string errors;
550  bool ok = processSingleSubscription(s, into, errors);
552  if (ok) {
553  ++i;
554  } else {
555  i = mySubscriptions.erase(i);
556  }
557  }
558 }
559 
560 
561 void
562 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
563  writeStatusCmd(commandId, status, description, myOutputStorage);
564 }
565 
566 
567 void
568 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
569  if (status == RTYPE_ERR) {
570  WRITE_ERROR("Answered with error to command " + toHex(commandId, 2) + ": " + description);
571  } else if (status == RTYPE_NOTIMPLEMENTED) {
572  WRITE_ERROR("Requested command not implemented (" + toHex(commandId, 2) + "): " + description);
573  }
574  outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
575  outputStorage.writeUnsignedByte(commandId); // command type
576  outputStorage.writeUnsignedByte(status); // status
577  outputStorage.writeString(description); // description
578 }
579 
580 
581 bool
582 TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
583  writeStatusCmd(commandId, RTYPE_ERR, description, outputStorage);
584  return false;
585 }
586 
587 
588 void
590  tcpip::Storage writeInto;
591  std::string errors;
592  if (processSingleSubscription(s, writeInto, errors)) {
594  writeStatusCmd(s.commandId, RTYPE_ERR, "Subscription has ended.");
595  } else {
596  mySubscriptions.push_back(s);
598  }
599  } else {
600  writeStatusCmd(s.commandId, RTYPE_ERR, "Could not add subscription (" + errors + ").");
601  }
602  myOutputStorage.writeStorage(writeInto);
603 }
604 
605 
606 void
607 TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
608  bool found = false;
609  for (std::vector<Subscription>::iterator j = mySubscriptions.begin(); j != mySubscriptions.end();) {
610  if ((*j).id == id && (*j).commandId == commandId && (domain < 0 || (*j).contextDomain == domain)) {
611  j = mySubscriptions.erase(j);
612  found = true;
613  continue;
614  }
615  ++j;
616  }
617  // try unsubscribe
618  if (found) {
619  writeStatusCmd(commandId, RTYPE_OK, "");
620  } else {
621  writeStatusCmd(commandId, RTYPE_OK, "The subscription to remove was not found.");
622  }
623 }
624 
625 
626 bool
627 TraCIServer::findObjectShape(int domain, const std::string& id, PositionVector& shape) {
628  Position p;
629  switch (domain) {
632  shape.push_back(p);
633  return true;
634  }
635  break;
637  break;
639  break;
641  if (TraCIServerAPI_Lane::getShape(id, shape)) {
642  return true;
643  }
644  break;
647  shape.push_back(p);
648  return true;
649  }
650  break;
652  break;
654  break;
656  if (TraCIServerAPI_POI::getPosition(id, p)) {
657  shape.push_back(p);
658  return true;
659  }
660  return false;
662  if (TraCIServerAPI_Polygon::getShape(id, shape)) {
663  return true;
664  }
665  break;
668  shape.push_back(p);
669  return true;
670  }
671  break;
673  if (TraCIServerAPI_Edge::getShape(id, shape)) {
674  return true;
675  }
676  break;
678  return false;
680  break;
681  default:
682  break;
683  }
684  return false;
685 }
686 
687 void
688 TraCIServer::collectObjectsInRange(int domain, const PositionVector& shape, SUMOReal range, std::set<std::string>& into) {
689  // build the look-up tree if not yet existing
690  if (myObjects.find(domain) == myObjects.end()) {
691  switch (domain) {
694  break;
703  break;
706  break;
709  break;
712  break;
713  default:
714  break;
715  }
716  }
717  const Boundary b = shape.getBoxBoundary().grow(range);
718  const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
719  const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
720  switch (domain) {
725  Named::StoringVisitor sv(into);
726  myObjects[domain]->Search(cmin, cmax, sv);
727  }
728  break;
732  TraCIServerAPI_Lane::StoringVisitor sv(into, shape, range, domain);
733  myLaneTree->Search(cmin, cmax, sv);
734  }
735  break;
736  default:
737  break;
738  }
739 }
740 
741 
742 bool
744  std::string& errors) {
745  bool ok = true;
746  tcpip::Storage outputStorage;
747  const int getCommandId = s.contextVars ? s.contextDomain : s.commandId - 0x30;
748  std::set<std::string> objIDs;
749  if (s.contextVars) {
750  PositionVector shape;
751  if (!findObjectShape(s.commandId, s.id, shape)) {
752  return false;
753  }
754  collectObjectsInRange(s.contextDomain, shape, s.range, objIDs);
755  } else {
756  objIDs.insert(s.id);
757  }
758  const int numVars = s.contextVars && s.variables.size() == 1 && s.variables[0] == ID_LIST ? 0 : (int)s.variables.size();
759  for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
760  if (s.contextVars) {
761  outputStorage.writeString(*j);
762  }
763  if (numVars > 0) {
764  std::vector<std::vector<unsigned char> >::const_iterator k = s.parameters.begin();
765  for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i, ++k) {
766  tcpip::Storage message;
767  message.writeUnsignedByte(*i);
768  message.writeString(*j);
769  message.writePacket(*k);
770  tcpip::Storage tmpOutput;
771  if (myExecutors.find(getCommandId) != myExecutors.end()) {
772  ok &= myExecutors[getCommandId](*this, message, tmpOutput);
773  } else {
774  writeStatusCmd(s.commandId, RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
775  ok = false;
776  }
777  // copy response part
778  if (ok) {
779  int length = tmpOutput.readUnsignedByte();
780  while (--length > 0) {
781  tmpOutput.readUnsignedByte();
782  }
783  int lengthLength = 1;
784  length = tmpOutput.readUnsignedByte();
785  if (length == 0) {
786  lengthLength = 5;
787  length = tmpOutput.readInt();
788  }
789  //read responseType
790  tmpOutput.readUnsignedByte();
791  int variable = tmpOutput.readUnsignedByte();
792  std::string id = tmpOutput.readString();
793  outputStorage.writeUnsignedByte(variable);
794  outputStorage.writeUnsignedByte(RTYPE_OK);
795  length -= (lengthLength + 1 + 4 + (int)id.length());
796  while (--length > 0) {
797  outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
798  }
799  } else {
800  //read length
801  tmpOutput.readUnsignedByte();
802  //read cmd
803  tmpOutput.readUnsignedByte();
804  //read status
805  tmpOutput.readUnsignedByte();
806  std::string msg = tmpOutput.readString();
807  outputStorage.writeUnsignedByte(*i);
808  outputStorage.writeUnsignedByte(RTYPE_ERR);
809  outputStorage.writeUnsignedByte(TYPE_STRING);
810  outputStorage.writeString(msg);
811  errors = errors + msg;
812  }
813  }
814  }
815  }
816  unsigned int length = (1 + 4) + 1 + (4 + (int)(s.id.length())) + 1 + (int)outputStorage.size();
817  if (s.contextVars) {
818  length += 4;
819  }
820  writeInto.writeUnsignedByte(0); // command length -> extended
821  writeInto.writeInt(length);
822  writeInto.writeUnsignedByte(s.commandId + 0x10);
823  writeInto.writeString(s.id);
824  if (s.contextVars) {
825  writeInto.writeUnsignedByte(s.contextDomain);
826  }
827  writeInto.writeUnsignedByte(numVars);
828  if (s.contextVars) {
829  writeInto.writeInt((int)objIDs.size());
830  }
831  if (!s.contextVars || objIDs.size() != 0) {
832  writeInto.writeStorage(outputStorage);
833  }
834  return ok;
835 }
836 
837 
838 bool
839 TraCIServer::addObjectVariableSubscription(const int commandId, const bool hasContext) {
840  const SUMOTime beginTime = myInputStorage.readInt();
841  const SUMOTime endTime = myInputStorage.readInt();
842  const std::string id = myInputStorage.readString();
843  const int domain = hasContext ? myInputStorage.readUnsignedByte() : 0;
844  const SUMOReal range = hasContext ? myInputStorage.readDouble() : 0.;
845  const int num = myInputStorage.readUnsignedByte();
846  std::vector<int> variables;
847  std::vector<std::vector<unsigned char> > parameters;
848  for (int i = 0; i < num; ++i) {
849  const int varID = myInputStorage.readUnsignedByte();
850  variables.push_back(varID);
851  parameters.push_back(std::vector<unsigned char>());
852  for (int j = 0; j < myParameterSizes[varID]; j++) {
853  parameters.back().push_back(myInputStorage.readChar());
854  }
855  }
856  // check subscribe/unsubscribe
857  if (variables.size() == 0) {
858  removeSubscription(commandId, id, -1);
859  return true;
860  }
861  // process subscription
862  Subscription s(commandId, id, variables, parameters, beginTime, endTime, hasContext, domain, range);
864  return true;
865 }
866 
867 
868 void
870  if (tempMsg.size() < 254) {
871  outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
872  } else {
873  outputStorage.writeUnsignedByte(0); // command length -> extended
874  outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
875  }
876  outputStorage.writeStorage(tempMsg);
877 }
878 
879 
880 bool
882  if (inputStorage.readUnsignedByte() != TYPE_INTEGER) {
883  return false;
884  }
885  into = inputStorage.readInt();
886  return true;
887 }
888 
889 
890 bool
892  if (inputStorage.readUnsignedByte() != TYPE_DOUBLE) {
893  return false;
894  }
895  into = inputStorage.readDouble();
896  return true;
897 }
898 
899 
900 bool
901 TraCIServer::readTypeCheckingString(tcpip::Storage& inputStorage, std::string& into) {
902  if (inputStorage.readUnsignedByte() != TYPE_STRING) {
903  return false;
904  }
905  into = inputStorage.readString();
906  return true;
907 }
908 
909 
910 bool
911 TraCIServer::readTypeCheckingStringList(tcpip::Storage& inputStorage, std::vector<std::string>& into) {
912  if (inputStorage.readUnsignedByte() != TYPE_STRINGLIST) {
913  return false;
914  }
915  into = inputStorage.readStringList();
916  return true;
917 }
918 
919 
920 bool
922  if (inputStorage.readUnsignedByte() != TYPE_COLOR) {
923  return false;
924  }
925  unsigned char r = static_cast<unsigned char>(inputStorage.readUnsignedByte());
926  unsigned char g = static_cast<unsigned char>(inputStorage.readUnsignedByte());
927  unsigned char b = static_cast<unsigned char>(inputStorage.readUnsignedByte());
928  unsigned char a = static_cast<unsigned char>(inputStorage.readUnsignedByte());
929  into.set(r, g, b, a);
930  return true;
931 }
932 
933 
934 bool
936  if (inputStorage.readUnsignedByte() != POSITION_2D) {
937  return false;
938  }
939  SUMOReal x = inputStorage.readDouble();
940  SUMOReal y = inputStorage.readDouble();
941  into.set(x, y, 0);
942  return true;
943 }
944 
945 
946 bool
948  if (inputStorage.readUnsignedByte() != TYPE_BOUNDINGBOX) {
949  return false;
950  }
951  const SUMOReal xmin = inputStorage.readDouble();
952  const SUMOReal ymin = inputStorage.readDouble();
953  const SUMOReal xmax = inputStorage.readDouble();
954  const SUMOReal ymax = inputStorage.readDouble();
955  into.set(xmin, ymin, xmax, ymax);
956  return true;
957 }
958 
959 
960 bool
962  if (inputStorage.readUnsignedByte() != TYPE_BYTE) {
963  return false;
964  }
965  into = inputStorage.readByte();
966  return true;
967 }
968 
969 
970 bool
972  if (inputStorage.readUnsignedByte() != TYPE_UBYTE) {
973  return false;
974  }
975  into = inputStorage.readUnsignedByte();
976  return true;
977 }
978 
979 
980 bool
982  if (inputStorage.readUnsignedByte() != TYPE_POLYGON) {
983  return false;
984  }
985  into.clear();
986  unsigned int noEntries = inputStorage.readUnsignedByte();
987  PositionVector shape;
988  for (unsigned int i = 0; i < noEntries; ++i) {
989  SUMOReal x = inputStorage.readDouble();
990  SUMOReal y = inputStorage.readDouble();
991  into.push_back(Position(x, y));
992  }
993  return true;
994 }
995 
996 #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:421
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:77
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:668
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:869
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)
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:154
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
#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:210
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:660
#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:196
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 myDoCloseConnection
Whether the connection was set to be to close.
Definition: TraCIServer.h:304
void postProcessVTD()
The vehicles starts to stop.
Definition: MSNet.h:435
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:429
The vehicle arrived at his destination (is deleted)
Definition: MSNet.h:427
StorageType::const_iterator end() const
Definition: storage.h:118
The vehicles starts to park.
Definition: MSNet.h:431
int commandId
commandIdArg The command id of the subscription
Definition: TraCIServer.h:356
std::vector< Subscription > mySubscriptions
The list of known, still valid subscriptions.
Definition: TraCIServer.h:377
Representation of a vehicle.
Definition: SUMOVehicle.h:63
SUMOReal range
The range of the context.
Definition: TraCIServer.h:372
virtual int readInt()
bool commandCloseConnection()
Indicates the connection as being closed.
std::vector< const MSEdge * > MSEdgeVector
Definition: MSPerson.h:53
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:85
A list of positions.
std::vector< int > variables
The subscribed variables.
Definition: TraCIServer.h:360
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition: MSNet.h:263
#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.
void setVTDControlled(bool c, MSLane *l, SUMOReal pos, int edgeOffset, const MSEdgeVector &route)
Definition: MSVehicle.h:964
#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:423
#define CMD_GET_SIM_VARIABLE
virtual std::string readString()
void setVTDControlled(MSVehicle *v, MSLane *l, SUMOReal pos, int edgeOffset, MSEdgeVector route)
#define CMD_GET_EDGE_VARIABLE
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition: MSGlobals.h:70
#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:433
#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
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:52
TraCI server used to control sumo by a remote TraCI client.
Definition: TraCIServer.h:74
virtual void writeStorage(tcpip::Storage &store)
#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:227
VehicleState
Definition of a vehicle state.
Definition: MSNet.h:417
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
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:419
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:201
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:2293
#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:62
static bool getPosition(const std::string &id, Position &p)
Returns the named junction's position.
#define CMD_SUBSCRIBE_VEHICLE_VARIABLE
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:437
#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:738
#define CMD_SUBSCRIBE_TL_VARIABLE
#define SUMOReal
Definition: config.h:215
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:75
#define DELTA_T
Definition: SUMOTime.h:50
void simulationStep()
Performs a single simulation step.
Definition: MSNet.cpp:364
static bool processGet(TraCIServer &server, tcpip::Storage &inputStorage, tcpip::Storage &outputStorage)
Processes a get value command (Command 0xa1: Get MeMeDetector Variable)
bool vtdDebug() const
int contextDomain
The domain ID of the context.
Definition: TraCIServer.h:370
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:197
#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:425
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