Exemple #1
0
def removeVehicles(vehiclesToDel, priorityVehicles, mPriorityVehicles, mtraci, outputSocket, vehicles, mVehicles):
    """ Removes the specified vehicles from the simulation """
    returnCode = constants.ACK_OK
    
    mVehicles.acquire()
    for vehicleToDel in vehiclesToDel:
        mPriorityVehicles.acquire()
        if vehicleToDel in priorityVehicles:
            priorityVehicles.remove(vehicleToDel)
        mPriorityVehicles.release()
        
        try:
            vehicles.remove(vehicleToDel)
        except:
            pass
        
        try:
            mtraci.acquire()
            traci.vehicle.remove(vehicleToDel)
            mtraci.release()
        except:
            mtraci.release()
            returnCode = constants.VEHICLE_DELETE_FAILED_UNKNOWN
    mVehicles.release()
    
    sendAck(constants.PRINT_PREFIX_VEHICLE, returnCode, outputSocket)
Exemple #2
0
def processSetDetailsRequest(command, commandSize, outputSocket, mtraci):
    """
    Gets a traffic lights details from
    """
    # SET tllId currentPhaseIndex state0 duration0 ... stateN durationN
    returnCode = constants.ACK_OK
    command.pop(0)
    tllId = command.pop(0)
    currentPhaseIndex = int(command.pop(0))

    # Setting current phase index
    mtraci.acquire()
    oldPhaseIndex = traci.trafficlights.getPhase(tllId)
    try:
        traci.trafficlights.setPhase(tllId, currentPhaseIndex)
    except:
        traci.trafficlights.setPhase(tllId, oldPhaseIndex)
        mtraci.release()
        returnCode = constants.TLL_PHASE_INDEX_ERROR
        sendAck(constants.PRINT_PREFIX_TLL, returnCode, outputSocket)
        raise
    mtraci.release()

    # Setting complete phases definition
    if commandSize > 3:
        mtraci.acquire()
        oldPhasesDefinition = traci.trafficlights.getCompleteRedYellowGreenDefinition(
            tllId)
        try:
            returnCode = setCompletePhasesDefinition(tllId, command,
                                                     currentPhaseIndex, mtraci)
            mtraci.release()
        except:
            oldPhasesDetails = getPhasesDetails(oldPhasesDefinition)
            setCompletePhasesDefinition(tllId, oldPhasesDetails, oldPhaseIndex,
                                        mtraci)
            mtraci.release()
            returnCode = constants.TLL_PHASE_STATE_ERROR

    # Sending ack
    sendAck(constants.PRINT_PREFIX_TLL, returnCode, outputSocket)
Exemple #3
0
def processSetDetailsRequest(command, commandSize, outputSocket, mtraci):
    """
    Gets a traffic lights details from
    """
    # SET tllId currentPhaseIndex state0 duration0 ... stateN durationN
    returnCode = constants.ACK_OK
    command.pop(0)
    tllId = command.pop(0)
    currentPhaseIndex = int(command.pop(0))

    # Setting current phase index
    mtraci.acquire()
    oldPhaseIndex = traci.trafficlights.getPhase(tllId)
    try:
        traci.trafficlights.setPhase(tllId, currentPhaseIndex)
    except:
        traci.trafficlights.setPhase(tllId, oldPhaseIndex)
        mtraci.release()
        returnCode = constants.TLL_PHASE_INDEX_ERROR
        sendAck(constants.PRINT_PREFIX_TLL, returnCode, outputSocket)
        raise
    mtraci.release()
    
    # Setting complete phases definition
    if commandSize > 3:
        mtraci.acquire()
        oldPhasesDefinition = traci.trafficlights.getCompleteRedYellowGreenDefinition(tllId)
        try:
            returnCode = setCompletePhasesDefinition(tllId, command, currentPhaseIndex, mtraci)
            mtraci.release()
        except:
            oldPhasesDetails = getPhasesDetails(oldPhasesDefinition)
            setCompletePhasesDefinition(tllId, oldPhasesDetails, oldPhaseIndex, mtraci)
            mtraci.release()
            returnCode = constants.TLL_PHASE_STATE_ERROR
            
    # Sending ack
    sendAck(constants.PRINT_PREFIX_TLL, returnCode, outputSocket)
