SceneExploration.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 '''
4 Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Trautmann Jeremias, Wittenbeck Valerij
5 
6 All rights reserved.
7 
8 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
9 
10 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
11 
12 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
13 
14 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
15 
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17 '''
18 
19 import roslib
20 import rospy
21 import smach
22 import smach_ros
23 import json
24 import random
25 import shutil
26 import csv
27 import time
28 
29 from actionlib import *
30 from actionlib.msg import *
31 import sensor_msgs.msg
32 import math
33 from indirect_search.indirect_search_sm import IndirectSearchStateMachine
34 from direct_search.direct_search_sm import DirectSearchStateMachine
35 from random_search.random_search_sm import RandomSearchStateMachine
36 from cropbox_search.cropbox_search_sm import CropBoxSearchStateMachine
37 from cropbox_search.cropbox_record_sm import CropBoxRecordStateMachine
38 from direct_search.grid_init_record_sm import GridInitRecordStateMachine
39 import common.init
40 from common.state_acquisition import GetRobotState
41 import __builtin__ # hack for sharing log dir
42 import signal
43 import subprocess
44 from os.path import expanduser
45 from asr_fake_object_recognition.srv import ClearAllRecognizers as FakeObjectClearAllRecognizers
46 from asr_descriptor_surface_based_recognition.srv import ClearAllRecognizers as DescriptorSurfaceClearAllRecognizers
47 from asr_aruco_marker_recognition.srv import ReleaseRecognizer
48 from asr_visualization_server.srv import DrawAllModelsMild
49 
50 # Naming convention
51 # State names are all capitalized with underscores, e.g. MVU_PTU
52 # State names that are (sub-) state machines start with SM_
53 # State variables are lowercase separated by underscores
54 # Classes follow the CapWords convention, e.g. MoveBase
55 # Method names shoud be lowercase separated by underscores
56 #
57 # remapping should always be defined even if its identical
58 
59 global rosbag_proc
60 
61 def main():
62  """
63  Start automata and introspection server
64  """
65 
66  #config variables that should be outsourced in production TODO
67  rospy.init_node('scene_exploration_sm')
68 
69  # Define before on_shutdown -> so that they are known
70  global rosbag_proc
71  rosbag_proc = None
72  global smach_server
73  smach_server = None
74 
75 
76  # register closing callback
77  rospy.on_shutdown(shutdown_hook)
78 
79  # NOTE: Writing variables in __builtin__ is bad and I don't encourage it,
80  # but we need to access the log_dir in several other modules
81 
82  # Set True if you want to wait for key press after states
83  __builtin__.evaluation = False
84 
85  log_dir = common.init.create_log_folder()
86  __builtin__.log_dir = log_dir
87 
88  # Record to rosbag
89  rosbag_proc = common.init.start_rosbag(log_dir)
90  # Add 3d models to labor map
91  rospy.loginfo("Waiting for visualization_server-service to become available")
92  rospy.wait_for_service('visualization/draw_all_models_mild')
93  try:
94  draw_all_models_mild = rospy.ServiceProxy('visualization/draw_all_models_mild', DrawAllModelsMild)
95  draw_all_models_mild()
96  rospy.loginfo("Publishing room model")
97  except rospy.ServiceException, e:
98  rospy.logwarn("Error calling the draw all models mild service")
99 
100 
101  # get initial objects from user
102  # sleep just to wait till all init output is done
103  rospy.sleep(1)
104  initial_objects = common.init.get_initial_objects()
105  rospy.loginfo("initial_objects: " + str(initial_objects))
106 
107 
108  # write start time to logfile
109  with open(__builtin__.log_dir + '/log.csv', 'a') as log:
110  logwriter = csv.writer(log, delimiter=' ',
111  quotechar='|', quoting=csv.QUOTE_MINIMAL)
112 
113  logwriter.writerow([time.time()])
114 
115  rospy.loginfo("Initial robot state:\n" + str(GetRobotState().get_robot_state()))
116 
117  #Decide with which state machine (e.g. from above or from included modules) we want to start searching.
118  rospy.loginfo("We are running our state machine in the following mode:")
119 
120  mode = rospy.get_param("/scene_exploration_sm/mode")
121  if mode is not 1 and mode is not 2 and mode is not 3 and mode is not 4 and mode is not 5 and mode is not 6 and mode is not 7:
122  #Make informative search the default search
123  rospy.logwarn("Unknown mode was set in params -> informative search will be taken as default")
124  rospy.set_param("/scene_exploration_sm/mode", 2)
125  mode = 2
126 
127 
128  if mode is 1 :
129  rospy.loginfo("Direct Search mode as stand alone")
130  sm_direct_search_as_standalone = DirectSearchStateMachine().sm_direct_search_as_standalone
131  smach_server = startIntrospectionServer(sm_direct_search_as_standalone, '/DIRECT_SEARCH')
132  smach_thread = threading.Thread(target = sm_direct_search_as_standalone.execute)
133  elif mode is 2 :
134  rospy.loginfo("Indirect Search mode as stand alone")
135  sm_indirect_search = IndirectSearchStateMachine().get_indirect_sm_as_stand_alone(initial_objects)
136  smach_server = startIntrospectionServer(sm_indirect_search, '/INDIRECT_SEARCH')
137  smach_thread = threading.Thread(target=sm_indirect_search.execute)
138  elif mode is 3:
139  rospy.loginfo("Object Search mode")
140 
141  #Meta state machine containing direct- and indirect search
142  sm_object_search = smach.StateMachine(outcomes=['aborted',
143  'found_all_objects',
144  'found_all_required_scenes',
145  'nowhere_left_to_search'])
146  # construct meta state machine
147  with sm_object_search:
148  smach.StateMachine.add('OBJECT_SEARCH_INIT',
150  transitions={'succeeded':'DIRECT_SEARCH',
151  'aborted':'aborted'})
152 
153  smach.StateMachine.add('DIRECT_SEARCH',
154  DirectSearchStateMachine().sm_direct_search_for_object_search,
155  transitions={'found_objects':'INDIRECT_SEARCH',
156  'aborted':'aborted',
157  'nowhere_left_to_search':'nowhere_left_to_search'})
158 
159  smach.StateMachine.add('INDIRECT_SEARCH',
160  IndirectSearchStateMachine().get_indirect_sm_for_object_search(),
161  transitions={'no_predictions_left':'DIRECT_SEARCH',
162  'aborted':'aborted',
163  'found_all_objects':'found_all_objects',
164  'found_all_required_scenes':'found_all_required_scenes'})
165 
166  smach_server = startIntrospectionServer(sm_object_search, '/OBJECT_SEARCH')
167  smach_thread = threading.Thread(target=sm_object_search.execute)
168  elif mode is 4:
169  rospy.loginfo("Random search mode")
170  sm_random_search = RandomSearchStateMachine.sm_random_search
171  smach_server = startIntrospectionServer(sm_random_search, '/RANDOM_SEARCH')
172  smach_thread = threading.Thread(target=sm_random_search.execute)
173  elif mode is 5:
174  rospy.loginfo("Cropbox search mode")
175  sm_cropbox_search = CropBoxSearchStateMachine().sm_cropbox_search
176  smach_server = startIntrospectionServer(sm_cropbox_search, '/CROPBOX_SEARCH')
177  smach_thread = threading.Thread(target=sm_cropbox_search.execute)
178  elif mode is 6:
179  rospy.loginfo("Cropbox record mode")
180  sm_cropbox_record = CropBoxRecordStateMachine().sm_cropbox_record
181  smach_server = startIntrospectionServer(sm_cropbox_record, '/CROPBOX_RECORD')
182  smach_thread = threading.Thread(target=sm_cropbox_record.execute)
183  elif mode is 7:
184  rospy.loginfo("Grid init record mode")
185  sm_grid_init_record_search = GridInitRecordStateMachine().sm_grid_init_record_search
186  smach_server = startIntrospectionServer(sm_grid_init_record_search, '/GRID_INIT_RECORD')
187  smach_thread = threading.Thread(target=sm_grid_init_record_search.execute)
188 
189  #Start searching
190  smach_thread.start()
191  rospy.spin()
192 
193 
194 def startIntrospectionServer(sm, nameOfSearch):
195  if rospy.get_param("/scene_exploration_sm/enableSmachViewer"):
196  rospy.loginfo("Smach viewer enabled")
197  # Construct graphical output of SMACH automata.
198  server = smach_ros.IntrospectionServer(
199  'scene_exploration_state_machine',
200  sm,
201  nameOfSearch)
202  #Start logging SMACH automat
203  server.start()
204  return server
205  else:
206  rospy.loginfo("Smach viewer disabled")
207  return None
208 
210  rospy.loginfo("Enter shutdown_hook")
211  """ Close rosbag recording, copy nbv logs and leave"""
212  global rosbag_proc
213  if rosbag_proc is not None:
214  rospy.loginfo("Stop rosbag_proc")
215  rosbag_proc.send_signal(subprocess.signal.SIGINT)
216 
217  #Stop logging SMACH automata
218  global smach_server
219  if smach_server is not None:
220  rospy.loginfo("Stop smach_server")
221  smach_server.stop()
222 
223  if __builtin__.log_dir:
224  home = expanduser("~")
225  try:
226  shutil.copy(home + "/log/nbv.log", __builtin__.log_dir)
227  except IOError:
228  pass
229  try:
230  shutil.copy(home + "/log/world_model.log", __builtin__.log_dir)
231  except IOError:
232  pass
233  try:
234  shutil.copy(home + "/log/ism.log", __builtin__.log_dir)
235  except IOError:
236  pass
237  try:
238  shutil.copy(home + "/log/state_machine.log", __builtin__.log_dir)
239  except IOError:
240  pass
241  try:
242  shutil.copy(home + "/log/direct_search_manager.log", __builtin__.log_dir)
243  except IOError:
244  pass
245  try:
246  shutil.copy(home + "/log/viz_server.log", __builtin__.log_dir)
247  except IOError:
248  pass
249 
250  #Stop recognizers in case signal is caught during object detection.
251  if rospy.get_param("/scene_exploration_sm/use_sensors") is False:
252  try:
253  release_fake_recognizers = rospy.ServiceProxy('/asr_fake_object_recognition/clear_all_recognizers', FakeObjectClearAllRecognizers)
254  release_fake_recognizers()
255  except rospy.ServiceException, e:
256  rospy.logwarn("Error calling the clear for /asr_fake_object_recognition/clear_all_recognizers service: " + str(e))
257  else:
258  try:
259  release_desc_recognizers = rospy.ServiceProxy('/asr_descriptor_surface_based_recognition/clear_all_recognizers', DescriptorSurfaceClearAllRecognizers)
260  release_desc_recognizers()
261  except rospy.ServiceException, e:
262  rospy.logwarn("Error calling the clear for /asr_descriptor_surface_based_recognition/clear_all_recognizers service: " + str(e))
263  try:
264  release_marker_recognizers = rospy.ServiceProxy('/asr_aruco_marker_recognition/release_recognizer', ReleaseRecognizer)
265  release_marker_recognizers()
266  except rospy.ServiceException, e:
267  rospy.logwarn("Error calling the clear for /asr_aruco_marker_recognition/release_recognizer service: " + str(e))
268 
269  rospy.loginfo("Finished shutdown_hook")
270 
271 
272 if __name__ == '__main__':
273  try:
274  main()
275  except rospy.ROSInterruptException:
276  pass
def startIntrospectionServer(sm, nameOfSearch)


asr_state_machine
Author(s): Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Marek Felix, Meißner Pascal, Trautmann Jeremias, Wittenbeck Valerij
autogenerated on Mon Feb 28 2022 21:53:50