コード例 #1
0
ファイル: main_main.py プロジェクト: bornobob/DES-Exercises
def create_runner():
    r = Robot(SensorMap(sensor_map_master),
              bluetooth=BluetoothMaster(MAC_ADDRESS, PORT))

    mission_Mission = Mission([
        BorderAction(priority=5),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=4),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=3),
        UltrasoundAction(rotate_degrees=0.5, dodge_rocks=False, priority=2),
        DriveAction(priority=1)
    ])
    mission_Mission2 = Mission([
        BorderAction(priority=5),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=4),
        DontDrownAction(
            lakes=[ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW],
            priority=3),
        UltrasoundAction(rotate_degrees=0.5, dodge_rocks=False, priority=2),
        DriveAction(priority=1)
    ])

    Runner(r, [mission_Mission, mission_Mission2]).run()
コード例 #2
0
def remove_missions_with_redundancies(strategies):
    final_possible_strategies = []

    #chaque stratégie est un tuple de missions, c'est à dire une assignation spécifique d'une mission par groupe
    while len(
            strategies
    ) > 1:  #on parcourt la liste des stratégies, et on elève celles qui ont des doublons
        mission_tuple = strategies[-1]
        strategies.pop()
        #on reconverti cette assignation de missions sous forme d'une liste d'actions
        actionList = convertStratToActions(mission_tuple)
        # Et on vérifie qu'il n'y a pas de doublons dans les groupes visés par ces actions
        target_list = []
        duplicate_count = 0
        for action in actionList:
            if action.target_group not in target_list:
                target_list.append(action.target_group)
            else:  #todo plutot que de l'effacer brutalement, implementer merge
                duplicate_count += 1
        if duplicate_count == 0:
            newMission = Mission(actionList)
            final_possible_strategies.append(newMission)
    final_possible_strategies.append(
        Mission(convertStratToActions(strategies[0]))
    )  #mais, quoi qu'il arrive, on rajoute toujours au moins une stratégie

    return final_possible_strategies
コード例 #3
0
ファイル: main_main.py プロジェクト: bornobob/DES-Exercises
def create_runner():
    r = Robot(SensorMap(sensor_map_master),
              bluetooth=BluetoothMaster(MAC_ADDRESS, PORT))

    mission_Name24 = Mission([
        BorderAction(rotate_degrees=0.3, priority=4),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=3),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=2),
        DriveAction(speed=3, priority=1)
    ], SpeakCelebration('weeeeeeeeeeeeeeeeeee'))
    mission_Name52 = Mission([
        BorderAction(priority=4),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=3),
        PushRockAction(number_of_rocks=1, priority=2),
        DriveAction(speed=3, priority=1)
    ], DanceCelebration())

    Runner(r, [mission_Name24, mission_Name52]).run()
コード例 #4
0
class TestMissionMethods(unittest.TestCase):
    def setUp(self):
        waypoint_dict = open('waypoints_test.json', 'rb')
        waypoint_list = json.loads(waypoint_dict.read())
        self.mission = Mission(waypoint_list["waypoints"], mission_type='regular_flight', takeoff_required=True)

    def test_intermidate_waypoint_generation(self):
        self.mission.generate_intermediate_waypoints()
        self.assertEqual(10, len(self.mission.primary_route))
    
    def test_take_off_command_added(self):
        first_waypoint = self.mission.initial_waypoint_list[0]
        self.mission.add_take_off_command()
        self.assertEqual(self.mission.command_sequence[1], Command(0,0,0,      
                                                            mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
                                                            mavutil.mavlink.MAV_CMD_NAV_TAKEOFF,
                                                            0, 0, 0, 0, 0, 0,
                                                            first_waypoint["latitude"], first_waypoint["longitude"], first_waypoint["altitude"]))
    
    def test_command_sequence_generation(self):
        self.mission.generate_intermediate_waypoints()
        self.mission.add_take_off_command()
        self.mission.build_mission_command_sequence()
        self.assertEqual(10, len(self.mission.command_sequence))
        self.assertEqual(self.mission.command_sequence[9].x, 37.443188)
        self.assertEqual(self.mission.command_sequence[9].y, -95.5827334)
        self.assertEqual(self.mission.command_sequence[9].z, 25)
        self.assertEqual(self.mission.command_sequence[9].command, 16)
コード例 #5
0
ファイル: mission_control.py プロジェクト: pelotron/GrindBot
    def __update_db_missions(self, mission_tree):
        """
        Postorder traversal of a list of MissionJson objects that converts them into
        missions that are stored in the DB.  Recursive.
        """
        parent_dbm_list = []

        for mission in mission_tree:
            # recurse down to leaf nodes
            child_dbm_list = self.__update_db_missions(mission.branches)

            db_mission = None

            try:
                # update existing missions
                db_mission = database.session.query(Mission).filter(
                    Mission._name == mission.name).one()
                db_mission.update_data(mission)
            except orm.exc.NoResultFound:
                # add new mission
                db_mission = Mission(mission)
                database.session.add(db_mission)

            db_mission._branches = child_dbm_list
            parent_dbm_list.append(db_mission)

        return parent_dbm_list
コード例 #6
0
    def refresh_missions(self):
        results = self.web.get_started()
        for mission in results['missions']:
            if (mission['user_id'] != 2091):
                logging.info('mission of id {} is not owned by 2091 - {}'.format(mission['id'], mission['user_id']))
                continue
            if str(mission['id']) not in self.missions:
                self.missions[str(mission['id'])] = Mission(mission)
            else:
                self.missions[str(mission['id'])].update(mission)

            if (str(mission['id']) not in self.mission_ids):
                self.mission_ids.append(str(mission['id']))
        for drive in results['drive']:
            self.queue.put({
                'type': 'unit_update',
                'data': {
                    'id': drive['id'],
                    'fms_real': drive['fms_real'],
                    'mission_id': drive['mid']
                }
            })
        for patient in results['combined_patients']:
            self.queue.put({'type':'patientcombined_add','data':patient})
        for patient in results['patients']:
            self.queue.put({'type':'patient_add','data':patient})