Exemple #4
0
def unblockEdges(mtraci, edgesBlocked, outputSocket):
    """
    Unblocks edges in the SUMO simulated network by removing blocked vehicle previously added
    """
    returnCode = constants.ACK_OK
    
    for edgeBlocked in edgesBlocked:
        try:
            mtraci.acquire()
            blockedVehicles = traci.edge.getLastStepVehicleIDs(edgeBlocked)
            mtraci.release()
        except:
            mtraci.release()
            sendAck(constants.PRINT_PREFIX_GRAPH, constants.GRAPH_UNKNOWN_EDGE, outputSocket)
            return
            
        for blockedVehicle in blockedVehicles:
            if blockedVehicle.startswith(constants.BLOCKED_VEHICLE_ID_PREFIX):
                mtraci.acquire()
                traci.vehicle.remove(blockedVehicle)
                mtraci.release()
                
    sendAck(constants.PRINT_PREFIX_GRAPH, returnCode, outputSocket)
Exemple #5
0
def blockEdges(mtraci, edgesBlocked, idCpt, outputSocket):
    """
    Blocks edges in the SUMO simulated network by adding stopped vehicles
    """
    cpt = 1
    i = 0
    returnCode = constants.ACK_OK
    
    while i < len(edgesBlocked):
        try:
            edgeBlocked = edgesBlocked[i]
            i += 1
            nbLanesBlocked = int(edgesBlocked[i])
            i += 1
        except:
            sendAck(constants.PRINT_PREFIX_GRAPH, constants.GRAPH_INVALID_BLOCK_MSG, outputSocket)
            return cpt
        
        routeId = constants.BLOCKED_ROUTE_ID_PREFIX + str(idCpt + cpt)
        route = [edgeBlocked]
        laneIndex = 0
        laneBlocked = edgeBlocked + '_0'
        
        try:
            mtraci.acquire()
            traci.route.add(routeId, route)
            mtraci.release()
        except:
            mtraci.release()
            sendAck(constants.PRINT_PREFIX_GRAPH, constants.GRAPH_UNKNOWN_EDGE, outputSocket)
            return cpt
            
        while laneIndex != nbLanesBlocked - 1:
            vehicleId = constants.BLOCKED_VEHICLE_ID_PREFIX + str(idCpt + cpt)
            # TODO: improve, we can use the lane number by adding it to a dictionary when parsing the network
            try:
                mtraci.acquire()
                laneLength = traci.lane.getLength(laneBlocked)
                mtraci.release()
            except:
                mtraci.release()
                break
               
            laneLength /= 2.0
    
            mtraci.acquire()
            traci.vehicle.add(vehicleId, routeId, -2, 0, 0, 0, constants.DEFAULT_VEHICLE_TYPE)
            traci.vehicle.setStop(vehicleId, edgeBlocked, laneLength, laneIndex, 2147483646)
            mtraci.release()
            
            cpt += 1
            laneIndex += 1
            laneBlocked = laneBlocked[:-1] + str(laneIndex)
            
    sendAck(constants.PRINT_PREFIX_GRAPH, returnCode, outputSocket)
    return cpt
