Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions docs/web/docs/TraCI/Control-related_commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,13 @@ so the parser should regard the id of the returned command.
| :-----------: | :-----------: |
| \- | [executeMove](https://sumo.dlr.de/pydoc/traci.html#executeMove) |

Performs only the first part of a simulation step until the vehicles have moved but before the outputs are generated.
A subsequent call to simulation step will then create the output.
This command moves vehicles without completing the simulation step. The response contains the command status. The Python, libtraci, and libsumo interfaces refresh ordinary and context subscriptions after movement when the server supports this feature. A subsequent **Simulation Step** call writes the simulation outputs and advances simulation time.

## Command 0x7C: Get Subscription Snapshot

This command takes no parameters and returns the current ordinary and context subscription results in the same format as the **Simulation Step** response. It leaves the simulation time and movement unchanged.

Read the simulation parameter `traci.subscriptionSnapshot` with an empty object ID to check support. A server that supports this command returns `true`. Use this command after **Execute Move** to retrieve the subscription results for the state after movement.

## Command 0x7F: Close

Expand Down
4 changes: 4 additions & 0 deletions src/libsumo/Simulation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ Simulation::step(const double time) {
void
Simulation::executeMove() {
MSNet::getInstance()->simulationStep(true);
Helper::handleSubscriptions(SIMSTEP);
}


Expand Down Expand Up @@ -954,6 +955,9 @@ Simulation::getParameter(const std::string& objectID, const std::string& key) {
}
throw TraCIException("Unknown parameter '" + key + "'");
} else if (objectID == "") {
if (key == "traci.subscriptionSnapshot") {
return "true";
}
return MSNet::getInstance()->getParameter(key, "");
} else {
throw TraCIException("Simulation parameter '" + key + "' is not supported for object id '" + objectID + "'. Use empty id for generic network parameters");
Expand Down
3 changes: 3 additions & 0 deletions src/libsumo/TraCIConstants.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ TRACI_CONST int CMD_LOAD = 0x01;
// command: execute move (half step)
TRACI_CONST int CMD_EXECUTEMOVE = 0x7d;

/// command: retrieve subscription results without advancing the simulation
TRACI_CONST int CMD_GET_SUBSCRIPTION_SNAPSHOT = 0x7c;

// command: simulation step
TRACI_CONST int CMD_SIMSTEP = 0x02;

Expand Down
23 changes: 23 additions & 0 deletions src/libtraci/Connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ Connection::simulationStep(double time) {

tcpip::Storage inMsg;
check_resultState(inMsg, libsumo::CMD_SIMSTEP);
readSubscriptions(inMsg);
}


void
Connection::executeMove() {
std::unique_lock<std::mutex> lock{myMutex};
if (!mySupportsSubscriptionSnapshot.has_value()) {
tcpip::Storage parameter;
parameter.writeUnsignedByte(libsumo::TYPE_STRING);
parameter.writeString("traci.subscriptionSnapshot");
tcpip::Storage& result = doCommand(libsumo::CMD_GET_SIM_VARIABLE, libsumo::VAR_PARAMETER, "", &parameter, libsumo::TYPE_STRING);
mySupportsSubscriptionSnapshot = result.readString() == "true";
}
doCommand(libsumo::CMD_EXECUTEMOVE);
if (mySupportsSubscriptionSnapshot.value()) {
readSubscriptions(doCommand(libsumo::CMD_GET_SUBSCRIPTION_SNAPSHOT));
}
}


void
Connection::readSubscriptions(tcpip::Storage& inMsg) {
mySubscriptionResults.clear();
myContextSubscriptionResults.clear();
int numSubs = inMsg.readInt();
Expand Down
8 changes: 8 additions & 0 deletions src/libtraci/Connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include <iomanip>
#include <thread>
#include <mutex>
#include <optional>
#include <foreign/tcpip/socket.h>
#include <libsumo/Subscription.h>

Expand Down Expand Up @@ -95,6 +96,9 @@ class Connection {
*/
void simulationStep(double time);

/// @brief Executes movement and refreshes subscription results when supported.
void executeMove();


/** @brief Sends a SetOrder command
*/
Expand Down Expand Up @@ -133,6 +137,9 @@ class Connection {
void readVariables(tcpip::Storage& inMsg, const std::string& objectID, int variableCount, libsumo::SubscriptionResults& into);

private:
/// @brief Replace cached results with the received ordinary and context subscriptions.
void readSubscriptions(tcpip::Storage& inMsg);

/** @brief Validates the result state of a command
* @param[in] inMsg The buffer to read the message from
* @param[in] command The original command id
Expand Down Expand Up @@ -187,6 +194,7 @@ class Connection {

std::map<int, libsumo::SubscriptionResults> mySubscriptionResults;
std::map<int, libsumo::ContextSubscriptionResults> myContextSubscriptionResults;
std::optional<bool> mySupportsSubscriptionSnapshot;

static Connection* myActive;
static std::map<const std::string, Connection*> myConnections;
Expand Down
3 changes: 1 addition & 2 deletions src/libtraci/Simulation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,7 @@ Simulation::step(const double time) {

void
Simulation::executeMove() {
std::unique_lock<std::mutex> lock{ libtraci::Connection::getActive().getMutex() };
Connection::getActive().doCommand(libsumo::CMD_EXECUTEMOVE);
Connection::getActive().executeMove();
}


Expand Down
33 changes: 22 additions & 11 deletions src/traci-server/TraCIServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,11 @@ TraCIServer::dispatchCommand() {
success = true;
writeStatusCmd(libsumo::CMD_EXECUTEMOVE, libsumo::RTYPE_OK, "");
break;
case libsumo::CMD_GET_SUBSCRIPTION_SNAPSHOT:
writeStatusCmd(commandId, libsumo::RTYPE_OK, "");
writeSubscriptionResults(myOutputStorage);
success = true;
break;
case libsumo::CMD_SIMSTEP: {
const double nextT = myInputStorage.readDouble();
if (nextT == 0.) {
Expand Down Expand Up @@ -1328,11 +1333,22 @@ TraCIServer::commandGetVersion() {

void
TraCIServer::postProcessSimulationStep() {
SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
#ifdef DEBUG_MULTI_CLIENTS
std::cout << " postProcessSimulationStep() at time=" << t << std::endl;
std::cout << " postProcessSimulationStep() at time=" << MSNet::getInstance()->getCurrentTimeStep() << std::endl;
#endif
writeStatusCmd(libsumo::CMD_SIMSTEP, libsumo::RTYPE_OK, "");
mySubscriptionCache.reset();
writeSubscriptionResults(mySubscriptionCache);
myOutputStorage.writeStorage(mySubscriptionCache);
#ifdef DEBUG_SUBSCRIPTIONS
std::cout << " Size after writing subscriptions is " << mySubscriptionCache.size() << std::endl;
#endif
}


void
TraCIServer::writeSubscriptionResults(tcpip::Storage& output) {
const SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
int noActive = 0;
for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
const libsumo::Subscription& s = *i;
Expand All @@ -1351,14 +1367,13 @@ TraCIServer::postProcessSimulationStep() {
}
++noActive;
}
mySubscriptionCache.reset();
#ifdef DEBUG_SUBSCRIPTIONS
std::cout << " Initial size of mySubscriptionCache is " << mySubscriptionCache.size()
std::cout << " Initial size of subscription output is " << output.size()
<< "\n Nr. of active subscriptions = " << noActive << std::endl;
#endif
mySubscriptionCache.writeInt(noActive);
output.writeInt(noActive);
#ifdef DEBUG_SUBSCRIPTIONS
std::cout << " Size after writing an int is " << mySubscriptionCache.size() << std::endl;
std::cout << " Size after writing an int is " << output.size() << std::endl;
#endif
for (std::vector<libsumo::Subscription>::iterator i = mySubscriptions.begin(); i != mySubscriptions.end();) {
const libsumo::Subscription& s = *i;
Expand All @@ -1373,17 +1388,13 @@ TraCIServer::postProcessSimulationStep() {
std::cout << " Size of into-store for subscription " << s.id
<< ": " << into.size() << std::endl;
#endif
mySubscriptionCache.writeStorage(into);
output.writeStorage(into);
if (ok) {
++i;
} else {
i = eraseSubscription(i);
}
}
myOutputStorage.writeStorage(mySubscriptionCache);
#ifdef DEBUG_SUBSCRIPTIONS
std::cout << " Size after writing subscriptions is " << mySubscriptionCache.size() << std::endl;
#endif
}


Expand Down
3 changes: 3 additions & 0 deletions src/traci-server/TraCIServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ class TraCIServer final : public MSNet::VehicleStateListener, public libsumo::Va
/** @brief Handles subscriptions to send after a simstep2 command
*/
void postProcessSimulationStep();

/// @brief Write the current ordinary and context subscription results.
void writeSubscriptionResults(tcpip::Storage& into);
/// @}


Expand Down
4 changes: 4 additions & 0 deletions tests/complex/traci/misc/execute_move/output.complex
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
step 0.0
0.0
1.4338497789110989
Variable subscription matches True
Context subscription matches True
step 1.0
1.4338497789110989
4.033343723951839
Variable subscription matches True
Context subscription matches True
step 2.0
4.033343723951839
4 changes: 4 additions & 0 deletions tests/complex/traci/misc/execute_move/output.complex.meso
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
step 0.0
11.109620887
11.109620887
Variable subscription matches True
Context subscription vehicles []
step 1.0
11.109620887
11.109620887
Variable subscription matches True
Context subscription vehicles []
step 2.0
11.109620887
21 changes: 17 additions & 4 deletions tests/complex/traci/misc/execute_move/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,29 @@ def step():
return s


def move():
traci.executeMove()
speed = traci.vehicle.getSpeed("veh0")
print(speed)
variable_speed = traci.vehicle.getSubscriptionResults("veh0")[traci.constants.VAR_SPEED]
print("Variable subscription matches", variable_speed == speed)
context = traci.vehicle.getContextSubscriptionResults("veh0")
if "veh0" in context:
print("Context subscription matches", context["veh0"][traci.constants.VAR_SPEED] == speed)
else:
print("Context subscription vehicles", sorted(context))


traci.start([sumolib.checkBinary('sumo'), "-c", "sumo.sumocfg"] + sys.argv[1:])
print("step", step())
traci.vehicle.subscribe("veh0", [traci.constants.VAR_SPEED])
traci.vehicle.subscribeContext("veh0", traci.constants.CMD_GET_VEHICLE_VARIABLE, 100, [traci.constants.VAR_SPEED])

print(traci.vehicle.getSpeed("veh0"))
traci.executeMove()
print(traci.vehicle.getSpeed("veh0"))
move()
print("step", step())
print(traci.vehicle.getSpeed("veh0"))
traci.executeMove()
print(traci.vehicle.getSpeed("veh0"))
move()
print("step", step())
print(traci.vehicle.getSpeed("veh0"))

Expand Down
4 changes: 2 additions & 2 deletions tools/traci/_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,11 @@ def step(self, time=0.):

def executeMove(self):
"""executeMove() -> None
Make "half" a simulation step.
Move vehicles and refresh subscription results without completing the simulation step.
"""
if self._connection is None:
raise FatalTraCIError("Not connected.")
self._connection._sendCmd(tc.CMD_EXECUTEMOVE, None, None)
self._connection.executeMove()

def getCurrentTime(self):
"""getCurrentTime() -> integer
Expand Down
18 changes: 16 additions & 2 deletions tools/traci/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def __init__(self, host, port, process, traceFile, traceGetters, label=None):
self._string = bytes()
self._queue = []
self._subscriptionMapping = {}
self._lock = threading.Lock()
self._supportsSubscriptionSnapshot = None
self._lock = threading.RLock()
for domain in DOMAINS:
domain._register(self, self._subscriptionMapping)
if traceFile is not None:
Expand Down Expand Up @@ -377,14 +378,27 @@ def simulationStep(self, step=0.):
if type(step) is int and step >= 1000:
warnings.warn("API change now handles step as floating point seconds", stacklevel=2)
result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step)
responses = self._readSubscriptions(result)
self.manageStepListeners(step)
return responses

def executeMove(self):
with self._lock:
if self._supportsSubscriptionSnapshot is None:
self._supportsSubscriptionSnapshot = (
self.simulation.getParameter("", "traci.subscriptionSnapshot") == "true")
self._sendCmd(tc.CMD_EXECUTEMOVE, None, None)
if self._supportsSubscriptionSnapshot:
self._readSubscriptions(self._sendCmd(tc.CMD_GET_SUBSCRIPTION_SNAPSHOT, None, None))

def _readSubscriptions(self, result):
for subscriptionResults in self._subscriptionMapping.values():
subscriptionResults.reset()
numSubs = result.readInt()
responses = []
while numSubs > 0:
responses.append(self._readSubscription(result))
numSubs -= 1
self.manageStepListeners(step)
return responses

def getVersion(self):
Expand Down
3 changes: 3 additions & 0 deletions tools/traci/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
# command: execute move (half step)
CMD_EXECUTEMOVE = 0x7d

# command: retrieve subscription results without advancing the simulation
CMD_GET_SUBSCRIPTION_SNAPSHOT = 0x7c

# command: simulation step
CMD_SIMSTEP = 0x02

Expand Down
2 changes: 1 addition & 1 deletion tools/traci/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def simulationStepLegacy(step=0):

def executeMove():
"""executeMove() -> None
Make "half" a simulation step.
Move vehicles and refresh subscription results without completing the simulation step.
"""
connection.check().simulation.executeMove()

Expand Down
Loading