コード例 #7
0
ファイル: game.py プロジェクト: ajmitc/b-17
    def init_mission(self):
        self.game.mission = Mission( len(self.game.missions) + 1 )
        self.init_bomber()

        # Get Target City and Target Type
        targettable = MissionTargetTable()
        target, targettype, targetzone = targettable.get_mission( self.game.mission.mission_number )
        self.game.mission.target = target
        self.game.mission.target_type = targettype
        self.game.mission.target_zone = targetzone

        print "Mission %d: %s [%s] Zone %d" % (self.game.mission.mission_number, target, targettype, targetzone)
        self.pause()

        # Get formation position
        formationtable = FormationPositionTable()
        self.game.mission.position_in_formation = formationtable.get_position()
        self.game.mission.position_in_squadron  = formationtable.get_squadron_position()

        print "Formation Position: %s" % self.game.mission.position_in_formation
        if self.game.mission.mission_number >= 6:
            print "Squadron Position: %s" % self.game.mission.position_in_squadron
        self.pause()

        # Get fighter coverage
        fightercoveragetable = FighterCoverageTable()
        for zone in xrange( 2, targetzone + 1 ):
            self.game.mission.fighter_coverage[ OUT  ][ zone ] = fightercoveragetable.get_fighter_coverage( self.game.mission.mission_number )
            self.game.mission.fighter_coverage[ BACK ][ zone ] = fightercoveragetable.get_fighter_coverage( self.game.mission.mission_number )

        # Get fighter waves modifiers
        flightlogtable = FlightLogGazeteer()
        for zone in xrange( 2, targetzone + 1 ):
            self.game.mission.fighter_waves_modifiers[ zone ] = flightlogtable.get_modifier( target, zone )
コード例 #8
0
  def test_complete_rover_missions_multi(self):
    mission_str = '''
      5 5
      1 2 N
      LMLMLMLMM
      3 3 E
      MMRMMRMRRM
    '''
    mission = Mission.from_str(mission_str)

    r = mission.rovers[0]
    self.assertEqual(r.current_position(), "x: 1, y: 2, heading: N")
    r = mission.rovers[1]
    self.assertEqual(r.current_position(), "x: 3, y: 3, heading: E")
    
    mission.complete_rover_missions()

    # 5 5
    # 3 3 E
    # MM RMM RM RRM
    # MM  -> 5,3 E
    # RMM -> 5,1 S
    # RM  -> 4,1 W
    # RRM -> 5,1 E
    r = mission.rovers[0]
    self.assertEqual(r.current_position(), "x: 1, y: 3, heading: N")
    r = mission.rovers[1]
    self.assertEqual(r.current_position(), "x: 5, y: 1, heading: E")
コード例 #9
0
ファイル: game.py プロジェクト: Bobbadillio/ResistanceGame
    def round(self):
        nPlayers = len(self.players)
        voteCounter = 0
        #set up the mission
        plan=self.getPlan(self.missionCounter)
        for player in self.players:
            player.setState(self.gameState)
        while voteCounter<5:
            #maybe players communicate somehow 
            #leader proposes a mission
           
            leader = self.getLeader()
            team = leader.proposeTeam(plan,self.players)
            #Display option:
            #print "proposal #{}:".format(voteCounter+1), " ".join([player.name for player in team])

            #every player votes
            votes = [player.vote(team) for player in self.players]
            nApprove = sum(1 for vote in votes if vote)
            nReject = sum(1 for vote in votes if not(vote))
            #leader counter increments
            self.incrementLeaderCounter()
        
            #if mission is approved
            if nApprove>nReject:
                # make a mission for the proposed team
                thisMission = Mission(team,plan)
                # run the mission
                thisMission.run()
                # add it to the game state's mission list
                
                self.gameState.addMission(thisMission)
                self.missionCounter+=1
                return
            else:
            #  increment voteCounter
                voteCounter+=1
            if voteCounter>=5:
                # Missions fail after 5 tries
                thisMission = Mission([],plan)
                this.Mission.result='fail'
                self.gameState.addMission(thisMission)
                return
コード例 #10
0
def generate_group_missions(groupes, state, species, max_split_rate):
    nb_human_groups = len(state.getMembers(Species.human))
    nb_enemy_groups = len(state.getMembers(species.inverse()))
    nb_my_groups = len(groupes)
    sub_missions_array = []
    #on genere une liste de missions possibles par groupe (split et non split)
    for groupMe in groupes:
        possible_actions = enumerate_possible_actions(state, groupMe, species,
                                                      nb_my_groups,
                                                      max_split_rate)

        possible_simple_actions = possible_actions[0]
        possible_simple_rates = []
        possible_split_actions = possible_actions[1]
        possible_split_rates = []
        group_missions = []

        for action in possible_simple_actions:
            #on calcule les notes des actions "simples": un groupe attaque un groupe d'humains
            action.calc_mark(state)
            possible_simple_rates.append(action.mark)
        for actions in possible_split_actions:
            #on calcule les notes des missions splittées
            actions[0].calc_mark(state)
            actions[1].calc_mark(state)
            possible_split_rates.append(actions[0].mark + actions[1].mark)

        #ensuite, on cree notre liste de missions possibles pour ce groupe
        for action in possible_simple_actions:
            group_missions.append(Mission([action]))
        for split_couple in possible_split_actions:
            group_missions.append(Mission([split_couple[0], split_couple[1]]))

        merged_rates = possible_simple_rates + possible_split_rates

        group_missions.sort(key=dict(zip(group_missions, merged_rates)).get,
                            reverse=True)

        #on rajoute les missions possibles de ce groupe (déjà pré-tronquée) à la liste de sous-missions globales
        sub_missions_array.append(group_missions[:(nb_human_groups +
                                                   nb_enemy_groups)])

    return sub_missions_array
