예제 #1
0
 def traverse(self, dir_items, stack):
     print '***** stack: ' + str(stack)
     i = 0
     for (handle, url, listitem, isFolder) in dir_items:
         i += 1
         params = url.split('?')[1]
         if isFolder or (self.traverse_video and url.find('plugin') == 0):
             self.xbmcplugin.reset()
             swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin,
                                       self.xbmcgui, self.xbmcaddon)
             nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                              self.xbmcaddon, swe, 'plugin', '1',
                              '?' + params)
             if listitem.caption == nav.localize(30301):
                 continue
             stack.append(i)
             print '***** selecting %d: %s' % (i, listitem.caption)
             nav.dispatch()
             new_list = deepcopy(self.xbmcplugin.dir_items)
             self.traverse(new_list, stack)
         else:
             pass
     if len(stack) > 0:
         stack.pop()
     return
    def __init__(self):
        
      # Debugging purposes
      self.print_velocities = rospy.get_param('print_velocities')

      # Where and when should you use this?
      self.stop_robot = False

      # Create the needed objects
      self.sonar_aggregation = SonarDataAggregator()
      self.laser_aggregation = LaserDataAggregator()
      self.navigation  = Navigation()

      self.linear_velocity  = 0
      self.angular_velocity = 0

      # Check if the robot moves with target or just wanders
      self.move_with_target = rospy.get_param("calculate_target")

      # The timer produces events for sending the speeds every 110 ms
      rospy.Timer(rospy.Duration(0.11), self.publishSpeeds)
      self.velocity_publisher = rospy.Publisher(\
              rospy.get_param('speeds_pub_topic'), Twist,\
              queue_size = 10)

      # Read the velocities architecture
      self.velocity_arch = rospy.get_param("velocities_architecture")
      print "The selected velocities architecture is " + self.velocity_arch
예제 #3
0
    def __init__(self,
                 point_ids,
                 locations,
                 neighbors,
                 landmark_ids,
                 landmark_positions,
                 landmark_angles,
                 jerky=False,
                 walking_speed=1):

        # create map position
        self.map_pos = Point()
        self.map_angle = 0

        # create a path variable so that we can navigate via waypoints
        self._path = None

        # initialize what we're inheriting from
        Localization.__init__(self, point_ids, locations, neighbors,
                              landmark_ids, landmark_positions,
                              landmark_angles)
        Navigation.__init__(self, jerky=jerky, walking_speed=walking_speed)

        self._logger = Logger("NavLoc")

        # give ourselves a second to see if there's a nearby AR tag
        timer = time()
        while time() - timer < 0.75:
            pass
예제 #4
0
class Torpedo(MovableSeaObject):
    def __init__(self, sea):
        MovableSeaObject.__init__(self, sea, max_speed=42, max_turn_rate_hour=math.radians(720)*60)
        self.navigation = Navigation(self)
        self.deep = 100
        self.armed = False
        self.fuel = 100 * 40 # seconds at 40 knots

    def launch(self, pos, speed = 40):
        self.navigation.set_destination(pos)
        self.speed = speed

    def get_deep(self):
        return self.deep

    def get_fuel_consumption(self, time_elapsed):
        # 1 fuel unit per second per knot
        return 1.0 * time_elapsed * self.navigation.get_actual_speed()

    def turn(self, time_elapsed):
        MovableSeaObject.turn(self, time_elapsed)
        self.fuel -= self.get_fuel_consumption(time_elapsed)
        if self.fuel <= 0:
            self.navigation.MAX_SPEED = 0
            self.MAX_SPEED = 0

    def explode(self):
        self.sea.report_explosion(self.get_pos())
예제 #5
0
 def setUp(self):
     self.dialog = Xbmcgui.Dialog()
     self.dialog.select = MagicMock(name='select')
     xbmcgui = Xbmcgui()
     xbmcgui.Dialog = MagicMock(name='Dialog')
     xbmcgui.Dialog.return_value = self.dialog
     self.navigation = Navigation(None, None, xbmcgui, [None, 1])
예제 #6
0
파일: tdd.py 프로젝트: ABZTV/HALOW-LIVE-TV
 def traverse(self, dir_items, stack):
     print '***** stack: ' + str(stack)
     i = 0
     for (handle, url, listitem, isFolder) in dir_items:
         i += 1
         params = url.split('?')[1]
         if isFolder or (self.traverse_video and url.find('plugin') == 0):
             self.xbmcplugin.reset()
             swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin,
                                       self.xbmcgui, self.xbmcaddon)
             nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                              self.xbmcaddon, swe, 'plugin', '1',
                              '?' + params)
             if listitem.caption == nav.localize(30301):
                 continue
             stack.append(i)
             print '***** selecting %d: %s' % (i, listitem.caption)
             nav.dispatch()
             new_list = deepcopy(self.xbmcplugin.dir_items)
             self.traverse(new_list, stack)
         else:
             pass
     if len(stack) > 0:
         stack.pop()
     return
예제 #7
0
    def __init__(self):

        # Debugging purposes
        self.print_velocities = rospy.get_param('print_velocities')

        # Where and when should you use this?
        self.stop_robot = False

        # Create the needed objects
        self.sonar_aggregation = SonarDataAggregator()
        self.laser_aggregation = LaserDataAggregator()
        self.navigation = Navigation()

        self.linear_velocity = 0
        self.angular_velocity = 0

        self.previous_turn_dir = None

        # Check if the robot moves with target or just wanders
        self.move_with_target = rospy.get_param("calculate_target")

        # The timer produces events for sending the speeds every 110 ms
        rospy.Timer(rospy.Duration(0.11), self.publishSpeeds)
        self.velocity_publisher = rospy.Publisher(
            rospy.get_param('speeds_pub_topic'), Twist, queue_size=10)

        # Obstacle Avoidance state
        self.obstacle_avoidance__active = False
        self.obstacle_avoidance__remaining_steps = 20
예제 #8
0
class Torpedo(MovableSeaObject):
    def __init__(self, sea):
        MovableSeaObject.__init__(self,
                                  sea,
                                  max_speed=42,
                                  max_turn_rate_hour=math.radians(720) * 60)
        self.navigation = Navigation(self)
        self.deep = 100
        self.armed = False
        self.fuel = 100 * 40  # seconds at 40 knots

    def launch(self, pos, speed=40):
        self.navigation.set_destination(pos)
        self.speed = speed

    def get_deep(self):
        return self.deep

    def get_fuel_consumption(self, time_elapsed):
        # 1 fuel unit per second per knot
        return 1.0 * time_elapsed * self.navigation.get_actual_speed()

    def turn(self, time_elapsed):
        MovableSeaObject.turn(self, time_elapsed)
        self.fuel -= self.get_fuel_consumption(time_elapsed)
        if self.fuel <= 0:
            self.navigation.MAX_SPEED = 0
            self.MAX_SPEED = 0

    def explode(self):
        self.sea.report_explosion(self.get_pos())
    def __init__(self):

        self.print_velocities = rospy.get_param('print_velocities')     # For Printing Velocity Calculated
        self.debug = rospy.get_param('debug')   # For Debugging
        self.move_with_target = rospy.get_param("calculate_target")     # Robot moves with target or just wanders
        self.initial_turn = rospy.get_param('initial_turn')     # Perform a 360 turn when starting

        # Where and when should you use this?
        self.stop_robot = False
        self.sonar_on = False

        # Create the needed Objects
        self.laser_aggregation = LaserDataAggregator()
        self.navigation = Navigation()
        if self.sonar_on:
            self.sonar_aggregation = SonarDataAggregator()  # Enable this if Robot has Sonar!

        # Speed Parameters for Turtlebot
        self.linear_velocity = 0
        self.angular_velocity = 0
        self.low_turn_limit = 4.2
        self.max_linear_velocity = rospy.get_param('max_linear_speed')
        self.max_angular_velocity = rospy.get_param('max_angular_speed')

        # The Timer Produces Events for Sending Speeds Every 110 ms
        rospy.Timer(rospy.Duration(0.11), self.publishSpeeds)

        # The Turtlebot Speed Publisher Topic
        self.velocity_publisher = rospy.Publisher(rospy.get_param('turtlebot_speeds_topic'),
                                                  Twist, queue_size = 10)
