class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map,occupancy_map, pos_init, pos_goal, max_speed, max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS
        
        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()
        #print imu_meas
        #self.ros_interface.command_velocity(0., -8.)        
        if meas and meas != None:
            state=np.array([meas[0][0],meas[0][1],meas[0][2]])
            vw=self.diff_drive_controller.compute_vel(state,np.array([[0,0]]))
            print vw
            while vw[2]:
                self.ros_interface.command_velocity(0,0)
            self.ros_interface.command_velocity(vw[0],vw[1])
Exemple #2
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS

        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        #self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()

        self.ros_interface.command_velocity(0, 0)

        return
Exemple #3
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        self.kalman_filter = KalmanFilter(world_map)
        print("INITSTATE", self.kalman_filter.state)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)
        self.vel = 0
        self.omega = 0
        self.curInd = 0

        self.path = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init,
                              pos_goal)
        print(self.path)
        self.curGoal = self.path[0]
        self.done = False

    def process_measurements(self):
        """ 
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        print("Mesurements", meas)
        imu_meas = self.ros_interface.get_imu()
        print(imu_meas)
        updatedPosition = self.kalman_filter.step_filter(
            self.vel, self.omega, imu_meas, meas)
        print(np.linalg.norm(self.curGoal - updatedPosition[0:1]))
        if ((np.abs(self.curGoal[0] - updatedPosition[0]) > 0.1)
                or (np.abs(self.curGoal[1] - updatedPosition[1]) > 0.1)):
            (v, omega, done) = self.diff_drive_controller.compute_vel(
                updatedPosition, self.curGoal)
            self.vel = v
            self.omega = omega
            print("commanded vel:", v, omega)
            self.ros_interface.command_velocity(v, omega)
        else:
            print("updating")
            self.curInd = self.curInd + 1
            if self.curInd < len(self.path):
                self.curGoal = self.path[self.curInd]
            else:
                self.done = True

        updatedPosition.shape = (3, 1)

        return
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS

        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()
        #print(meas)

        done = False
        #print("time = " + str(self.robot_sim.last_meas_time))
        if meas is not None and meas != []:
            print "meas = " + str(meas[0][0:3])
            #print type(meas)
            state = -np.array(meas[0][0:3])
            goal = np.array([0, 0])
            print "state = " + str(state)
            #print type(state)
            #print goal
            #print type(goal)
            v, omega, done = self.diff_drive_controller.compute_vel(
                state, goal)
            #print done
            #self.robot_sim.command_velocity(v, omega)
            self.ros_interface.command_velocity(v, omega)
        else:
            #print "No measurement"
            #self.robot_sim.command_velocity(0, 0)
            v = 0
            omega = 0
            self.ros_interface.command_velocity(v, omega)
        print "v = " + str(v)
        print "omega = " + str(omega)

        return
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS
        self.markers = world_map
        self.vel = np.array([0., 0.])
        self.imu_meas = np.array([])
        self.meas = []
        # self.max_speed = max_speed
        # self.max_omega = max_omega
        # self.goals    = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init, pos_goal)
        # self.total_goals = self.goals.shape[0]
        # self.cur_goal    = 2
        # self.end_goal    = self.goals.shape[0] - 1

        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        #self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()
        self.meas = meas
        self.imu_meas = imu_meas

        #  for computing motor gain
        v = 0.3
        w = 0.
        self.ros_interface.command_velocity(v, w)

        return
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        Inputs: (all loaded from the parameter YAML file)
        world_map - a P by 4 numpy array specifying the location, orientation,
            and identification of all the markers/AprilTags in the world. The
            format of each row is (x,y,theta,id) with x,y giving 2D position,
            theta giving orientation, and id being an integer specifying the
            unique identifier of the tag.
        occupancy_map - an N by M numpy array of boolean values (represented as
            integers of either 0 or 1). This represents the parts of the map
            that have obstacles. It is mapped to metric coordinates via
            x_spacing and y_spacing
        pos_init - a 3 by 1 array specifying the initial position of the robot,
            formatted as usual as (x,y,theta)
        pos_goal - a 3 by 1 array specifying the final position of the robot,
            also formatted as (x,y,theta)
        max_speed - a parameter specifying the maximum forward speed the robot
            can go (i.e. maximum control signal for v)
        max_omega - a parameter specifying the maximum angular speed the robot
            can go (i.e. maximum control signal for omega)
        x_spacing - a parameter specifying the spacing between adjacent columns
            of occupancy_map
        y_spacing - a parameter specifying the spacing between adjacent rows
            of occupancy_map
        t_cam_to_body - numpy transformation between the camera and the robot
            (not used in simulation)
        """

        # TODO for student: Comment this when running on the robot
        #self.robot_sim = RobotSim(world_map, occupancy_map, pos_init, pos_goal,
        #	                            max_speed, max_omega, x_spacing, y_spacing)
        # TODO for student: Use this when transferring code to robot
        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS

        # speed control variables
        self.v = 0.1  # allows persistent cmds through detection misses
        self.omega = -0.1  # allows persistent cmds through detection misses
        self.last_detect_time = rospy.get_time()  #TODO on bot only
        self.missed_vision_debounce = 1

        self.start_time = 0

        # generate the path assuming we know our start location, goal, and environment
        self.path = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init,
                              pos_goal)
        self.path_idx = 0
        self.mission_complete = False
        self.carrot_distance = 0.22

        # Uncomment as completed
        self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """
        YOUR CODE HERE
        Main loop of the robot - where all measurements, control, and esimtaiton
        are done. This function is called at 60Hz
        """

        print(' ')

        # TODO for student: Comment this when running on the robot
        #meas = self.robot_sim.get_measurements()
        #imu_meas = self.robot_sim.get_imu()

        # TODO for student: Use this when transferring code to robot
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()

        # meas is the position of the robot with respect to the AprilTags
        # print(meas)

        # now that we have the measurements, update the predicted state
        self.kalman_filter.step_filter(self.v, imu_meas, meas)
        # print(self.kalman_filter.x_t)

        # TODO remove on bot, shows predicted state on simulator
        #self.robot_sim.set_est_state(self.kalman_filter.x_t)

        # pull the next path point from the list
        cur_goal = self.getCarrot()

        # cur_goal = self.path[self.path_idx]
        # TODO test to just go to a goal
        # cur_goal[0] = 0.43
        # cur_goal[1] = 2

        # calculate the control commands need to reach next path point
        #print('')
        #print('current goal:')
        #print(cur_goal)
        #print('current state:')
        #print(self.kalman_filter.x_t)

        control_cmd = self.diff_drive_controller.compute_vel(
            self.kalman_filter.x_t, cur_goal)
        self.v = control_cmd[0]
        self.omega = control_cmd[1]

        #print('control command:')
        # print(control_cmd)

        if self.mission_complete:
            self.v = 0
            self.omega = 0

        #print(control_cmd)
        if control_cmd[2]:
            if len(self.path) > (self.path_idx + 1):
                self.path_idx = self.path_idx + 1
                print('next goal')
            else:
                self.mission_complete = True

        #TODO calibration test on bot only for linear velocity
        '''
        if self.start_time - 0 < 0.0001:
            self.start_time = rospy.get_time()

        if(rospy.get_time() - self.start_time > 4):
            self.v = 0
            self.omega = 0
        else:
            self.v = 0.15
            self.omega = 0
        '''

        #TODO on bot only
        self.ros_interface.command_velocity(self.v, self.omega)

        #TODO for simulation
        #self.robot_sim.command_velocity(self.v,self.omega)

        return

    def getCarrot(self):
        '''
        getCarrot - generates an artificial goal location along a path out 
        infront of the robot.
        path - the set of points which make up the waypoints in the path
        position - the current position of the robot
        '''
        path = self.path
        idx = self.path_idx
        pos = self.kalman_filter.x_t

        # if the current line segment ends in the goal point, set that to the goal
        if self.path_idx + 1 == len(self.path):
            return self.path[(len(self.path) - 1)]
        else:
            # find the point on the current line closest to the robot
            # calculate current line's slope and intercept
            pt1 = self.path[self.path_idx]
            pt2 = self.path[self.path_idx + 1]
            x_diff = pt2[0] - pt1[0]
            y_diff = pt2[1] - pt1[1]
            vert = abs(x_diff) < 0.001

            # using the current line's slope and intercept find the point on that
            # line closest to the robots current point
            # assumes all lines are either veritcal or horizontal
            x_bot = pos[0][0]
            y_bot = pos[1][0]
            if vert:
                x_norm = pt2[0]
                y_norm = y_bot
            else:
                x_norm = x_bot
                y_norm = pt2[1]

            # if the normal point is past the end point of this segment inc path idx
            # assumes all lines are either vertical or horizontal
            inc = False
            if vert:
                if (y_diff > 0 and y_norm > pt2[1]) or (y_diff < 0
                                                        and y_norm < pt2[1]):
                    inc = True
            else:
                if (x_diff > 0 and x_norm > pt2[0]) or (x_diff < 0
                                                        and x_norm < pt2[0]):
                    inc = True

            if (inc):
                self.path_idx = self.path_idx + 1
                print('increment path index')

            # find a point L distance infront of the normal point on this line
            # assumes all lines are either vertical or horizontal
            if vert:
                x_goal = pt2[0]
                if y_diff > 0:
                    y_goal = y_bot + self.carrot_distance
                else:
                    y_goal = y_bot - self.carrot_distance
            else:
                y_goal = pt2[1]
                if x_diff > 0:
                    x_goal = x_bot + self.carrot_distance
                else:
                    x_goal = x_bot - self.carrot_distance

            goal = np.array([x_goal, y_goal])

            #print(goal)

            return goal
