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.sourceforge.net/
18 // Copyright (C) 2001-2013 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>
63 #include <utils/shapes/Polygon.h>
64 #include <utils/xml/XMLSubSys.h>
65 #include <microsim/MSNet.h>
67 #include <microsim/MSVehicle.h>
68 #include <microsim/MSEdge.h>
70 #include <microsim/MSJunction.h>
71 #include <microsim/MSEdgeControl.h>
72 #include <microsim/MSLane.h>
73 #include <microsim/MSGlobals.h>
75 #include "TraCIConstants.h"
76 #include "TraCIServer.h"
79 #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 
90 #ifdef CHECK_MEMORY_LEAKS
91 #include <foreign/nvwa/debug_new.h>
92 #endif // CHECK_MEMORY_LEAKS
93 
94 
95 // ===========================================================================
96 // used namespaces
97 // ===========================================================================
98 namespace traci {
99 
100 // ===========================================================================
101 // static member definitions
102 // ===========================================================================
103 TraCIServer* TraCIServer::myInstance = 0;
105 
106 
107 // ===========================================================================
108 // method definitions
109 // ===========================================================================
111  : mySocket(0), myTargetTime(0), myDoingSimStep(false), myHaveWarnedDeprecation(false), myAmEmbedded(port == 0) {
112 
113  myVehicleStateChanges[MSNet::VEHICLE_STATE_BUILT] = std::vector<std::string>();
114  myVehicleStateChanges[MSNet::VEHICLE_STATE_DEPARTED] = std::vector<std::string>();
115  myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_TELEPORT] = std::vector<std::string>();
116  myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_TELEPORT] = std::vector<std::string>();
117  myVehicleStateChanges[MSNet::VEHICLE_STATE_ARRIVED] = std::vector<std::string>();
118  myVehicleStateChanges[MSNet::VEHICLE_STATE_NEWROUTE] = std::vector<std::string>();
119  MSNet::getInstance()->addVehicleStateListener(this);
120 
141 
142  myDoCloseConnection = false;
143 
144  // display warning if internal lanes are not used
146  WRITE_WARNING("Starting TraCI without using internal lanes!");
147  MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
148  MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
149  }
150 
151  if (!myAmEmbedded) {
152  try {
153  WRITE_MESSAGE("***Starting server on port " + toString(port) + " ***");
154  mySocket = new tcpip::Socket(port);
155  mySocket->accept();
156  // When got here, a client has connected
157  } catch (tcpip::SocketException& e) {
158  throw ProcessError(e.what());
159  }
160  }
161 }
162 
163 
165  MSNet::getInstance()->removeVehicleStateListener(this);
166  if (mySocket != NULL) {
167  mySocket->close();
168  delete mySocket;
169  }
170  for (std::map<int, TraCIRTree*>::const_iterator i = myObjects.begin(); i != myObjects.end(); ++i) {
171  delete(*i).second;
172  }
173 }
174 
175 
176 // ---------- Initialisation and Shutdown
177 void
178 TraCIServer::openSocket(const std::map<int, CmdExecutor>& execs) {
179  if (myInstance == 0) {
180  if (!myDoCloseConnection && OptionsCont::getOptions().getInt("remote-port") != 0) {
181  myInstance = new traci::TraCIServer(OptionsCont::getOptions().getInt("remote-port"));
182  for (std::map<int, CmdExecutor>::const_iterator i = execs.begin(); i != execs.end(); ++i) {
183  myInstance->myExecutors[i->first] = i->second;
184  }
185  }
186  }
187 }
188 
189 
190 void
192  if (myInstance != 0) {
193  delete myInstance;
194  myInstance = 0;
195  myDoCloseConnection = true;
196  }
197 }
198 
199 
200 bool
202  return myDoCloseConnection;
203 }
204 
205 
206 void
208  myVTDControlledVehicles[v->getID()] = v;
209  v->getInfluencer().setVTDControlled(true, l, pos, edgeOffset, route);
210 }
211 
212 void
214  for (std::map<std::string, MSVehicle*>::const_iterator i = myVTDControlledVehicles.begin(); i != myVTDControlledVehicles.end(); ++i) {
215  if (MSNet::getInstance()->getVehicleControl().getVehicle((*i).first) != 0) {
216  (*i).second->getInfluencer().postProcessVTD((*i).second);
217  } else {
218  WRITE_WARNING("Vehicle '" + (*i).first + "' was removed though being controlled by VTD");
219  }
220  }
221  myVTDControlledVehicles.clear();
222 }
223 
224 
225 bool
227  return true;
228 }
229 
230 
231 // ---------- Initialisation and Shutdown
232 
233 
234 void
236  if (myDoCloseConnection || OptionsCont::getOptions().getInt("remote-port") == 0) {
237  return;
238  }
239  myVehicleStateChanges[to].push_back(vehicle->getID());
240 }
241 
242 
243 void
245  try {
246  if (myInstance == 0) {
247  if (!myDoCloseConnection && OptionsCont::getOptions().getInt("remote-port") != 0) {
248  myInstance = new traci::TraCIServer(OptionsCont::getOptions().getInt("remote-port"));
249  } else {
250  return;
251  }
252  }
253  if (myInstance->myAmEmbedded || step < myInstance->myTargetTime) {
254  return;
255  }
256  // Simulation should run until
257  // 1. end time reached or
258  // 2. got CMD_CLOSE or
259  // 3. Client closes socket connection
260  if (myInstance->myDoingSimStep) {
262  myInstance->myDoingSimStep = false;
263  }
264  while (!myDoCloseConnection) {
266  if (myInstance->myOutputStorage.size() > 0) {
267  // send out all answers as one storage
269  }
272  // Read a message
274  }
276  // dispatch each command
277  int cmd = myInstance->dispatchCommand();
278  if (cmd == CMD_SIMSTEP2) {
279  myInstance->myDoingSimStep = true;
280  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
281  (*i).second.clear();
282  }
283  return;
284  }
285  }
286  }
288  // send out all answers as one storage
290  }
291  for (std::map<MSNet::VehicleState, std::vector<std::string> >::iterator i = myInstance->myVehicleStateChanges.begin(); i != myInstance->myVehicleStateChanges.end(); ++i) {
292  (*i).second.clear();
293  }
294  } catch (std::invalid_argument& e) {
295  throw ProcessError(e.what());
296  } catch (TraCIException& e) {
297  throw ProcessError(e.what());
298  } catch (tcpip::SocketException& e) {
299  throw ProcessError(e.what());
300  }
301  if (myInstance != NULL) {
302  delete myInstance;
303  myInstance = 0;
304  myDoCloseConnection = true;
305  }
306 }
307 
308 
309 
310 
311 #ifdef HAVE_PYTHON
312 // ===========================================================================
313 // python functions (traciemb module)
314 // ===========================================================================
315 static PyObject*
316 traciemb_execute(PyObject* /* self */, PyObject* args) {
317  const char* msg;
318  int size;
319  if (!PyArg_ParseTuple(args, "s#", &msg, &size)) {
320  return NULL;
321  }
322  std::string result = traci::TraCIServer::execute(std::string(msg, size));
323  return Py_BuildValue("s#", result.c_str(), result.size());
324 }
325 
326 static PyMethodDef EmbMethods[] = {
327  {
328  "execute", traciemb_execute, METH_VARARGS,
329  "Execute the given TraCI command and return the result."
330  },
331  {NULL, NULL, 0, NULL}
332 };
333 
334 
335 std::string
336 TraCIServer::execute(std::string cmd) {
337  try {
338  if (myInstance == 0) {
339  if (!myDoCloseConnection) {
341  } else {
342  return "";
343  }
344  }
347  for (std::string::iterator i = cmd.begin(); i != cmd.end(); ++i) {
349  }
351  return std::string(myInstance->myOutputStorage.begin(), myInstance->myOutputStorage.end());
352  } catch (std::invalid_argument& e) {
353  throw ProcessError(e.what());
354  } catch (TraCIException& e) {
355  throw ProcessError(e.what());
356  } catch (tcpip::SocketException& e) {
357  throw ProcessError(e.what());
358  }
359 }
360 
361 
362 void
363 TraCIServer::runEmbedded(std::string pyFile) {
364  PyObject* pName, *pModule;
365  Py_Initialize();
366  Py_InitModule("traciemb", EmbMethods);
367  if (pyFile.length() > 3 && !pyFile.compare(pyFile.length() - 3, 3, ".py")) {
368  FILE* pFile = fopen(pyFile.c_str(), "r");
369  PyRun_SimpleFile(pFile, pyFile.c_str());
370  fclose(pFile);
371  } else {
372  pName = PyString_FromString(pyFile.c_str());
373  /* Error checking of pName left out */
374  pModule = PyImport_Import(pName);
375  Py_DECREF(pName);
376  if (pModule == NULL) {
377  PyErr_Print();
378  throw ProcessError("Failed to load \"" + pyFile + "\"!");
379  }
380  }
381  Py_Finalize();
382 }
383 #endif
384 
385 
386 int
388  unsigned int commandStart = myInputStorage.position();
389  unsigned int commandLength = myInputStorage.readUnsignedByte();
390  if (commandLength == 0) {
391  commandLength = myInputStorage.readInt();
392  }
393 
394  int commandId = myInputStorage.readUnsignedByte();
395  bool success = false;
396  // dispatch commands
397  if (myExecutors.find(commandId) != myExecutors.end()) {
398  success = myExecutors[commandId](*this, myInputStorage, myOutputStorage);
399  } else {
400  switch (commandId) {
401  case CMD_GETVERSION:
402  success = commandGetVersion();
403  break;
404  case CMD_SIMSTEP2: {
405  SUMOTime nextT = myInputStorage.readInt();
406  success = true;
407  if (nextT != 0) {
408  myTargetTime = nextT;
409  } else {
411  }
412  if (myAmEmbedded) {
413  MSNet::getInstance()->simulationStep();
415  }
416  return commandId;
417  }
418  case CMD_CLOSE:
419  success = commandCloseConnection();
420  break;
421  case CMD_ADDVEHICLE:
423  WRITE_WARNING("Using old TraCI API, please update your client!");
425  }
426  success = commandAddVehicle();
427  break;
441  success = addObjectVariableSubscription(commandId);
442  break;
456  success = addObjectContextSubscription(commandId);
457  break;
458  default:
459  writeStatusCmd(commandId, RTYPE_NOTIMPLEMENTED, "Command not implemented in sumo");
460  }
461  }
462  if (!success) {
463  while (myInputStorage.valid_pos() && myInputStorage.position() < commandStart + commandLength) {
465  }
466  }
467  if (myInputStorage.position() != commandStart + commandLength) {
468  std::ostringstream msg;
469  msg << "Wrong position in requestMessage after dispatching command.";
470  msg << " Expected command length was " << commandLength;
471  msg << " but " << myInputStorage.position() - commandStart << " Bytes were read.";
472  writeStatusCmd(commandId, RTYPE_ERR, msg.str());
473  myDoCloseConnection = true;
474  }
475  return commandId;
476 }
477 
478 
479 // ---------- Server-internal command handling
480 bool
482  std::string sumoVersion = VERSION_STRING;
483  // Prepare response
484  tcpip::Storage answerTmp;
485  answerTmp.writeInt(TRACI_VERSION);
486  answerTmp.writeString(std::string("SUMO ") + sumoVersion);
487  // When we get here, the response is stored in answerTmp -> put into myOutputStorage
489  // command length
490  myOutputStorage.writeUnsignedByte(1 + 1 + static_cast<int>(answerTmp.size()));
491  // command type
493  // and the parameter dependant part
494  myOutputStorage.writeStorage(answerTmp);
495  return true;
496 }
497 
498 
499 bool
501  myDoCloseConnection = true;
502  // write answer
503  writeStatusCmd(CMD_CLOSE, RTYPE_OK, "Goodbye");
504  return true;
505 }
506 
507 
508 void
510  SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
512  int noActive = 0;
513  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
514  const Subscription& s = *i;
516  if ((s.endTime < t) || isArrivedVehicle) {
517  i = mySubscriptions.erase(i);
518  continue;
519  }
520  ++i;
521  if (s.beginTime > t) {
522  continue;
523  }
524  ++noActive;
525  }
526  myOutputStorage.writeInt(noActive);
527  for (std::vector<Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end(); ++i) {
528  const Subscription& s = *i;
529  if (s.beginTime > t) {
530  continue;
531  }
532  tcpip::Storage into;
533  std::string errors;
534  processSingleSubscription(s, into, errors);
536  }
537 }
538 
539 
540 bool
542 
543  // read parameters
544  std::string vehicleId = myInputStorage.readString();
545  std::string vehicleTypeId = myInputStorage.readString();
546  std::string routeId = myInputStorage.readString();
547  std::string laneId = myInputStorage.readString();
548  SUMOReal insertionPosition = myInputStorage.readFloat();
549  SUMOReal insertionSpeed = myInputStorage.readFloat();
550 
551  // find vehicleType
552  MSVehicleType* vehicleType = MSNet::getInstance()->getVehicleControl().getVType(vehicleTypeId);
553  if (!vehicleType) {
554  return writeErrorStatusCmd(CMD_ADDVEHICLE, "Invalid vehicleTypeId: '" + vehicleTypeId + "'", myOutputStorage);
555  }
556 
557  // find route
558  const MSRoute* route = MSRoute::dictionary(routeId);
559  if (!route) {
560  return writeErrorStatusCmd(CMD_ADDVEHICLE, "Invalid routeId: '" + routeId + "'", myOutputStorage);
561  }
562 
563  // find lane
564  MSLane* lane;
565  if (laneId != "") {
566  lane = MSLane::dictionary(laneId);
567  if (!lane) {
568  return writeErrorStatusCmd(CMD_ADDVEHICLE, "Invalid laneId: '" + laneId + "'", myOutputStorage);
569  }
570  } else {
571  lane = route->getEdges()[0]->getLanes()[0];
572  if (!lane) {
573  return writeErrorStatusCmd(CMD_STOP, "Could not find first lane of first edge in routeId '" + routeId + "'", myOutputStorage);
574  }
575  }
576 
577  if (&lane->getEdge() != *route->begin()) {
578  return writeErrorStatusCmd(CMD_STOP, "The route must start at the edge the lane starts at.", myOutputStorage);
579  }
580 
581  // build vehicle
582  SUMOVehicleParameter* vehicleParams = new SUMOVehicleParameter();
583  vehicleParams->id = vehicleId;
584  vehicleParams->depart = MSNet::getInstance()->getCurrentTimeStep() + 1;
585  MSVehicle* vehicle = static_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().buildVehicle(vehicleParams, route, vehicleType));
586  if (vehicle == NULL) {
587  return writeErrorStatusCmd(CMD_STOP, "Could not build vehicle", myOutputStorage);
588  }
589 
590  // calculate speed
591  float clippedInsertionSpeed;
592  if (insertionSpeed < 0) {
593  clippedInsertionSpeed = (float) MIN2(lane->getVehicleMaxSpeed(vehicle), vehicle->getMaxSpeed());
594  } else {
595  clippedInsertionSpeed = (float) MIN3(lane->getVehicleMaxSpeed(vehicle), vehicle->getMaxSpeed(), insertionSpeed);
596  }
597 
598  // insert vehicle into the dictionary
599  if (!MSNet::getInstance()->getVehicleControl().addVehicle(vehicle->getID(), vehicle)) {
600  return writeErrorStatusCmd(CMD_ADDVEHICLE, "Could not add vehicle to VehicleControl", myOutputStorage);
601  }
602 
603  // try to emit
604  if (!lane->isInsertionSuccess(vehicle, clippedInsertionSpeed, insertionPosition, true)) {
605  MSNet::getInstance()->getVehicleControl().deleteVehicle(vehicle);
606  return writeErrorStatusCmd(CMD_ADDVEHICLE, "Could not insert vehicle", myOutputStorage);
607  }
608 
609  // exec callback
610  vehicle->onDepart();
611 
612  // create a reply message
614 
615  return true;
616 }
617 
618 
619 void
620 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description) {
621  writeStatusCmd(commandId, status, description, myOutputStorage);
622 }
623 
624 
625 void
626 TraCIServer::writeStatusCmd(int commandId, int status, const std::string& description, tcpip::Storage& outputStorage) {
627  if (status == RTYPE_ERR) {
628  WRITE_ERROR("Answered with error to command " + toString(commandId) + ": " + description);
629  } else if (status == RTYPE_NOTIMPLEMENTED) {
630  WRITE_ERROR("Requested command not implemented (" + toString(commandId) + "): " + description);
631  }
632  outputStorage.writeUnsignedByte(1 + 1 + 1 + 4 + static_cast<int>(description.length())); // command length
633  outputStorage.writeUnsignedByte(commandId); // command type
634  outputStorage.writeUnsignedByte(status); // status
635  outputStorage.writeString(description); // description
636 }
637 
638 
639 bool
640 TraCIServer::writeErrorStatusCmd(int commandId, const std::string& description, tcpip::Storage& outputStorage) {
641  writeStatusCmd(commandId, RTYPE_ERR, description, outputStorage);
642  return false;
643 }
644 
645 
646 void
648  tcpip::Storage writeInto;
649  std::string errors;
650  if (processSingleSubscription(s, writeInto, errors)) {
652  writeStatusCmd(s.commandId, RTYPE_ERR, "Subscription has ended.");
653  } else {
654  mySubscriptions.push_back(s);
656  }
657  } else {
658  writeStatusCmd(s.commandId, RTYPE_ERR, "Could not add subscription (" + errors + ").");
659  }
660  myOutputStorage.writeStorage(writeInto);
661 }
662 
663 
664 void
665 TraCIServer::removeSubscription(int commandId, const std::string& id, int domain) {
666  bool found = false;
667  for (std::vector<Subscription>::iterator j = mySubscriptions.begin(); j != mySubscriptions.end();) {
668  if ((*j).id == id && (*j).commandId == commandId && (domain < 0 || (*j).contextDomain == domain)) {
669  j = mySubscriptions.erase(j);
670  found = true;
671  continue;
672  }
673  ++j;
674  }
675  // try unsubscribe
676  if (found) {
677  writeStatusCmd(commandId, RTYPE_OK, "");
678  } else {
679  writeStatusCmd(commandId, RTYPE_OK, "The subscription to remove was not found.");
680  }
681 }
682 
683 
684 bool
685 TraCIServer::findObjectShape(int domain, const std::string& id, PositionVector& shape) {
686  Position p;
687  switch (domain) {
690  shape.push_back(p);
691  break;
692  }
693  return false;
695  return false;
697  return false;
699  if (TraCIServerAPI_Lane::getShape(id, shape)) {
700  break;
701  }
702  return false;
705  shape.push_back(p);
706  break;
707  }
708  return false;
710  return false;
712  return false;
714  if (TraCIServerAPI_POI::getPosition(id, p)) {
715  shape.push_back(p);
716  break;
717  }
718  return false;
720  if (TraCIServerAPI_Polygon::getShape(id, shape)) {
721  break;
722  }
723  return false;
726  shape.push_back(p);
727  break;
728  }
729  return false;
731  if (TraCIServerAPI_Edge::getShape(id, shape)) {
732  break;
733  }
734  return false;
736  return false;
738  return false;
739  default:
740  return false;
741  }
742  return true;
743 }
744 
745 void
746 TraCIServer::collectObjectsInRange(int domain, const PositionVector& shape, SUMOReal range, std::set<std::string>& into) {
747  // build the look-up tree if not yet existing
748  if (myObjects.find(domain) == myObjects.end()) {
749  switch (domain) {
752  break;
754  break;
755  case CMD_GET_TL_VARIABLE:
756  break;
759  break;
761  if (myObjects.find(CMD_GET_LANE_VARIABLE) == myObjects.end()) {
763  }
764  break;
766  break;
768  break;
771  break;
774  break;
777  break;
780  break;
782  break;
784  break;
785  default:
786  break;
787  }
788  }
789  const Boundary b = shape.getBoxBoundary().grow(range);
790  const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
791  const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
792  switch (domain) {
794  Named::StoringVisitor sv(into);
795  myObjects[CMD_GET_INDUCTIONLOOP_VARIABLE]->Search(cmin, cmax, sv);
796  }
797  break;
799  break;
800  case CMD_GET_TL_VARIABLE:
801  break;
802  case CMD_GET_LANE_VARIABLE: {
803  Named::StoringVisitor sv(into);
804  myObjects[CMD_GET_LANE_VARIABLE]->Search(cmin, cmax, sv);
805  if (shape.size() == 1) {
806  for (std::set<std::string>::iterator i = into.begin(); i != into.end();) {
807  const MSLane* const l = MSLane::dictionary(*i);
808  if (l->getShape().distance(shape[0]) > range) {
809  into.erase(i++);
810  } else {
811  ++i;
812  }
813  }
814  }
815  }
816  break;
818  std::set<std::string> tmp;
819  Named::StoringVisitor sv(tmp);
820  myObjects[CMD_GET_LANE_VARIABLE]->Search(cmin, cmax, sv);
821  for (std::set<std::string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
822  MSLane* l = MSLane::dictionary(*i);
823  if (l != 0) {
824  const std::deque<MSVehicle*>& vehs = l->getVehiclesSecure();
825  for (std::deque<MSVehicle*>::const_iterator j = vehs.begin(); j != vehs.end(); ++j) {
826  if (shape.distance((*j)->getPosition()) <= range) {
827  into.insert((*j)->getID());
828  }
829  }
830  l->releaseVehicles();
831  }
832  }
833  }
834  break;
836  break;
838  break;
839  case CMD_GET_POI_VARIABLE: {
840  Named::StoringVisitor sv(into);
841  myObjects[CMD_GET_POI_VARIABLE]->Search(cmin, cmax, sv);
842  }
843  break;
845  Named::StoringVisitor sv(into);
846  myObjects[CMD_GET_POLYGON_VARIABLE]->Search(cmin, cmax, sv);
847  }
848  break;
850  Named::StoringVisitor sv(into);
851  myObjects[CMD_GET_JUNCTION_VARIABLE]->Search(cmin, cmax, sv);
852  }
853  break;
854  case CMD_GET_EDGE_VARIABLE: {
855  Named::StoringVisitor sv(into);
856  myObjects[CMD_GET_EDGE_VARIABLE]->Search(cmin, cmax, sv);
857  }
858  break;
860  break;
862  break;
863  default:
864  break;
865  }
866 }
867 
868 
869 bool
871  std::string& errors) {
872  bool ok = true;
873  tcpip::Storage outputStorage;
874  int getCommandId = s.contextVars ? s.contextDomain : s.commandId - 0x30;
875  std::set<std::string> objIDs;
876  if (s.contextVars) {
877  getCommandId = s.contextDomain;
878  PositionVector shape;
879  if (!findObjectShape(s.commandId, s.id, shape)) {
880  return false;
881  }
882  collectObjectsInRange(s.contextDomain, shape, s.range, objIDs);
883  } else {
884  getCommandId = s.commandId - 0x30;
885  objIDs.insert(s.id);
886  }
887 
888  for (std::set<std::string>::iterator j = objIDs.begin(); j != objIDs.end(); ++j) {
889  if (s.contextVars) {
890  outputStorage.writeString(*j);
891  }
892  for (std::vector<int>::const_iterator i = s.variables.begin(); i != s.variables.end(); ++i) {
893  tcpip::Storage message;
894  message.writeUnsignedByte(*i);
895  message.writeString(*j);
896  tcpip::Storage tmpOutput;
897  if (myExecutors.find(getCommandId) != myExecutors.end()) {
898  ok &= myExecutors[getCommandId](*this, message, tmpOutput);
899  } else {
900  writeStatusCmd(s.commandId, RTYPE_NOTIMPLEMENTED, "Unsupported command specified", tmpOutput);
901  ok = false;
902  }
903  // copy response part
904  if (ok) {
905  int length = tmpOutput.readUnsignedByte();
906  while (--length > 0) {
907  tmpOutput.readUnsignedByte();
908  }
909  int lengthLength = 1;
910  length = tmpOutput.readUnsignedByte();
911  if (length == 0) {
912  lengthLength = 5;
913  length = tmpOutput.readInt();
914  }
915  //read responseType
916  tmpOutput.readUnsignedByte();
917  int variable = tmpOutput.readUnsignedByte();
918  std::string id = tmpOutput.readString();
919  outputStorage.writeUnsignedByte(variable);
920  outputStorage.writeUnsignedByte(RTYPE_OK);
921  length -= (lengthLength + 1 + 4 + (int)id.length());
922  while (--length > 0) {
923  outputStorage.writeUnsignedByte(tmpOutput.readUnsignedByte());
924  }
925  } else {
926  //read length
927  tmpOutput.readUnsignedByte();
928  //read cmd
929  tmpOutput.readUnsignedByte();
930  //read status
931  tmpOutput.readUnsignedByte();
932  std::string msg = tmpOutput.readString();
933  outputStorage.writeUnsignedByte(*i);
934  outputStorage.writeUnsignedByte(RTYPE_ERR);
935  outputStorage.writeUnsignedByte(TYPE_STRING);
936  outputStorage.writeString(msg);
937  errors = errors + msg;
938  }
939  }
940  }
941  unsigned int length = (1 + 4) + 1 + (4 + (int)(s.id.length())) + 1 + (int)outputStorage.size();
942  if (s.contextVars) {
943  length += 4;
944  }
945  writeInto.writeUnsignedByte(0); // command length -> extended
946  writeInto.writeInt(length);
947  writeInto.writeUnsignedByte(s.commandId + 0x10);
948  writeInto.writeString(s.id);
949  if (s.contextVars) {
950  writeInto.writeUnsignedByte(s.contextDomain);
951  }
952  writeInto.writeUnsignedByte((int)(s.variables.size()));
953  if (s.contextVars) {
954  writeInto.writeInt((int)objIDs.size());
955  }
956  if (!s.contextVars || objIDs.size() != 0) {
957  writeInto.writeStorage(outputStorage);
958  }
959  return ok;
960 }
961 
962 
963 bool
965  SUMOTime beginTime = myInputStorage.readInt();
966  SUMOTime endTime = myInputStorage.readInt();
967  std::string id = myInputStorage.readString();
968  int no = myInputStorage.readUnsignedByte();
969  std::vector<int> variables;
970  for (int i = 0; i < no; ++i) {
971  variables.push_back(myInputStorage.readUnsignedByte());
972  }
973  // check subscribe/unsubscribe
974  if (variables.size() == 0) {
975  removeSubscription(commandId, id, -1);
976  return true;
977  }
978  // process subscription
979  Subscription s(commandId, id, variables, beginTime, endTime, false, 0, 0);
981  return true;
982 }
983 
984 
985 bool
987  SUMOTime beginTime = myInputStorage.readInt();
988  SUMOTime endTime = myInputStorage.readInt();
989  std::string id = myInputStorage.readString();
990  int domain = myInputStorage.readUnsignedByte();
992  int no = myInputStorage.readUnsignedByte();
993  std::vector<int> variables;
994  for (int i = 0; i < no; ++i) {
995  variables.push_back(myInputStorage.readUnsignedByte());
996  }
997  // check subscribe/unsubscribe
998  if (variables.size() == 0) {
999  removeSubscription(commandId, id, -1);
1000  return true;
1001  }
1002  Subscription s(commandId, id, variables, beginTime, endTime, true, domain, range);
1004  return true;
1005 }
1006 
1007 
1008 void
1010  if (tempMsg.size() < 254) {
1011  outputStorage.writeUnsignedByte(1 + (int)tempMsg.size()); // command length -> short
1012  } else {
1013  outputStorage.writeUnsignedByte(0); // command length -> extended
1014  outputStorage.writeInt(1 + 4 + (int)tempMsg.size());
1015  }
1016  outputStorage.writeStorage(tempMsg);
1017 }
1018 
1019 
1020 bool
1022  if (inputStorage.readUnsignedByte() != TYPE_INTEGER) {
1023  return false;
1024  }
1025  into = inputStorage.readInt();
1026  return true;
1027 }
1028 
1029 
1030 bool
1032  if (inputStorage.readUnsignedByte() != TYPE_DOUBLE) {
1033  return false;
1034  }
1035  into = inputStorage.readDouble();
1036  return true;
1037 }
1038 
1039 
1040 bool
1041 TraCIServer::readTypeCheckingString(tcpip::Storage& inputStorage, std::string& into) {
1042  if (inputStorage.readUnsignedByte() != TYPE_STRING) {
1043  return false;
1044  }
1045  into = inputStorage.readString();
1046  return true;
1047 }
1048 
1049 
1050 bool
1051 TraCIServer::readTypeCheckingStringList(tcpip::Storage& inputStorage, std::vector<std::string>& into) {
1052  if (inputStorage.readUnsignedByte() != TYPE_STRINGLIST) {
1053  return false;
1054  }
1055  into = inputStorage.readStringList();
1056  return true;
1057 }
1058 
1059 
1060 bool
1062  if (inputStorage.readUnsignedByte() != TYPE_COLOR) {
1063  return false;
1064  }
1065  unsigned char r = static_cast<unsigned char>(inputStorage.readUnsignedByte());
1066  unsigned char g = static_cast<unsigned char>(inputStorage.readUnsignedByte());
1067  unsigned char b = static_cast<unsigned char>(inputStorage.readUnsignedByte());
1068  unsigned char a = static_cast<unsigned char>(inputStorage.readUnsignedByte());
1069  into.set(r, g, b, a);
1070  return true;
1071 }
1072 
1073 
1074 bool
1076  if (inputStorage.readUnsignedByte() != POSITION_2D) {
1077  return false;
1078  }
1079  SUMOReal x = inputStorage.readDouble();
1080  SUMOReal y = inputStorage.readDouble();
1081  into.set(x, y, 0);
1082  return true;
1083 }
1084 
1085 
1086 bool
1088  if (inputStorage.readUnsignedByte() != TYPE_BOUNDINGBOX) {
1089  return false;
1090  }
1091  const SUMOReal xmin = inputStorage.readDouble();
1092  const SUMOReal ymin = inputStorage.readDouble();
1093  const SUMOReal xmax = inputStorage.readDouble();
1094  const SUMOReal ymax = inputStorage.readDouble();
1095  into.set(xmin, ymin, xmax, ymax);
1096  return true;
1097 }
1098 
1099 
1100 bool
1102  if (inputStorage.readUnsignedByte() != TYPE_BYTE) {
1103  return false;
1104  }
1105  into = inputStorage.readByte();
1106  return true;
1107 }
1108 
1109 
1110 bool
1112  if (inputStorage.readUnsignedByte() != TYPE_UBYTE) {
1113  return false;
1114  }
1115  into = inputStorage.readUnsignedByte();
1116  return true;
1117 }
1118 
1119 
1120 bool
1122  if (inputStorage.readUnsignedByte() != TYPE_POLYGON) {
1123  return false;
1124  }
1125  into.clear();
1126  unsigned int noEntries = inputStorage.readUnsignedByte();
1127  PositionVector shape;
1128  for (unsigned int i = 0; i < noEntries; ++i) {
1129  SUMOReal x = inputStorage.readDouble();
1130  SUMOReal y = inputStorage.readDouble();
1131  into.push_back(Position(x, y));
1132  }
1133  return true;
1134 }
1135 
1136 }
1137 
1138 #endif