예제 #10
0
 def __init__(self, teamname, pitstop_num, comms):
     self.teamname = teamname
     self.pitstop_num = pitstop_num
     self.start_num = -1
     self.teammates = []
     self.comms = comms
     self.comms.subscriber.on_message = self.message_handler
     self.nav = Navigation()
예제 #11
0
파일: tdd.py 프로젝트: nghdallas/Halowrepo
 def diritems(self, params=None):
     self.xbmcplugin.reset()
     swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin, self.xbmcgui,
                               self.addon)
     nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                      self.addon, swe, 'plugin', '1', params)
     nav.dispatch()
     return self.xbmcplugin.dir_items
예제 #12
0
 def diritems(self, params=None):
     self.xbmcplugin.reset()
     swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin, self.xbmcgui,
                               self.xbmcaddon)
     nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                      self.xbmcaddon, swe, 'plugin', '1', params)
     nav.dispatch()
     return self.xbmcplugin.dir_items
예제 #13
0
    def Navigation(self, request, context):
        nav = Navigation("Python Plugin", "/octant-py-plugin", "cloud")
        
        nav.add(Navigation("View One", "/octant-py-plugin/view-one", "folder"))
        nav.add(Navigation("View Two", "/octant-py-plugin/view-two", "folder"))
        nav.add(Navigation("View Three", "/octant-py-plugin/view-three", "folder"))

        return nav.toResponse()
예제 #14
0
class GPSNavigation:
    def __init__(self):
        self.imu = Imu()
        self.navigation = Navigation()

    def update_nav(self, lat, lon):
        destiny = self.imu.get_degrees_and_distance_to_gps_coords(lat, lon)
        self.navigation.navigate(destiny, lat, lon)
예제 #15
0
    def _ekfCallback(self, data):
        """ Process robot_pose_ekf data. """

        # get the ekf data
        Navigation._ekfCallback(self, data)

        # compute map data
        self.map_pos = self.transformPoint(self.p, "odom", "map")
        self.map_angle = self.transformAngle(self.angle, "odom", "map")
예제 #16
0
 def test_main_menu(self):
     argv = ['plugin.video.dreamfilm', '1']
     xbmc = Xbmc()
     xbmcplugin = Xbmcplugin()
     xbmcgui = Xbmcgui()
     df = dreamfilm.Dreamfilm()
     navigation = Navigation(df, xbmc, xbmcplugin, xbmcgui, argv)
     navigation.dispatch()
     self.assertEqual(len(xbmcplugin.dir_items), 8)
예제 #17
0
def main():
    Helper.init()
    while True:
        Navigation.menu('questing')
        Questing.start()
        Questing.updateInfo()
        Questing.status()
        if args.force_zone:
            if Questing.is_major:
                print('major quest. will not skip')
            else:
                while Questing.quest_zone != args.force_zone:
                    Questing.skip()
                    Questing.start()
                    Questing.updateInfo()
                    Questing.status()

        # Inventory.boostCube()  # unclutter inventory
        # invManagement(boost=2, merge=0)
        start = time.time()
        Adventure.adventureZone(Questing.quest_zone)
        Navigation.menu('questing')
        while not Questing.is_completed:
            # Navigation.menu('inventory')
            # farm that zone
            Navigation.menu('adventure')
            Adventure.turnIdleOff()
            kc = 0
            while kc < args.kills:
                while not Adventure.enemySpawn():
                    sleep(0.03)
                # kill the enemy
                Adventure.snipe(fast=True)
                kc += 1

            if args.verbose:
                print(f'killed {args.kills} monsters')
                print(f'time: ', end='')
                printTime()

            Navigation.menu('inventory')
            # Inventory.boostCube()
            # invManagement(boost=2, merge=0)
            Questing.turnInItems(Questing.quest_zone)
            # ygg()
            Questing.updateInfo()
            if args.verbose:
                Questing.status()

            Navigation.menu('questing')
            if Questing.is_completed:
                Questing.complete()
                end = time.time()
                print(f'completed quest at ')
                printTime()
                print(f'duration: {round((end-start)/60, 2)} minutes')
                break
예제 #18
0
 def __init__(self, sea):
     MovableSeaObject.__init__(self,
                               sea,
                               max_speed=42,
                               max_turn_rate_hour=math.radians(720) * 60)
     self.navigation = Navigation(self)
     self.deep = 100
     self.armed = False
     self.fuel = 100 * 40  # seconds at 40 knots
예제 #19
0
    def ready(self):

        logger = logging.getLogger(__name__)
        logger.debug("-- starting backend ----")

        from navigation import Navigation
        self.nav = Navigation()
        self.nav.start()
        self.nav.setup_controls_and_dialogs()

        logger.debug("-- backend is started ----")
예제 #20
0
    def __init__(self, parent=None):
        super(GLWidget, self).__init__(parent)
        self.parent = parent
        self.setMouseTracking(True)

        self.nav = Navigation()
        self.navInterface = NavigationInterface(self.nav)
        self.dataDisplay = DataDisplay()

        # self.navigateSignal.connect(self.navigateEvent)
        SIGNALS.navigateSignal.connect(self.navigateEvent)
예제 #21
0
def main():

    Helper.init()

    totalTime = 0
    duration = args.duration
    if args.nosetup:
        itopod_setup = True
    else:
        itopod_setup = False
    while True:
        if not args.notitans:
            if args.verbose:
                print('getting available titans')
            titans = Adventure.getTitans()
            if titans:
                # after this needs to reset loadout and diggers and e/m
                Adventure.turnIdleOff()

                print('calling killTitans with args.snipe {args.snipe}')
                Adventure.killTitans(titans,
                                     verbose=args.verbose,
                                     snipe=args.snipe)

                itopod_setup = False

        if not itopod_setup:
            Setup.setup(args.setup)
            itopod_setup = True

        Navigation.menu('adventure')

        if not args.nobeast:
            if not Statistics.checkPixelColor(*coords.BEAST_MODE_ON,
                                              coords.BEAST_MODE_COLOR):
                Helper.click(*coords.BEAST_MODE)

        print('*' * 30)
        Itopod.itopodExperimental(duration=duration,
                                  optimal_floor=args.optimal)
        totalTime += duration
        print(f'total exp: {Itopod.EXP_gained}')
        print(f'total ap: {Itopod.AP_gained}')
        print(f'kills: {Itopod.kills}')
        print(f'total time: {totalTime} minutes')
        print('*' * 30)

        Navigation.menu('inventory')
        if Inventory.getEmptySlots() < 20:
            invManagement(boost=0, merge=0)

        if not args.noygg:
            Yggdrasil.harvestAll()
예제 #22
0
def run10():
    """ Perform a 10 minute run. """
    start = time.time()
    Inventory.loadout(2)  # loadout 2 is bars-heavy
    BasicTraining.basicTraining()
    FightBosses.fightBosses()
    Adventure.adventureZone()  # go to latest zone

    Misc.inputResource()  # all energy

    print(f'Time Machine loop for 5 minutes')
    while time.time() - start < 300:
        TimeMachine.addEnergy()
        TimeMachine.addMagic()
        print(f'sleeping for 30 seconds')
        sleep(30)

    Inventory.loadout(1)
    BasicTraining.basicTraining()

    Misc.reclaimAll()  # reclaim energy and magic from TM

    print(f'Main loop until 10 minutes')
    mainStart = time.time()
    pushAdventure = False
    while time.time() - start < 570:
        # push to new adventure zone
        if time.time() - mainStart > 120 and not pushAdventure:
            Adventure.adventureZone()
            pushAdventure = True
        print(f'sleeping 30 seconds')
        sleep(30)
        # fight bosses
        FightBosses.nuke()
        for _ in range(5):
            FightBosses.fightBoss()
        # augments
        Misc.inputResource(amount='quarter', idle=True)
        for _ in range(3):
            Augmentation.augmentation(aug=4)
        Augmentation.augmentation(aug=4, upgrade=True)
        # blood magic
        BloodMagic.addMagic(cap=True)
        BloodMagic.addMagic(magic=2, cap=True)
        BloodMagic.addMagic(magic=3, cap=True)

    MoneyPit.moneyPit()
    Navigation.menu('rebirth')
    while time.time() - start < 600:
        sleep(1)
    Rebirth.rebirth()
