traci.connection
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 connection.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 print_function 23from __future__ import absolute_import 24import socket 25import struct 26import sys 27import warnings 28import threading 29 30from . import constants as tc 31from .exceptions import TraCIException, FatalTraCIError 32from .domain import DOMAINS 33from .storage import Storage 34from .step import StepManager 35 36_DEBUG = False 37_RESULTS = {0x00: "OK", 0x01: "Not implemented", 0xFF: "Error"} 38 39_connections = {} 40_connectHook = None 41 42 43def check(): 44 if "" not in _connections: 45 raise FatalTraCIError("Not connected.") 46 return _connections[""] 47 48 49def has(label): 50 return label in _connections 51 52 53def get(label="default"): 54 if label not in _connections: 55 raise TraCIException("Connection '%s' is not known." % label) 56 return _connections[label] 57 58 59def switch(label): 60 con = get(label) 61 _connections[""] = con 62 for domain in DOMAINS: 63 domain._setConnection(con) 64 65 66class Connection(StepManager): 67 68 """Contains the socket, the composed message string 69 together with a list of TraCI commands which are inside. 70 """ 71 72 def __init__(self, host, port, process, traceFile, traceGetters, label=None): 73 StepManager.__init__(self) 74 if label in _connections: 75 raise TraCIException("Connection '%s' is already active." % label) 76 if sys.platform.startswith('java'): 77 # working around jython 2.7.0 bug #2273 78 self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) 79 else: 80 self._socket = socket.socket() 81 self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 82 try: 83 self._socket.connect((host, port)) 84 except socket.error: 85 self._socket.close() 86 raise 87 self._process = process 88 self._string = bytes() 89 self._queue = [] 90 self._subscriptionMapping = {} 91 self._lock = threading.Lock() 92 for domain in DOMAINS: 93 domain._register(self, self._subscriptionMapping) 94 if traceFile is not None: 95 self.startTracing(traceFile, traceGetters, [getattr(self, domain._name) for domain in DOMAINS]) 96 self._label = label 97 if _connectHook is not None: 98 _connectHook(self) 99 if label is not None: 100 _connections[label] = self 101 102 def getLabel(self): 103 return self._label 104 105 def _recvExact(self): 106 try: 107 # Accumulate chunks in a bytearray for speedup over repeated bytes concatenation. 108 result = bytearray() 109 while len(result) < 4: 110 t = self._socket.recv(4 - len(result)) 111 if not t: 112 return None 113 result.extend(t) 114 length = struct.unpack("!i", result)[0] - 4 115 result = bytearray() 116 while len(result) < length: 117 t = self._socket.recv(length - len(result)) 118 if not t: 119 return None 120 result.extend(t) 121 return Storage(bytes(result)) 122 except socket.error: 123 return None 124 125 def _sendExact(self): 126 if self._socket is None: 127 raise FatalTraCIError("Connection already closed.") 128 length = struct.pack("!i", len(self._string) + 4) 129 if _DEBUG: 130 print("sending", Storage(length + self._string).getDebugString()) 131 # sendall makes sure that the complete framed message is sent across partial writes. 132 self._socket.sendall(length + self._string) 133 result = self._recvExact() 134 if _DEBUG: 135 print("receiving", result.getDebugString()) 136 if not result: 137 self._socket.close() 138 self._socket = None 139 raise FatalTraCIError("Connection closed by SUMO.") 140 for command in self._queue: 141 prefix = result.read("!BBB") 142 err = result.readString() 143 if prefix[2] or err: 144 self._string = bytes() 145 self._queue = [] 146 raise TraCIException(err, prefix[1], _RESULTS[prefix[2]]) 147 elif prefix[1] != command: 148 raise FatalTraCIError("Received answer %s for command %s." % (prefix[1], command)) 149 elif prefix[1] == tc.CMD_STOP: 150 length = result.read("!B")[0] - 1 151 result.read("!%sx" % length) 152 self._string = bytes() 153 self._queue = [] 154 return result 155 156 def _pack(self, format, *values): 157 # Grow list payloads without repeatedly copying the encoded prefix. 158 packed = bytearray() 159 for f, v in zip(format, values): 160 if f == "i": 161 packed += struct.pack("!Bi", tc.TYPE_INTEGER, int(v)) 162 elif f == "I": # raw int for setOrder 163 packed += struct.pack("!i", int(v)) 164 elif f == "d": 165 packed += struct.pack("!Bd", tc.TYPE_DOUBLE, float(v)) 166 elif f == "D": # raw double for some base commands like simstep 167 packed += struct.pack("!d", float(v)) 168 elif f == "b": 169 packed += struct.pack("!Bb", tc.TYPE_BYTE, int(v)) 170 elif f == "B": 171 packed += struct.pack("!BB", tc.TYPE_UBYTE, int(v)) 172 elif f == "u": # raw unsigned byte needed for distance command and subscribe 173 packed += struct.pack("!B", int(v)) 174 elif f == "s": 175 if sys.version_info[0] > 2 or not isinstance(v, str): 176 v = str(v).encode("utf8") 177 packed += struct.pack("!Bi", tc.TYPE_STRING, len(v)) + v 178 elif f == "p": # polygon 179 if len(v) <= 255: 180 packed += struct.pack("!BB", tc.TYPE_POLYGON, len(v)) 181 else: 182 packed += struct.pack("!BBi", tc.TYPE_POLYGON, 0, len(v)) 183 for p in v: 184 packed += struct.pack("!dd", *p) 185 elif f == "t": # tuple aka compound 186 packed += struct.pack("!Bi", tc.TYPE_COMPOUND, v) 187 elif f == "c": # color 188 packed += struct.pack("!BBBBB", tc.TYPE_COLOR, int(v[0]), int(v[1]), int(v[2]), 189 int(v[3]) if len(v) > 3 else 255) 190 elif f == "l": # string list 191 packed += struct.pack("!Bi", tc.TYPE_STRINGLIST, len(v)) 192 for s in v: 193 s = str(s).encode("utf8") 194 packed += struct.pack("!i", len(s)) + s 195 elif f == "f": # float list 196 packed += struct.pack("!Bi", tc.TYPE_DOUBLELIST, len(v)) 197 for x in v: 198 packed += struct.pack("!d", x) 199 elif f == "o": 200 packed += struct.pack("!Bdd", tc.POSITION_2D, *v) 201 elif f == "O": 202 packed += struct.pack("!Bddd", tc.POSITION_3D, *v) 203 elif f == "g": 204 packed += struct.pack("!Bdd", tc.POSITION_LON_LAT, *v) 205 elif f == "G": 206 packed += struct.pack("!Bddd", tc.POSITION_LON_LAT_ALT, *v) 207 elif f == "r": 208 s = str(v[0]).encode("utf8") 209 packed += struct.pack("!Bi", tc.POSITION_ROADMAP, len(s)) + s 210 packed += struct.pack("!dB", v[1], v[2]) 211 return bytes(packed) 212 213 def _sendCmd(self, cmdID, varID, objID, format="", *values): 214 with self._lock: 215 packed = self._pack(format, *values) 216 objID = str(objID).encode("utf8") 217 length = len(packed) + 1 + 1 # length and command 218 if varID is not None: 219 if isinstance(varID, tuple): # begin and end of a subscription 220 length += 8 + 8 + 4 + len(objID) 221 else: 222 length += 1 + 4 + len(objID) 223 if length <= 255: 224 command = struct.pack("!BB", length, cmdID) 225 else: 226 command = struct.pack("!BiB", 0, length + 4, cmdID) 227 if varID is not None: 228 if isinstance(varID, tuple): 229 command += struct.pack("!dd", *varID) 230 else: 231 command += struct.pack("!B", varID) 232 command += struct.pack("!i", len(objID)) + objID 233 self._queue.append(cmdID) 234 self._string += command + packed 235 return self._sendExact() 236 237 def _readSubscription(self, result): 238 if _DEBUG: 239 print("reading subscription", result.getDebugString()) 240 result.readLength() 241 response = result.read("!B")[0] 242 isVariableSubscription = ((response >= tc.RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE and 243 response <= tc.RESPONSE_SUBSCRIBE_BUSSTOP_VARIABLE) or 244 (response >= tc.RESPONSE_SUBSCRIBE_PARKINGAREA_VARIABLE and 245 response <= tc.RESPONSE_SUBSCRIBE_OVERHEADWIRE_VARIABLE)) 246 objectID = result.readString() 247 contextDomain = 0 if isVariableSubscription else result.read("!B")[0] 248 numVars = result.read("!B")[0] 249 if isVariableSubscription: 250 while numVars > 0: 251 varID, status = result.read("!BB") 252 if status: 253 print("Error!", result.readTypedString()) 254 elif response in self._subscriptionMapping: 255 self._subscriptionMapping[response].add(objectID, varID, result) 256 else: 257 raise FatalTraCIError( 258 "Cannot handle subscription response %02x for %s." % (response, objectID)) 259 numVars -= 1 260 else: 261 objectNo = result.read("!i")[0] 262 subsMap = self._subscriptionMapping[response] 263 subsMap.addContext(objectID) 264 for _ in range(objectNo): 265 oid = result.readString() 266 if numVars == 0: 267 subsMap.addContext(objectID, oid) 268 for __ in range(numVars): 269 varID, status = result.read("!BB") 270 if status: 271 print("Error!", result.readTypedString()) 272 elif contextDomain in self._subscriptionMapping: 273 subsMap.addContext(objectID, oid, varID, 274 self._subscriptionMapping[contextDomain].parse(varID, result)) 275 else: 276 raise FatalTraCIError( 277 "Cannot handle subscription response %02x for %s." % (response, objectID)) 278 return objectID, response 279 280 def _subscriptionArgs(self, varIDs, parameters): 281 format = "u" 282 args = [len(varIDs)] 283 for v in varIDs: 284 format += "u" 285 args.append(v) 286 if parameters is not None and v in parameters: 287 if isinstance(parameters[v], tuple): 288 format += parameters[v][0] 289 for a in parameters[v][1:]: 290 args.append(a) 291 elif isinstance(parameters[v], int): 292 format += "i" 293 args.append(parameters[v]) 294 elif isinstance(parameters[v], float): 295 format += "d" 296 args.append(parameters[v]) 297 else: 298 format += "s" 299 args.append(parameters[v]) 300 return format, args 301 302 def _subscribe(self, cmdID, begin, end, objID, varIDs, parameters): 303 format, args = self._subscriptionArgs(varIDs, parameters) 304 result = self._sendCmd(cmdID, (begin, end), objID, format, *args) 305 if varIDs: 306 objectID, response = self._readSubscription(result) 307 if response - cmdID != 16 or objectID != objID: 308 raise FatalTraCIError("Received answer %02x,%s for subscription command %02x,%s." % ( 309 response, objectID, cmdID, objID)) 310 311 def _getSubscriptionResults(self, cmdID): 312 return self._subscriptionMapping[cmdID] 313 314 def _subscribeContext(self, cmdID, begin, end, objID, domain, dist, varIDs, parameters=None): 315 format, args = self._subscriptionArgs(varIDs, parameters) 316 result = self._sendCmd(cmdID, (begin, end), objID, "uD" + format, domain, dist, *args) 317 if varIDs: 318 objectID, response = self._readSubscription(result) 319 if response - cmdID != 16 or objectID != objID: 320 raise FatalTraCIError("Received answer %02x,%s for context subscription command %02x,%s." % ( 321 response, objectID, cmdID, objID)) 322 323 def _addSubscriptionFilter(self, filterType, params=None): 324 if filterType in (tc.FILTER_TYPE_NONE, tc.FILTER_TYPE_NOOPPOSITE, 325 tc.FILTER_TYPE_LEAD_FOLLOW): 326 # filter without parameter 327 assert params is None 328 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "u", filterType) 329 elif filterType in (tc.FILTER_TYPE_DOWNSTREAM_DIST, tc.FILTER_TYPE_UPSTREAM_DIST, 330 tc.FILTER_TYPE_TURN, tc.FILTER_TYPE_FIELD_OF_VISION, 331 tc.FILTER_TYPE_LATERAL_DIST): 332 # filter with float parameter 333 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ud", filterType, params) 334 elif filterType in (tc.FILTER_TYPE_VCLASS, tc.FILTER_TYPE_VTYPE): 335 # filter with list(string) parameter 336 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ul", filterType, params) 337 elif filterType == tc.FILTER_TYPE_LANES: 338 # filter with list(byte) parameter 339 # check uniqueness of given lanes in list 340 lanes = set() 341 for i in params: 342 lane = int(i) 343 if lane < 0: 344 lane += 256 345 lanes.add(lane) 346 if len(lanes) < len(list(params)): 347 warnings.warn("Ignoring duplicate lane specification for subscription filter.") 348 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, 349 (len(lanes) + 2) * "u", filterType, len(lanes), *lanes) 350 351 def hasGUI(self): 352 try: 353 self.gui.getIDList() 354 return True 355 except TraCIException: 356 return False 357 358 def load(self, args): 359 """ 360 Load a simulation from the given arguments. 361 """ 362 if self._traceFile: 363 self._traceFile.write("traci.load(%s)\n" % repr(args)) 364 self._sendCmd(tc.CMD_LOAD, None, None, "l", args) 365 for subscriptionResults in self._subscriptionMapping.values(): 366 subscriptionResults.reset() 367 368 def simulationStep(self, step=0.): 369 """ 370 Make a simulation step and simulate up to the given second in sim time. 371 If the given value is 0 or absent, exactly one step is performed. 372 Values smaller than or equal to the current sim time result in no action. 373 """ 374 if self._traceFile: 375 args = "" if step == 0 else str(step) 376 self._traceFile.write("traci.simulationStep(%s)\n" % args) 377 if type(step) is int and step >= 1000: 378 warnings.warn("API change now handles step as floating point seconds", stacklevel=2) 379 result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step) 380 for subscriptionResults in self._subscriptionMapping.values(): 381 subscriptionResults.reset() 382 numSubs = result.readInt() 383 responses = [] 384 while numSubs > 0: 385 responses.append(self._readSubscription(result)) 386 numSubs -= 1 387 self.manageStepListeners(step) 388 return responses 389 390 def getVersion(self): 391 command = tc.CMD_GETVERSION 392 result = self._sendCmd(command, None, None) 393 result.readLength() 394 response = result.read("!B")[0] 395 if response != command: 396 raise FatalTraCIError("Received answer %s for command %s." % (response, command)) 397 return result.readInt(), result.readString() 398 399 def setOrder(self, order): 400 self._sendCmd(tc.CMD_SETORDER, None, None, "I", order) 401 402 def close(self, wait=True): 403 try: 404 StepManager.close(self, True) 405 for listenerID in list(self._stepListeners.keys()): 406 self.removeStepListener(listenerID) 407 if self._socket is not None: 408 self._sendCmd(tc.CMD_CLOSE, None, None) 409 finally: 410 if self._socket is not None: 411 self._socket.close() 412 self._socket = None 413 self.simulation._setConnection(None) 414 if self._label is not None: 415 if _connections.get("") is self: 416 del _connections[""] 417 if _connections.get(self._label) is self: 418 del _connections[self._label] 419 if wait and self._process is not None: 420 self._process.wait()
def
check():
def
has(label):
def
get(label='default'):
def
switch(label):
class
Connection(traci.step.StepManager):
67class Connection(StepManager): 68 69 """Contains the socket, the composed message string 70 together with a list of TraCI commands which are inside. 71 """ 72 73 def __init__(self, host, port, process, traceFile, traceGetters, label=None): 74 StepManager.__init__(self) 75 if label in _connections: 76 raise TraCIException("Connection '%s' is already active." % label) 77 if sys.platform.startswith('java'): 78 # working around jython 2.7.0 bug #2273 79 self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) 80 else: 81 self._socket = socket.socket() 82 self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 83 try: 84 self._socket.connect((host, port)) 85 except socket.error: 86 self._socket.close() 87 raise 88 self._process = process 89 self._string = bytes() 90 self._queue = [] 91 self._subscriptionMapping = {} 92 self._lock = threading.Lock() 93 for domain in DOMAINS: 94 domain._register(self, self._subscriptionMapping) 95 if traceFile is not None: 96 self.startTracing(traceFile, traceGetters, [getattr(self, domain._name) for domain in DOMAINS]) 97 self._label = label 98 if _connectHook is not None: 99 _connectHook(self) 100 if label is not None: 101 _connections[label] = self 102 103 def getLabel(self): 104 return self._label 105 106 def _recvExact(self): 107 try: 108 # Accumulate chunks in a bytearray for speedup over repeated bytes concatenation. 109 result = bytearray() 110 while len(result) < 4: 111 t = self._socket.recv(4 - len(result)) 112 if not t: 113 return None 114 result.extend(t) 115 length = struct.unpack("!i", result)[0] - 4 116 result = bytearray() 117 while len(result) < length: 118 t = self._socket.recv(length - len(result)) 119 if not t: 120 return None 121 result.extend(t) 122 return Storage(bytes(result)) 123 except socket.error: 124 return None 125 126 def _sendExact(self): 127 if self._socket is None: 128 raise FatalTraCIError("Connection already closed.") 129 length = struct.pack("!i", len(self._string) + 4) 130 if _DEBUG: 131 print("sending", Storage(length + self._string).getDebugString()) 132 # sendall makes sure that the complete framed message is sent across partial writes. 133 self._socket.sendall(length + self._string) 134 result = self._recvExact() 135 if _DEBUG: 136 print("receiving", result.getDebugString()) 137 if not result: 138 self._socket.close() 139 self._socket = None 140 raise FatalTraCIError("Connection closed by SUMO.") 141 for command in self._queue: 142 prefix = result.read("!BBB") 143 err = result.readString() 144 if prefix[2] or err: 145 self._string = bytes() 146 self._queue = [] 147 raise TraCIException(err, prefix[1], _RESULTS[prefix[2]]) 148 elif prefix[1] != command: 149 raise FatalTraCIError("Received answer %s for command %s." % (prefix[1], command)) 150 elif prefix[1] == tc.CMD_STOP: 151 length = result.read("!B")[0] - 1 152 result.read("!%sx" % length) 153 self._string = bytes() 154 self._queue = [] 155 return result 156 157 def _pack(self, format, *values): 158 # Grow list payloads without repeatedly copying the encoded prefix. 159 packed = bytearray() 160 for f, v in zip(format, values): 161 if f == "i": 162 packed += struct.pack("!Bi", tc.TYPE_INTEGER, int(v)) 163 elif f == "I": # raw int for setOrder 164 packed += struct.pack("!i", int(v)) 165 elif f == "d": 166 packed += struct.pack("!Bd", tc.TYPE_DOUBLE, float(v)) 167 elif f == "D": # raw double for some base commands like simstep 168 packed += struct.pack("!d", float(v)) 169 elif f == "b": 170 packed += struct.pack("!Bb", tc.TYPE_BYTE, int(v)) 171 elif f == "B": 172 packed += struct.pack("!BB", tc.TYPE_UBYTE, int(v)) 173 elif f == "u": # raw unsigned byte needed for distance command and subscribe 174 packed += struct.pack("!B", int(v)) 175 elif f == "s": 176 if sys.version_info[0] > 2 or not isinstance(v, str): 177 v = str(v).encode("utf8") 178 packed += struct.pack("!Bi", tc.TYPE_STRING, len(v)) + v 179 elif f == "p": # polygon 180 if len(v) <= 255: 181 packed += struct.pack("!BB", tc.TYPE_POLYGON, len(v)) 182 else: 183 packed += struct.pack("!BBi", tc.TYPE_POLYGON, 0, len(v)) 184 for p in v: 185 packed += struct.pack("!dd", *p) 186 elif f == "t": # tuple aka compound 187 packed += struct.pack("!Bi", tc.TYPE_COMPOUND, v) 188 elif f == "c": # color 189 packed += struct.pack("!BBBBB", tc.TYPE_COLOR, int(v[0]), int(v[1]), int(v[2]), 190 int(v[3]) if len(v) > 3 else 255) 191 elif f == "l": # string list 192 packed += struct.pack("!Bi", tc.TYPE_STRINGLIST, len(v)) 193 for s in v: 194 s = str(s).encode("utf8") 195 packed += struct.pack("!i", len(s)) + s 196 elif f == "f": # float list 197 packed += struct.pack("!Bi", tc.TYPE_DOUBLELIST, len(v)) 198 for x in v: 199 packed += struct.pack("!d", x) 200 elif f == "o": 201 packed += struct.pack("!Bdd", tc.POSITION_2D, *v) 202 elif f == "O": 203 packed += struct.pack("!Bddd", tc.POSITION_3D, *v) 204 elif f == "g": 205 packed += struct.pack("!Bdd", tc.POSITION_LON_LAT, *v) 206 elif f == "G": 207 packed += struct.pack("!Bddd", tc.POSITION_LON_LAT_ALT, *v) 208 elif f == "r": 209 s = str(v[0]).encode("utf8") 210 packed += struct.pack("!Bi", tc.POSITION_ROADMAP, len(s)) + s 211 packed += struct.pack("!dB", v[1], v[2]) 212 return bytes(packed) 213 214 def _sendCmd(self, cmdID, varID, objID, format="", *values): 215 with self._lock: 216 packed = self._pack(format, *values) 217 objID = str(objID).encode("utf8") 218 length = len(packed) + 1 + 1 # length and command 219 if varID is not None: 220 if isinstance(varID, tuple): # begin and end of a subscription 221 length += 8 + 8 + 4 + len(objID) 222 else: 223 length += 1 + 4 + len(objID) 224 if length <= 255: 225 command = struct.pack("!BB", length, cmdID) 226 else: 227 command = struct.pack("!BiB", 0, length + 4, cmdID) 228 if varID is not None: 229 if isinstance(varID, tuple): 230 command += struct.pack("!dd", *varID) 231 else: 232 command += struct.pack("!B", varID) 233 command += struct.pack("!i", len(objID)) + objID 234 self._queue.append(cmdID) 235 self._string += command + packed 236 return self._sendExact() 237 238 def _readSubscription(self, result): 239 if _DEBUG: 240 print("reading subscription", result.getDebugString()) 241 result.readLength() 242 response = result.read("!B")[0] 243 isVariableSubscription = ((response >= tc.RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE and 244 response <= tc.RESPONSE_SUBSCRIBE_BUSSTOP_VARIABLE) or 245 (response >= tc.RESPONSE_SUBSCRIBE_PARKINGAREA_VARIABLE and 246 response <= tc.RESPONSE_SUBSCRIBE_OVERHEADWIRE_VARIABLE)) 247 objectID = result.readString() 248 contextDomain = 0 if isVariableSubscription else result.read("!B")[0] 249 numVars = result.read("!B")[0] 250 if isVariableSubscription: 251 while numVars > 0: 252 varID, status = result.read("!BB") 253 if status: 254 print("Error!", result.readTypedString()) 255 elif response in self._subscriptionMapping: 256 self._subscriptionMapping[response].add(objectID, varID, result) 257 else: 258 raise FatalTraCIError( 259 "Cannot handle subscription response %02x for %s." % (response, objectID)) 260 numVars -= 1 261 else: 262 objectNo = result.read("!i")[0] 263 subsMap = self._subscriptionMapping[response] 264 subsMap.addContext(objectID) 265 for _ in range(objectNo): 266 oid = result.readString() 267 if numVars == 0: 268 subsMap.addContext(objectID, oid) 269 for __ in range(numVars): 270 varID, status = result.read("!BB") 271 if status: 272 print("Error!", result.readTypedString()) 273 elif contextDomain in self._subscriptionMapping: 274 subsMap.addContext(objectID, oid, varID, 275 self._subscriptionMapping[contextDomain].parse(varID, result)) 276 else: 277 raise FatalTraCIError( 278 "Cannot handle subscription response %02x for %s." % (response, objectID)) 279 return objectID, response 280 281 def _subscriptionArgs(self, varIDs, parameters): 282 format = "u" 283 args = [len(varIDs)] 284 for v in varIDs: 285 format += "u" 286 args.append(v) 287 if parameters is not None and v in parameters: 288 if isinstance(parameters[v], tuple): 289 format += parameters[v][0] 290 for a in parameters[v][1:]: 291 args.append(a) 292 elif isinstance(parameters[v], int): 293 format += "i" 294 args.append(parameters[v]) 295 elif isinstance(parameters[v], float): 296 format += "d" 297 args.append(parameters[v]) 298 else: 299 format += "s" 300 args.append(parameters[v]) 301 return format, args 302 303 def _subscribe(self, cmdID, begin, end, objID, varIDs, parameters): 304 format, args = self._subscriptionArgs(varIDs, parameters) 305 result = self._sendCmd(cmdID, (begin, end), objID, format, *args) 306 if varIDs: 307 objectID, response = self._readSubscription(result) 308 if response - cmdID != 16 or objectID != objID: 309 raise FatalTraCIError("Received answer %02x,%s for subscription command %02x,%s." % ( 310 response, objectID, cmdID, objID)) 311 312 def _getSubscriptionResults(self, cmdID): 313 return self._subscriptionMapping[cmdID] 314 315 def _subscribeContext(self, cmdID, begin, end, objID, domain, dist, varIDs, parameters=None): 316 format, args = self._subscriptionArgs(varIDs, parameters) 317 result = self._sendCmd(cmdID, (begin, end), objID, "uD" + format, domain, dist, *args) 318 if varIDs: 319 objectID, response = self._readSubscription(result) 320 if response - cmdID != 16 or objectID != objID: 321 raise FatalTraCIError("Received answer %02x,%s for context subscription command %02x,%s." % ( 322 response, objectID, cmdID, objID)) 323 324 def _addSubscriptionFilter(self, filterType, params=None): 325 if filterType in (tc.FILTER_TYPE_NONE, tc.FILTER_TYPE_NOOPPOSITE, 326 tc.FILTER_TYPE_LEAD_FOLLOW): 327 # filter without parameter 328 assert params is None 329 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "u", filterType) 330 elif filterType in (tc.FILTER_TYPE_DOWNSTREAM_DIST, tc.FILTER_TYPE_UPSTREAM_DIST, 331 tc.FILTER_TYPE_TURN, tc.FILTER_TYPE_FIELD_OF_VISION, 332 tc.FILTER_TYPE_LATERAL_DIST): 333 # filter with float parameter 334 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ud", filterType, params) 335 elif filterType in (tc.FILTER_TYPE_VCLASS, tc.FILTER_TYPE_VTYPE): 336 # filter with list(string) parameter 337 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ul", filterType, params) 338 elif filterType == tc.FILTER_TYPE_LANES: 339 # filter with list(byte) parameter 340 # check uniqueness of given lanes in list 341 lanes = set() 342 for i in params: 343 lane = int(i) 344 if lane < 0: 345 lane += 256 346 lanes.add(lane) 347 if len(lanes) < len(list(params)): 348 warnings.warn("Ignoring duplicate lane specification for subscription filter.") 349 self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, 350 (len(lanes) + 2) * "u", filterType, len(lanes), *lanes) 351 352 def hasGUI(self): 353 try: 354 self.gui.getIDList() 355 return True 356 except TraCIException: 357 return False 358 359 def load(self, args): 360 """ 361 Load a simulation from the given arguments. 362 """ 363 if self._traceFile: 364 self._traceFile.write("traci.load(%s)\n" % repr(args)) 365 self._sendCmd(tc.CMD_LOAD, None, None, "l", args) 366 for subscriptionResults in self._subscriptionMapping.values(): 367 subscriptionResults.reset() 368 369 def simulationStep(self, step=0.): 370 """ 371 Make a simulation step and simulate up to the given second in sim time. 372 If the given value is 0 or absent, exactly one step is performed. 373 Values smaller than or equal to the current sim time result in no action. 374 """ 375 if self._traceFile: 376 args = "" if step == 0 else str(step) 377 self._traceFile.write("traci.simulationStep(%s)\n" % args) 378 if type(step) is int and step >= 1000: 379 warnings.warn("API change now handles step as floating point seconds", stacklevel=2) 380 result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step) 381 for subscriptionResults in self._subscriptionMapping.values(): 382 subscriptionResults.reset() 383 numSubs = result.readInt() 384 responses = [] 385 while numSubs > 0: 386 responses.append(self._readSubscription(result)) 387 numSubs -= 1 388 self.manageStepListeners(step) 389 return responses 390 391 def getVersion(self): 392 command = tc.CMD_GETVERSION 393 result = self._sendCmd(command, None, None) 394 result.readLength() 395 response = result.read("!B")[0] 396 if response != command: 397 raise FatalTraCIError("Received answer %s for command %s." % (response, command)) 398 return result.readInt(), result.readString() 399 400 def setOrder(self, order): 401 self._sendCmd(tc.CMD_SETORDER, None, None, "I", order) 402 403 def close(self, wait=True): 404 try: 405 StepManager.close(self, True) 406 for listenerID in list(self._stepListeners.keys()): 407 self.removeStepListener(listenerID) 408 if self._socket is not None: 409 self._sendCmd(tc.CMD_CLOSE, None, None) 410 finally: 411 if self._socket is not None: 412 self._socket.close() 413 self._socket = None 414 self.simulation._setConnection(None) 415 if self._label is not None: 416 if _connections.get("") is self: 417 del _connections[""] 418 if _connections.get(self._label) is self: 419 del _connections[self._label] 420 if wait and self._process is not None: 421 self._process.wait()
Contains the socket, the composed message string together with a list of TraCI commands which are inside.
Connection(host, port, process, traceFile, traceGetters, label=None)
73 def __init__(self, host, port, process, traceFile, traceGetters, label=None): 74 StepManager.__init__(self) 75 if label in _connections: 76 raise TraCIException("Connection '%s' is already active." % label) 77 if sys.platform.startswith('java'): 78 # working around jython 2.7.0 bug #2273 79 self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) 80 else: 81 self._socket = socket.socket() 82 self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 83 try: 84 self._socket.connect((host, port)) 85 except socket.error: 86 self._socket.close() 87 raise 88 self._process = process 89 self._string = bytes() 90 self._queue = [] 91 self._subscriptionMapping = {} 92 self._lock = threading.Lock() 93 for domain in DOMAINS: 94 domain._register(self, self._subscriptionMapping) 95 if traceFile is not None: 96 self.startTracing(traceFile, traceGetters, [getattr(self, domain._name) for domain in DOMAINS]) 97 self._label = label 98 if _connectHook is not None: 99 _connectHook(self) 100 if label is not None: 101 _connections[label] = self
def
load(self, args):
359 def load(self, args): 360 """ 361 Load a simulation from the given arguments. 362 """ 363 if self._traceFile: 364 self._traceFile.write("traci.load(%s)\n" % repr(args)) 365 self._sendCmd(tc.CMD_LOAD, None, None, "l", args) 366 for subscriptionResults in self._subscriptionMapping.values(): 367 subscriptionResults.reset()
Load a simulation from the given arguments.
def
simulationStep(self, step=0.0):
369 def simulationStep(self, step=0.): 370 """ 371 Make a simulation step and simulate up to the given second in sim time. 372 If the given value is 0 or absent, exactly one step is performed. 373 Values smaller than or equal to the current sim time result in no action. 374 """ 375 if self._traceFile: 376 args = "" if step == 0 else str(step) 377 self._traceFile.write("traci.simulationStep(%s)\n" % args) 378 if type(step) is int and step >= 1000: 379 warnings.warn("API change now handles step as floating point seconds", stacklevel=2) 380 result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step) 381 for subscriptionResults in self._subscriptionMapping.values(): 382 subscriptionResults.reset() 383 numSubs = result.readInt() 384 responses = [] 385 while numSubs > 0: 386 responses.append(self._readSubscription(result)) 387 numSubs -= 1 388 self.manageStepListeners(step) 389 return responses
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.
def
getVersion(self):
391 def getVersion(self): 392 command = tc.CMD_GETVERSION 393 result = self._sendCmd(command, None, None) 394 result.readLength() 395 response = result.read("!B")[0] 396 if response != command: 397 raise FatalTraCIError("Received answer %s for command %s." % (response, command)) 398 return result.readInt(), result.readString()
def
close(self, wait=True):
403 def close(self, wait=True): 404 try: 405 StepManager.close(self, True) 406 for listenerID in list(self._stepListeners.keys()): 407 self.removeStepListener(listenerID) 408 if self._socket is not None: 409 self._sendCmd(tc.CMD_CLOSE, None, None) 410 finally: 411 if self._socket is not None: 412 self._socket.close() 413 self._socket = None 414 self.simulation._setConnection(None) 415 if self._label is not None: 416 if _connections.get("") is self: 417 del _connections[""] 418 if _connections.get(self._label) is self: 419 del _connections[self._label] 420 if wait and self._process is not None: 421 self._process.wait()