traci
1# -*- coding: utf-8 -*- 2# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo 3# Copyright (C) 2008-2026 German Aerospace Center (DLR) and others. 4# This program and the accompanying materials are made available under the 5# terms of the Eclipse Public License 2.0 which is available at 6# https://www.eclipse.org/legal/epl-2.0/ 7# This Source Code may also be made available under the following Secondary 8# Licenses when the conditions for such availability set forth in the Eclipse 9# Public License 2.0 are satisfied: GNU General Public License, version 2 10# or later which is available at 11# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html 12# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later 13 14# @file __init__.py 15# @author Michael Behrisch 16# @author Lena Kalleske 17# @author Mario Krumnow 18# @author Daniel Krajzewicz 19# @author Jakob Erdmann 20# @date 2008-10-09 21 22from __future__ import absolute_import 23import os 24import sys 25import warnings 26 27__all__ = ['busstop', 'calibrator', 'chargingstation', 'edge', 'gui', 'inductionloop', 'junction', 'lane', 'lanearea', # noqa 28 'multientryexit', 'overheadwire', 'parkingarea', 'person', 'poi', 'polygon', 'rerouter', 'route', 29 'routeprobe', 'simulation', 'trafficlight', 'variablespeedsign', 'vehicle', 'vehicletype', 30 'connection', 'constants', 'domain', 'exceptions', 31 'start', 'close', 'load', 'executeMove', 'getVersion', 'load', 'setOrder', 'simulationStep', 32 'setConnectHook', 'connect', 'init', 'isLibsumo', 'isLibtraci', 'hasGUI', 'isLoaded', 33 'addStepListener', 'removeStepListener'] 34 35try: 36 # this tries to determine the version number of an installed wheel 37 import importlib.metadata # noqa 38 __version__ = importlib.metadata.version(__name__) 39except ImportError: 40 # this is the fallback version, it gets replaced with the current version on "make install" or "make dist" 41 __version__ = "0.0.0" 42 43# the pure python version needs to be the first variant to help IDEs finding the docstrings 44if 'LIBSUMO_AS_TRACI' not in os.environ and 'LIBTRACI_AS_TRACI' not in os.environ: 45 from .main import * # noqa 46else: 47 try: 48 if 'LIBSUMO_AS_TRACI' in os.environ: 49 from libsumo import * # noqa 50 if os.environ['LIBSUMO_AS_TRACI'] != "quiet": 51 print("Using libsumo as traci as requested by environment variable.") 52 else: 53 from libtraci import * # noqa 54 if os.environ['LIBTRACI_AS_TRACI'] != "quiet": 55 print("Using libtraci as traci as requested by environment variable.") 56 except ImportError as e: 57 if 'LIBSUMO_AS_TRACI' in os.environ: 58 warnings.warn("Could not import libsumo using %s, falling back to pure python traci (%s)." % 59 (sys.executable, e)) 60 else: 61 warnings.warn("Could not import libtraci, falling back to pure python traci (%s)." % e) 62 from .main import * # noqa
123def start(cmd, port=None, numRetries=tc.DEFAULT_NUM_RETRIES, label="default", verbose=False, 124 traceFile=None, traceGetters=True, stdout=None, doSwitch=True): 125 """ 126 Start a sumo server using cmd, establish a connection to it and 127 store it under the given label. This method is not thread-safe. 128 129 - cmd (list): uses the Popen syntax. i.e. ['sumo', '-c', 'run.sumocfg']. The remote 130 port option will be added automatically 131 - numRetries (int): retries on failing to connect to sumo (more retries are needed 132 if a big .net.xml file must be loaded) 133 - label (string) : distinguish multiple traci connections used in the same script 134 - verbose (bool): print complete cmd 135 - traceFile (string): write all traci commands to FILE for debugging 136 - traceGetters (bool): whether to include get-commands in traceFile 137 - stdout (iostream): where to pipe sumo process stdout 138 """ 139 if connection.has(label): 140 raise TraCIException("Connection '%s' is already active." % label) 141 while numRetries >= 0 and not connection.has(label): 142 sumoPort = getFreeSocketPort() if port is None else port 143 cmd2 = cmd + ["--remote-port", str(sumoPort)] 144 if verbose: 145 print("Calling " + ' '.join(cmd2)) 146 sumoProcess = subprocess.Popen(cmd2, stdout=stdout) 147 try: 148 result = init(sumoPort, numRetries, "localhost", label, sumoProcess, doSwitch, traceFile, traceGetters) 149 if traceFile is not None: 150 connection.get(label)._traceFile.write("import traci\n") 151 connection.get(label)._traceFile.write("traci.start(%s, port=%s, label=%s)\n" % ( 152 repr(cmd), repr(port), repr(label))) 153 return result 154 except TraCIException as e: 155 if port is not None: 156 break 157 warnings.warn(("Could not connect to TraCI server using port %s (%s)." + 158 " Retrying with different port.") % (sumoPort, e)) 159 numRetries -= 1 160 raise FatalTraCIError("Could not connect.")
Start a sumo server using cmd, establish a connection to it and store it under the given label. This method is not thread-safe.
- cmd (list): uses the Popen syntax. i.e. ['sumo', '-c', 'run.sumocfg']. The remote port option will be added automatically
- numRetries (int): retries on failing to connect to sumo (more retries are needed if a big .net.xml file must be loaded)
- label (string) : distinguish multiple traci connections used in the same script
- verbose (bool): print complete cmd
- traceFile (string): write all traci commands to FILE for debugging
- traceGetters (bool): whether to include get-commands in traceFile
- stdout (iostream): where to pipe sumo process stdout
261def close(wait=True): 262 """ 263 Tells TraCI to close the connection. 264 """ 265 connection.check().close(wait)
Tells TraCI to close the connection.
178def load(args): 179 """load([optionOrParam, ...]) 180 Let sumo load a simulation using the given command line like options 181 Example: 182 load(['-c', 'run.sumocfg']) 183 load(['-n', 'net.net.xml', '-r', 'routes.rou.xml']) 184 """ 185 return connection.check().load(args)
load([optionOrParam, ...]) Let sumo load a simulation using the given command line like options Example: load(['-c', 'run.sumocfg']) load(['-n', 'net.net.xml', '-r', 'routes.rou.xml'])
215def executeMove(): 216 """executeMove() -> None 217 Make "half" a simulation step. 218 """ 219 connection.check().simulation.executeMove()
executeMove() -> None Make "half" a simulation step.
241def getVersion(): 242 """getVersion() -> tuple 243 244 Returns a tuple containing the TraCI API version number (integer) 245 and a string identifying the SUMO version running on the TraCI server in human-readable form. 246 """ 247 return connection.check().getVersion()
getVersion() -> tuple
Returns a tuple containing the TraCI API version number (integer) and a string identifying the SUMO version running on the TraCI server in human-readable form.
250def setOrder(order): 251 """ 252 Tells TraCI to give the current client the given position in the 253 execution order. It is mandatory to send this as the first command after 254 connecting to the TraCI server when using multiple clients. Each client 255 must be assigned a unique integer but there are not further restrictions 256 on numbering. 257 """ 258 return connection.check().setOrder(order)
Tells TraCI to give the current client the given position in the execution order. It is mandatory to send this as the first command after connecting to the TraCI server when using multiple clients. Each client must be assigned a unique integer but there are not further restrictions on numbering.
195def simulationStep(step=0): 196 """simulationStep(float) -> None 197 Make a simulation step and simulate up to the given second in sim time. 198 If the given value is 0 or absent, exactly one step is performed. 199 Values smaller than or equal to the current sim time result in no action. 200 """ 201 connection.check().simulationStep(step)
simulationStep(float) -> None Make a simulation step and simulate up to the given second in sim time. If the given value is 0 or absent, exactly one step is performed. Values smaller than or equal to the current sim time result in no action.
80def setConnectHook(hookFunc): 81 """ 82 Set a function which is called whenever a new connection has been established. 83 The function should take a single parameter which is the connection object. 84 """ 85 connection._connectHook = hookFunc
Set a function which is called whenever a new connection has been established. The function should take a single parameter which is the connection object.
88def connect(port=8813, numRetries=tc.DEFAULT_NUM_RETRIES, host="localhost", proc=None, waitBetweenRetries=1, 89 traceFile=None, traceGetters=True, label=None): 90 """ 91 Establish a connection to a TraCI-Server and return the 92 connection object. If label is not set, the connection is not saved in the pool and not 93 accessible via traci.switch. It should be safe to use different 94 connections established by this method in different threads. 95 """ 96 for retry in range(1, numRetries + 2): 97 try: 98 return connection.Connection(host, port, proc, traceFile, traceGetters, label) 99 except socket.error as e: 100 if proc is not None and proc.poll() is not None: 101 raise TraCIException("TraCI server already finished") 102 if retry > 1: 103 print("Could not connect to TraCI server at %s:%s" % (host, port), e) 104 if retry < numRetries + 1: 105 print(" Retrying in %s seconds" % waitBetweenRetries) 106 time.sleep(waitBetweenRetries) 107 raise FatalTraCIError("Could not connect in %s tries" % (numRetries + 1))
Establish a connection to a TraCI-Server and return the connection object. If label is not set, the connection is not saved in the pool and not accessible via traci.switch. It should be safe to use different connections established by this method in different threads.
110def init(port=8813, numRetries=tc.DEFAULT_NUM_RETRIES, host="localhost", label="default", proc=None, doSwitch=True, 111 traceFile=None, traceGetters=True): 112 """ 113 Establish a connection to a TraCI-Server and store it under the given 114 label. This method is not thread-safe. It accesses the connection 115 pool concurrently. 116 """ 117 con = connect(port, numRetries, host, proc, 1, traceFile, traceGetters, label) 118 if doSwitch: 119 switch(label) 120 return con.getVersion()
Establish a connection to a TraCI-Server and store it under the given label. This method is not thread-safe. It accesses the connection pool concurrently.
171def hasGUI(): 172 """ 173 Return whether a GUI and the corresponding GUI commands are available for the current connection. 174 """ 175 return connection.check().hasGUI()
Return whether a GUI and the corresponding GUI commands are available for the current connection.
188def isLoaded(): 189 """ 190 Returns whether there is an active connection. 191 """ 192 return connection.has("")
Returns whether there is an active connection.
222def addStepListener(listener): 223 """addStepListener(traci.StepListener) -> int 224 225 Append the step listener (its step function is called at the end of every call to traci.simulationStep()) 226 to the current connection. 227 Returns the ID assigned to the listener if it was added successfully, None otherwise. 228 """ 229 return connection.check().addStepListener(listener)
addStepListener(traci.StepListener) -> int
Append the step listener (its step function is called at the end of every call to traci.simulationStep()) to the current connection. Returns the ID assigned to the listener if it was added successfully, None otherwise.
232def removeStepListener(listenerID): 233 """removeStepListener(traci.StepListener) -> bool 234 235 Remove the step listener from the current connection's step listener container. 236 Returns True if the listener was removed successfully, False if it wasn't registered. 237 """ 238 return connection.check().removeStepListener(listenerID)
removeStepListener(traci.StepListener) -> bool
Remove the step listener from the current connection's step listener container. Returns True if the listener was removed successfully, False if it wasn't registered.