Exemple #6
0
def run(mtraci, inputSocket, outputSocket, eShutdown, eGraphReady, eManagerReady, graphDict, edgesDict):
    """
    See file description
    """
    bufferSize = 32768
    blockedIdCpt = 0
                        
    mtraci.acquire()
    edges = traci.edge.getIDList()
    mtraci.release()
    
    eGraphReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)
    
    while not eShutdown.is_set():
        try:
            try:
                # Read the message from the input socket (blocked until a message is read)
                buff = inputSocket.recv(bufferSize)
            except:
                raise constants.ClosedSocketException("The listening socket has been closed")
            
            if len(buff) == 0:
                    raise constants.ClosedSocketException("The distant socket has been closed")
                
            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)
            
            for cmd in listCommands:
                if len(cmd) != 0:
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]
                        
                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r'):
                        cmd = cmd[:-1]
                        
                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)
                    
                    for i in range(0, commandSize):
                        command[i] = str(command[i])
                        
                    Logger.infoFile("{} Message received: {}".format(constants.PRINT_PREFIX_GRAPH, cmd))
                        
                    #===== EDGES COORDINATES =====
                    # Send all edges coordinates to Client
                    if commandSize == 1 and command[0] == constants.ALL_EDGES_COORDS_REQUEST_HEADER:
                        sendEdgesDetails(edges, outputSocket, mtraci, constants.EDGES_COORDS, edgesDict, False)
                    
                    # Send the specified edges coordinates to Client    
                    elif commandSize > 1 and command[0] == constants.EDGES_COORDS_REQUEST_HEADER:
                        command.pop(0)
                        sendEdgesDetails(command, outputSocket, mtraci, constants.EDGES_COORDS, edgesDict, True)
                    
                    
                    #===== EDGES LENGTH =====
                    # Send all edges length to Client
                    elif commandSize == 1 and command[0] == constants.ALL_EDGES_LENGTH_REQUEST_HEADER:
                        sendEdgesDetails(edges, outputSocket, mtraci, constants.EDGES_LENGTH, None, False)
                    
                    # Send the specified edges length to Client    
                    elif commandSize > 1 and command[0] == constants.EDGES_LENGTH_REQUEST_HEADER:
                        command.pop(0)
                        sendEdgesDetails(command, outputSocket, mtraci, constants.EDGES_LENGTH, None, True)
                    
                    
                    #===== EDGES CONGESTION =====
                    # Send all edges congestion to Client
                    elif commandSize == 1 and command[0] == constants.ALL_EDGES_CONGESTION_REQUEST_HEADER:
                        sendEdgesDetails(edges, outputSocket, mtraci, constants.EDGES_CONGESTION, None, False)
                    
                    # Send the specified edges congestion to Client    
                    elif commandSize > 1 and command[0] == constants.EDGES_CONGESTION_REQUEST_HEADER:
                        command.pop(0)
                        sendEdgesDetails(command, outputSocket, mtraci, constants.EDGES_CONGESTION, None, True)
                    
                    
                    #===== EDGES SUCCESSORS (GRAPH) =====
                    # Send the graph dictionary to Client
                    elif commandSize == 1 and command[0] == constants.ALL_SUCCESSORS_REQUEST_HEADER:
                        sendEdgesDetails(edges, outputSocket, mtraci, constants.EDGES_SUCCESSORS, graphDict, False)
                    
                    # Send the specified edges successors with the corresponding distance to Client    
                    elif commandSize > 1 and command[0] == constants.SUCCESSORS_REQUEST_HEADER:
                        command.pop(0)
                        sendEdgesDetails(command, outputSocket, mtraci, constants.EDGES_SUCCESSORS, graphDict, True)
                        
                        
                    #===== BLOCK/UNBLOCK EDGES =====
                    # Block edges in the SUMO simulation
                    elif commandSize > 2 and command[0] == constants.BLOCK_EDGE_REQUEST_HEADER:
                        command.pop(0)
                        blockedIdCpt += blockEdges(mtraci, command, blockedIdCpt, outputSocket)
                        
                    # Unblock edges in the SUMO simulation
                    elif commandSize > 1 and command[0] == constants.UNBLOCK_EDGE_REQUEST_HEADER:
                        command.pop(0)
                        unblockEdges(mtraci, command, outputSocket)
                        
                        
                    #===== EDGE ID =====
                    # Sending an edge ID from geographic coordinates
                    elif commandSize == 3 and command[0] == constants.EDGE_ID_REQUEST_HEADER:
                        sendEdgeId(mtraci, command[1], command[2], outputSocket)
                        
                        
                    #===== UNKNOWN REQUEST =====
                    else:
                        Logger.warning("{}Invalid command received: {}".format(constants.PRINT_PREFIX_GRAPH, command))
                        sendAck(constants.PRINT_PREFIX_GRAPH, constants.INVALID_MESSAGE, outputSocket)

        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_GRAPH))
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_GRAPH, e.__class__.__name__))
                Logger.exception(e)
