Skip to content

Commit

Permalink
Added new state for recording a rosbag of the run
Browse files Browse the repository at this point in the history
  • Loading branch information
RaresAmbrus committed May 2, 2016
1 parent 5559488 commit 332f79a
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 41 deletions.
3 changes: 2 additions & 1 deletion learn_objects_action/scripts/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@
planning_method = rospy.get_param("~view_planner", "ral16")
if planning_method == "ral16":
rospy.loginfo("Using the RAL-16 method for learning the object.")
sm = LearnObjectActionMachineRAL16(model_path, rois_file, debug_mode)
sm = LearnObjectActionMachineRAL16(model_path, rois_file, debug_mode, record_run)
pass
elif planning_method == "infogain":
sm = LearnObjectActionMachineInfoGain(model_path, debug_mode)
else:
rospyt.logerr("The chosen planning method is not available.")
sys.exit(1)

record_run = rospy.get_param("~record_run", False)

# Construct action server wrapper
asw = ActionServerWrapper(
Expand Down
77 changes: 48 additions & 29 deletions learn_objects_action/src/learn_objects_action/machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@
from std_msgs.msg import String
from learn_objects_action.util import get_ros_service
from util import DebugModeServices
from record import StartRecording, StopRecording

class LearnObjectActionMachineRAL16(smach.StateMachine):
def __init__(self, model_path, rois_file, debug_mode):
def __init__(self, model_path, rois_file, debug_mode, record_run):
smach.StateMachine.__init__(self,
outcomes=['succeeded', 'failed', 'preempted'],
input_keys=['action_goal'],
output_keys=['action_result'],
input_keys=['action_goal'],
output_keys=['action_result'],
)

self.userdata.action_result = LearnObjectResult()
self._debug_mode = debug_mode
self._debug_services = DebugModeServices(self.preempt_requested) if self._debug_mode else None

self._record_run = record_run

with self:
smach.StateMachine.add('METRIC_MAP_SWEEP', MetricSweep(debug_mode, self._debug_services),
transitions={'done':'SELECT_CLUSTER',
Expand All @@ -40,9 +42,18 @@ def __init__(self, model_path, rois_file, debug_mode):
transitions={'error':'failed',
'success':'START_TRANSFORM',
'preempted': 'preempted'})
smach.StateMachine.add('START_TRANSFORM', StartTransformation(debug_mode, self._debug_services),
transitions={'error':'failed',
'success':'START_PTU_TRACK'})
if self._record_run :
smach.StateMachine.add('START_TRANSFORM', StartTransformation(debug_mode, self._debug_services),
transitions={'error':'failed',
'success':'START_RECORDING'})
smach.StateMachine.add('START_RECORDING', StartRecording(debug_mode, self._debug_services),
transitions={'error':'failed',
'success':'START_PTU_TRACK'})
else:
smach.StateMachine.add('START_TRANSFORM', StartTransformation(debug_mode, self._debug_services),
transitions={'error':'failed',
'success':'START_PTU_TRACK'})

smach.StateMachine.add('START_PTU_TRACK', StartPTUTrack(debug_mode, self._debug_services),
transitions={'error':'failed',
'success':'START_CAMERA_TRACK' })
Expand All @@ -55,9 +66,18 @@ def __init__(self, model_path, rois_file, debug_mode):
'done':'STOP_CAMERA_TRACK',
'preempted':'preempted'})
self._stop_cam_track = StopCameraTrack(debug_mode, self._debug_services)
smach.StateMachine.add('STOP_CAMERA_TRACK', self._stop_cam_track,
transitions={'error':'failed',
'success':'STOP_PTU_TRACK' })
self._stop_recording = StopRecording(debug_mode, self._debug_services)
if self._record_run :
smach.StateMachine.add('STOP_CAMERA_TRACK', self._stop_cam_track,
transitions={'error':'failed',
'success':'STOP_RECORDING' })
smach.StateMachine.add('STOP_RECORDING', self._stop_recording,
transitions={'error':'failed',
'success':'STOP_PTU_TRACK' })
else:
smach.StateMachine.add('STOP_CAMERA_TRACK', self._stop_cam_track,
transitions={'error':'failed',
'success':'STOP_PTU_TRACK' })
self._stop_ptu_track = StopPTUTrack(debug_mode, self._debug_services)
smach.StateMachine.add('STOP_PTU_TRACK', self._stop_ptu_track,
transitions={'error':'failed',
Expand All @@ -70,7 +90,7 @@ def __init__(self, model_path, rois_file, debug_mode):
transitions={'error':'failed',
'done':'succeeded',
'preempted': 'preempted' })

self.set_initial_state(["METRIC_MAP_SWEEP"], userdata=self.userdata)
self.register_termination_cb(self.finish)
self._prior_movebase_config = {}
Expand All @@ -83,7 +103,7 @@ def __init__(self, model_path, rois_file, debug_mode):
String)



def execute(self, parent_ud = smach.UserData()):
# Reduce the robot velocity
self._prior_movebase_config = self._reconfigure_client.update_configuration({})
Expand All @@ -101,15 +121,15 @@ def execute(self, parent_ud = smach.UserData()):
rospy.set_param("/monitored_navigation/recover_states", recoveries)