예제 #23
0
파일: tdd.py 프로젝트: ABZTV/HALOW-LIVE-TV
    def test_traverse_all(self):
        self.xbmcplugin.reset()
        swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin, self.xbmcgui,
                                  self.xbmcaddon)
        nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                         self.xbmcaddon, swe, 'plugin', '1', '')
        self.assertEquals(nav.plugin_url, 'plugin')
        self.assertEquals(nav.handle, 1)
        self.assertEquals(nav.params, {})

        # call with no parameters
        nav.dispatch()
        self.traverse_video = True
        self.traverse(self.xbmcplugin.dir_items, [])
예제 #24
0
 def __init__(self, sea):
     MovableSeaObject.__init__(self, sea, 15)
     self.nav = Navigation(self)
     self.sea = sea
     self.nav.destination = None
     self.bands_swim = Bands().add_random([10, 20], [60, 80])
     self.bands_swim_sing = self.bands_swim.add_random([2000, 5000],
                                                       [120, 150],
                                                       times=3)
     self.deep = random.randint(10, 20)
     print("Swim: " + str(self.bands_swim))
     print("Sing: " + str(self.bands_swim_sing))
     self.singing = False
     self.counter = (random.randint(5, 10) + random.gauss(6, 5)) / 60
예제 #25
0
def _explr(stdscr, obj):
    assert curses.has_colors()
    init_color_pairs()

    stdscr.clear()
    curses.curs_set(0)

    selection = Navigation(obj)

    print_obj(stdscr, obj, selection.expanded, selection.position)

    while True:
        c = stdscr.getch()
        if c == ord('q'):
            break
        elif c == curses.KEY_UP or c == ord('k'):
            selection.move_up()
        elif c == curses.KEY_DOWN or c == ord('j'):
            selection.move_down()
        elif c == curses.KEY_RIGHT or c == ord('l'):
            selection.expand()
        stdscr.clear()
        print_obj(stdscr, obj, selection.expanded, selection.position)
        stdscr.refresh()

    stdscr.clear()
    stdscr.refresh()
예제 #26
0
    def __init__(self):
        rospy.init_node("finalRace")
        self.lidarData = None
        self.cmd = AckermannDriveStamped()
        self.AR = 0

        self.pleaseGo = False

        self.direction = None

        self.navigation = Navigation()
        self.drive_pub = rospy.Publisher(DRIVE_TOPIC,
                                         AckermannDriveStamped,
                                         queue_size=1)
        self.scan_sub = rospy.Subscriber(SCAN_TOPIC, LaserScan,
                                         self.driveCallback)
        self.ar_sub = rospy.Subscriber(AR_TOPIC, AlvarMarkers, self.arCallback)
        self.joy_sub = rospy.Subscriber(JOY_TOPIC, Joy, self.joy_callback)
        self.signList = []

        self.camera_data = Zed_converter(False, save_image=False)

        self.lastTag = 0

        self.tagsAndStates = (
            "self.navigation.potential_fields(2)",  #0
            "self.highway()",  #madefaster
            "self.navigation.potential_fields(1.5)",
            "self.navigation.wall_follower(1, 0.6, side = 1)",
            "self.beforeGraves()",
            "self.graves()",  #5 #should be proportional? switch back
            "self.navigation.potential_fields(2)",
            "self.highway()",
            "self.navigation.wall_follower(1.5, 1, side = -1)",
            "self.navigation.potential_fields(1)",
            "self.detectSign()",  #10
            "self.navigation.wall_follower(1.5, 1, side = -1)",
            "self.navigation.wall_follower(1.5, 1, side = -1)",
            "self.navigation.potential_fields(1.7)",
            "self.final()",
            "self.final()",  #15
            "self.final()",
            "self.final()")

        self.auto = False
        self.sign = 0
        self.time = None

        self.signState = 0
        self.line = None
예제 #27
0
    def test_traverse_all(self):
        self.xbmcplugin.reset()
        swe = swefilmer.Swefilmer(self.xbmc, self.xbmcplugin, self.xbmcgui,
                                  self.xbmcaddon)
        nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                         self.xbmcaddon, swe, 'plugin', '1', '')
        self.assertEquals(nav.plugin_url, 'plugin')
        self.assertEquals(nav.handle, 1)
        self.assertEquals(nav.params, {})

        # call with no parameters
        nav.dispatch()
        self.traverse_video = False
        self.traverse(self.xbmcplugin.dir_items, [])
예제 #28
0
class AppSmApiConfig(AppConfig):
    name = 'app_sm_api'

    def ready(self):

        logger = logging.getLogger(__name__)
        logger.debug("-- starting backend ----")

        from navigation import Navigation
        self.nav = Navigation()
        self.nav.start()
        self.nav.setup_controls_and_dialogs()

        logger.debug("-- backend is started ----")
예제 #29
0
    def test_traverse_all(self):
        argv = ['plugin', '1', '']
        self.streamtv = streamtv.Streamtv(self.xbmc, self.xbmcplugin,
                                          self.xbmcgui, self.xbmcaddon)
        nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                         self.xbmcaddon, self.streamtv, argv)
        self.assertEquals(nav.plugin_url, 'plugin')
        self.assertEquals(nav.handle, 1)
        self.assertEquals(nav.params, {})

        # call with no parameters
        nav.dispatch()
        self.traverse_video = False
        self.traverse(self.xbmcplugin.dir_items, [])
	def __init__(self):
		rospy.init_node("test_mission",log_level=rospy.INFO)		#initialize the pixhawk node
		print('node initialized')
		self.rate=rospy.Rate(10)
		self.subs=Subscribers()						#initialize streaming of subscribers
		self.comp=Computations()			
		self.commands=Commands()
		self.navigation=Navigation()
		self.arrow=Arrow()						#object for arrow detection class
		self.road_follow=RoadFollow()					#object for road detection class
		#initialize the publishers
		self.setpoint_publisher = rospy.Publisher("/mavros/setpoint_position/local", PoseStamped, queue_size=10)
	    	self.setvel_publisher = rospy.Publisher("/mavros/setpoint_velocity/cmd_vel", TwistStamped, queue_size = 10)
	    	self.setaccel_publisher = rospy.Publisher("/mavros/setpoint_accel/accel",Vector3Stamped,queue_size=10)
		print('Publishers initialized')
예제 #31
0
    def test_list_latest_movies(self):
        url = 'plugin.video.dreamfilm'
        params = Navigation.encode_parameters({'action': 'latestmovies'})
        argv = [url, 1, params]
        xbmc = Xbmc()
        xbmcplugin = Xbmcplugin()
        xbmcgui = Xbmcgui()
        df = dreamfilm.Dreamfilm()
        with open('fixtures/startpage.html') as f:
            df._latest_movie_html = mock.MagicMock(return_value=f.read())

        navigation = Navigation(df, xbmc, xbmcplugin, xbmcgui, argv)
        navigation.dispatch()

        self.assertEqual(len(xbmcplugin.dir_items), 12)
예제 #32
0
파일: tests.py 프로젝트: shahraam/Halowrepo
 def setUp(self):
     self.dialog = Xbmcgui.Dialog()
     self.dialog.select = MagicMock(name='select')
     xbmcgui = Xbmcgui()
     xbmcgui.Dialog = MagicMock(name='Dialog')
     xbmcgui.Dialog.return_value = self.dialog
     self.navigation = Navigation(None, None, xbmcgui, [None, 1])
예제 #33
0
    def test_search_dispatch(self):
        # Mock
        xbmc = Xbmc()
        xbmcplugin = Xbmcplugin()
        xbmcgui = Xbmcgui()
        xbmc.Keyboard.getText = mock.MagicMock(return_value='bad')
        df = dreamfilm.Dreamfilm()

        with open('fixtures/search.html') as f:
            df._search = mock.MagicMock(return_value=f.read())

        params = Navigation.encode_parameters({'action': 'search'})
        argv = ['plugin.video.dreamfilm', '1', params]
        navigation = Navigation(df, xbmc, xbmcplugin, xbmcgui, argv)
        navigation.dispatch()
        self.assertEqual(len(xbmcplugin.dir_items), 3)