Exemple #7
0
def run(mtraci, inputSocket, outputSocket, eShutdown, priorityVehicles, mPriorityVehicles, eVehicleReady, eManagerReady, vehicles, mVehicles):
    """
    See file description
    """
    bufferSize = 32768
    cRouteId = 0
    
    eVehicleReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)
    
    while not eShutdown.is_set():
        try:
            try:
                # Read the message from the input socket (blocked until a message is read)
                buff = inputSocket.recv(bufferSize)
            except:
                raise constants.ClosedSocketException("The listening socket has been closed")
            
            if len(buff) == 0:
                    raise constants.ClosedSocketException("The distant socket has been closed")
                
            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)
            
            for cmd in listCommands:
                if len(cmd) != 0:
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]
                        
                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r'):
                        cmd = cmd[:-1]
                        
                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)
                    
                    for i in range(0, commandSize):
                        command[i] = str(command[i])
                        
                    Logger.infoFile("{} Message received: {}".format(constants.PRINT_PREFIX_VEHICLE, cmd))
                    
                    # Add the user ID and the route to the map
                    if commandSize > 2 and command[0] == constants.VEHICLE_ADD_REQUEST_HEADER:
                        try:
                            command.pop(0)
                            vehicleId = command[0]
                            command.pop(0)
                            priority = command[0]
                            command.pop(0)
                            addVehicle(vehicleId, priority, command, mtraci, cRouteId, outputSocket, priorityVehicles, mPriorityVehicles, vehicles, mVehicles)
                        except Exception as e:
                            sendIdentifiedAck(command[1], constants.VEHICLE_INVALID_ROUTE, outputSocket)
                            raise
                        cRouteId += 1
                        
                        
                    # Remove the specified vehicles from the simulation
                    elif commandSize >= 1 and command[0] == constants.VEHICLE_DELETE_REQUEST_HEADER:
                        if commandSize == 1:
                            removeVehicles(list(vehicles), priorityVehicles, mPriorityVehicles, mtraci, outputSocket, vehicles, mVehicles)
                        else:
                            command.pop(0)
                            removeVehicles(command, priorityVehicles, mPriorityVehicles, mtraci, outputSocket, vehicles, mVehicles)
                        
                        
                    # Stress test, add random vehicles to the simulation
                    elif commandSize == 4 and command[0] == constants.VEHICLE_ADD_RAND_REQUEST_HEADER:
                        try:
                            addRandomVehicles(command[1], int(command[2]), int(command[3]), mtraci, outputSocket, vehicles, mVehicles)
                        except:
                            sendAck(constants.PRINT_PREFIX_VEHICLE, constants.VEHICLE_MOCK_FAILED, outputSocket)
                            raise
                        
                        
                    # Send vehicles speed to the remote client
                    elif commandSize >= 1 and command[0] == constants.VEHICLE_SPEED_REQUEST_HEADER:
                        if commandSize == 1:
                            sendVehiclesSpeed(vehicles, outputSocket, mtraci, mVehicles)
                        else:
                            command.pop(0)
                            sendVehiclesSpeed(command, outputSocket, mtraci, mVehicles)
                        
                        
                    # Send vehicles geographic coordinates to the remote client
                    elif commandSize >= 1 and command[0] == constants.VEHICLE_COORDS_REQUEST_HEADER:
                        if commandSize == 1:
                            sendVehiclesCoordinates(vehicles, mtraci, outputSocket, mVehicles)
                        else:
                            command.pop(0)
                            sendVehiclesCoordinates(command, mtraci, outputSocket, mVehicles)
                        
                        
                    # Send arrived vehicles ID to the remote client
                    elif commandSize == 1 and command[0] == constants.VEHICLE_ARRIVED_REQUEST_HEADER:
                        mtraci.acquire()
                        arrivedVehicles = traci.simulation.getArrivedIDList()
                        mtraci.release()
                        arrivedVehicles = getRegularVehicles(arrivedVehicles)
                        sendArrivedVehicles(vehicles, outputSocket, mtraci)
                        
                        
                    # Error
                    else:
                        Logger.warning("{}Invalid command received: {}".format(constants.PRINT_PREFIX_VEHICLE, command))
                        sendAck(constants.PRINT_PREFIX_VEHICLE, constants.INVALID_MESSAGE, outputSocket)

        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_VEHICLE))
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_VEHICLE, e.__class__.__name__))
                Logger.exception(e)
