Beispiel #1
0
def traciLoop(port, traciEndTime, index, orderOdd):
    orderTime = 0.25
    time.sleep(orderTime * index)  # assure ordering of outputs
    print("Starting process %s" % (index))
    sys.stdout.flush()
    step = 1
    try:
        traci.init(port)
        if orderOdd and index % 2 == 1:
            traci.setOrder(index)
        sumoStop = False
        while not step > traciEndTime:
            traci.simulationStep()
            vehs = traci.vehicle.getIDList()
            if len(vehs) > 3:
                print("Something is wrong")
            step += 1
        endTime = traci.simulation.getCurrentTime() / DELTA_T
        traci.close()
    #~ except traci.FatalTraCIError as e:
    except Exception as e:
        time.sleep(orderTime * index)  # assure ordering of outputs
        sumoStop = True
        print("client %s: " % index, str(e), " (at TraCIStep %s)" % step)
        sys.stdout.flush()
    if not sumoStop:
        time.sleep(orderTime * index)  # assure ordering of outputs
        print("Process %s ended at step %s" % (index, endTime))
        sys.stdout.flush()
Beispiel #2
0
    def __init__(self, sumoconfig):
        self.frame = 0;             #初始步长为0
        self.inductionloopid = '##'
        #traci.start(['sumo-gui', '--start', '-c', sumoconfig])
        traci.start(cmd=['sumo-gui', '--start', '-c', sumoconfig,
                         "--num-clients", "2"], port=8813, label="sim1")
        traci.setOrder(1)

        self.start = time.perf_counter()
        print("        3.2、启动sumo-gui,初始启动时间:", self.start)
Beispiel #3
0
def start_server(sumo_cmd):
    traci.start(sumo_cmd, port=1111)
    traci.setOrder(1)

    #tracking.track_in_new_thread(traci, 'veh0')
    # vehicleId = 'veh0'
    # traci.vehicle.highlight(vehicleId)

    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()

    traci.close()
Beispiel #4
0
def traciLoop(port, traciEndTime, i, runNr, steplength=0):
    orderTime = 0.25
    time.sleep(orderTime * i)  # assure ordering of outputs
    if steplength == 0:
        steplength = DELTA_T / 1000.
    # order index dependent on runNr
    index = i if (runNr % 2 == 0) else 10 - i
    sys.stdout.flush()
    traci.init(port)
    traci.setOrder(index)
    message = ("Starting process %s (order: %s) with steplength %s\n" % (i, index, steplength))
    step = 1
    vehID = ""
    traciEndStep = math.ceil(traciEndTime / steplength)
    vehResults = traci.vehicle.getSubscriptionResults()
    simResults = traci.simulation.getSubscriptionResults()
    while not step > traciEndStep:
        message = ""
        message += ("Process %s:\n" % (i))
        message += ("   %s vehicle subscription results: %s\n" % (i, str(vehResults)))
        message += ("   %s simulation subscription results: %s\n" % (i, str(simResults)))
        if (vehID == ""):
            vehs = traci.vehicle.getIDList()
            if len(vehs) > 0:
                vehID = vehs[0]
                if i == 1:
                    message += ("   %s subscribing to speed (ID = %s) of vehicle '%s'\n" % (i, tc.VAR_SPEED, vehID))
                    traci.vehicle.subscribe(vehID, [tc.VAR_SPEED])
                    message += ("   -> %s\n" % str(traci.vehicle.getSubscriptionResults()))
                else:
                    message += ("   %s subscribing to acceleration (ID = %s) of vehicle '%s'\n" %
                                (i, tc.VAR_ACCEL, vehID))
                    traci.vehicle.subscribe(vehID, [tc.VAR_ACCEL])
                    message += ("   -> %s\n" % str(traci.vehicle.getSubscriptionResults()))
                    sys.stdout.flush()
        elif len(vehs) == 0:
            message += ("   %s breaking execution: traced vehicle '%s' left." % (i, vehID))
            print(message)
            sys.stdout.flush()
            break
        message += ("   %s stepping (step %s)..." % (i, step))
        print(message)
        sys.stdout.flush()
        message = ""
        time.sleep(0.01)  # give message time to be printed
        simResults = traci.simulationStep(int(step * steplength * 1000))
        vehResults = traci.vehicle.getSubscriptionResults()
        step += 1
    endTime = traci.simulation.getCurrentTime() / DELTA_T
    traci.close()
    time.sleep(orderTime * i)  # assure ordering of outputs
    print("Process %s (order %s) ended at step %s" % (i, index, endTime))
    sys.stdout.flush()