super(LearnObjectActionMachineRAL16, self).execute(parent_ud)


def finish(self, userdata, terminal_states, outcome):
print "Restoring monitored_nav & move_base parameters"
# Restore movebase velocities
self._reconfigure_client.update_configuration(self._prior_movebase_config)
print "Parameters:"
print rospy.get_param("/monitored_navigation/recover_states")

# Re-enable monitored nav recoveries
rospy.set_param("/monitored_navigation/recover_states",
self._prior_recoveries)
Expand All @@ -118,6 +138,10 @@ def finish(self, userdata, terminal_states, outcome):
print "Stopping camera tracker."
self._stop_cam_track.execute(userdata) # this is such an uggly way of doing this!

if self._record_run:
print "Stopping recoring camera topics"
self._stop_recording(userdata) # this should already be triggered, but just to double check

# Ensure the PTU has zero velocity
print "Stopping PTU tracker."
self._stop_ptu_track.execute(userdata)
Expand All @@ -132,7 +156,7 @@ def finish(self, userdata, terminal_states, outcome):

# Double certain to save to RombusDB
self._status_publisher.publish(String("stop_viewing"))


###############################################

Expand All @@ -141,14 +165,14 @@ class LearnObjectActionMachineInfoGain(smach.StateMachine):
def __init__(self, model_path, debug_mode):
smach.StateMachine.__init__(self,
outcomes=['succeeded', 'failed', 'preempted'],
input_keys=['action_goal'],
output_keys=['action_result'],
input_keys=['action_goal'],
output_keys=['action_result'],
)

self.userdata.action_result = LearnObjectResult()
self._debug_mode = debug_mode
self._debug_services = DebugModeServices(self.preempt_requested) if self._debug_mode else None

with self:
smach.StateMachine.add('METRIC_MAP_SWEEP', MetricSweep(debug_mode, self._debug_services),
transitions={'done':'SELECT_CLUSTER',
Expand All @@ -165,7 +189,7 @@ def __init__(self, model_path, debug_mode):
transitions={'error':'failed',
'done':'succeeded',
'preempted': 'preempted' })

self.set_initial_state(["METRIC_MAP_SWEEP"], userdata=self.userdata)
self.register_termination_cb(self.finish)
self._prior_movebase_config = {}
Expand All @@ -178,7 +202,7 @@ def __init__(self, model_path, debug_mode):
String)



def execute(self, parent_ud = smach.UserData()):
# Reduce the robot velocity
self._prior_movebase_config = self._reconfigure_client.update_configuration({})
Expand All @@ -196,23 +220,18 @@ def execute(self, parent_ud = smach.UserData()):
rospy.set_param("/monitored_navigation/recover_states", recoveries)

super(LearnObjectActionMachineInfoGain, self).execute(parent_ud)


def finish(self, userdata, terminal_states, outcome):
print "Restoring monitored_nav & move_base parameters"
# Restore movebase velocities
self._reconfigure_client.update_configuration(self._prior_movebase_config)
print "Parameters:"
print rospy.get_param("/monitored_navigation/recover_states")

# Re-enable monitored nav recoveries
rospy.set_param("/monitored_navigation/recover_states",
self._prior_recoveries)

# Double certain to save to RombusDB
self._status_publisher.publish(String("stop_viewing"))





36 changes: 25 additions & 11 deletions learn_objects_action/src/learn_objects_action/metric_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@

class MetricSweep(smach.State):
def __init__(self, debug_mode, debug_services):
smach.State.__init__( self, outcomes=['done', 'failed', 'preempted'],
input_keys=['action_goal'] )
smach.State.__init__( self, outcomes=['done', 'failed', 'preempted'],
input_keys=['action_goal'],
output_keys=['sweep_folder'] )

# self._metric_sweep_action = actionlib.SimpleActionClient(
# '/ptu_pan_tilt_metric_map',
Expand All @@ -38,13 +39,14 @@ def __init__(self, debug_mode, debug_services):
self._set_waypoint_map = get_ros_service("/set_waypoint",
ChangeWaypoint)

self._latest_observation = ''

self._goal = SweepGoal()
self._goal.type = "medium"

self._debug_mode = debug_mode
self._debug_services = debug_services

def execute(self, userdata):
try:
if self._debug_mode:
Expand All @@ -64,6 +66,20 @@ def execute(self, userdata):
self.service_preempt()
break
else:
# wait for the message that the sweep has finished
try:
latest_observation = rospy.wait_for_message("/local_metric_map/room_observations", RoomObservation,
timeout=120)
self._latest_observation = latest_observation.xml_file_name
print 'Latest observation ', self._latest_observation
slash = self._latest_observation.rfind('/')
self._obs_folder = self._latest_observation[0:slash+1]
print 'Observation folder ', self._obs_folder
userdata['sweep_folder'] = self._obs_folder
except rospy.ROSException, e:
rospy.logwarn("Never got a message to say that a metric "
"map was recorded. Learn objects action failed.")