Exemple #8
0
            # Adding route and vehicle to SUMO
            mVehicles.acquire()
			if not constants.IGNORED_VEHICLES_REGEXP.match(vehicle):
				vehicles.append(vehicleId)
            mtraci.acquire()
            traci.route.add(routeId, route)
            traci.vehicle.add(vehicleId, routeId, -2, 0, 0, 0, "DEFAULT_VEHTYPE")
            mtraci.release()
            mVehicles.release()
            route[:] = []
            i += 1
        else:
            route = []
            
    Logger.info("{}Done".format(constants.PRINT_PREFIX_VEHICLE))
    sendAck(constants.PRINT_PREFIX_VEHICLE, returnCode, outputSocket)
    

def sendVehiclesSpeed(vehiclesId, outputSocket, mtraci, mVehicles):
    """
    Sends the speed of the given vehicles to the distant client
    """
    speedMsg = []
    speedMsg.append(constants.VEHICLE_SPEED_RESPONSE_HEADER)
    
    mVehicles.acquire()
    for vehicleId in vehiclesId:
        try:
            mtraci.acquire()
            speed = traci.vehicle.getSpeed(vehicleId)
            mtraci.release()
Exemple #9
0
def run(mtraci, inputSocket, outputSocket, eShutdown, eRouteReady,
        eManagerReady, graphDict, junctionsDict, edgesDict):
    """
    See file description
    """
    bufferSize = 1024

    eRouteReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)

    while not eShutdown.is_set():
        try:
            # Read the message from the input socket (blocked until a message is read)
            try:
                buff = inputSocket.recv(bufferSize)
            except:
                raise constants.ClosedSocketException(
                    "The listening socket has been closed")

            if len(buff) == 0:
                raise constants.ClosedSocketException(
                    "The distant socket has been closed")

            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)

            for cmd in listCommands:
                if len(cmd) != 0:
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]

                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE
                                          or cmd[-1] == '\r'):
                        cmd = cmd[:-1]

                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)

                    for i in range(0, commandSize):
                        command[i] = str(command[i])

                    Logger.infoFile("{} Message received: {}".format(
                        constants.PRINT_PREFIX_ROUTER, cmd))

                    # Routing request
                    if commandSize >= 6 and command[
                            0] == constants.ROUTING_REQUEST_HEADER:
                        try:
                            command.pop(0)
                            algorithm = command[0]
                            command.pop(0)
                            geo = int(command[0])
                            command.pop(0)
                            processRouteRequest(algorithm, geo, command,
                                                junctionsDict, graphDict,
                                                edgesDict, outputSocket,
                                                mtraci)
                        except Exception as e:
                            if e.__class__.__name__ != constants.CLOSED_SOCKET_EXCEPTION and e.__class__.__name__ != constants.TRACI_EXCEPTION:
                                sendRoutingError(
                                    outputSocket,
                                    constants.ROUTE_ROUTING_REQUEST_FAILED)
                                raise

                    # Error
                    else:
                        Logger.warning("{}Invalid command received: {}".format(
                            constants.PRINT_PREFIX_ROUTER, command))
                        sendAck(constants.PRINT_PREFIX_ROUTER,
                                constants.INVALID_MESSAGE, outputSocket)

        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(
                    constants.PRINT_PREFIX_ROUTER))
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(
                    constants.PRINT_PREFIX_ROUTER, e.__class__.__name__))
                Logger.exception(e)