コード例 #11
0
    def save_model(self, request, obj, form, change):
        ip = obj.host.ip
        username = obj.host.username
        password = obj.host.password
        rule = obj.firewall_template.config_message
        value = json.loads(obj.template_value)
        command = rule.format(**value)
        print command
        # TODO:下发添加命令
        Mission().create_firewall_rule(ip, username, password, command)

        obj.save()
コード例 #12
0
    def __init__(self, config):
        self.default_webserver_ip = config.ip
        self.default_port = config.port
        self.default_webserver_port = config.webport
        self.id = config.id
        self.ip = config.ip
        self.home_location = LocationGlobalRelative(config.lat, config.lon,
                                                    config.alt)
        self.sitl = config.sitl
        # Follow instructions @ https://github.com/abearman/sparrow-dev/wiki/How-to-use-the-DroneKit-SITL-simulator
        self.instance = self.id - 1
        self.sitlInstance = SITL(instance=self.instance)
        self.sitlInstance.download('copter', '3.3', verbose=True)
        # system (e.g. "copter", "solo"), version (e.g. "3.3"), verbose

        if self.sitl:
            sitl_args = [
                '--simin=127.0.0.1:4000', '--simout=127.0.0.1:4001', '--model',
                'quad', '--home=' + str(self.home_location.lat) + "," +
                str(self.home_location.lon) + "," +
                str(self.home_location.alt) + ",360"
            ]
            print(str(sitl_args))
            self.sitlInstance.launch(sitl_args,
                                     verbose=False,
                                     await_ready=False,
                                     restart=True)
            self.connection_string = self.sitlInstance.connection_string()
        else:
            self.connection_string = '/dev/tty/ACM0'

        self.formation = None
        self.webserver = str(self.ip) + ":" + str(self.default_webserver_port)
        print('\nConnecting to vehicle on: %s\n' % self.connection_string)
        #print(site.USER_SITE)
        self.vehicle = connect(self.connection_string)
        print("Drone: " + str(self.id) + " connected!")
        self.drone_data = self.get_drone_data()
        # print(self.drone_data.__dict__.get(str(self.id)))
        # self.print_drone_data()
        self.mission = Mission(self.vehicle)
        # logger config
        self.logger = logging.getLogger("/logs/drone" + str(self.id) + "_log")
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler("drone" + str(self.id) + "_log")
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
コード例 #13
0
    def __init__(self, building_height):
        rospy.init_node('offb')
        self.height = building_height
        self.GPS_ready = False

        # Wait for Offboard and drone to be ready
        ready = rospy.wait_for_message('/gps_ready_from_offboard', Bool, timeout=rospy.Duration(60*5)) # Wait for offboard to get GPS fix for 5 minutes, because sometimes GPS locks take long to get when a board is booted up the first time

        if ready:
            nav = NavSatFix()
            # And now put the node into a waiting loop to wait for GPS Lock from Offboard
            nav = rospy.wait_for_message('mavros/global_position/global', NavSatFix)
            self.coordinates = np.array([nav.latitude, nav.longitude])
        else:
            rospy.loginfo("Never got position confirmation from Offboard")

        self.house_result_pub = rospy.Publisher('/house_results_from_overpass_local', BuildingPolygonResult, queue_size=5) # Information about the house
        self.camera_stuff_pub = rospy.Publisher('/camera_and_distances', CameraStuff, queue_size=1)
        self.impression_keyframes_pub = rospy.Publisher('/impression_poses_from_planner', PoseArray, queue_size=5) # Poses to take one image of each facade of the house
        self.inspection_keyframes_pub = rospy.Publisher('/keyframes_poses_from_planner', PoseArray, queue_size=5)

        #self.segmented_image_sub = rospy.Subscriber('segmented_image_from_cnn', cnnResult, self.segmented_image_callback, queue_size=5)

        self.image_and_rois_sub = rospy.Subscriber('/segmented_image_from_cnn', ImageAndRois, callback=self.image_and_rois_callback)

        self.get_tiles_ready = False

        self.images_list = []
        self.rois_list = []

        self.s = Sun(self.coordinates[0], self.coordinates[1])
        self.m = Mission(80, 80)
        self.model_walls = []
        self.model_windows = []

        self.fig_thread = Thread(target=self.draw_thread, args=())
        self.fig_thread.daemon = True

        self.fig = []
        self.ax = []
コード例 #14
0
def get_missions():
	connection = psycopg2.connect("dbname=mydb user=searcher password=allDatSQL")
	myCursor = connection.cursor()
	myCursor.execute("SELECT * FROM missions ORDER BY level;")
	missions = []
	results = myCursor.fetchall()
	for miss in results:
		pk = int(miss[0])
		name = miss[1]
		description = miss[2]
		level = int(miss[3])
		new_mission = Mission(pk, name, level, description)
		missions.append(new_mission)
	return missions