Beispiel #5
0
def traciLoop(port, traciEndTime, i, runNr, steplength=0):
    orderTime = 0.25
    time.sleep(orderTime * i)  # assure ordering of outputs
    if steplength == 0:
        steplength = DELTA_T / 1000.
    # order index dependent on runNr
    index = i if (runNr % 2 == 0) else 10 - i
    print("Starting process %s (order: %s) with steplength %s" %
          (i, index, steplength))
    sys.stdout.flush()
    traci.init(port)
    traci.setOrder(index)
    step = 1
    lastVehID = ""
    traciEndStep = math.ceil(traciEndTime / steplength)
    while not step > traciEndStep:
        print("Process %s:" % (i))
        print("   stepping (step %s)..." % step)
        traci.simulationStep(int(step * steplength * 1000))
        vehs = traci.vehicle.getIDList()
        if len(vehs) != 0:
            vehID = vehs[0]
            if vehID != lastVehID and lastVehID != "":
                print("   breaking execution: traced vehicle '%s' left." %
                      lastVehID)
                break
            else:
                lastVehID = vehID
            print(
                "   Retrieving position for vehicle '%s' -> %s on lane '%s'" %
                (vehID, traci.vehicle.getLanePosition(vehID),
                 traci.vehicle.getLaneID(vehID)))
            print("   Retrieving speed for vehicle '%s' -> %s" %
                  (vehID, traci.vehicle.getSpeed(vehID)))
            traci.vehicle.setSpeedMode(vehID, 0)
            newSpeed = i * 5
            print("   Setting speed for vehicle '%s' -> %s" %
                  (vehID, newSpeed))
            print("   Retrieving speed for vehicle '%s' -> %s" %
                  (vehID, traci.vehicle.getSpeed(vehID)))
            traci.vehicle.setSpeed(vehID, newSpeed)
        elif lastVehID != "":
            print("   breaking execution: traced vehicle '%s' left." %
                  lastVehID)
            break
        step += 1
        sys.stdout.flush()
    endTime = traci.simulation.getCurrentTime() / DELTA_T
    traci.close()
    time.sleep(orderTime * i)  # assure ordering of outputs
    print("Process %s (order %s) ended at step %s" % (i, index, endTime))
    sys.stdout.flush()
Beispiel #6
0
    def __init__(self,
                 cfg_file,
                 step_length,
                 host=None,
                 port=None,
                 sumo_gui=False,
                 client_order=1):
        if sumo_gui is True:
            sumo_binary = sumolib.checkBinary('sumo-gui')
        else:
            sumo_binary = sumolib.checkBinary('sumo')

        if host is None or port is None:
            logging.info('Starting new sumo server...')
            if sumo_gui is True:
                logging.info(
                    'Remember to press the play button to start the simulation'
                )

            traci.start([
                sumo_binary, '--configuration-file', cfg_file, '--step-length',
                str(step_length), '--lateral-resolution', '0.25',
                '--collision.check-junctions'
            ])

        else:
            logging.info('Connection to sumo server. Host: %s Port: %s', host,
                         port)
            traci.init(host=host, port=port)

        traci.setOrder(client_order)

        # Retrieving net from configuration file.
        self.net = _get_sumo_net(cfg_file)

        # To keep track of the vehicle classes for which a route has been generated in sumo.
        self._routes = set()

        # Variable to asign an id to new added actors.
        self._sequential_id = 0

        # Structures to keep track of the spawned and destroyed vehicles at each time step.
        self.spawned_actors = set()
        self.destroyed_actors = set()

        # Traffic light manager.
        self.traffic_light_manager = SumoTLManager()