Exemple #10
0
def run(mtraci, inputSocket, outputSocket, eShutdown, eTrafficLightsReady,
        eManagerReady):
    """
    See file description
    """
    bufferSize = 1024

    mtraci.acquire()
    trafficLightsId = traci.trafficlights.getIDList()
    mtraci.release()

    eTrafficLightsReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)

    while not eShutdown.is_set():
        try:
            # Read the message from the input socket (blocked until a message is read)
            try:
                buff = inputSocket.recv(bufferSize)
            except:
                traceback.print_exc()
                raise constants.ClosedSocketException(
                    "The listening socket has been closed")

            if len(buff) == 0:
                raise constants.ClosedSocketException(
                    "The distant socket has been closed")

            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)

            for cmd in listCommands:
                if len(cmd) != 0:
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]

                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE
                                          or cmd[-1] == '\r'):
                        cmd = cmd[:-1]

                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)

                    for i in range(0, commandSize):
                        command[i] = str(command[i])

                    Logger.infoFile("{} Message received: {}".format(
                        constants.PRINT_PREFIX_TLL, cmd))

                    # Send all traffic lights geographic coordinates to the client
                    if commandSize == 1 and command[
                            0] == constants.ALL_TLL_COORDS_REQUEST_HEADER:
                        sendTrafficLightsPosition(trafficLightsId, mtraci,
                                                  outputSocket, False)

                    # Send the requested traffic lights geographic coordinates to the client
                    elif commandSize > 1 and command[
                            0] == constants.TLL_COORDS_REQUEST_HEADER:
                        command.pop(0)
                        sendTrafficLightsPosition(command, mtraci,
                                                  outputSocket, True)

                    # Process a GET details request (**)
                    elif commandSize == 5 and command[
                            0] == constants.TLL_GET_DETAILS_REQUEST_HEADER:
                        processGetDetailsRequest(command[1], command[2],
                                                 int(command[3]), outputSocket,
                                                 mtraci, int(command[4]))

                    # Process a SET details request (**)
                    elif commandSize > 2 and command[
                            0] == constants.TLL_SET_DETAILS_REQUEST_HEADER:
                        processSetDetailsRequest(command, commandSize,
                                                 outputSocket, mtraci)

                    # Error
                    else:
                        Logger.warning("{}Invalid command received: {}".format(
                            constants.PRINT_PREFIX_TLL, command))
                        sendAck(constants.PRINT_PREFIX_TLL,
                                constants.INVALID_MESSAGE, outputSocket)

        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(
                    constants.PRINT_PREFIX_TLL))
                Logger.exception(e)
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(
                    constants.PRINT_PREFIX_TLL, e.__class__.__name__))
                Logger.exception(e)
Exemple #11
0
def run(mtraci, inputSocket, outputSocket, eShutdown, eRouteReady, eManagerReady, graphDict, junctionsDict, edgesDict):
    """
    See file description
    """
    bufferSize = 1024
    
    eRouteReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)
    
    while not eShutdown.is_set():
        try:
            # Read the message from the input socket (blocked until a message is read)
            try:
                buff = inputSocket.recv(bufferSize)
            except:
                raise constants.ClosedSocketException("The listening socket has been closed")
            
            if len(buff) == 0:
                    raise constants.ClosedSocketException("The distant socket has been closed")
                
            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)
            
            for cmd in listCommands:
                if len(cmd) != 0:
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]
                        
                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r'):
                        cmd = cmd[:-1]
                        
                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)
                    
                    for i in range(0, commandSize):
                        command[i] = str(command[i])
                        
                    Logger.infoFile("{} Message received: {}".format(constants.PRINT_PREFIX_ROUTER, cmd))
                
                    # Routing request
                    if commandSize >= 6 and command[0] == constants.ROUTING_REQUEST_HEADER:
                        try:
                            command.pop(0)
                            algorithm = command[0]
                            command.pop(0)
                            geo = int(command[0])
                            command.pop(0)
                            processRouteRequest(algorithm, geo, command, junctionsDict, graphDict, edgesDict, outputSocket, mtraci)
                        except Exception as e:
                            if e.__class__.__name__ != constants.CLOSED_SOCKET_EXCEPTION and e.__class__.__name__ != constants.TRACI_EXCEPTION:
                                sendRoutingError(outputSocket, constants.ROUTE_ROUTING_REQUEST_FAILED)
                                raise
                        
                        
                    # Error
                    else:
                        Logger.warning("{}Invalid command received: {}".format(constants.PRINT_PREFIX_ROUTER, command))
                        sendAck(constants.PRINT_PREFIX_ROUTER, constants.INVALID_MESSAGE, outputSocket)
                
        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_ROUTER))
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_ROUTER, e.__class__.__name__))
                Logger.exception(e)