Exemple #7
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        Inputs: (all loaded from the parameter YAML file)
        world_map - a P by 4 numpy array specifying the location, orientation,
            and identification of all the markers/AprilTags in the world. The
            format of each row is (x,y,theta,id) with x,y giving 2D position,
            theta giving orientation, and id being an integer specifying the
            unique identifier of the tag.
        occupancy_map - an N by M numpy array of boolean values (represented as
            integers of either 0 or 1). This represents the parts of the map
            that have obstacles. It is mapped to metric coordinates via
            x_spacing and y_spacing
        pos_init - a 3 by 1 array specifying the initial position of the robot,
            formatted as usual as (x,y,theta)
        pos_goal - a 3 by 1 array specifying the final position of the robot,
            also formatted as (x,y,theta)
        max_speed - a parameter specifying the maximum forward speed the robot
            can go (i.e. maximum control signal for v)
        max_omega - a parameter specifying the maximum angular speed the robot
            can go (i.e. maximum control signal for omega)
        x_spacing - a parameter specifying the spacing between adjacent columns
            of occupancy_map
        y_spacing - a parameter specifying the spacing between adjacent rows
            of occupancy_map
        t_cam_to_body - numpy transformation between the camera and the robot
            (not used in simulation)
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        self.kalman_filter = KalmanFilter(world_map)
        self.prev_v = 0
        self.est_pose = np.array([[0], [0], [0]])
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)
        self.prev_imu_meas = np.array([[0], [0], [0], [0], [0]])

    def process_measurements(self, waypoint):
        """ 
        waypoint is a 1D list [x,y] containing the next waypoint the rover needs to go
        YOUR CODE HERE
        Main loop of the robot - where all measurements, control, and esimtaiton
        are done. This function is called at 60Hz
        """

        #This gives the xy location and the orientation of the tag in the rover frame
        #The orientation is zero when the rover faces directly at the tag
        meas = self.ros_interface.get_measurements()

        self.est_pose = self.kalman_filter.step_filter(self.prev_v,
                                                       self.prev_imu_meas,
                                                       meas)

        state = [self.est_pose[0, 0], self.est_pose[1, 0], self.est_pose[2, 0]]
        goal = [waypoint[0], waypoint[1]]
        controls = self.diff_drive_controller.compute_vel(state, goal)

        self.ros_interface.command_velocity(controls[0], controls[1])
        self.prev_v = controls[0]
        imu_meas = self.ros_interface.get_imu()
        if imu_meas != None:
            imu_meas[3, 0] = -imu_meas[
                3, 0]  #clockwise angular vel is positive from IMU

        self.prev_imu_meas = imu_meas

        return controls[2]