コード例 #15
0
def save_missions(soup):
    dprint('Extracting missions...            ', end='')
    sys.stdout.flush()
    locations = []
    rewardsTableNames = [
        'missionRewards', 'keyRewards', 'transientRewards', 'sortieRewards'
    ]
    for name in rewardsTableNames:
        locations += next(
            soup.find_all(id=name)[0].next_sibling.children).contents
    missions = []
    for element in locations:
        if 'class' in element and element['class'] == 'blank-row':
            continue
        if element.contents[0].name == 'th' and len(element.contents) == 1:
            if element.contents[0].string.split()[0] == 'Rotation':
                rotation = element.string.split()[1]
            else:
                rotation = ''
                current_element = element.string
        elif len(element.contents
                 ) == 2 and not element.contents[0].name == 'th':
            event = False
            mission = current_element.replace('Infested Salvage', 'Salvage')
            if mission.split()[0] == "Event:":
                event = True
                mission = ' '.join(mission.split()[1:])
            if re.match(r'^([\w -]+)/([\w -]+) \(([\w -]+)\)$', mission):
                match = re.search(r'^([\w -]+)/([\w -]+) \(([\w -]+)\)$',
                                  mission)
                mission = Mission(match.group(1), match.group(2),
                                  match.group(3), event)
            elif mission.startswith('Orokin Derelict'):
                mission_type = mission.split()[-1]
                mission = Mission('Derelict', mission_type, mission_type,
                                  False)
            else:

                mission = GenericDropLocation(mission)
            missions.append(
                MissionDrop(
                    mission, element.contents[0].string, rotation,
                    float(element.contents[1].string.split()[-1][1:-2])))
    dprint('done.')
    dprint('Writing to file...                ', end='')
    sys.stdout.flush()

    if not os.path.exists('data/missions.db'):
        open('data/missions.db', 'x').close()
    open('data/missions.db', 'w').write(repr(missions))
    dprint('done.')
コード例 #16
0
ファイル: main.py プロジェクト: QidiLiu/Python_Apps
    def dp_wd():
        dp_wd = Toplevel()
        dp_wd.title('待办事项')
        to_do_list = Frame(dp_wd)
        to_do_list.pack(fill='x')
        add_mission = Frame(dp_wd)
        add_mission.pack(fill='x')

        with open('data.json', 'r') as f:
            data = load(f)

        for i in range(len(data)):
            locals()[data[i]['MID']] = Mission(data[i]['content'], 'Top')
            locals()[data[i]['MID']].display(to_do_list)

        new_mission_entry = Entry(add_mission, width=20)
        new_mission_entry.pack(side=LEFT)

        def add_mission_button():
            locals()['MS' + strftime('%Y%m%d%H%M%S', localtime())] = Mission(
                new_mission_entry.get(), 'Top')
            locals()['MS' +
                     strftime('%Y%m%d%H%M%S', localtime())].display(to_do_list)

            def is_MS(s):
                if list(s)[0] == 'M' and list(s)[1] == 'S':
                    return s

            new_list = list(filter(is_MS, list(locals())))

            def ms2dict(ms):
                return {'MID': 'MS' + ms.MID, 'content': ms.content}

            for i in range(len(new_list)):
                new_list[i] = ms2dict(locals()[new_list[i]])
            with open('data.json', 'w') as f:
                f.write(dumps(new_list))

        Button(add_mission, text='添加',
               command=add_mission_button).pack(side=RIGHT)

        test_list = [{
            'MID': 'MS002',
            'content': 'Test suceed!'
        }, {
            'MID': 'MS003',
            'content': 'Succed again!'
        }]
コード例 #17
0
ファイル: main.py プロジェクト: QidiLiu/Python_Apps
        def add_mission_button():
            locals()['MS' + strftime('%Y%m%d%H%M%S', localtime())] = Mission(
                new_mission_entry.get(), 'Top')
            locals()['MS' +
                     strftime('%Y%m%d%H%M%S', localtime())].display(to_do_list)

            def is_MS(s):
                if list(s)[0] == 'M' and list(s)[1] == 'S':
                    return s

            new_list = list(filter(is_MS, list(locals())))

            def ms2dict(ms):
                return {'MID': 'MS' + ms.MID, 'content': ms.content}

            for i in range(len(new_list)):
                new_list[i] = ms2dict(locals()[new_list[i]])
            with open('data.json', 'w') as f:
                f.write(dumps(new_list))
コード例 #18
0
ファイル: droneBrain.py プロジェクト: UND-UCAS/UAV_Swarm_Dev
    def __init__(self, config):
        self.default_webserver_ip = config.ip
        self.default_port = config.port
        self.default_webserver_port = config.webport
        self.id = config.id
        self.ip = config.ip
        self.sitl = config.sitl
        self.sitlInstance = SITL('/home/dino/.dronekit/sitl/copter-3.3/apm')
        if self.sitl:
            sitl_args = [
                '--instance ' + str(self.id - 1), '-I0', '--model', 'quad',
                '--home=-35.363261,149.165230,584,353'
            ]
            self.sitlInstance.launch(sitl_args,
                                     verbose=False,
                                     await_ready=False,
                                     restart=True)
            self.connection_string = self.sitlInstance.connection_string()
        else:
            self.connection_string = '/dev/tty/ACM0'

        self.formation = None
        self.webserver = str(self.ip) + ":" + str(self.default_webserver_port)
        print('\nConnecting to vehicle on: %s\n' % self.connection_string)
        self.vehicle = connect(self.connection_string)
        print("Drone: " + str(self.id) + " connected!")
        self.drone_data = self.get_drone_data()
        self.print_drone_data()
        self.mission = Mission(self.vehicle)
        # logger config
        self.logger = logging.getLogger("drone" + (str)(self.id) + "_log")
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler("drone" + (str)(self.id) + "_log")
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
コード例 #19
0
ファイル: test.py プロジェクト: cmu-mars/p2c2-base-image
def build_mission(
        map_file: str,
        world_file: str,
        start_x: float,
        start_y: float,
        end_x: float,
        end_y: float,
        base_launch_file: str = os.path.join(
            os.path.dirname(__file__), 'robotest.launch'),  # noqa: pycodestyle
        distance_threshold: float = 0.3) -> Mission:
    pos_start = (start_x, start_y)
    pos_target = (end_x, end_y)
    mission = Mission(map_position_initial=pos_start,
                      map_position_end=pos_target,
                      base_launch_file=base_launch_file,
                      map_to_world=map_to_world,
                      map_file=map_file,
                      world_file=world_file,
                      time_limit=90,
                      distance_threshold=distance_threshold)
    return mission
