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        if traceFile is not None:
 93            self.startTracing(traceFile, traceGetters, DOMAINS)
 94        for domain in DOMAINS:
 95            domain._register(self, self._subscriptionMapping)
 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 _subscribe(self, cmdID, begin, end, objID, 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        result = self._sendCmd(cmdID, (begin, end), objID, format, *args)
301        if varIDs:
302            objectID, response = self._readSubscription(result)
303            if response - cmdID != 16 or objectID != objID:
304                raise FatalTraCIError("Received answer %02x,%s for subscription command %02x,%s." % (
305                    response, objectID, cmdID, objID))
306
307    def _getSubscriptionResults(self, cmdID):
308        return self._subscriptionMapping[cmdID]
309
310    def _subscribeContext(self, cmdID, begin, end, objID, domain, dist, varIDs, parameters=None):
311        result = self._sendCmd(cmdID, (begin, end), objID, "uDu" + (len(varIDs) * "u"),
312                               domain, dist, len(varIDs), *varIDs)
313        if varIDs:
314            objectID, response = self._readSubscription(result)
315            if response - cmdID != 16 or objectID != objID:
316                raise FatalTraCIError("Received answer %02x,%s for context subscription command %02x,%s." % (
317                    response, objectID, cmdID, objID))
318
319    def _addSubscriptionFilter(self, filterType, params=None):
320        if filterType in (tc.FILTER_TYPE_NONE, tc.FILTER_TYPE_NOOPPOSITE,
321                          tc.FILTER_TYPE_LEAD_FOLLOW):
322            # filter without parameter
323            assert params is None
324            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "u", filterType)
325        elif filterType in (tc.FILTER_TYPE_DOWNSTREAM_DIST, tc.FILTER_TYPE_UPSTREAM_DIST,
326                            tc.FILTER_TYPE_TURN, tc.FILTER_TYPE_FIELD_OF_VISION,
327                            tc.FILTER_TYPE_LATERAL_DIST):
328            # filter with float parameter
329            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ud", filterType, params)
330        elif filterType in (tc.FILTER_TYPE_VCLASS, tc.FILTER_TYPE_VTYPE):
331            # filter with list(string) parameter
332            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ul", filterType, params)
333        elif filterType == tc.FILTER_TYPE_LANES:
334            # filter with list(byte) parameter
335            # check uniqueness of given lanes in list
336            lanes = set()
337            for i in params:
338                lane = int(i)
339                if lane < 0:
340                    lane += 256
341                lanes.add(lane)
342            if len(lanes) < len(list(params)):
343                warnings.warn("Ignoring duplicate lane specification for subscription filter.")
344            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None,
345                          (len(lanes) + 2) * "u", filterType, len(lanes), *lanes)
346
347    def hasGUI(self):
348        try:
349            self.gui.getIDList()
350            return True
351        except TraCIException:
352            return False
353
354    def load(self, args):
355        """
356        Load a simulation from the given arguments.
357        """
358        if self._traceFile:
359            self._traceFile.write("traci.load(%s)\n" % repr(args))
360        self._sendCmd(tc.CMD_LOAD, None, None, "l", args)
361
362    def simulationStep(self, step=0.):
363        """
364        Make a simulation step and simulate up to the given second in sim time.
365        If the given value is 0 or absent, exactly one step is performed.
366        Values smaller than or equal to the current sim time result in no action.
367        """
368        if self._traceFile:
369            args = "" if step == 0 else str(step)
370            self._traceFile.write("traci.simulationStep(%s)\n" % args)
371        if type(step) is int and step >= 1000:
372            warnings.warn("API change now handles step as floating point seconds", stacklevel=2)
373        result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step)
374        for subscriptionResults in self._subscriptionMapping.values():
375            subscriptionResults.reset()
376        numSubs = result.readInt()
377        responses = []
378        while numSubs > 0:
379            responses.append(self._readSubscription(result))
380            numSubs -= 1
381        self.manageStepListeners(step)
382        return responses
383
384    def getVersion(self):
385        command = tc.CMD_GETVERSION
386        result = self._sendCmd(command, None, None)
387        result.readLength()
388        response = result.read("!B")[0]
389        if response != command:
390            raise FatalTraCIError("Received answer %s for command %s." % (response, command))
391        return result.readInt(), result.readString()
392
393    def setOrder(self, order):
394        self._sendCmd(tc.CMD_SETORDER, None, None, "I", order)
395
396    def close(self, wait=True):
397        try:
398            StepManager.close(self, True)
399            for listenerID in list(self._stepListeners.keys()):
400                self.removeStepListener(listenerID)
401            if self._socket is not None:
402                self._sendCmd(tc.CMD_CLOSE, None, None)
403        finally:
404            if self._socket is not None:
405                self._socket.close()
406            self._socket = None
407            self.simulation._setConnection(None)
408            if self._label is not None:
409                if _connections.get("") is self:
410                    del _connections[""]
411                if _connections.get(self._label) is self:
412                    del _connections[self._label]
413        if wait and self._process is not None:
414            self._process.wait()
def check():
44def check():
45    if "" not in _connections:
46        raise FatalTraCIError("Not connected.")
47    return _connections[""]
def has(label):
50def has(label):
51    return label in _connections
def get(label='default'):
54def get(label="default"):
55    if label not in _connections:
56        raise TraCIException("Connection '%s' is not known." % label)
57    return _connections[label]
def switch(label):
60def switch(label):
61    con = get(label)
62    _connections[""] = con
63    for domain in DOMAINS:
64        domain._setConnection(con)
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        if traceFile is not None:
 94            self.startTracing(traceFile, traceGetters, DOMAINS)
 95        for domain in DOMAINS:
 96            domain._register(self, self._subscriptionMapping)
 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 _subscribe(self, cmdID, begin, end, objID, 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        result = self._sendCmd(cmdID, (begin, end), objID, format, *args)
302        if varIDs:
303            objectID, response = self._readSubscription(result)
304            if response - cmdID != 16 or objectID != objID:
305                raise FatalTraCIError("Received answer %02x,%s for subscription command %02x,%s." % (
306                    response, objectID, cmdID, objID))
307
308    def _getSubscriptionResults(self, cmdID):
309        return self._subscriptionMapping[cmdID]
310
311    def _subscribeContext(self, cmdID, begin, end, objID, domain, dist, varIDs, parameters=None):
312        result = self._sendCmd(cmdID, (begin, end), objID, "uDu" + (len(varIDs) * "u"),
313                               domain, dist, len(varIDs), *varIDs)
314        if varIDs:
315            objectID, response = self._readSubscription(result)
316            if response - cmdID != 16 or objectID != objID:
317                raise FatalTraCIError("Received answer %02x,%s for context subscription command %02x,%s." % (
318                    response, objectID, cmdID, objID))
319
320    def _addSubscriptionFilter(self, filterType, params=None):
321        if filterType in (tc.FILTER_TYPE_NONE, tc.FILTER_TYPE_NOOPPOSITE,
322                          tc.FILTER_TYPE_LEAD_FOLLOW):
323            # filter without parameter
324            assert params is None
325            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "u", filterType)
326        elif filterType in (tc.FILTER_TYPE_DOWNSTREAM_DIST, tc.FILTER_TYPE_UPSTREAM_DIST,
327                            tc.FILTER_TYPE_TURN, tc.FILTER_TYPE_FIELD_OF_VISION,
328                            tc.FILTER_TYPE_LATERAL_DIST):
329            # filter with float parameter
330            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ud", filterType, params)
331        elif filterType in (tc.FILTER_TYPE_VCLASS, tc.FILTER_TYPE_VTYPE):
332            # filter with list(string) parameter
333            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ul", filterType, params)
334        elif filterType == tc.FILTER_TYPE_LANES:
335            # filter with list(byte) parameter
336            # check uniqueness of given lanes in list
337            lanes = set()
338            for i in params:
339                lane = int(i)
340                if lane < 0:
341                    lane += 256
342                lanes.add(lane)
343            if len(lanes) < len(list(params)):
344                warnings.warn("Ignoring duplicate lane specification for subscription filter.")
345            self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None,
346                          (len(lanes) + 2) * "u", filterType, len(lanes), *lanes)
347
348    def hasGUI(self):
349        try:
350            self.gui.getIDList()
351            return True
352        except TraCIException:
353            return False
354
355    def load(self, args):
356        """
357        Load a simulation from the given arguments.
358        """
359        if self._traceFile:
360            self._traceFile.write("traci.load(%s)\n" % repr(args))
361        self._sendCmd(tc.CMD_LOAD, None, None, "l", args)
362
363    def simulationStep(self, step=0.):
364        """
365        Make a simulation step and simulate up to the given second in sim time.
366        If the given value is 0 or absent, exactly one step is performed.
367        Values smaller than or equal to the current sim time result in no action.
368        """
369        if self._traceFile:
370            args = "" if step == 0 else str(step)
371            self._traceFile.write("traci.simulationStep(%s)\n" % args)
372        if type(step) is int and step >= 1000:
373            warnings.warn("API change now handles step as floating point seconds", stacklevel=2)
374        result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step)
375        for subscriptionResults in self._subscriptionMapping.values():
376            subscriptionResults.reset()
377        numSubs = result.readInt()
378        responses = []
379        while numSubs > 0:
380            responses.append(self._readSubscription(result))
381            numSubs -= 1
382        self.manageStepListeners(step)
383        return responses
384
385    def getVersion(self):
386        command = tc.CMD_GETVERSION
387        result = self._sendCmd(command, None, None)
388        result.readLength()
389        response = result.read("!B")[0]
390        if response != command:
391            raise FatalTraCIError("Received answer %s for command %s." % (response, command))
392        return result.readInt(), result.readString()
393
394    def setOrder(self, order):
395        self._sendCmd(tc.CMD_SETORDER, None, None, "I", order)
396
397    def close(self, wait=True):
398        try:
399            StepManager.close(self, True)
400            for listenerID in list(self._stepListeners.keys()):
401                self.removeStepListener(listenerID)
402            if self._socket is not None:
403                self._sendCmd(tc.CMD_CLOSE, None, None)
404        finally:
405            if self._socket is not None:
406                self._socket.close()
407            self._socket = None
408            self.simulation._setConnection(None)
409            if self._label is not None:
410                if _connections.get("") is self:
411                    del _connections[""]
412                if _connections.get(self._label) is self:
413                    del _connections[self._label]
414        if wait and self._process is not None:
415            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        if traceFile is not None:
 94            self.startTracing(traceFile, traceGetters, DOMAINS)
 95        for domain in DOMAINS:
 96            domain._register(self, self._subscriptionMapping)
 97        self._label = label
 98        if _connectHook is not None:
 99            _connectHook(self)
