rampalli.sarma 0 Newbie Poster

Dear friends,

Greetings

I am copying the code which is giving only one error. Please help. I have attached the file also..

cross.py

import subprocess, sys, socket, time, struct, random
from traciControl import initTraCI, simStep, close, getVehNoOfIndLoop, setPhase

PORT = 8813

NSGREEN = ["0101", "0101", "0000"]
NSYELLOW = ["0000", "0000", "0101"]
WEGREEN = ["1010", "1010", "0000"]
WEYELLOW = ["0000", "0000", "1010"]

PROGRAM = [WEYELLOW,WEYELLOW,WEYELLOW,NSGREEN,NSGREEN,NSGREEN,NSGREEN,NSGREEN,NSGREEN,NSGREEN,NSGREEN,NSYELLOW,NSYELLOW,WEGREEN]

N = 9000


pWE = 1./10
pEW = 1./11
pNS = 1./30

routes = open("cross.rou.xml", "w")
print >> routes, '<routes>'
print >> routes, '  <vtype id="typeWE" accel="0.8" decel="4.5" sigma="0.5" length="7.5" maxspeed="16.67"/>'
print >> routes, '  <vtype id="typeNS" accel="0.8" decel="4.5" sigma="0.5" length="20" maxspeed="25"/>'
print >> routes, ""
print >> routes, '  <route id="right" edges="51o 1i 2o 52i" />'
print >> routes, '  <route id="left" edges="52o 2i 1o 51i" />'
print >> routes, '  <route id="down" edges="54o 4i 3o 53i" />'
print >> routes, ""
lastVeh = 0
vehNr = 0
for i in range(N):
    if random.uniform(0,1) < pWE:
        print >> routes, '  <vehicle id="%i" type="typeWE" route="right" depart="%i" />' % (vehNr, i)
        vehNr += 1
        lastVeh = i
    if random.uniform(0,1) < pEW:
        print >> routes, '  <vehicle id="%i" type="typeWE" route="left" depart="%i" />' % (vehNr, i)
        vehNr += 1
        lastVeh = i
    if random.uniform(0,1) < pNS:
        print >> routes, '  <vehicle id="%i" type="typeNS" route="down" depart="%i" color="1,0,0"/>' % (vehNr, i)
        vehNr += 1
        lastVeh = i

print >> routes, "</routes>"
routes.close()
    


sumoExe = "guisim"
sumoConfig = "cross.sumo.cfg"
sumoProcess = subprocess.Popen("%s -c %s" % (sumoExe, sumoConfig), shell=True, stdout=sys.stdout)


initTraCI(PORT)

programPointer = len(PROGRAM)-1
veh = []
step = 0
while not (step > lastVeh and veh == []):
    veh = simStep(1)
    programPointer = min(programPointer+1, len(PROGRAM)-1)
    no = getVehNoOfIndLoop("0")
    if no > 0:
        programPointer = (0 if programPointer == len(PROGRAM)-1 else 3)
    setPhase("0", PROGRAM[programPointer])
    step += 1
    
close()

traciControl.py

import socket, time, struct

CMD_SIMSTEP = 0x01
CMD_STOP = 0x12
CMD_CHANGETARGET = 0x31
CMD_CLOSE = 0x7F
CMD_MOVENODE = 0x80
CMD_INDLOOP = 0xa0
CMD_CHANGETLSTATE = 0xc2

POSITION_ROADMAP = 0x04

VEHICLE_NUMBER = 0x10

STRINGLIST = 0x0E

TLSTATE = 0x21

RESULTS = {0x00: "OK", 0x01: "Not implemented", 0xFF: "Error"}

class Message:
    string = ""
    queue = []

_socket = socket.socket()
_message = Message()

class Storage:

    def __init__(self, content):
        self._content = content
        self._pos = 0

    def read(self, format):
        oldPos = self._pos
        self._pos += struct.calcsize(format)
        return struct.unpack(format, self._content[oldPos:self._pos])

    def readString(self):
        length = self.read("!i")[0]
        return self.read("!%ss" % length)[0]
    
    def ready(self):
        return self._pos < len(self._content) 


def _recvExact():
    result = ""
    while len(result) < 4:
        result += _socket.recv(4 - len(result))
    length = struct.unpack("!i", result)[0] - 4
    result = ""
    while len(result) < length:
        result += _socket.recv(length - len(result))
    return Storage(result)

def _sendExact():
    length = struct.pack("!i", len(_message.string)+4)
    _socket.send(length)
    _socket.send(_message.string)
    _message.string = ""
    result = _recvExact()
    for command in _message.queue:
        prefix = result.read("!BBB")
        err = result.readString()
        if prefix[2] or err:
            print prefix, RESULTS[prefix[2]], err
        elif prefix[1] != command:
            print "Error! Received answer %s for command %s." % (prefix[1], command)
        elif prefix[1] == CMD_STOP:
            length = result.read("!B")[0] - 1
            result.read("!%sx" % length)
    _message.queue = []
    return result

def initTraCI(port):
    for wait in range(10):
        try:
            _socket.connect(("localhost", port))
            break
        except socket.error:
            time.sleep(wait)

def simStep(step):
    _message.queue.append(CMD_SIMSTEP)
    _message.string += struct.pack("!BBdB", 1+1+8+1, CMD_SIMSTEP, float(step), POSITION_ROADMAP)
    result = _sendExact()
    updates = []
    while result.ready():
        if result.read("!BB")[1] == CMD_MOVENODE: 
            updates.append((result.read("!idB")[0], result.readString(), result.read("!fB")[0]))
    return updates

def getVehNoOfIndLoop(IndLoopID):
    _message.queue.append(CMD_INDLOOP)
    _message.string += struct.pack("!BBBi", 1+1+1+4+len(IndLoopID), CMD_INDLOOP, VEHICLE_NUMBER, len(IndLoopID)) + IndLoopID
    result = _sendExact()
    result.read("!B")
    result.read("!B")
    result.read("!B")
    result.read("!B")
    result.read("!B")     # Length
    result.read("!B")     # Identifier
    result.read("!B")     # Variable
    result.readString()   # Induction Loop ID
    result.read("!B")     # Return type of the variable
    return result.read("!i")[0]    # Variable value

def setPhase(TLID, state):
    [phase, brake, yellow] = state
    _message.queue.append(CMD_CHANGETLSTATE)
    _message.string += struct.pack("!BBBi", 1+1+1+4+len(TLID)+1+4+4+len(phase)+4+len(brake)+4+len(yellow), CMD_CHANGETLSTATE, TLSTATE, len(TLID)) + TLID
    _message.string += struct.pack("!Bi", STRINGLIST, 3)
    _message.string += struct.pack("!i", len(phase)) + phase
    _message.string += struct.pack("!i", len(brake)) + brake
    _message.string += struct.pack("!i", len(yellow)) + yellow
    _sendExact()
 
def close():
    _message.queue.append(CMD_CLOSE)
    _message.string += struct.pack("!BB", 1+1, CMD_CLOSE)
    _sendExact()
    _socket.close()

I get error in the place i highlighted or see code snippet below

print prefix, RESULTS[prefix[2]], err

Please help!

Thanks in advance

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.