# wait for the message that it has been processed...
try:
status = rospy.wait_for_message("/local_metric_map/status", String,
Expand All @@ -74,7 +90,7 @@ def execute(self, userdata):
return 'failed'
if status.data != "finished_processing_observation":
return 'failed'

# Update the local waypoint 2d map
resp = self._set_waypoint_map(userdata.action_goal.waypoint)
if not resp.is_ok:
Expand All @@ -94,10 +110,10 @@ def execute(self, userdata):
class SelectCluster(smach.State):
def __init__(self, rois_file, debug_mode, debug_services):
smach.State.__init__( self, outcomes=['selected', 'none'],
input_keys=['action_goal','object'],
input_keys=['action_goal','object','sweep_folder'],
#input_keys=['waypoint'],
output_keys=['dynamic_object', 'dynamic_object_centroid',
'dynamic_object_points','dynamic_object_id', 'object'])
'dynamic_object_points','dynamic_object_id', 'object', 'sweep_folder'])
self._get_clusters = get_ros_service("/object_manager_node/ObjectManager/DynamicObjectsService",
DynamicObjectsService)
self._get_specific_cluster = get_ros_service("/object_manager_node/ObjectManager/GetDynamicObjectService",
Expand All @@ -114,7 +130,7 @@ def execute(self, userdata):
# Load the waypoint to soma from file
if self._rois_file != "NONE":
with open(self._rois_file, "r") as f:
somas = yaml.load(f.read())
somas = yaml.load(f.read())
soma_region = somas[userdata.action_goal.waypoint]
else:
soma_region = ""
Expand All @@ -140,10 +156,10 @@ def execute(self, userdata):
p = Pose()
p.position.x = pnt.x
p.position.y = pnt.y
poses = self._get_plan_points(min_dist=1.0,
poses = self._get_plan_points(min_dist=1.0,
max_dist=1.5,
number_views=25,
inflation_radius=0.3,
inflation_radius=0.3,
target_pose=p,
SOMA_region=soma_region,
return_as_trajectory=True)
Expand Down Expand Up @@ -172,5 +188,3 @@ def execute(self, userdata):
rospy.logwarn("Failed to select a cluster!!!!")
rospy.logwarn("-> Exceptions was: %s" % str(e))
return "none"


76 changes: 76 additions & 0 deletions learn_objects_action/src/learn_objects_action/record.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import rospy
import smach
import math

from actionlib import *
from actionlib.msg import *
from scitos_ptu.msg import PtuGotoAction,PtuGotoGoal

from std_srvs.srv import Empty
from geometry_msgs.msg import TransformStamped
from util import get_ros_service
from sensor_msgs.msg import JointState, PointCloud2
from rosbag_openni_compression.msg import RosbagRecordCameraAction, RosbagRecordCameraActionGoal, RosbagRecordCameraGoal

class StartRecording(smach.State):
def __init__(self, debug_mode, debug_services):
smach.State.__init__( self, outcomes=['error', 'success'],
input_keys=['sweep_folder'],
output_keys=['sweep_folder'])

self._data_compression_action = actionlib.SimpleActionClient(
'/rosbag_record_camera',
RosbagRecordCameraAction)
rospy.loginfo("Initialising LeanObjects SM: "
"Waiting for data compression action server...")
if not self._data_compression_action.wait_for_server(rospy.Duration(5)):
rospy.logerr("Data compression action can't be found!")
raise Exception("LearnObject SM can't initialise; missing service.")
self._data_compression_goal = RosbagRecordCameraGoal()

self._debug_mode = debug_mode
self._debug_services = debug_services


def execute(self, userdata):
try:
self._data_compression_goal.camera = 'head_xtion'
self._data_compression_goal.bagfile = userdata['sweep_folder']+'tracking.bag'
self._data_compression_goal.with_depth = True
self._data_compression_goal.with_rgb = True

# Start logging of camera topics
self._data_compression_action.send_goal(self._data_compression_goal)
rospy.sleep(20)
rospy.loginfo("Starting recording head_xtion camera topics ")
return "success"
except Exception, e:
print e
return "error"

class StopRecording(smach.State):
def __init__(self, debug_mode, debug_services):
smach.State.__init__( self, outcomes=['error', 'success'],
input_keys=['sweep_folder'],
output_keys=['sweep_folder'])

self._data_compression_action = actionlib.SimpleActionClient(
'/rosbag_record_camera',
RosbagRecordCameraAction)
rospy.loginfo("Initialising LeanObjects SM: "
"Waiting for data compression action server...")
if not self._data_compression_action.wait_for_server(rospy.Duration(5)):
rospy.logerr("Data compression action can't be found!")
raise Exception("LearnObject SM can't initialise; missing service.")

self._debug_mode = debug_mode
self._debug_services = debug_services


def execute(self, userdata):
try:
self._data_compression_action.cancel_all_goals()
rospy.loginfo("Stopped recording head_xtion topics")
return "success"
except:
return "error"

0 comments on commit 332f79a

Please sign in to comment.