예제 #34
0
class Ship(MovableSeaObject):
    def __init__(self, sea):
        MovableSeaObject.__init__(self, sea)
        self.navigation = Navigation(self)

    def get_deep(self):
        return 0

    def get_pos(self):
        return self.pos

    def turn(self, time_elapsed):
        MovableSeaObject.turn(self, time_elapsed)

    def add_waypoint(self, dest):
        self.navigation.add_waypoint(dest)
예제 #35
0
class Ship(MovableSeaObject):
    def __init__(self, sea):
        MovableSeaObject.__init__(self, sea)
        self.navigation = Navigation(self)

    def get_deep(self):
        return 0

    def get_pos(self):
        return self.pos

    def turn(self, time_elapsed):
        MovableSeaObject.turn(self, time_elapsed)

    def add_waypoint(self, dest):
        self.navigation.add_waypoint(dest)
예제 #36
0
    def _handleObstacle(self):
        """ Handle obstacle and reset path if necessary. """

        if Navigation._handleObstacle(self):
            self._path = None
            return True

        return False
예제 #37
0
    def __init__(self):
        """ To initialize the TaskManger. """

        self.navi = Navigation()
        #TODO will be used with h_nav, r_nav and m_nav       

        self.coordinates = []
        self.dice_pair = []
        self.tasks = []
예제 #38
0
 def render_preference_panel(self, req, panel):
     nav = Navigation(self.env)
     if panel == 'navigation':
         nav.save(req)
         
     nav_choices = nav.get_display_choices()
     selected = {'display_nav': nav.get_display(req),
                 'wiki.href': nav.get_wiki_href(req),
                 'tickets.href': nav.get_ticket_href(req)}
     system_defaults = {'display_nav': nav.get_system_default_display(), 
                        'wiki.href': nav.get_system_default_wiki_href(),
                        'tickets.href': nav.get_system_default_tickets_href()}
     
     data = {'selected': selected,
             'nav_choices': nav_choices,
             'choices_doc': CHOICES_DOC,
             'system_defaults': system_defaults}
     return 'prefs_display.html', data
예제 #39
0
    def __init__(self):
        rospy.init_node("finalRace")
        self.lidarData = None
        self.cmd = AckermannDriveStamped()

        self.drive_pub = rospy.Publisher(DRIVE_TOPIC, AckermannDriveStamped, queue_size=1)
        self.scan_sub = rospy.Subscriber(SCAN_TOPIC, LaserScan, self.driveCallback)

        self.navigation = Navigation()
        #self.sound_pub = rospy.Publisher("state", String, queue_size=1)

        #self.camera_data = Zed_converter(False, save_image=False)

        #self.currentPosition = (x,y)

        self.pleaseGo = True

        self.camera_data = Zed_converter(False, save_image=False)
예제 #40
0
class finalRaceDrive(object):
    DESIRED_DISTANCE = 1


    def __init__(self):
        rospy.init_node("finalRace")
        self.lidarData = None
        self.cmd = AckermannDriveStamped()

        self.drive_pub = rospy.Publisher(DRIVE_TOPIC, AckermannDriveStamped, queue_size=1)
        self.scan_sub = rospy.Subscriber(SCAN_TOPIC, LaserScan, self.driveCallback)

        self.navigation = Navigation()
        #self.sound_pub = rospy.Publisher("state", String, queue_size=1)

        #self.camera_data = Zed_converter(False, save_image=False)

        #self.currentPosition = (x,y)

        self.pleaseGo = True

        self.camera_data = Zed_converter(False, save_image=False)


    def scan(self,data):
        self.data = data
        self.navigation.lidar = data.ranges


    def drive(self):
        spd = self.navigation.spd
        angle = self.navigation.angle
        self.cmd.drive.speed = spd
        self.cmd.drive.steering_angle = angle
        print("spd: {} angle: {}".format(self.cmd.drive.speed, self.cmd.drive.steering_angle))
        self.drive_pub.publish(self.cmd)


    def driveCallback(self, data):
        self.scan(data)
        # self.navigation.potential_fields()
        # self.navigation.find_goals()
        self.navigation.wall_follower(1.5, 1, -1)
        self.drive()
예제 #41
0
    def __init__(self, x, y, idx, team, nav_type, the_map, config):
        '''
        x,y - the player/agent sprite starting location on the map
        idx - the player index (unique per team)
        team - blue or red
        nav_type - navigation algorithm: ['direct', 'bfs', 'dfs', 'astar']
        the_map - a reference to the global map with speeds, flag locations, player locations
        config - configurable settings
        '''
        self.config = config
        self.nav_type = nav_type
        self.navigation = Navigation(the_map)
        
        # list of actions for current goal
        self.goal_actions = []
        
        
        # needed for preventing sprite from overlapping a 0 speed location
        self.half_size = config.terrain_tile_size // 2

        # w,a,d,s are the keyboard directions for up, left, right, down
        self.actions = ['w', 'a', 'd', 's']

        # for debugging
        self.speed_terr = {v: k for k, v in self.config.terrain_speeds.items()}

        self.player_idx = idx
        self.team = team
        self.the_map = the_map
        self.sprite = None

        # current status
        self.speed = self.config.player_max_speed
        self.has_flag = False
        self.is_incapacitated = False
        self.incapacitated_countdown = 0
        self.in_enemy_territory = False
        self.in_flag_area = False

        self.x = x
        self.y = y
        self.tile_col, self.tile_row = self.the_map.xy_to_cr(x, y)
        self.blocked_countdown = 0
예제 #42
0
 def __init__(self, parent=None):
     super(GLWidget, self).__init__(parent)
     self.parent = parent
     self.setMouseTracking(True)
     
     self.nav = Navigation()
     self.navInterface = NavigationInterface(self.nav)
     self.dataDisplay = DataDisplay()
     
     # self.navigateSignal.connect(self.navigateEvent)
     SIGNALS.navigateSignal.connect(self.navigateEvent)
예제 #43
0
 def __init__(self, sea):
     MovableSeaObject.__init__(self, sea, 15)
     self.nav = Navigation(self)
     self.sea = sea
     self.nav.destination = None
     self.bands_swim = Bands().add_random([10, 20], [60, 80])
     self.bands_swim_sing = self.bands_swim.add_random([2000, 5000], [120, 150], times=3)
     self.deep = random.randint(10, 20)
     print ("Swim: " + str(self.bands_swim))
     print ("Sing: " + str(self.bands_swim_sing))
     self.singing = False
     self.counter = (random.randint(5, 10) + random.gauss(6, 5)) / 60
예제 #44
0
 def __init__(self, webserver_queue=None, looprate=0.2):
   self.arduino = Arduino()
   self.navigation = Navigation(self.arduino)
   self.state = State.COLLECT_spin_and_search_cone
   # Define constants
   self.looprate = looprate
   # Variables updated from webserver
   self.webserver_queue = webserver_queue
   self.mode = "auto"
   self.manual_direction = "stop"
   # Variables used by states
   self.start_time = None
   self.ready_to_deliver = False