Beispiel #7
0
def start_sumo_executable(gui, sumo_args, sumocfg_file):
    if sumo_args.sumo_port:
        traci.init(port=int(sumo_args.sumo_port), label="")
        traci.setOrder(1)
    else:
        sumoBinary = sumolib.checkBinary('sumo' if not gui else 'sumo-gui')
        additional_args = shlex.split(
            sumo_args.sumo_args) if sumo_args.sumo_args else []
        args = [sumoBinary, '-c', sumocfg_file] + additional_args
        print('Executing %s' % ' '.join(args))
        traci.start(args)
    traci.simulation.subscribe()

    # Subscribe to all traffic lights. This set of IDs should never change.
    for light_id in traci.trafficlights.getIDList():
        traci.trafficlights.subscribe(
            light_id, [tc.TL_CURRENT_PHASE, tc.TL_CURRENT_PROGRAM])
    def simulation(self):
        #traci.start(['sumo-gui', '-c', './scenario/sumodata/shihuxilu_add.sumocfg', '--start'])
        traci.init(8813)
        traci.setOrder(2)

        for junctionID in self.agentids:
            traci.junction.subscribeContext(  #位置、           角度、          类型、        车长、          颜色、         速度
                junctionID, tc.CMD_GET_VEHICLE_VARIABLE, 1500, [
                    tc.VAR_POSITION, tc.VAR_ANGLE, tc.VAR_TYPE, tc.VAR_LENGTH,
                    tc.VAR_COLOR, tc.VAR_SPEED
                ])

        #traci.inductionloop.subscribeContext("d_1", tc.CMD_GET_INDUCTIONLOOP_VARIABLE, 0, [tc.VAR_LANE_ID, tc.LAST_STEP_VEHICLE_NUMBER])
        traci.lane.subscribeContext(
            "lane1_0", tc.CMD_GET_LANE_VARIABLE, -1,
            [tc.LAST_STEP_MEAN_SPEED, tc.LAST_STEP_VEHICLE_NUMBER])

        while traci.simulation.getMinExpectedNumber() > 0:
            # print("size : ", len(traci.vehicle.getIDList()))
            # for vec_id in traci.vehicle.getIDList():
            #     # 订阅车辆信息:坐标,角度,车辆类型,颜色,速度
            #     traci.vehicle.subscribe(str(vec_id),
            #                             (tc.VAR_POSITION, tc.VAR_ANGLE, tc.VAR_TYPE, tc.VAR_COLOR, tc.VAR_SPEED))
            traci.simulationStep()  ##整合在一起时,只需要一个切帧
            self.frame += 1
            # n = traci.inductionloop.getLastStepVehicleNumber("d_2")
            # print("getLastStepVehicleNumber = ", n)
            dict_sub = traci.lane.getContextSubscriptionResults("lane1_0")
            #print("lane dict = ", dict_sub)
            self.process_vehpos_v17()  #函数用生成帧数据
            #self.process_vehpos()
            #帧间休眠
            sleeping = config.steplength*self.frame - \
                (time.perf_counter() - self.start)
            # print(sleeping)
            if sleeping > 0:
                time.sleep(sleeping)

        sys.stdout.flush()
        traci.close()
        #self.record_file.close()
        self.producer.close()
        exit(0)