コード例 #20
0
  def test_complete_rover_missions_single(self):
    mission_str = '''
      5 5
      1 2 N
      LMLMLMLMM
    '''
    mission = Mission.from_str(mission_str)
  
    r = mission.rovers[0]
    self.assertEqual(r.current_position(), "x: 1, y: 2, heading: N")
    
    mission.complete_rover_missions()

    # 5 5
    # 1 2 N
    # LM LM LM LMM
    # LM -> 0,2 W
    # LM -> 0,1 S
    # LM -> 1,1 E
    # LMM -> 1,3 N
    r = mission.rovers[0]
    self.assertEqual(r.current_position(), "x: 1, y: 3, heading: N")
コード例 #21
0
def build_mission(start_x: float, start_y: float, end_x: float,
                  end_y: float) -> Mission:
    pos_start = (start_x, start_y)
    pos_target = (end_x, end_y)

    # TODO: parameterise
    dir_catkin = '/home/mars/catkin_ws'
    dir_turtlebot_gazebo = os.path.join(
        dir_catkin, 'src/turtlebot_simulator/turtlebot_gazebo')
    map_file = os.path.join(dir_turtlebot_gazebo, 'maps/playground.yaml')
    world_file = os.path.join(dir_turtlebot_gazebo, 'worlds/playground.world')
    base_launch_file = os.path.join(os.path.dirname(__file__),
                                    'robotest.launch')

    mission = Mission(map_position_initial=pos_start,
                      map_position_end=pos_target,
                      base_launch_file=base_launch_file,
                      map_to_world=map_to_world,
                      map_file=map_file,
                      world_file=world_file,
                      time_limit=90)
    return mission
コード例 #22
0
 def handle_mission(self, data):
     if self.Title:
         self.Title_Text = data
         self.Title = False
         position = self.Title_Text.find('(')
         self.Missions.append(
             Mission(self.Title_Text[:position - 1],
                     self.Title_Text[position:]))
     elif self.Rotation:
         self.Rotation = False
         self.Rotation_Number = data
     else:
         if self.Loot == "":
             self.Loot = data
         else:
             self.Loot_Rarity = self.parse_luck(data)
             if self.Rotation_Number is not None:
                 self.Missions[-1].add_loot(self.Loot, self.Loot_Rarity,
                                            self.Rotation_Number)
             else:
                 self.Missions[-1].add_loot(self.Loot, self.Loot_Rarity)
             self.Loot = ""
             self.Loot_Rarity = ""
コード例 #23
0
 async def daily(self, ctx):
     if ctx.invoked_subcommand is None:
         sub_command = ctx.subcommand_passed
         await ctx.send(embed=Mission(self, sub_command).embed_daily)
コード例 #24
0
def yaml_parse(yaml_text, navigator, total_time):
    my_missions = {}
    mission_to_mission_dep = {}
    count = 0
    base_mission = None
    missions_left = []
    tree = []

    for name in yaml_text.keys():
        mission = yaml_text[name]
        marker_dep = mission["marker_dep"]
        mis_dep = mission["mission_dep"]
        is_base = mission["is_base"]
        min_time = mission["min_time"]
        points = mission["points"]
        looking_for = mission["looking_for"]
        weight = mission["weight"]
        if marker_dep != "None":
            marker = yield navigator.database_query(marker_dep,
                                                    raise_exception=False)
            if not marker.found:
                fprint("NOT COMPLETING {}, NO MARKER FOUND".format(name),
                       msg_color="green")
                continue
            marker = marker.objects[0]
        else:
            marker = None

        num_mission_deps = len(mis_dep)
        if mis_dep == "None":
            num_mission_deps = 0
        if type(mis_dep) is not list:
            num_mission_deps = 1

        if "mission_script" in mission.keys():
            mission_script = mission["mission_script"]
            m = Mission(name,
                        marker,
                        min_time,
                        weight,
                        points,
                        looking_for,
                        num_mission_deps,
                        mission_script=mission_script)
        else:
            m = Mission(name, marker, min_time, weight, points, looking_for,
                        num_mission_deps)
        my_missions[name] = m

        if is_base:
            base_mission = m
        elif mis_dep == "None":
            count += 1
            missions_left.append(m)
            tree.append(m)
        else:
            count += 1
            missions_left.append(m)
            mission_to_mission_dep[name] = mis_dep

    # Go through the missions and give them all children dependencies
    for mission_name in mission_to_mission_dep.keys():
        parent_name = mission_to_mission_dep[mission_name]
        if type(parent_name) is not list:
            parent_names = []
            parent_names.append(parent_name)
        else:
            parent_names = parent_name
        for p in parent_names:
            child_name = mission_name
            parent_mission = my_missions[p]
            child_mission = my_missions[child_name]
            parent_mission.add_child(child_mission)

    total_time -= count * 60
    defer.returnValue((missions_left, base_mission, tree, total_time))
コード例 #25
0
 def test_mission_initialization(self):
   mission = Mission.from_str(MissionTest.mission_str)
 
   self.assertEqual(mission.terrain.latitude, 5)
   self.assertEqual(mission.terrain.longitude, 5)
   self.assertEqual(mission.rovers.__len__(), 1)
コード例 #26
0
ファイル: motor_demo.py プロジェクト: mattvenn/v2
from arduino import Commands, Arduino
from time import sleep
from motors import Motors
from mission import Mission
board = Arduino()
board.connect()
move = Motors()

mission = Mission()

power_f = 100
power_t = 100

mission.startMission()
while True:
        
	
	print("Forward") 
	move.forward(power_f)
	sleep(4)
	move.stop()

	print("turn left")
	move.leftMotor(power_f, 0)
	move.rightMotor(power_f, 1)
	sleep(1)
	move.stop()
	sleep(1)

	print("turn right")
	move.leftMotor(power_f, 1)