예제 #45
0
파일: navpath.py 프로젝트: IFT-SE/pfis3
    def __removeGapNavigations(self):
        # We do a second pass over the navigations so that we remove any
        # parts of the navigation that have been previously identified as being
        # a navigation to a gap (a space between two method definitions).
        finalNavigations = []
        fromNav = None
        toNav = None
        foundGap = False

        for navigation in self._navigations:
            if not foundGap:
                if navigation.fromFileNav is None:
                    if navigation.toFileNav.isGap:
                        fromNav = navigation.fromFileNav
                        foundGap = True
                    else:
                        finalNavigations.append(navigation)
                elif not navigation.fromFileNav.isGap and navigation.toFileNav.isGap:
                    fromNav = navigation.fromFileNav
                    foundGap = True
                elif navigation.fromFileNav.isGap and navigation.toFileNav.isGap:
                    raise RuntimeError('removeGapNavigations: cannot have a navigation with a fromFileNav that is a gap without a prior navigation with a gap in the toFileNav')
                else:
                    if not navigation.isToSameMethod():
                        finalNavigations.append(navigation)
            elif foundGap:
                if navigation.fromFileNav.isGap and not navigation.toFileNav.isGap:
                    toNav = navigation.toFileNav
                    foundGap = False
                    newNavigation = Navigation(fromNav, toNav)
                    if not newNavigation.isToSameMethod():
                        finalNavigations.append(Navigation(fromNav, toNav))
                elif navigation.fromFileNav.isGap and navigation.toFileNav.isGap:
                    continue
                else:
                    raise RuntimeError('removeGapNavigations: cannot have a fromFileNav without a gap if the prior navigation had a gap in the toFileNav')

        self._navigations = finalNavigations
예제 #46
0
 def traverse(self, dir_items, stack):
     print '***** stack: ' + str(stack)
     self.streamtv = streamtv.Streamtv(self.xbmc, self.xbmcplugin,
                                       self.xbmcgui, self.xbmcaddon)
     i = 0
     for (handle, url, listitem, isFolder) in dir_items:
         i += 1
         params = url.split('?')[1]
         if isFolder or (self.traverse_video and url.find('plugin') == 0):
             stack.append(i)
             print '***** selecting %d: %s' % (i, listitem.caption)
             argv = ['plugin', '1', '?' + params]
             self.xbmcplugin.reset()
             nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                              self.xbmcaddon, self.streamtv, argv)
             nav.dispatch()
             new_list = deepcopy(self.xbmcplugin.dir_items)
             self.traverse(new_list, stack)
         else:
             pass
     if len(stack) > 0:
         stack.pop()
     return
예제 #47
0
class Interface(object):
    def __init__(self):
        self._lcd_plate = LcdPlate()

        self._navigation = Navigation()

        self.initScreen()

    def initScreen(self):
        self._lcd_plate.clear()

        self._lcd_plate.setBackLightCyan()

        # Set the screen to the top of the menu
        self._lcd_plate.message(self._navigation.currentItem())

    def pressedDown(self):
        self._navigation.moveDown()

    def pressedLeft(self):
        self._navigation.moveLeft()

    def pressedRight(self):
        self._navigation.moveRight()

    def pressedSelect(self):
        # TODO: Actually run the process that the navigation items expects
        self._lcd_plate.clear()
        self._lcd_plate.message("In Select")

    def pressedUp(self):
        self._navigation.moveUp()

    def run(self):
        while True:
            for button in self._lcd_plate.buttons():
                # Check if a button is pressed & there has been pause in pressing the buttons
                if self._lcd_plate.pressedSinceLastCheck(button):
                    # Call function of the button pressed
                    getattr(self, 'pressed' + self._lcd_plate.titleOfButton(button))()

                    self.initScreen()
예제 #48
0
class QualitySelectTests(unittest.TestCase):

    def setUp(self):
        self.dialog = Xbmcgui.Dialog()
        self.dialog.select = MagicMock(name='select')
        xbmcgui = Xbmcgui()
        xbmcgui.Dialog = MagicMock(name='Dialog')
        xbmcgui.Dialog.return_value = self.dialog
        self.navigation = Navigation(None, None, xbmcgui, [None, 1])

    def tearDown(self):
        actual = self.navigation.quality_select_dialog(self.input)
        self.assertEqual(actual, self.expected)

        if self.dialog_arg:
            self.dialog.select.assert_called_once_with("Quality Select", self.dialog_arg)
        else:
            self.assertFalse(self.dialog.select.called, "Dialog called!")

    def test_only_one_input(self):
        self.input = [("240p", "url_240")]
        self.expected = "url_240"
        self.dialog_arg = None

    def test_select_first_url(self):
        self.input = [("360p", "url_360"), ('720p', 'url_720')]
        self.dialog_arg = ["360p", "720p"]
        self.dialog.select.return_value = 0
        self.expected = "url_360"

    def test_select_second_url(self):
        self.input = [("360p", "url_360"), ('720p', 'url_720')]
        self.dialog_arg = ["360p", "720p"]
        self.dialog.select.return_value = 1
        self.expected = "url_720"

    def test_unsorted_input(self):
        self.input = [("1080p", "url_1080"), ('720p', 'url_720')]
        self.dialog_arg = ["720p", "1080p"]
        self.dialog.select.return_value = 1
        self.expected = "url_1080"

    def test_select_leading_whitespace_url(self):
        self.input = [("360p", "url_360"), ('720p', ' url_720')]
        self.dialog_arg = ["360p", "720p"]
        self.dialog.select.return_value = 1
        self.expected = "url_720"
예제 #49
0
    def test_navigation(self):
        argv = ['plugin', '1', '']
        self.streamtv = streamtv.Streamtv(self.xbmc, self.xbmcplugin,
                                          self.xbmcgui, self.xbmcaddon)
        nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                         self.xbmcaddon, self.streamtv, argv)
        self.assertEquals(nav.plugin_url, 'plugin')
        self.assertEquals(nav.handle, 1)
        self.assertEquals(nav.params, {})

        # call with no parameters
        nav.dispatch()
        self.assertTrue(len(self.xbmcplugin.dir_items) > 0)
        self.assertEquals(self.xbmcplugin.dir_items[0][2].caption, 'Alla')

        # select first item in list
        params = self.xbmcplugin.dir_items[0][1].split('?')[1]
        argv = ['plugin', '1', '?' + params]
        self.xbmcplugin.reset()
        nav = Navigation(self.xbmc, self.xbmcplugin, self.xbmcgui,
                         self.xbmcaddon, self.streamtv, argv)
        nav.dispatch()
        self.assertTrue(len(self.xbmcplugin.dir_items) > 0)
예제 #50
0
class Whale(MovableSeaObject):
    # f = 12 Hz - @2-5 kHz for “whale songs”, SL up to 188 dB
    # Swimming: 10 - 20 Hz, 60 to 80 DB
    # Sing: 2Khz - 5 Khz, 120 to 190 DB (AI should handle this later)
    def __init__(self, sea):
        MovableSeaObject.__init__(self, sea, 15)
        self.nav = Navigation(self)
        self.sea = sea
        self.nav.destination = None
        self.bands_swim = Bands().add_random([10, 20], [60, 80])
        self.bands_swim_sing = self.bands_swim.add_random([2000, 5000], [120, 150], times=3)
        self.deep = random.randint(10, 20)
        print ("Swim: " + str(self.bands_swim))
        print ("Sing: " + str(self.bands_swim_sing))
        self.singing = False
        self.counter = (random.randint(5, 10) + random.gauss(6, 5)) / 60

        # The blue whale is a marine mammal belonging to the suborder of
        # baleen whales (called Mysticeti). At up to 32.9 metres (108 ft)
        # in length and 172 metric tons (190 short tons) or more in weight,
        # it is the largest animal ever to have existed.
        #
        # Blue whales can reach speeds of 50 kilometres per hour (31 mph)
        # over short bursts, usually when interacting with other whales, but 20
        # kilometres per hour (12 mph) is a more typical traveling speed. When feeding,
        # they slow down to 5 kilometres per hour (3.1 mph).

    def turn(self, time_elapsed):
        MovableSeaObject.turn(self, time_elapsed)
        self.nav.turn(time_elapsed)
        self.counter -= time_elapsed
        if self.counter <= 0:
            if self.singing:
                self.singing = False
                self.counter = (random.randint(10, 5) + random.gauss(5, 5)) / 60
            else:
                self.singing = True
                self.counter = (random.gauss(10, 3) + 5) / 60

        if self.nav.destination is None:
            self.nav.destination = Point(random.randint(0, 10), random.randint(0, 10))
            self.nav.speed = (random.random() * 10) + 3

    def get_deep(self):
        return self.deep

    def get_pos(self):
        return self.pos

    def get_bands(self):
        if self.singing:
            return self.bands_swim_sing
        else:
            return self.bands_swim

    def __str__(self):
        return "Whale {is_singing}, {pos}, swim:{swim}, sing:{sing}, counter:{counter}, dest:{dest}".format(
                                                                               is_singing = self.singing,
                                                                               pos=MovableSeaObject.__str__(self),
                                                                               swim=str(self.bands_swim),
                                                                               sing=str(self.bands_swim_sing),
                                                                               counter=self.counter,
                                                                               dest=self.nav.destination)