100        if label is not None:
101            _connections[label] = self
def getLabel(self):
103    def getLabel(self):
104        return self._label
def hasGUI(self):
348    def hasGUI(self):
349        try:
350            self.gui.getIDList()
351            return True
352        except TraCIException:
353            return False
def load(self, args):
355    def load(self, args):
356        """
357        Load a simulation from the given arguments.
358        """
359        if self._traceFile:
360            self._traceFile.write("traci.load(%s)\n" % repr(args))
361        self._sendCmd(tc.CMD_LOAD, None, None, "l", args)

Load a simulation from the given arguments.

def simulationStep(self, step=0.0):
363    def simulationStep(self, step=0.):
364        """
365        Make a simulation step and simulate up to the given second in sim time.
366        If the given value is 0 or absent, exactly one step is performed.
367        Values smaller than or equal to the current sim time result in no action.
368        """
369        if self._traceFile:
370            args = "" if step == 0 else str(step)
371            self._traceFile.write("traci.simulationStep(%s)\n" % args)
372        if type(step) is int and step >= 1000:
373            warnings.warn("API change now handles step as floating point seconds", stacklevel=2)
374        result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step)
375        for subscriptionResults in self._subscriptionMapping.values():
376            subscriptionResults.reset()
377        numSubs = result.readInt()
378        responses = []
379        while numSubs > 0:
380            responses.append(self._readSubscription(result))
381            numSubs -= 1
382        self.manageStepListeners(step)
383        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):
385    def getVersion(self):
386        command = tc.CMD_GETVERSION
387        result = self._sendCmd(command, None, None)
388        result.readLength()
389        response = result.read("!B")[0]
390        if response != command:
391            raise FatalTraCIError("Received answer %s for command %s." % (response, command))
392        return result.readInt(), result.readString()
def setOrder(self, order):
394    def setOrder(self, order):
395        self._sendCmd(tc.CMD_SETORDER, None, None, "I", order)
def close(self, wait=True):
397    def close(self, wait=True):
398        try:
399            StepManager.close(self, True)
400            for listenerID in list(self._stepListeners.keys()):
401                self.removeStepListener(listenerID)
402            if self._socket is not None:
403                self._sendCmd(tc.CMD_CLOSE, None, None)
404        finally:
405            if self._socket is not None:
406                self._socket.close()
407            self._socket = None
408            self.simulation._setConnection(None)
409            if self._label is not None:
410                if _connections.get("") is self:
411                    del _connections[""]
412                if _connections.get(self._label) is self:
413                    del _connections[self._label]
414        if wait and self._process is not None:
415            self._process.wait()