コード例 #27
0
ファイル: msl.py プロジェクト: wsilva32/tol
	#Default Ka-1 Radar Location (Table mountain)
	Ka1_location = [40.1451,-105.2408,1676]

	#Default connection to aircraft (SITL)
	ac_address = 'udp:localhost'
	io_port = '14550'
	gcs_port = '14551'

	#stuff for Auto Mode
	ottegoal = 1
	auto = False
	autostack = [2,1,2,1,2,1] #stack read from right to left because it's a pop stack
	oldwpcount = 0

	#Create mission instance (this will try to connect to the aircraft)
	mission = Mission(Ka1_location, ac_address + ':' + io_port)

	#Create ground control station thread (but don't start unless we are connected to aircraft)
	gcs = ge_interface(ac_address + ':' + gcs_port,Ka1_location)
	gcs.daemon = True

	if mission.connected:
		gcs.start()

	user_input = 0
	while True:
		clear = lambda : os.system('tput reset')
		clear()
		print("Ka-1 Location: {0}").format(Ka1_location)
		print("Aircraft address: {0} (IO: {1}, GCS: {2})").format(ac_address,io_port,gcs_port)
		if mission.connected:
コード例 #28
0
 def setUp(self):
     waypoint_dict = open('waypoints_test.json', 'rb')
     waypoint_list = json.loads(waypoint_dict.read())
     self.mission = Mission(waypoint_list["waypoints"], mission_type='regular_flight', takeoff_required=True)
コード例 #29
0
  def test_display_rover_missions(self):
    mission = Mission.from_str(MissionTest.mission_str)

    mission.display_rover_missions()
コード例 #30
0
ファイル: app.py プロジェクト: nikita-kostin/multiplanning
from logger import get_logger

parser = argparse.ArgumentParser()
parser.add_argument('filenames',
                    metavar='<str>',
                    type=str,
                    nargs=True,
                    help='Files to process.')

logger = get_logger(__name__)

if __name__ == '__main__':
    logger.info('Starting...')

    args = parser.parse_args()

    for filename in args.filenames:
        logger.info("Processing file, filename = {}".format(filename))
        mission = Mission(filename)

        return_code = mission.read()
        if return_code != 0:
            logger.info('Skipping...')
            continue

        mission.compute()

        mission.write()

    logger.info('Terminating...')
コード例 #31
0
#!/usr/bin/env python3
from character import Character
from mission import Mission

bStats = {"hp": 100, "defense": 20, "dmg": 10, "catch_rate": 70}
gStats = {"hp": 130, "defense": 20, "dmg": 10, "catch_rate": 30}
jStats = {"hp": 100, "defense": 40, "dmg": 10, "catch_rate": 80}
uStats = {"hp": 120, "defense": 30, "dmg": 10, "catch_rate": 40}
batman = Character("batman", bStats)
greenLantern = Character("green lantern", bStats)
joker = Character("joker", jStats)
universe = Character("univers", uStats)

mission = Mission("Death squad", [joker, universe])
mission.heroes.append(batman)
mission.heroes.append(greenLantern)
mission.start_mission()
print("j hp: " + str(joker.hp))
print("u hp: " + str(universe.hp))
print("b hp: " + str(batman.hp))
print("g hp: " + str(greenLantern.hp))

コード例 #32
0
ファイル: main_main.py プロジェクト: bornobob/DES-Exercises
def create_runner():
	r = Robot(SensorMap(sensor_map_master), bluetooth=BluetoothMaster(MAC_ADDRESS, PORT))
	
	mission_Mission = Mission([BorderAction(priority=2), ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=0), DontDrownAction(lakes=[ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW, ColorSensor.COLOR_BLUE], priority=1), DriveAction(priority=0)])
	
	Runner(r, [mission_Mission]).run()
コード例 #33
0
ファイル: game.py プロジェクト: JStation/WCPGW_Game
 def load_missions(self):
     for mission in Game.load_json_objects(self.PATH_MISSIONS):
         self._missions.add(Mission.from_json(mission))
コード例 #34
0
 async def next(self, ctx, *, arg1=None):
     sub_command = ctx.subcommand_passed
     await ctx.send(embed=Mission(self, sub_command).embed_daily)