예제 #51
0
class Driver():
  # Wait .05 sec between loops
  # This waits after the loop is run. This will not subtract the time it took to run loop() from the total wait time.
  def __init__(self, webserver_queue=None, looprate=0.2):
    self.arduino = Arduino()
    self.navigation = Navigation(self.arduino)
    self.state = State.COLLECT_spin_and_search_cone
    # Define constants
    self.looprate = looprate
    # Variables updated from webserver
    self.webserver_queue = webserver_queue
    self.mode = "auto"
    self.manual_direction = "stop"
    # Variables used by states
    self.start_time = None
    self.ready_to_deliver = False

  def start(self):
    self.stop = False

    s = sched.scheduler(time.time, self.arduino.board.sleep)
    s.enter(0, 1, self.loop, (s,))
    s.run()

  def stop_on_next_loop(self):
    self.stop = True

  def loop(self, sc):
    # Read webserver queue for new messages
    while((self.webserver_queue != None) and (len(self.webserver_queue) > 0)):
      self.process_message(self.webserver_queue.popleft())

    # If stopped, just loop
    if (self.stop):
      sc.enter(self.looprate, 1, self.loop, (sc,))
      return

    if (self.mode == "auto"):

      # ---- Collect Spin and Search Cone ----

      if (self.state == State.COLLECT_spin_and_search_cone):
        if (self.start_time == None):
          self.start_time = time.time()

        if (time.time() - self.start_time >= constants.SPIN_TIME):
          self.start_time = None
          self.navigation.stop()
          self.change_state(State.COLLECT_wander_and_search_cone)
        # TODO: Use signatures with pixy
        else:
          status = self.navigation.spin_and_search_cone()
          if (status == "CONE_FOUND"):
            self.start_time = None
            self.change_state(State.COLLECT_approach_cone)

      # ---- Collect Wander and Search ----

      elif (self.state == State.COLLECT_wander_and_search_cone):
        if (self.start_time == None):
          self.start_time = time.time()

        if (time.time() - self.start_time >= constants.WANDER_TIME):
          self.start_time = None
          self.navigation.stop()
          self.change_state(State.COLLECT_spin_and_search_cone)
        # TODO: Use signatures with pixy
        else:
          status = self.navigation.wander_and_search_cone()
          if (status == "CONE_FOUND"):
            self.start_time = None
            self.change_state(State.COLLECT_approach_cone)

      # ---- Collect Approach Cone ----

      elif (self.state == State.COLLECT_approach_cone):
        status = self.navigation.approach_cone()
        if (status == "LOST_CONE"):
          self.change_state(State.COLLECT_wander_and_search_cone)
        elif (status == "CONE_IN_RANGE"):
          self.change_state(State.COLLECT_acquire_cone)

      # ---- Collect Acquire Cone ----

      elif (self.state == State.COLLECT_acquire_cone):
        self.arduino.close_claw()

        ping = self.arduino.get_ping()
        if (ping <= constants.PING_CONE_THRESHOLD and ping != 0):
          if (self.ready_to_deliver == True):
            self.change_state(State.DELIVER_spin_and_search_target)
            self.ready_to_deliver = False
          else:
            print("Waiting for inter-bot command to deliver...")
        else:
          self.change_state(State.COLLECT_open_claw)

      # ---- Collect Open Claw ----

      elif (self.state == State.COLLECT_open_claw):
        self.arduino.open_claw()
        self.change_state(State.COLLECT_approach_cone)

      # ---- Deliver Spin and Search Target ----

      elif (self.state == State.DELIVER_spin_and_search_target):
        if (self.start_time == None):
          self.start_time = time.time()

        if (time.time() - self.start_time >= constants.SPIN_TIME):
          self.start_time = None
          self.navigation.stop()
          self.change_state(State.DELIVER_wander_and_search_target)
        # TODO: Use signatures with pixy
        else:
          status = self.navigation.spin_and_search_target()
          if (status == "TARGET_FOUND"):
            self.start_time = None
            self.change_state(State.DELIVER_approach_target)

      # ---- Deliver Wander and Search Target ----

      elif (self.state == State.DELIVER_wander_and_search_target):
        if (self.start_time == None):
          self.start_time = time.time()

        if (time.time() - self.start_time >= constants.WANDER_TIME):
          self.start_time = None
          self.navigation.stop()
          self.change_state(State.DELIVER_spin_and_search_target)
        # TODO: Use signatures with pixy
        else:
          status = self.navigation.wander_and_search_target()
          if (status == "TARGET_FOUND"):
            self.start_time = None
            self.change_state(State.DELIVER_approach_target)

      # ---- Deliver Approach Target ----

      elif (self.state == State.DELIVER_approach_target):
        status = self.navigation.approach_target()
        if (status == "LOST_TARGET"):
          self.change_state(State.DELIVER_wander_and_search_target)
        elif (status == "TARGET_IN_RANGE"):
          self.change_state(State.DELIVER_verify_target)

      # ---- Deliver Verify Target ----

      elif (self.state == State.DELIVER_verify_target):
        self.change_state(State.DELIVER_release_cone)

      # ---- Deliver Release Cone ----

      elif (self.state == State.DELIVER_release_cone):
        self.arduino.open_claw()
        self.arduino.board.sleep(1)

        self.navigation.reverse()
        self.arduino.board.sleep(2)

        self.navigation.spin_clockwise()
        self.arduino.board.sleep(3)

        print("Starting over...")
        self.change_state(State.COLLECT_spin_and_search_cone)

        try:
          endpoint = "http://" + constants.GROUP10_IP + constants.GROUP10_ENDPOINT_READY
          print("Hitting endpoint: " + endpoint)
          # requests.get(endpoint, timeout=0.001)
          urlopen(endpoint)
        except:
          print("Failed to hit Group10 Endpoint, trying again...")
          print("Just kidding, I'm giving up!")


    elif (self.mode == "manual"):
      # print("In manual mode")
      if (self.manual_direction == "stop"):
        (left_motor, right_motor) = (0.0, 0.0)
      elif (self.manual_direction == "forward"):
        (left_motor, right_motor) = (0.2, 0.2)
      elif (self.manual_direction == "backward"):
        (left_motor, right_motor) = (-0.2, -0.2)
      elif (self.manual_direction == "right"):
        (left_motor, right_motor) = (0.2, 0.0)
      elif (self.manual_direction == "left"):
        (left_motor, right_motor) = (0.0, 0.2)

      print("L: " + str(left_motor) + " R: " + str(right_motor))
      self.arduino.set_motors(left_motor, right_motor)

    elif (self.mode == "kill"):
      self.shutdown()
      sys.exit(0)

    # Loop again after delay
    sc.enter(self.looprate, 1, self.loop, (sc,))

  def change_state(self, new_state):
    print("[State Change] " + str(self.state) + " -> " + str(new_state))
    self.state = new_state

  def process_message(self, message):
    if (message == "stop"):
      self.stop_on_next_loop()
    elif (message == "start"):
      self.start()
    elif (message == "print"):
      print("Print!")

    # Modes
    elif (message == "auto"):
      self.mode = "auto"
    elif (message == "manual"):
      self.mode = "manual"
    elif (message == "kill"):
      self.mode = "kill"

    # Inter-Bot commands
    elif (message == "bot_ready_to_deliver"):
      print("Received inter-bot communication: ready_to_deliver")
      self.ready_to_deliver = True

    # Manual Directions
    elif (message == "manual_forward"):
      self.manual_direction = "forward"
    elif (message == "manual_backward"):
      self.manual_direction = "backward"
    elif (message == "manual_right"):
      self.manual_direction = "right"
    elif (message == "manual_left"):
      self.manual_direction = "left"
    elif (message == "manual_stop"):
      self.manual_direction = "stop"
    elif (message == "manual_claw_open"):
      self.arduino.open_claw()
    elif (message == "manual_claw_close"):
      self.arduino.close_claw()

  def shutdown(self, signal=None, frame=None):
    self.arduino.shutdown()