Exemple #12
0
def run(mtraci, inputSocket, outputSocket, eShutdown, eTrafficLightsReady, eManagerReady):
    """
    See file description
    """
    bufferSize = 1024
    
    mtraci.acquire()
    trafficLightsId = traci.trafficlights.getIDList()
    mtraci.release()
    
    eTrafficLightsReady.set()
    while not eManagerReady.is_set():
        time.sleep(constants.SLEEP_SYNCHRONISATION)
        
    while not eShutdown.is_set():
        try:
            # Read the message from the input socket (blocked until a message is read)
            try:
                buff = inputSocket.recv(bufferSize)
            except:
                traceback.print_exc()
                raise constants.ClosedSocketException("The listening socket has been closed")
            
            if len(buff) == 0:
                    raise constants.ClosedSocketException("The distant socket has been closed")
            
            listCommands = buff.decode().split(constants.MESSAGES_SEPARATOR)
            
            for cmd in listCommands:
                if len(cmd) != 0:    
                    if cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r':
                        cmd = cmd[:-1]
                        
                    if len(cmd) != 0 and (cmd[-1] == constants.END_OF_LINE or cmd[-1] == '\r'):
                        cmd = cmd[:-1]
                        
                    command = cmd.split(constants.SEPARATOR)
                    commandSize = len(command)
                    
                    for i in range(0, commandSize):
                        command[i] = str(command[i])
                    
                    Logger.infoFile("{} Message received: {}".format(constants.PRINT_PREFIX_TLL, cmd))
                    
                    # Send all traffic lights geographic coordinates to the client
                    if commandSize == 1 and command[0] == constants.ALL_TLL_COORDS_REQUEST_HEADER:
                        sendTrafficLightsPosition(trafficLightsId, mtraci, outputSocket, False)
                    
                    
                    # Send the requested traffic lights geographic coordinates to the client    
                    elif commandSize > 1 and command[0] == constants.TLL_COORDS_REQUEST_HEADER:
                        command.pop(0)
                        sendTrafficLightsPosition(command, mtraci, outputSocket, True)
                        
                        
                    # Process a GET details request (**)
                    elif commandSize == 5 and command[0] == constants.TLL_GET_DETAILS_REQUEST_HEADER:
                        processGetDetailsRequest(command[1], command[2], int(command[3]), outputSocket, mtraci, int(command[4]))
                        
                        
                    # Process a SET details request (**)
                    elif commandSize > 2 and command[0] == constants.TLL_SET_DETAILS_REQUEST_HEADER:
                        processSetDetailsRequest(command, commandSize, outputSocket, mtraci)
                    
                    
                    # Error
                    else:
                        Logger.warning("{}Invalid command received: {}".format(constants.PRINT_PREFIX_TLL, command))
                        sendAck(constants.PRINT_PREFIX_TLL, constants.INVALID_MESSAGE, outputSocket)

        except Exception as e:
            if e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION or e.__class__.__name__ == constants.TRACI_EXCEPTION:
                Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_TLL))
                Logger.exception(e)
                sys.exit()
            else:
                Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_TLL, e.__class__.__name__))
                Logger.exception(e)