コード例 #35
0
    def configure(self):

        #Add Components
        compress = self.add('compress', CompressionSystem())
        mission = self.add('mission', Mission())
        pod = self.add('pod', Pod())
        flow_limit = self.add('flow_limit', TubeLimitFlow())
        tube_wall_temp = self.add('tube_wall_temp', TubeWallTemp())

        #Boundary Input Connections
        #Hyperloop -> Compress
        self.connect('Mach_pod_max', 'compress.Mach_pod_max')
        self.connect('Ps_tube', 'compress.Ps_tube')
        self.connect('Mach_c1_in', 'compress.Mach_c1_in')  #Design Variable
        self.connect('c1_PR_des', 'compress.c1_PR_des')  #Design Variable
        #Hyperloop -> Mission
        self.connect('tube_length', 'mission.tube_length')
        self.connect('pwr_marg', 'mission.pwr_marg')
        #Hyperloop -> Flow Limit
        self.connect('Mach_pod_max', 'flow_limit.Mach_pod')
        self.connect('Ps_tube', 'flow_limit.Ps_tube')
        self.connect('pod.radius_inlet_back_outer', 'flow_limit.radius_inlet')
        self.connect('Mach_bypass', 'flow_limit.Mach_bypass')
        #Hyperloop -> Pod
        self.connect('Ps_tube', 'pod.Ps_tube')
        self.connect('hub_to_tip', 'pod.hub_to_tip')
        self.connect('coef_drag', 'pod.coef_drag')
        self.connect('n_rows', 'pod.n_rows')
        self.connect('length_row', 'pod.length_row')
        #Hyperloop -> TubeWallTemp
        self.connect('solar_heating_factor',
                     'tube_wall_temp.nn_incidence_factor')
        self.connect('tube_length', 'tube_wall_temp.length_tube')

        #Inter-component Connections
        #Compress -> Mission
        self.connect('compress.speed_max', 'mission.speed_max')
        self.connect('compress.pwr_req', 'mission.pwr_req')
        #Compress -> Pod
        self.connect('compress.area_c1_in', 'pod.area_inlet_out')
        self.connect('compress.area_inlet_in', 'pod.area_inlet_in')
        self.connect('compress.rho_air', 'pod.rho_air')
        self.connect('compress.F_net', 'pod.F_net')
        self.connect('compress.speed_max', 'pod.speed_max')
        #Compress -> TubeWallTemp
        self.connect('compress.nozzle_Fl_O', 'tube_wall_temp.nozzle_air')
        self.connect('compress.bearing_Fl_O', 'tube_wall_temp.bearing_air')
        #Mission -> Pod
        self.connect('mission.time', 'pod.time_mission')
        self.connect('mission.energy', 'pod.energy')

        #Add Solver
        solver = self.add('solver', BroydenSolver())
        solver.itmax = 50  #max iterations
        solver.tol = .001
        #Add Parameters and Constraints
        solver.add_parameter('compress.W_in', low=-1e15, high=1e15)
        solver.add_parameter('compress.c2_PR_des', low=-1e15, high=1e15)
        solver.add_parameter([
            'compress.Ts_tube', 'flow_limit.Ts_tube',
            'tube_wall_temp.temp_boundary'
        ],
                             low=-1e-15,
                             high=1e15)
        solver.add_parameter(
            ['flow_limit.radius_tube', 'pod.radius_tube_inner'],
            low=-1e15,
            high=1e15)

        solver.add_constraint('.01*(compress.W_in-flow_limit.W_excess) = 0')
        solver.add_constraint('compress.Ps_bearing_residual=0')
        solver.add_constraint('tube_wall_temp.ss_temp_residual=0')
        solver.add_constraint(
            '.01*(pod.area_compressor_bypass-compress.area_c1_out)=0')

        driver = self.driver
        driver.workflow.add('solver')
        #driver.recorders = [CSVCaseRecorder(filename="hyperloop_data.csv")] #record only converged
        #driver.printvars = ['Mach_bypass', 'Mach_pod_max', 'Mach_c1_in', 'c1_PR_des', 'pod.radius_inlet_back_outer',
        #                    'pod.inlet.radius_back_inner', 'flow_limit.radius_tube', 'compress.W_in', 'compress.c2_PR_des',
        #                    'pod.net_force', 'compress.F_net', 'compress.pwr_req', 'pod.energy', 'mission.time',
        #                    'compress.speed_max', 'tube_wall_temp.temp_boundary']

        #Declare Solver Workflow
        solver.workflow.add(
            ['compress', 'mission', 'pod', 'flow_limit', 'tube_wall_temp'])
コード例 #36
0
ファイル: rfid_test.py プロジェクト: mattvenn/v2
from arduino import Commands, Arduino
from time import sleep
from motors import Motors
from mission import Mission

mission = Mission()
board = Arduino()
board.connect()
move = Motors()

print("ok")

move.stop()
sleep(2)
print("sampling")
location = mission.getLocation()
sample = mission.takeSample(location)

print(sample)

mission.endMission()
コード例 #37
0
ファイル: project.py プロジェクト: gjh558/kaleidoscope
        status = mission.get_status()
        if (status != MissionStatus.UNSURE) and (
                status != MissionStatus.UNDONE) and (status !=
                                                     MissionStatus.DONE):
            print("Wrong mission status", status)
            return False
        self.__missions[status].remove(mission)
        return True

    def get_missions(self, status):
        return self.__missions[status]

    def get_mission(self, status, index):
        return self.__missions[status][index]


# Test
if __name__ == "__main__":
    p = Project("Adserver", "")
    p.set_deadline("2017-12-31")
    m1 = Mission("a mission", "details", MissionStatus.UNDONE)
    m2 = Mission("b mission", "details", MissionStatus.UNDONE)
    p.add_mission(m1)
    p.add_mission(m2)

    print("Project: %s" % p.get_name())
    print("Dealine: %s" % p.get_deadline())
    missions = p.get_missions(MissionStatus.UNDONE)
    for m in missions:
        print("-->%d: %s" % (m.id(), m.get_description()))
コード例 #38
0
ファイル: dump_targets.py プロジェクト: CnuUasLab/MISCONSYS
	with open('./config.json') as data_file:
		constants = json.load(data_file)
	util.succLog("Successfully extracted config data")

except IOError:
	util.errLog("WARNING: Config file not found!")
	util.errLog("Aborting operation! Make sure config.json exists in the /src directory.")
	sys.exit(0)


img_cli = IMGClient('0.0.0.0', '5001')

# Instantiate Mission module.
miss = Mission(
		constants['auvsi']['host'],
		constants['auvsi']['port'],
		constants['auvsi']['username'],
		constants['auvsi']['password']
		)

target_list = img_cli.getTargets()