class RobotController:

    # Constructor
    def __init__(self):
        
      # Debugging purposes
      self.print_velocities = rospy.get_param('print_velocities')

      # Where and when should you use this?
      self.stop_robot = False

      # Create the needed objects
      self.sonar_aggregation = SonarDataAggregator()
      self.laser_aggregation = LaserDataAggregator()
      self.navigation  = Navigation()

      self.linear_velocity  = 0
      self.angular_velocity = 0

      # Check if the robot moves with target or just wanders
      self.move_with_target = rospy.get_param("calculate_target")

      # The timer produces events for sending the speeds every 110 ms
      rospy.Timer(rospy.Duration(0.11), self.publishSpeeds)
      self.velocity_publisher = rospy.Publisher(\
              rospy.get_param('speeds_pub_topic'), Twist,\
              queue_size = 10)

      # Read the velocities architecture
      self.velocity_arch = rospy.get_param("velocities_architecture")
      print "The selected velocities architecture is " + self.velocity_arch

    # This function publishes the speeds and moves the robot
    def publishSpeeds(self, event):
        
      # Choose architecture
      if self.velocity_arch == "subsumption":
        self.produceSpeedsSubsumption()
      else:
        self.produceSpeedsMotorSchema()

      # Create the commands message
      twist = Twist()
      twist.linear.x = self.linear_velocity
      twist.linear.y = 0
      twist.linear.z = 0
      twist.angular.x = 0 
      twist.angular.y = 0
      twist.angular.z = self.angular_velocity

      # Send the command
      self.velocity_publisher.publish(twist)

      # Print the speeds for debuggind purposes
      if self.print_velocities == True:
        print "[L,R] = [" + str(twist.linear.x) + " , " + \
            str(twist.angular.z) + "]"

    # Produce speeds from sonars
    def produceSpeedsSonars(self):
      # Get the sonars' measurements
      front   = self.sonar_aggregation.sonar_front_range
      left    = self.sonar_aggregation.sonar_left_range
      right   = self.sonar_aggregation.sonar_right_range
      r_left  = self.sonar_aggregation.sonar_rear_left_range
      r_right = self.sonar_aggregation.sonar_rear_right_range
        
      linear  = 0
      angular = 0

      # YOUR CODE HERE ------------------------------------------------------
      # Adjust the linear and angular velocities using the five sonars values

      # ---------------------------------------------------------------------

      return [linear, angular]

    # Produces speeds from the laser
    def produceSpeedsLaser(self):

      # Get the laser scan
      scan   = self.laser_aggregation.laser_scan
        
      linear  = 0
      angular = 0

      # YOUR CODE HERE ------------------------------------------------------
      # Adjust the linear and angular velocities using the laser scan

      # ---------------------------------------------------------------------

      return [linear, angular]

    # Combines the speeds into one output using a subsumption approach
    def produceSpeedsSubsumption(self):
      
      # Produce target if not existent
      if self.move_with_target == True and self.navigation.target_exists == False:
        self.navigation.selectTarget()

      # Get the submodules' speeds
      [l_sonar, a_sonar] = self.produceSpeedsSonars()
      [l_laser, a_laser] = self.produceSpeedsLaser()
      [l_goal, a_goal] = self.navigation.velocitiesToNextSubtarget()

      self.linear_velocity  = 0
      self.angular_velocity = 0

      # Combine the speeds following the subsumption architecture
      # YOUR CODE HERE ------------------------------------------------------

      # ---------------------------------------------------------------------

    # Combines the speeds into one output using a motor schema approach
    def produceSpeedsMotorSchema(self):
 
      # Produce target if not existent
      if self.move_with_target == True and self.navigation.target_exists == False:
        self.navigation.selectTarget()

      # Get the submodule's speeds
      [l_sonar, a_sonar] = self.produceSpeedsSonars()
      [l_laser, a_laser] = self.produceSpeedsLaser()
      [l_goal, a_goal] = self.navigation.velocitiesToNextSubtarget()

      self.linear_velocity  = 0
      self.angular_velocity = 0
        
      # Get the speeds using the motor schema approach
      # YOUR CODE HERE ------------------------------------------------------
        
      # ---------------------------------------------------------------------

    # Assistive functions - Do you have to call them somewhere?
    def stopRobot(self):
      self.stop_robot = True

    def resumeRobot(self):
      self.stop_robot = False
예제 #53
0
파일: navpath.py 프로젝트: IFT-SE/pfis3
    def __findMethodsForFileNavigations(self, conn):
        # Here we map the file paths and offsets in the fileNavigations list to
        # FQNs of methods. This is done by querying for all the Method
        # declarations within the database and storing that data to the
        # self.knownMethods object. The insertions into knownMethods will create
        # entries if they are new or update them if they already exist. Since
        # code can be changed between navigations, we need to update
        # self.knownMethods to reflect the most recent state of the code up to
        # each navigation.
        # After building the known methods, we test an entry from
        # fileNavigations against the set of known methods by offset. This is
        # what maps Text selection offsets to methods.
        prevNavigation = None
        postProcessing = False

        # Iterate over the data gathered from the Text selection offsets
        for i in range(len(self.__fileNavigations)):
            toFileNavigation = self.__fileNavigations[i]
            if self.VERBOSE_PATH:
                print '\tProcessing text selection offset: ' + str(toFileNavigation)

            # For every navigation's timestamp, we fill the knownMethods object
            # with the details of every method declaration up to the timestamp
            # of the toFileNavigation. The knownMethods object will be queried to
            # determine in which method (if any) a text selection offset occurs.

            # Note that the queries here are by a method's FQN. This allows us
            # to update the method's declaration info if it gets updated at some
            # point in the future.

            c = conn.execute(self.METHOD_DECLARATIONS_QUERY, [toFileNavigation.timestamp])
            for row in c:
                action, target, referrer = row['action'], \
                    row['target'], row['referrer']

                if action == 'Method declaration':
                    self.knownPatches.addFilePatch(referrer)
                elif action == 'Method declaration offset':
                    method = self.knownPatches.findMethodByFqn(target)
                    if method is not None:
                        method.startOffset = int(referrer)
                elif action == 'Method declaration length':
                    method = self.knownPatches.findMethodByFqn(target)
                    if method is not None:
                        method.length = int(referrer);

            # Recall that navigations contains the navigation data after its
            # been translated to methods and headers

            # If there was at least 1 navigation already, the to destination
            # from the previous navigation serves as this navigations from. A
            # clone is necessary since this may be later transformed into a
            # PFIG header and we don't want to affect the to destination from
            # the previous navigation.

            fromFileNavigation = None
            fromMethodPatch = None

            if len(self._navigations) > 0:
                prevNavigation = self._navigations[-1]
                fromFileNavigation = prevNavigation.toFileNav.clone()
                self.__addPFIGFileHeadersIfNeeded(conn, prevNavigation, toFileNavigation)
                fromMethodPatch = self.knownPatches.findMethodByOffset(fromFileNavigation.filePath, fromFileNavigation.offset)


            # We query known methods here to see if the offset of the current
            # toFileNavigation is among the known patches.
            toMethodPatch = self.knownPatches.findMethodByOffset(toFileNavigation.filePath, toFileNavigation.offset)


            # Create the navigation object representing this navigation
            navigation = Navigation(fromFileNavigation, toFileNavigation.clone())

            # Set method FQN data
            if navigation.fromFileNav is not None and fromMethodPatch is not None:
                navigation.fromFileNav.methodFqn = fromMethodPatch.fqn
            if navigation.toFileNav is not None and toMethodPatch is not None:
                navigation.toFileNav.methodFqn = toMethodPatch.fqn

            if not navigation.isToSameMethod():
                self._navigations.append(navigation)

                if navigation.fromFileNav is not None:
                    if navigation.fromFileNav.methodFqn is None:
                        postProcessing = True
                        navigation.fromFileNav.isGap = True
                        prevNavigation.toFileNav.isGap = True
            c.close()

        if postProcessing:
            self.__removeGapNavigations()
