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() speedMsg.append(constants.SEPARATOR) speedMsg.append(vehicleId) speedMsg.append(constants.SEPARATOR) speedMsg.append(str(speed)) except: mtraci.release() mVehicles.release() speedMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(speedMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_VEHICLE, strmsg))
def sendTrafficLightsDetails(tllId, tmsLogin, screenshotPath, outputSocket, mtraci, detailsLevel): """ Sends a traffic lights details answer(***) to the remote client using an output socket """ # DTL tmsLogin screenshotPath currentPhaseIndex nextSwitchTime state0 duration0 ... stateN durationN try: mtraci.acquire() currentPhaseIndex = traci.trafficlights.getPhase(tllId) currentTime = traci.simulation.getCurrentTime() nextSwitchTime = traci.trafficlights.getNextSwitch(tllId) completePhasesDefinition = traci.trafficlights.getCompleteRedYellowGreenDefinition( tllId) mtraci.release() except: mtraci.release() raise nextSwitchTime = nextSwitchTime - currentTime phasesDetails = getPhasesDetails(completePhasesDefinition) details = [] details.append(constants.TLL_GET_DETAILS_RESPONSE_HEADER) details.append(constants.SEPARATOR) details.append(tmsLogin) details.append(constants.SEPARATOR) details.append(screenshotPath) details.append(constants.SEPARATOR) details.append(str(currentPhaseIndex)) details.append(constants.SEPARATOR) details.append(str(nextSwitchTime)) if detailsLevel == 1: i = 0 while i < len(phasesDetails): details.append(constants.SEPARATOR) details.append(phasesDetails[i]) i += 1 details.append(constants.SEPARATOR) details.append(phasesDetails[i]) i += 1 details.append(constants.END_OF_MESSAGE) strmsg = ''.join(details) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed")
def sendEdgeId(mtraci, lon, lat, outputSocket): """ Sends an edge ID calculated from geographic coordinates to the remote client """ edgeId = getEdgeFromCoords(lon, lat, mtraci) routeCoordsMsg = [] routeCoordsMsg.append(constants.EDGE_ID_RESPONSE_HEADER) routeCoordsMsg.append(constants.SEPARATOR) routeCoordsMsg.append(edgeId) routeCoordsMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(routeCoordsMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_GRAPH, strmsg))
def sendIdentifiedAck(vehicleId, errorCode, outputSocket): """ Sends an acknowledge(2) message to the remote client using an output socket """ errorMsg = [] errorMsg.append(constants.ACKNOWLEDGE_HEADER) errorMsg.append(constants.SEPARATOR) errorMsg.append(vehicleId) errorMsg.append(constants.SEPARATOR) errorMsg.append(str(errorCode)) errorMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(errorMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_VEHICLE, strmsg))
def sendArrivedVehicles(arrivedVehicles, mtraci, outputSocket): """ Gets all arrived vehicles ID from SUMO and send them to the remote client by output socket """ msgArrivedVehicles = [] msgArrivedVehicles.append(constants.VEHICLE_ARRIVED_RESPONSE_HEADER) for vehicleId in arrivedVehicles: msgArrivedVehicles.append(constants.SEPARATOR) msgArrivedVehicles.append(vehicleId) msgArrivedVehicles.append(constants.END_OF_MESSAGE) strmsg = ''.join(msgArrivedVehicles) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_SIMULATOR, strmsg))
def sendRoutingError(outputSocket, errorCode): """ Sends an error(3) message to the remote client with an error code """ errorMsg = [] errorMsg.append(constants.ERROR_HEADER) errorMsg.append(constants.SEPARATOR) errorMsg.append(str(errorCode)) errorMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(errorMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_ROUTER, strmsg))
def sendAck(printPrefix, code, outputSocket): """ Send an acknowledge with a return code to the remote client """ ack = [] ack.append(constants.ACKNOWLEDGE_HEADER) ack.append(constants.SEPARATOR) ack.append(str(code)) ack.append(constants.SEPARATOR) ack.append(constants.END_OF_MESSAGE) strmsg = ''.join(ack) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(printPrefix, strmsg))
def sendRoute(route, outputSocket): """ Sends a routing(2) message to Client using the outputSocket For this purpose, the route is converted to geographic coordinates by traci """ routeMsg = [] routeMsg.append(constants.ROUTING_RESPONSE_HEADER) for edge in route: routeMsg.append(constants.SEPARATOR) routeMsg.append(str(edge)) routeMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(routeMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_ROUTER, strmsg))
def sendVehiclesCoordinates(vehiclesId, mtraci, outputSocket, mVehicles): """ Gets every vehicles position from SUMO and send then these ones to the remote client by an output socket """ # If the simulated vehicles number we have to take into account is not 0 vehiclesPos = [] vehiclesPos.append(constants.VEHICLE_COORDS_RESPONSE_HEADER) mVehicles.acquire() for vehicleId in vehiclesId: try: mtraci.acquire() coords = traci.vehicle.getPosition(vehicleId) coordsGeo = traci.simulation.convertGeo(coords[0], coords[1], False) mtraci.release() # Build the message to send by the output socket vehiclesPos.append(constants.SEPARATOR) vehiclesPos.append(vehicleId) vehiclesPos.append(constants.SEPARATOR) vehiclesPos.append(str(coordsGeo[0])) vehiclesPos.append(constants.SEPARATOR) vehiclesPos.append(str(coordsGeo[1])) except: mtraci.release() mVehicles.release() # Send the position of each vehicle by the output socket vehiclesPos.append(constants.END_OF_MESSAGE) strmsg = ''.join(vehiclesPos) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed")
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)
def sendEdgesDetails(edges, outputSocket, mtraci, informationType, dictionary, uniqueMsg): """ Send information messages to Client, followed by and end message. The dictionary must be the edgesDictionary if an edges coordinates () request is specified The dictionary must be the graphDictionary if a graph () or successors () request is specified """ edgesNumber = 0 edgesMsg = [] informationHeader = getInformationHeader(informationType) informationEnd = getInformationEnd(informationType) edgeListSeparator = getEdgeListSeparator(informationType) maximumEdgesPerMsg = getMaximumEdgesPerMessage(informationType) # Adding specified header edgesMsg.append(informationHeader) for edge in edges: if edge[0] != ':': edgesMsg.append(edgeListSeparator) edgesMsg.append(edge) edgesMsg.append(constants.SEPARATOR) # EDGES COORDINATES if(informationType == constants.EDGES_COORDS): # Getting the two junctions ID linked with the current edge edgesJunctions = dictionary[edge] # Getting geographic coordinates of the two junctions center mtraci.acquire() predecessorCoords = traci.junction.getPosition(edgesJunctions[0]) predecessorCoordsGeo = traci.simulation.convertGeo(predecessorCoords[0], predecessorCoords[1], False) successorCoords = traci.junction.getPosition(edgesJunctions[1]) successorCoordsGeo = traci.simulation.convertGeo(successorCoords[0], successorCoords[1], False) mtraci.release() # Adding to the current message edgesMsg.append(str(predecessorCoordsGeo[0])) edgesMsg.append(constants.SEPARATOR) edgesMsg.append(str(predecessorCoordsGeo[1])) edgesMsg.append(constants.SEPARATOR) edgesMsg.append(str(successorCoordsGeo[0])) edgesMsg.append(constants.SEPARATOR) edgesMsg.append(str(successorCoordsGeo[1])) # EDGES LENGTH elif(informationType == constants.EDGES_LENGTH): lane = edge + '_0' # Getting edge length mtraci.acquire() length = traci.lane.getLength(lane) mtraci.release() # Adding to the current message edgesMsg.append(str(length)) # EDGES CONGESTION elif(informationType == constants.EDGES_CONGESTION): #Calculating congestion mtraci.acquire() congestion = traci.edge.getLastStepOccupancy(edge) mtraci.release() # Adding to the current message edgesMsg.append(str(congestion)) # EDGES SUCCESSORS (GRAPH) elif(informationType == constants.EDGES_SUCCESSORS): for edgeSucc in dictionary[edge]: edgesMsg.append(edgeSucc) edgesMsg.append(constants.SEPARATOR) edgesNumber += 1 # Sending the message if this one has reached the maximum edges number per message if not uniqueMsg and edgesNumber == maximumEdgesPerMsg: edgesMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(edgesMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: <{} edges information ({})>".format(constants.PRINT_PREFIX_GRAPH, maximumEdgesPerMsg, informationType)) edgesNumber = 0 edgesMsg[:] = [] # Adding specified header edgesMsg.append(informationHeader) edgesMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(edgesMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: <{} edges information ({})>".format(constants.PRINT_PREFIX_GRAPH, edgesNumber, informationType)) if not uniqueMsg: # Sending end of edges information messages edgesMsg[:] = [] # Adding specified header edgesMsg.append(informationHeader) edgesMsg.append(edgeListSeparator) # Adding specified ending edgesMsg.append(informationEnd) edgesMsg.append(constants.END_OF_MESSAGE) strmsg = ''.join(edgesMsg) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException("The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format(constants.PRINT_PREFIX_GRAPH, strmsg))
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)
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)
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)
def sendTrafficLightsPosition(trafficLightsId, mtraci, outputSocket, uniqueMsg): """ Sends traffic lights position messages(*) to the remote client using an output socket """ trafficLightsNumber = 0 trafficLightsPos = [] trafficLightsPos.append(constants.TLL_COORDS_REQUEST_HEADER) # Requires 32768 bytes buffer: sending traffic lights per packet of 500 for trafficId in trafficLightsId: tllCoords = getTrafficLightCoordinates(trafficId, mtraci) if tllCoords == -1: tllCoords = calculateTrafficLightCoordinates(trafficId, mtraci) trafficLightsPos.append(constants.SEPARATOR) trafficLightsPos.append(trafficId) trafficLightsPos.append(constants.SEPARATOR) trafficLightsPos.append(str(tllCoords[0])) trafficLightsPos.append(constants.SEPARATOR) trafficLightsPos.append(str(tllCoords[1])) trafficLightsNumber += 1 if not uniqueMsg and trafficLightsNumber == constants.TLL_NUMBER_PER_MESSAGE: trafficLightsPos.append(constants.SEPARATOR) trafficLightsPos.append(constants.END_OF_MESSAGE) strmsg = ''.join(trafficLightsPos) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile( "{} Message sent: <{} traffic lights positions>".format( constants.PRINT_PREFIX_TLL, constants.TLL_NUMBER_PER_MESSAGE)) trafficLightsNumber = 0 trafficLightsPos[:] = [] trafficLightsPos.append(constants.TLL_COORDS_REQUEST_HEADER) trafficLightsPos.append(constants.END_OF_MESSAGE) strmsg = ''.join(trafficLightsPos) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile("{} Message sent: <{} traffic lights positions>".format( constants.PRINT_PREFIX_TLL, trafficLightsNumber)) if not uniqueMsg: # Sending end of traffic lights position messages trafficLightsPos[:] = [] trafficLightsPos.append(constants.TLL_COORDS_REQUEST_HEADER) trafficLightsPos.append(constants.SEPARATOR) trafficLightsPos.append(constants.TLL_POS_END) trafficLightsPos.append(constants.END_OF_MESSAGE) strmsg = ''.join(trafficLightsPos) try: outputSocket.send(strmsg.encode()) except: raise constants.ClosedSocketException( "The listening socket has been closed") Logger.infoFile("{} Message sent: {}".format( constants.PRINT_PREFIX_TLL, strmsg))