for tgt in target_list:
    img_id = tgt['image']
    print img_id
    img_obj = img_cli.getImage(img_id)

    path = img_obj['img_photo']

    miss.postImage( lat=img_obj['lat'],
                    lon=img_obj['lon'],
コード例 #39
0
ファイル: testAll.py プロジェクト: mattvenn/v2
from arduino import Commands, Arduino
#from arduino import Commands, Arduino
from ultrasound import Ultrasound
from time import sleep
from motors import Motors
from mission import Mission
import RPi.GPIO as GPIO
import picamera
RED_LED_GPIO = 26
GREEN_LED_GPIO = 29
BUTTON = 36

GPIO.setmode(GPIO.BOARD)
board = Arduino()
move = Motors()
mission = Mission()

#variables to be set up for the test
power_f = 90
power_t = 90
del1 = 5
del2 = 3
speed = 50


def buttonWait():
	GPIO.output(GREEN_LED_GPIO,False)
	GPIO.output(RED_LED_GPIO,True)
	print("waiting for button...")
	while GPIO.input(BUTTON) == False:
		time.sleep(0.1)
コード例 #40
0
# Start Telemetry module to load data into.
telemetry = {}

# initialize the constants instance so that we can update the WebAPI
util.log("Accessing HTTPConst singleton instance")
HTTPConst = HTTPConstants()

util.succLog(
    "Setting up mavlink recieving protocol - Instantiating modules...")

# Instantiate a Mavlink module.
mavl = Mavlink(constants['mavl-incoming']['host'],
               constants['mavl-incoming']['port'])

# Instantiate Mission module.
miss = Mission(constants['auvsi']['host'], constants['auvsi']['port'],
               constants['auvsi']['username'], constants['auvsi']['password'])

# Grab mission/server data from the competition server.
missPacket = miss.getMissionComponents()

HTTPConst.setMission(missPacket)

packets_sent = 0
startTime = time.time()

# Starting front end components.
util.log("Initiating telemetry status console front end")

util.log("Ready to recieve Mavlink Packets...")

packets_sent = 0
コード例 #41
0
    def buildMissions(self):
        """
      Build a list of current missions and remove completed
    """
        print("Removing Completed")
        #Check and remove completed missions
        logger.debug("Removing completed missions")
        oldMissions = self.missionList
        compNum = 0
        haveVehiclesAvailable = False
        hrefs = []
        url = BASE_URL
        for oldMission in oldMissions:
            browser.get(BASE_URL + "missions/" + oldMission.getID())
            try:
                compNum = compNum + 1
                if browser.find_element_by_xpath(
                        "//div[contains(@class,'missionNotFound')]"):
                    logger.debug(
                        "%s wasn't found. Treating it as complete and removing.",
                        oldMission.getID())
                    print(Fore.GREEN + oldMission.getName() +
                          " was completed." + Style.RESET_ALL)
                    try:
                        self.missionList.remove(oldMission)
                    except Exception as e:
                        logger.debug("Caught .remove error, continuing.")
                        continue
                    for d in self.despatches:
                        if d.getID() == oldMission.getID():
                            for dv in d.getVehicles():
                                for v in self.vehicleList:
                                    if dv == v.getID():
                                        v.setStatus('1')
                    tempMissionSeen = self.missionsSeen

                    try:
                        for h in tempMissionSeen:
                            if oldMission.getID() in h:
                                self.missionsSeen.remove(h)
                        self.despatches.remove(oldMission)
                    except Exception as e:
                        logger.debug("Caught .remove error, continuing.")
                        continue
            except NoSuchElementException:
                continue
        logger.debug("%s missions completed", compNum)
        logger.debug("Building missions list")
        print("Building New Missions")
        logger.debug("Grabbing mission urls and hrefs")
        browser.get(url)
        links = browser.find_elements_by_xpath(
            "//div[contains(@id,'missions')]/div/div[not(contains(@class,'mission_alliance_distance_hide') or contains(@class,'mission_deleted'))]/div/div/a[contains(@href,'missions')]"
        )
        checked = 0
        currBatchNum = 0
        for link in links:
            hrefs.append(link.get_attribute('href'))
        print(f"{str(len(links))} mission/s found")
        logger.debug("Building info for %s missions", len(hrefs))
        for v in self.vehicleList:
            if v.despatchable():
                haveVehiclesAvailable = True
                break

        if haveVehiclesAvailable:
            for href in hrefs:
                missionId = href.split("/")[4]
                if href not in self.missionsSeen and currBatchNum < MISSION_BATCH_NUM:
                    currBatchNum += 1
                    self.missionsSeen.append(href)
                    try:
                        for mission in self.missionList:
                            if mission.getID() == missionId:
                                #since the mission is already in the list, we can continue it.
                                raise AlreadyExistsException()
                        browser.get(BASE_URL + "missions/" + missionId)
                        missionName = browser.find_element_by_id(
                            'missionH1').text
                        with open('../json/missions.json') as missions_json:
                            mdata = json.load(missions_json)
                            if missionName in mdata['missions']:
                                logger.debug("Mission exists in JSON file")
                                mission = mdata['missions'][missionName]
                                requirements = json.loads(
                                    mission['requirements'])
                                currMission = Mission(missionId, missionName,
                                                      requirements)
                            else:
                                logger.debug(
                                    "Mission does not exists in JSON file")
                                logger.debug(
                                    "%i/%i missions checked against batch amount",
                                    currBatchNum, MISSION_BATCH_NUM)
                                logger.debug("Getting vehicle info for %s",
                                             missionId)
                                logger.debug("Mission name is %s", missionName)
                                logger.debug("Getting requirements for %s",
                                             missionId)
                                requirements = getRequirements(missionId)
                                logger.debug("Mission requirements are %s",
                                             requirements)
                                currMission = Mission(missionId, missionName,
                                                      requirements)
                                with open('../json/missions.json',
                                          'w') as outfile:
                                    logger.debug(
                                        "Buidling mission JSON object")
                                    mdata['missions'][missionName] = {}
                                    mdata['missions'][missionName][
                                        'requirements'] = json.dumps(
                                            requirements, indent=4)
                                    logger.debug("Adding mission to JSON file")
                                    json.dump(mdata,
                                              outfile,
                                              sort_keys=True,
                                              indent=4)

                            logger.debug("Mission info built, adding to list")
                            self.missionList.append(currMission)
                            # Show user how many missions it's checked compared to how many it needs to.
                            checked += 1
                            print(
                                Fore.GREEN +
                                f"{checked}/{MISSION_BATCH_NUM} missions checked!"
                                + Fore.RESET)
                    except AlreadyExistsException:
                        continue
                logger.debug("%s/%s missions built", checked, len(hrefs))
        else:
            logging.debug("No vehicles available, not checking missions")