Beispiel #9
0
def traciLoop(port, traciEndTime, index, steplength=0):
    orderTime = 0.25
    time.sleep(orderTime * index)  # assure ordering of outputs
    if steplength == 0:
        steplength = DELTA_T / 1000.
    print("Starting process %s with steplength %s" % (index, steplength))
    sys.stdout.flush()
    traci.init(port)
    traci.setOrder(index)
    step = 1
    nrEnteredVehicles = 0
    sumoStop = False
    try:
        traciEndStep = math.ceil(traciEndTime / steplength)
        while not step > traciEndStep:
            traci.simulationStep(int(step * steplength * 1000))
            #print(index, "asking for vehicles")
            # sys.stdout.flush()
            vehs = traci.vehicle.getIDList()
            nrEnteredVehicles += traci.simulation.getDepartedNumber()
            #~ print(index, "Newly entered vehicles: ", traci.simulation.getDepartedNumber(), "(vehs: ", vehs, ")")
            #~ sys.stdout.flush()
            step += 1
        endTime = traci.simulation.getCurrentTime() / DELTA_T
        traci.close()
    except traci.FatalTraCIError as e:
        if str(e) == "connection closed by SUMO":
            time.sleep(orderTime * index)  # assure ordering of outputs
            sumoStop = True
            print("client %s: " % index, str(e), " (at TraCIStep %s)" % step)
            sys.stdout.flush()
        else:
            raise
    if not sumoStop:
        time.sleep(orderTime * index)  # assure ordering of outputs
        print("Process %s ended at step %s" % (index, endTime))
        print("Process %s was informed about %s entered vehicles" %
              (index, nrEnteredVehicles))
        sys.stdout.flush()
Beispiel #10
0
    step = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        print(step)
        # if step == 100:
        # traci.vehicle.changeTarget("1", "e9")
        # traci.vehicle.changeTarget("3", "e9")

        step += 1

    traci.close()
    sys.stdout.flush()


if __name__ == "__main__":
    options = get_options()

    # check binary
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # traci starts sumo as a subprocess and then this script connects and runs
    # traci.start([sumoBinary, "-c", "demo.sumocfg", "--tripinfo-output", "tripinfo.xml"])

    traci.init(55555)
    traci.setOrder(
        2)  # number can be anything as long as each client gets its own number

    run()
Beispiel #11
0
 def sumo_thread_func(self):
     traci.init(self.listen_port)
     traci.setOrder(self.current_order)
     print("current order: ", self.current_order)
     self.current_order += 1
Beispiel #12
0
    def __init__(self,
                 cfg_file,
                 step_length,
                 host=None,
                 port=None,
                 sumo_gui=False,
                 client_order=1,
                 ego_vehicle_id='0',
                 comm_range=50.0):
        if sumo_gui is True:
            sumo_binary = sumolib.checkBinary('sumo-gui')
        else:
            sumo_binary = sumolib.checkBinary('sumo')

        if host is None or port is None:
            logging.info('Starting new sumo server...')
            if sumo_gui is True:
                logging.info('Remember to press the play button to start the simulation')

            traci.start([sumo_binary,
                '--configuration-file', cfg_file,
                '--step-length', str(step_length),
                '--lateral-resolution', '0.25',
                '--collision.check-junctions'
            ])

        else:
            logging.info('Connection to sumo server. Host: %s Port: %s', host, port)
            traci.init(host=host, port=port)

        traci.setOrder(client_order)

        # Retrieving net from configuration file.
        self.net = _get_sumo_net(cfg_file)

        # Creating a random route to be able to spawn carla actors.
        traci.route.add("carla_route", [traci.edge.getIDList()[0]])

        # Variable to asign an id to new added actors.
        self._sequential_id = 0

        # Ego vehicle id and state
        assert isinstance(ego_vehicle_id, str), 'ego vehicle id should be string'
        self.ego_vehicle = ego_vehicle_id
        self.ego_vehicle_state = 0  # 0: not departed yet, 1: departed, 2: arrived
        self.comm_range = comm_range

        # Structures to keep track of the spawned, destroyed vehicles and the vehicles that are in the range of
        # ego vehicle at each time step.
        self.spawned_actors = set()
        self.destroyed_actors = set()
        self.inrange_actors = set()
        self.sensor_to_spawn = set()    # actors that should spawn sensors
        self.sensor_to_stop = set()  # actors on which the attached sensors should be destroyed
        self.perception_actors = set()

        # Traffic light manager.
        self.traffic_light_manager = SumoTLManager()

        # record num of ticks since the ego vehicle is alive
        self.ticks = 0