예제 #54
0
    def __init__(self):
        self._lcd_plate = LcdPlate()

        self._navigation = Navigation()

        self.initScreen()
예제 #55
0
# -*- coding: utf-8 -*-
import sys
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmc
from navigation import Navigation

navigation = Navigation(xbmc, xbmcplugin, xbmcgui, xbmcaddon, sys.argv)
navigation.dispatch()
예제 #56
0
 def __init__(self, sea):
     MovableSeaObject.__init__(self, sea)
     self.navigation = Navigation(self)
예제 #57
0
    def __init__(self, context):
        super(Milestone1GUI, self).__init__(context)
        self._sound_client = SoundClient()
        rospy.Subscriber('robotsound', SoundRequest, self.sound_cb)
        switch_srv_name = 'pr2_controller_manager/switch_controller'
        rospy.loginfo('Waiting for switch controller service...')
        rospy.wait_for_service(switch_srv_name)
        self.switch_service_client = rospy.ServiceProxy(switch_srv_name,
                                                 SwitchController)

        self.r_joint_names = ['r_shoulder_pan_joint',
                              'r_shoulder_lift_joint',
                              'r_upper_arm_roll_joint',
                              'r_elbow_flex_joint',
                              'r_forearm_roll_joint',
                              'r_wrist_flex_joint',
                              'r_wrist_roll_joint']
        self.l_joint_names = ['l_shoulder_pan_joint',
                              'l_shoulder_lift_joint',
                              'l_upper_arm_roll_joint',
                              'l_elbow_flex_joint',
                              'l_forearm_roll_joint',
                              'l_wrist_flex_joint',
                              'l_wrist_roll_joint']

        # Create a trajectory action client
        r_traj_controller_name = '/r_arm_controller/joint_trajectory_action'
        self.r_traj_action_client = SimpleActionClient(r_traj_controller_name,
                JointTrajectoryAction)
        rospy.loginfo('Waiting for a response from the trajectory action server for RIGHT arm...')
        self.r_traj_action_client.wait_for_server()
        
        l_traj_controller_name = '/l_arm_controller/joint_trajectory_action'
        self.l_traj_action_client = SimpleActionClient(l_traj_controller_name,
                JointTrajectoryAction)
        rospy.loginfo('Waiting for a response from the trajectory action server for LEFT arm...')
        self.l_traj_action_client.wait_for_server()

        #init torso
        self.torso = Torso()

        #init gripper
        self.l_gripper = Gripper('l')
        self.r_gripper = Gripper('r')

        #init navigation
        self.navigation = Navigation()

        self._widget = QWidget()
        self._widget.setFixedSize(600, 600)
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        
        large_box = QtGui.QVBoxLayout()

        #Button for outreaching to recieve book from Human
        button_box = QtGui.QVBoxLayout()
        box_1 = QtGui.QHBoxLayout()
        box_2 = QtGui.QHBoxLayout()
        box_3 = QtGui.QHBoxLayout()
        box_4 = QtGui.QHBoxLayout()
        box_5 = QtGui.QHBoxLayout()
        box_6 = QtGui.QHBoxLayout()
        box_7 = QtGui.QHBoxLayout()
        box_8 = QtGui.QHBoxLayout()
        box_9 = QtGui.QHBoxLayout()
        box_10 = QtGui.QHBoxLayout()

        box_1.addItem(QtGui.QSpacerItem(15,2))
        box_1.addWidget(self.create_button('Prepare To Take', self.prepare_to_take))
        box_1.addItem(QtGui.QSpacerItem(445,2))

        box_2.addItem(QtGui.QSpacerItem(15,2))
        box_2.addWidget(self.create_button('Take From Human', self.take_from_human))
        box_2.addItem(QtGui.QSpacerItem(445,2))

        box_3.addItem(QtGui.QSpacerItem(15,2))
        box_3.addWidget(self.create_button('Prepare To Navigate', self.prepare_to_navigate))
        box_3.addItem(QtGui.QSpacerItem(445,2))

        # Button to move to shelf
        box_5.addItem(QtGui.QSpacerItem(15,2))
        box_5.addWidget(self.create_button('Navigate To Shelf', self.navigate_to_shelf))
        box_5.addItem(QtGui.QSpacerItem(445,2))

        box_4.addItem(QtGui.QSpacerItem(15,2))
        box_4.addWidget(self.create_button('Place On Shelf', self.place_on_shelf))
        box_4.addItem(QtGui.QSpacerItem(445,2))

        box_6.addItem(QtGui.QSpacerItem(15,2))
        box_6.addWidget(self.create_button('Give Information', self.give_information))
        box_6.addItem(QtGui.QSpacerItem(445,2))

        box_7.addItem(QtGui.QSpacerItem(15,2))
        box_7.addWidget(self.create_button('Navigate To Person', self.navigate_to_person))
        box_7.addItem(QtGui.QSpacerItem(445,2))

        self.book_textbox = QtGui.QLineEdit()
        self.book_textbox.setFixedWidth(100)

        box_8.addItem(QtGui.QSpacerItem(15,2))
        box_8.addWidget(self.book_textbox)
        box_8.addWidget(self.create_button('Pick Up Book', self.pick_up_from_shelf_button))
        box_8.addItem(QtGui.QSpacerItem(445,2))
        
        box_9.addItem(QtGui.QSpacerItem(15,2))
        box_9.addWidget(self.create_button('Localize', self.spin_base))
        box_9.addItem(QtGui.QSpacerItem(445,2))
       
        box_10.addItem(QtGui.QSpacerItem(15,2))
        box_10.addWidget(self.create_button('Non-nav Pick Up', self.pick_up_from_shelf))
        box_10.addItem(QtGui.QSpacerItem(445,2))

        button_box.addItem(QtGui.QSpacerItem(20,120))
        button_box.addLayout(box_1)
        button_box.addLayout(box_2)
        button_box.addLayout(box_3)
        button_box.addLayout(box_5)
        button_box.addLayout(box_4)
        button_box.addLayout(box_6)
        button_box.addLayout(box_7)
        button_box.addLayout(box_8)
        button_box.addLayout(box_9)
        button_box.addLayout(box_10)
        button_box.addItem(QtGui.QSpacerItem(20,240))
        large_box.addLayout(button_box)
        self.marker_perception = ReadMarkers()
        self.speech_recognition = SpeechRecognition(self)
        self.bookDB = BookDB()
        self.book_map = self.bookDB.getAllBookCodes()
        self._widget.setObjectName('Milestone1GUI')
        self._widget.setLayout(large_box)
        context.add_widget(self._widget)
        self._widget.setStyleSheet("QWidget { image: url(%s) }" %
                (str(os.path.dirname(os.path.realpath(__file__))) +
                "/../../librarian_gui_background.jpg"))
예제 #58
0
 def __init__(self, sea):
     MovableSeaObject.__init__(self, sea, max_speed=42, max_turn_rate_hour=math.radians(720)*60)
     self.navigation = Navigation(self)
     self.deep = 100
     self.armed = False
     self.fuel = 100 * 40 # seconds at 40 knots
예제 #59
0
from navigation import Navigation
import dreamfilm
from mocks import Xbmc, Xbmcgui, Xbmcplugin

if __name__ == '__main__':
    argv = ['./offline.py', 1]
    history = []
    history.append(argv)
    while True:
        xbmc = Xbmc()
        xbmcplugin = Xbmcplugin()
        xbmcgui = Xbmcgui()
        navigation = Navigation(dreamfilm.Dreamfilm(), xbmc, xbmcplugin, xbmcgui, argv)
        ret = navigation.dispatch()
        if ret == Xbmc.BACK:
            history = history[:-1]
            argv = history[-1]
            continue

        if not xbmcplugin.dir_items:
            continue

        for idx, item in enumerate(xbmcplugin.dir_items):
            print "%d) %s" % (idx, item[2].caption)
        print "Enter number for menu option or '..' to go back"
        inp = raw_input('>> ')
        if inp == "..":
            history = history[:-1]
            argv = history[-1]
            continue