Exemple #8
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS

        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements(
        )  #type list (matriz de 1x3 meas[0][2], posicion del tag [[x, y, z, id]])
        imu_meas = self.ros_interface.get_imu()

        if meas != None:
            # convert meas into a np array
            measu = meas[0]

            # IMPORTANTE USAR ***MEASU*** Y NO MEAS!!!

            #print measurements, python 2 btw...
            print("*******")
            print("Tag: "),
            print(measu[3])
            measu3f = np.round(measu, 3)
            print("Measurements: "),
            print(measu3f[:3])

            #print state
            state = np.array([0.0, 0.0, 0.0])
            print("State: "),
            print(state)

            goal = np.array([measu[0], -measu[1], measu[2]])

            vw = self.diff_drive_controller.compute_vel(state, goal)

            #print comanded velocity
            vw3f = np.round(vw, 3)
            print("Computed command vel: "),
            print(vw3f[:2])

            if vw[2] == False:
                self.ros_interface.command_velocity(vw[0], vw[1])
            if vw[2] == True:
                print("*****The robot arrived its destination*****")
        else:
            #self.ros_interface.command_velocity(0, 0)
            return
Exemple #9
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map,occupancy_map, pos_init, pos_goal, max_speed, max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS
        self.markers   = world_map
        self.vel       = np.array([0.,0.])
        self.imu_meas  = np.array([]) 
        self.meas      = []
        self.max_speed = max_speed
        self.max_omega = max_omega
        # self.goals    = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init, pos_goal)
        # self.total_goals = self.goals.shape[0]
        # self.cur_goal    = 2
        # self.end_goal    = self.goals.shape[0] - 1

        # Uncomment as completed
        #self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas          = self.ros_interface.get_measurements()
        imu_meas      = self.ros_interface.get_imu()
        self.meas     = meas
        self.imu_meas = imu_meas
        
        # unit test for following april tag
        if (meas  != None and meas):
            cur_meas = meas[0]
            # print(cur_meas)
            tag_robot_pose = cur_meas[:3]
            # print(self.tag_pos(cur_meas[3]))
            tag_world_pose = np.float32(self.tag_pos(cur_meas[3]))
            # print(tag_world_pose)
            # print(tag_robot_pose)
            state    = self.robot_pos(tag_world_pose,tag_robot_pose)
            goal     = tag_world_pose
            v,w,done = self.diff_drive_controller.compute_vel(state,goal)
            if done:
                v = 0.01
                w = 0.
            vel = (v,w)
            self.vel  = vel[:2]
            self.done = done
        else:
            v = 0.
            w = 0.
        self.ros_interface.command_velocity(v,w)

        return


    def tag_pos(self, marker_id):
        # print(marker_id)
        # print(self.markers)
        for i in range(len(self.markers)):
            marker_i = np.copy(self.markers[i])
            if int(float(marker_i[3])) == marker_id:
                return marker_i[:3]
        return None


    def robot_pos(self, w_pos, r_pos):
        H_W = np.array([[np.cos(w_pos[2]), -np.sin(w_pos[2]), w_pos[0]],
                        [np.sin(w_pos[2]),  np.cos(w_pos[2]), w_pos[1]],
                        [0., 0., 1.]])
        H_R = np.array([[np.cos(r_pos[2]), -np.sin(r_pos[2]), r_pos[0]],
                        [np.sin(r_pos[2]),  np.cos(r_pos[2]), r_pos[1]],
                        [0., 0., 1.]])
        # print(np.linalg.inv(H_R))
        w_r = np.dot(H_W, np.linalg.inv(H_R))
        
        return np.array([[w_r[0,2]],[w_r[1,2]],[np.arctan2(w_r[1,0],w_r[0,0])]])
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map,occupancy_map, pos_init, pos_goal, max_speed, max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS
        
        # Uncomment as completed
        self.markers = world_map
        self.vel = np.array([0, 0])
        self.imu_meas = np.array([])
        self.meas = []
        
        # TODO for student: Use this when transferring code to robot
        # Handles all the ROS related items
        #self.ros_interface = ROSInterface(t_cam_to_body)

        # YOUR CODE AFTER THIS
        
        # Uncomment as completed
        self.goals = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init, pos_goal)
        # self.total_goals = self.goals.shape[0]
        self.cur_goal = 2
        self.end_goal = self.goals.shape[0] - 1
        self.kalman_filter = KalmanFilter(world_map)
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)

    def process_measurements(self):
        """ 
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        self.meas = meas;
        print 'tag output'
        print meas
        # imu_meas: measurment comig from the imu
        imu_meas = self.ros_interface.get_imu()
        self.imu_meas = imu_meas
        print 'imu measurement'
        print imu_meas
        pose = self.kalman_filter.step_filter(self.vel, self.imu_meas, np.asarray(self.meas))
        

        # Code to follow AprilTags
        '''
        if(meas != None and meas):
            cur_meas = meas[0]
            tag_robot_pose = cur_meas[0:3]
            tag_world_pose = self.tag_pos(cur_meas[3])
            state = self.robot_pos(tag_world_pose, tag_robot_pose)
            goal = tag_world_pose
            vel = self.diff_drive_controller.compute_vel(state, goal)        
            self.vel = vel[0:2];
            print vel
            if(not vel[2]):
                self.ros_interface.command_velocity(vel[0], vel[1])
            else:
                vel = (0.01, 0.1) 
                self.vel = vel
                self.ros_interface.command_velocity(vel[0], vel[1])
        '''


        # Code to move autonomously
        goal = self.goals[self.cur_goal]
        print 'pose'
        print pose
        print 'goal'
        print goal
        vel = self.diff_drive_controller.compute_vel(pose, goal)        
        self.vel = vel[0:2];
        print 'speed'
        print vel
        if(not vel[2]):
            self.ros_interface.command_velocity(vel[0], vel[1])
        else:
            vel = (0, 0) 
            if self.cur_goal < self.end_goal:
                self.cur_goal = self.cur_goal + 1
            self.ros_interface.command_velocity(vel[0], vel[1])
            self.vel = vel
        return

    def tag_pos(self, marker_id):
        for i in range(len(self.markers)):
            marker_i = np.copy(self.markers[i])
            if marker_i[3] == marker_id:
                return marker_i[0:3]
        return None

    def robot_pos(self, w_pos, r_pos):
        H_W = np.array([[math.cos(w_pos[2]), -math.sin(w_pos[2]), w_pos[0]],
                        [math.sin(w_pos[2]), math.cos(w_pos[2]), w_pos[1]],
                        [0, 0, 1]])
        H_R = np.array([[math.cos(r_pos[2]), -math.sin(r_pos[2]), r_pos[0]],
                        [math.sin(r_pos[2]), math.cos(r_pos[2]), r_pos[1]],
                        [0, 0, 1]])
        w_r = H_W.dot(inv(H_R))
        robot_pose =  np.array([[w_r[0,2]], [w_r[1,2]], [math.atan2(w_r[1,0], w_r[0, 0])]])
        return robot_pose
Exemple #11
0
class RobotControl(object):
    """
    Class used to interface with the rover. Gets sensor measurements through ROS subscribers,
    and transforms them into the 2D plane, and publishes velocity commands.
    """
    def __init__(self, world_map, occupancy_map, pos_init, pos_goal, max_speed,
                 max_omega, x_spacing, y_spacing, t_cam_to_body):
        """
        Initialize the class
        """

        # Handles all the ROS related items
        self.ros_interface = ROSInterface(t_cam_to_body)

        self.pos_goal = pos_goal

        # YOUR CODE AFTER THIS
        #-------------------------------------------#
        self.time = rospy.get_time()
        self.controlOut = (0.0, 0.0, False)
        self.count_noMeasurement = 0

        #-------------------------------------------#
        self.markers = world_map
        self.idx_target_marker = 0

        # Calculate the optimal path
        # From pos_init to pos_goal
        self.path_2D = dijkstras(occupancy_map, x_spacing, y_spacing, pos_init,
                                 pos_goal)
        self.idx_path = 0
        self.size_path = self.path_2D.shape[0]
        print "path.shape[0]", self.size_path
        # Generate the 3D path (include "theta")
        self.path = np.zeros((self.size_path, 3))
        theta = 0.0
        for idx in range(self.size_path - 1):
            delta = self.path_2D[(idx + 1), :] - self.path_2D[idx, :]
            theta = atan2(delta[1], delta[0])
            if theta > np.pi:
                theta -= np.pi * 2
            elif theta < -np.pi:
                theta += np.pi * 2
            self.path[idx, :] = np.concatenate(
                (self.path_2D[idx, :], np.array([theta])), axis=1)
        self.path[self.size_path - 1, 0:2] = self.path_2D[self.size_path - 1,
                                                          0:2]
        self.path[self.size_path - 1, 2] = pos_goal[2]  # theta
        #
        self.path[0, 2] = pos_init[2]  # theta
        print "3D path:"
        print self.path

        # Uncomment as completed
        # Kalman filter
        self.kalman_filter = KalmanFilter(world_map)
        self.kalman_filter.mu_est = pos_init  # 3*pos_init # For test

        # Differential drive
        self.diff_drive_controller = DiffDriveController(max_speed, max_omega)
        self.wayPointFollowing = wayPointFollowing(max_speed, max_omega)

        #
        self.task_done = False

    def process_measurements(self):
        """
        YOUR CODE HERE
        This function is called at 60Hz
        """
        meas = self.ros_interface.get_measurements()
        imu_meas = self.ros_interface.get_imu()

        # print 'meas',meas
        print 'imu_meas', imu_meas
        """
        # Control the robot to track the tag
        if (meas is None) or (meas == []):
            # stop
            # self.ros_interface.command_velocity(0.0,0.0)
            #
            if self.count_noMeasurement > 30:
                # Actually the ros_interface will stop the motor itself if we don't keep sending new commands
                self.ros_interface.command_velocity(0.0,0.0)
            else:
                # Keep the old command
                self.ros_interface.command_velocity(self.controlOut[0],self.controlOut[1])
                self.count_noMeasurement += 1
        else:
            print 'meas',meas
            self.count_noMeasurement = 0
            # Thew differential drive controller that lead the robot to the tag
            self.controlOut = self.diff_drive_controller.compute_vel((-1)*np.array(meas[0][0:3]),np.array([0.0,0.0,0.0]))
            self.ros_interface.command_velocity(self.controlOut[0],self.controlOut[1])

        (v,omega,done) = (self.controlOut[0], self.controlOut[1],False )
        """
        """
        if (rospy.get_time() - self.time) < 1.0:
            self.ros_interface.command_velocity(0.0, 3.0)
            # Linear velocity = 0.3 m/s, Angular velocity = 0.5 rad/s
        else:
            self.ros_interface.command_velocity(0.0,0.0)
        """
        """
        (v,omega,done) = (0.0, 0.0, False)
        self.ros_interface.command_velocity(v, omega)
        """
        """
        # Directly move to the goal position
        if self.controlOut[2]: # done
            self.ros_interface.command_velocity(0.0, 0.0)
        else:
            self.controlOut = self.wayPointFollowing.compute_vel(self.kalman_filter.mu_est, self.pos_goal )
            # self.controlOut = self.diff_drive_controller.compute_vel(self.kalman_filter.mu_est, self.pos_goal )
            if self.controlOut[2]: # done
                self.ros_interface.command_velocity(0.0, 0.0)
            else:
                self.ros_interface.command_velocity(self.controlOut[0], self.controlOut[1])
        """
        """
        #----------------------------------------#
        # Switch the targets (way-point of the optimal path) and do the position control
        # if self.controlOut[2] and self.idx_path == self.size_path-1: # all done
        if self.idx_path == self.size_path-1 and self.controlOut[0] < 0.05 and self.controlOut[1] < 0.1 : # all done
            self.ros_interface.command_velocity(0.0, 0.0)
        else:
            self.controlOut = self.diff_drive_controller.compute_vel(self.kalman_filter.mu_est, self.path[self.idx_path,:] )
            self.ros_interface.command_velocity(self.controlOut[0], self.controlOut[1])
            if self.controlOut[2] and self.idx_path < self.size_path-1: # way-point done
                self.idx_path += 1
        #----------------------------------------#
        """

        #----------------------------------------#
        print "self.idx_path", self.idx_path
        # Switch the targets (way-point of the optimal path) and do the position control
        # way-point following (no reducing speeed when reach a way-point)
        # if self.controlOut[2] and self.idx_path == self.size_path-1: # all done
        if self.task_done:  # all done
            self.ros_interface.command_velocity(0.0, 0.0)
        elif self.idx_path == self.size_path - 1:  # The last one
            # Change the threshold
            self.diff_drive_controller.threshold = 0.02  # 3 cm
            # Using diff_drive_controller to reach the goal position with right direction
            self.controlOut = self.diff_drive_controller.compute_vel(
                self.kalman_filter.mu_est, self.path[self.idx_path, :])
            # if self.controlOut[0] < 0.05 and self.controlOut[1] < 0.1 : # all done
            if self.controlOut[2]:  # all done
                self.ros_interface.command_velocity(0.0, 0.0)
                self.task_done = True  # all done
            else:
                self.ros_interface.command_velocity(self.controlOut[0],
                                                    self.controlOut[1])
        else:
            # The way-points, using wayPointFollowing to trace the trajectory without pausing

            if self.idx_path == self.size_path - 2:  # The last 2nd one
                self.controlOut = self.diff_drive_controller.compute_vel(
                    self.kalman_filter.mu_est, self.path[self.idx_path, :])
            else:
                self.controlOut = self.wayPointFollowing.compute_vel(
                    self.kalman_filter.mu_est, self.path[self.idx_path, :])

            # self.controlOut = self.wayPointFollowing.compute_vel(self.kalman_filter.mu_est, self.path[self.idx_path,:] )
            self.ros_interface.command_velocity(self.controlOut[0],
                                                self.controlOut[1])
            if self.controlOut[
                    2] and self.idx_path < self.size_path - 1:  # way-point done
                self.idx_path += 1
        #----------------------------------------#
        # self.time = rospy.get_time()
        # print "self.time",self.time

        # Kalman filter
        self.kalman_filter.step_filter(self.controlOut[0], (-1) * imu_meas,
                                       meas, rospy.get_time())
        print "mu_est", self.kalman_filter.mu_est

        return