def execute(self, ud): start_time = rospy.Time.now() n_checks = 0 outcome = 'false' while self._max_checks == -1 or n_checks <= self._max_checks: # Check for timeout if self._timeout and rospy.Time.now() - start_time > self._timeout: break # Check for preemption if self.preempt_requested(): self.service_preempt() outcome = 'preempted' break # Call the condition try: if self._cond_cb(ud): outcome = 'true' break except: raise smach.InvalidUserCodeError("Error thrown while executing condition callback %s: " % str( self._cond_cb) + traceback.format_exc()) n_checks += 1 rospy.sleep(self._poll_rate) if self.preempt_requested(): self.service_preempt() outcome = 'preempted' return outcome
def execute(self, ud): rate = self.node.create_rate(1 / self._poll_rate) start_time = self.node.get_clock().now() n_checks = 0 while self._max_checks == -1 or n_checks <= self._max_checks: # Check for timeout if self._timeout and self.node.get_clock().now( ) - start_time > self._timeout: break # Check for preemption if self.preempt_requested(): self.service_preempt() return 'preempted' # Call the condition try: if self._cond_cb(ud): return 'true' except: raise smach.InvalidUserCodeError( "Error thrown while executing condition callback %s: " % str(self._cond_cb) + traceback.format_exc()) n_checks += 1 rate.sleep() return 'false'
def __getattr__(self, name): if name[0] == '_': return object.__getattr__(self, name) if name not in self._input: raise smach.InvalidUserCodeError("Reading from SMACH userdata key '%s' but the only keys that were declared as input to this state were: %s. This key needs to be declaread as input to this state. " % (name, self._input)) if name not in self._output: return get_const(getattr(self._ud, self._remap(name))) return getattr(self._ud, self._remap(name))
def __getitem__(self, key): if key not in self._input: raise smach.InvalidUserCodeError( "Reading from SMACH userdata key '%s' but the only keys that were declared as input to this state were: %s. This key needs to be declaread as input to this state. " % (key, self._input)) if key not in self._output: return get_const(self._ud.__getitem__(self._remap(key))) return self._ud.__getitem__(self._remap(key))
def _state_runner(self, label): """Runs the states in parallel threads.""" # Wait until all threads are ready to start before beginnging self._ready_event.wait() self.call_transition_cbs() # Execute child state try: self._child_outcomes[label] = self._states[label].execute( smach.Remapper( self.userdata, self._states[label].get_registered_input_keys(), self._states[label].get_registered_output_keys(), self._remappings[label])) except PreemptException: self._child_outcomes[label] = self._default_outcome except: self._user_code_exception = True with self._done_cond: self._done_cond.notify_all() raise smach.InvalidStateError( ("Could not execute child state '%s': " % label) + traceback.format_exc()) # Make sure the child returned an outcome if self._child_outcomes[label] is None: raise smach.InvalidStateError( "Concurrent state '%s' returned no outcome on termination." % label) else: smach.loginfo( "Concurrent state '%s' returned outcome '%s' on termination." % (label, self._child_outcomes[label])) self._done_cond.acquire() self.request_preempt() self._done_cond.notify_all() self._done_cond.release() # Check if all of the states have completed with self._done_cond: # initialize preemption flag preempt_others = False # Call transition cb's self.call_transition_cbs() # Call child termination cb if it's defined if self._child_termination_cb: try: preempt_others = self._child_termination_cb( self._child_outcomes) except: raise smach.InvalidUserCodeError( "Could not execute child termination callback: " + traceback.format_exc()) # Notify the container to terminate (and preempt other states if neceesary) if preempt_others or all( [o is not None for o in self._child_outcomes.values()]): self._done_cond.notify_all()
def execute(self, parent_ud): self._is_running = True # Copy input keys self._copy_input_keys(parent_ud, self.userdata) self.call_start_cbs() # Iterate over items outcome = self._exhausted_outcome if hasattr(self._items, '__call__'): it = self._items().__iter__() else: it = self._items.__iter__() while not smach.is_shutdown(): try: item = next(it) except: outcome = self._exhausted_outcome break smach.loginfo("Iterating %s of %s" % (str(item), str(self._items))) self.userdata[self._items_label] = item # Enter the contained state try: outcome = self._state.execute(self.userdata) except smach.InvalidUserCodeError as ex: smach.logerr("Could not execute Iterator state '%s'" % self._state_label) raise ex except: raise smach.InvalidUserCodeError( "Could not execute iterator state '%s' of type '%s': " % (self._state_label, self._state) + traceback.format_exc()) # Check if we should stop preemptively if self.preempt_requested(): self.service_preempt() outcome = 'preempted' break if outcome in self._break_outcomes\ or (len(self._loop_outcomes) > 0 and outcome not in self._loop_outcomes): break self.call_transition_cbs() # Remap the outcome if necessary if outcome in self._final_outcome_map: outcome = self._final_outcome_map[outcome] # Copy output keys self._copy_output_keys(self.userdata, parent_ud) self._is_running = False self.call_termination_cbs(self._state_label, outcome) return outcome
def _execute_state(self, state, force_exit=False): result = None try: ud = smach.Remapper( self.userdata, state.get_registered_input_keys(), state.get_registered_output_keys(), self._remappings[state.name]) if force_exit: state.on_exit(ud) else: result = state.execute(ud) #print 'execute %s --> %s' % (state.name, self._returned_outcomes[state.name]) except smach.InvalidUserCodeError as ex: smach.logerr("State '%s' failed to execute." % state.name) raise ex except: raise smach.InvalidUserCodeError("Could not execute state '%s' of type '%s': " % (state.name, state) + traceback.format_exc()) return result
def _update_once(self): """Method that updates the state machine once. This checks if the current state is ready to transition, if so, it requests the outcome of the current state, and then extracts the next state label from the current state's transition dictionary, and then transitions to the next state. """ outcome = None transition_target = None last_state_label = self._current_label # Make sure the state exists if self._current_label not in self._states: raise smach.InvalidStateError( "State '%s' does not exist. Available states are: %s" % (self._current_label, list(self._states.keys()))) # Check if a preempt was requested before or while the last state was running if self.preempt_requested(): smach.loginfo( "Preempt requested on state machine before executing the next state." ) # We were preempted if self._preempted_state is not None: # We were preempted while the last state was running if self._preempted_state.preempt_requested(): smach.loginfo( "Last state '%s' did not service preempt. Preempting next state '%s' before executing..." % (self._preempted_label, self._current_label)) # The flag was not reset, so we need to keep preempting # (this will reset the current preempt) self._preempt_current_state() else: # The flag was reset, so the container can reset self._preempt_requested = False self._preempted_state = None else: # We were preempted after the last state was running # So we sho if(self._preempt_requested):uld preempt this state before we execute it self._preempt_current_state() # Execute the state self._tree_view_enable_state(self._current_label) try: self._state_transitioning_lock.release() outcome = self._current_state.execute( smach.Remapper( self.userdata, self._current_state.get_registered_input_keys(), self._current_state.get_registered_output_keys(), self._remappings[self._current_label])) except smach.InvalidUserCodeError as ex: smach.logerr("State '%s' failed to execute." % self._current_label) raise ex except: raise smach.InvalidUserCodeError( "Could not execute state '%s' of type '%s': " % (self._current_label, self._current_state) + traceback.format_exc()) finally: self._state_transitioning_lock.acquire() self._tree_view_disable_state(self._current_label) # Check if outcome was a potential outcome for this type of state if outcome not in self._current_state.get_registered_outcomes(): raise smach.InvalidTransitionError( "Attempted to return outcome '%s' preempt_requestedfrom state '%s' of" " type '%s' which only has registered outcomes: %s" % (outcome, self._current_label, self._current_state, self._current_state.get_registered_outcomes())) # Check if this outcome is actually mapped to any target if outcome not in self._current_transitions: raise smach.InvalidTransitionError( "Outcome '%s' of state '%s' is not bound to any transition target. Bound transitions include: %s" % (str(outcome), str( self._current_label), str(self._current_transitions))) # Set the transition target transition_target = self._current_transitions[outcome] # Check if the transition target is a state in this state machine, or an outcome of this state machine if transition_target in self._states: # Set the new state self._set_current_state(transition_target) # Spew some info smach.loginfo("State machine transitioning '%s':'%s'-->'%s'" % (last_state_label, outcome, transition_target)) # Call transition callbacks self.call_transition_cbs() else: # This is a terminal state if self._preempt_requested and self._preempted_state is not None: if not self._current_state.preempt_requested(): self.service_preempt() if transition_target not in self.get_registered_outcomes(): # This is a container outcome that will fall through transition_target = outcome if transition_target in self.get_registered_outcomes(): # The transition target is an outcome of the state machine self._set_current_state(None) # Spew some info smach.loginfo("State machine terminating '%s':'%s':'%s'" % (last_state_label, outcome, transition_target)) # Call termination callbacks self.call_termination_cbs([last_state_label], transition_target) return transition_target else: raise smach.InvalidTransitionError( "Outcome '%s' of state '%s' with transition target '%s' is neither a registered state nor a registered container outcome." % (outcome, self._current_label, transition_target)) return None
def execute(self, parent_ud=smach.UserData()): """Overridden execute method. This starts all the threads. """ # Clear the ready event self._ready_event.clear() # Reset child outcomes self._child_outcomes = {} # Copy input keys self._copy_input_keys(parent_ud, self.userdata) ## Copy the datamodel's value into the userData for data in self._datamodel: if (self._datamodel[data] != ""): self.userdata[data] = self._datamodel[data] ## Do the <onentry> if (self._onEntry is not None): try: self._onEntry.execute(self.userdata) except Exception as ex: rospy.logerr('%s::onEntry::execute() raised | %s' % (self.__class__.__name__, str(ex))) return "preempt" # Spew some info smach.loginfo("Concurrence starting with userdata: \n\t%s" % (str(list(self.userdata.keys())))) # Call start callbacks self.call_start_cbs() # Create all the threads for (label, state) in ((k, self._states[k]) for k in self._states): # Initialize child outcomes self._child_outcomes[label] = None self._threads[label] = threading.Thread(name='concurrent_split:' + label, target=self._state_runner, args=(label, )) # Launch threads for thread in self._threads.values(): thread.start() # Wait for done notification self._done_cond.acquire() # Notify all threads ready to go self._ready_event.set() # Wait for a done notification from a thread self._done_cond.wait() self._done_cond.release() # Preempt any running states smach.logdebug("SMACH Concurrence preempting running states.") for label in self._states: if self._child_outcomes[label] == None: self._states[label].request_preempt() # Wait for all states to terminate while not smach.is_shutdown(): if all([not t.isAlive() for t in self._threads.values()]): break self._done_cond.acquire() self._done_cond.wait(0.1) self._done_cond.release() # Check for user code exception if self._user_code_exception: self._user_code_exception = False raise smach.InvalidStateError( "A concurrent state raised an exception during execution.") # Check for preempt if self.preempt_requested(): # initialized serviced flag children_preempts_serviced = True # Service this preempt if for (label, state) in ((k, self._states[k]) for k in self._states): if state.preempt_requested(): # Reset the flag children_preempts_serviced = False # Complain smach.logwarn( "State '%s' in concurrence did not service preempt." % label) # Recall the preempt if it hasn't been serviced state.recall_preempt() if children_preempts_serviced: smach.loginfo("Concurrence serviced preempt.") self.service_preempt() # Spew some debyg info smach.loginfo("Concurrent Outcomes: " + str(self._child_outcomes)) # Initialize the outcome outcome = self._default_outcome # Determine the outcome from the outcome map smach.logdebug( "SMACH Concurrence determining contained state outcomes.") for (container_outcome, outcomes) in ((k, self._outcome_map[k]) for k in self._outcome_map): if all([ self._child_outcomes[label] == outcomes[label] for label in outcomes ]): smach.logdebug( "Terminating concurrent split with mapped outcome.") outcome = container_outcome # Check outcome callback if self._outcome_cb: try: cb_outcome = self._outcome_cb(copy.copy(self._child_outcomes)) if cb_outcome: if cb_outcome == str(cb_outcome): outcome = cb_outcome else: smach.logerr( "Outcome callback returned a non-string '%s', using default outcome '%s'" % (str(cb_outcome), self._default_outcome)) else: smach.logwarn( "Outcome callback returned None, using outcome '%s'" % outcome) except: raise smach.InvalidUserCodeError( ("Could not execute outcome callback '%s': " % self._outcome_cb) + traceback.format_exc()) # Cleanup self._threads = {} self._child_outcomes = {} # Call termination callbacks self.call_termination_cbs(list(self._states.keys()), outcome) ## Do the <onexit> if (self._onExit is not None): try: outcome = self._onExit.execute(self.userdata, outcome) except Exception as ex: rospy.logerr('%s::onExit::execute() raised | %s' % (self.__class__.__name__, str(ex))) return "preempt" # Copy output keys self._copy_output_keys(self.userdata, parent_ud) return outcome
def _update_once(self): #print 'update' # Check if a preempt was requested before or while the last state was running if self.preempt_requested() or PreemptableState.preempt: #if self._preempted_state is not None: # if self._preempted_state.preempt_requested(): # self._preempt_current_state() # else: # self._preempt_requested = False # self._preempted_state = None #else: # self._preempt_current_state() return self._preempted_name #self._state_transitioning_lock.release() for state in self._ordered_states: if state.name in self._returned_outcomes.keys() and self._returned_outcomes[state.name] != self._loopback_name: continue if PriorityContainer.active_container is not None and not PriorityContainer.active_container.startswith(state._get_path()): if isinstance(state, EventState): state._notify_skipped() elif state._get_deep_state() is not None: state._get_deep_state()._notify_skipped() continue try: ud = smach.Remapper( self.userdata, state.get_registered_input_keys(), state.get_registered_output_keys(), self._remappings[state.name]) self._returned_outcomes[state.name] = state.execute(ud) #print 'execute %s --> %s' % (state.name, self._returned_outcomes[state.name]) except smach.InvalidUserCodeError as ex: smach.logerr("State '%s' failed to execute." % state.name) raise ex except: raise smach.InvalidUserCodeError("Could not execute state '%s' of type '%s': " % (state.name, state) + traceback.format_exc()) #self._state_transitioning_lock.acquire() # Determine outcome outcome = self._loopback_name for item in self._conditions: (oc, cond) = item if all(self._returned_outcomes.has_key(sn) and self._returned_outcomes[sn] == o for sn,o in cond): outcome = oc break # preempt (?) if outcome == self._loopback_name: return None if outcome in self.get_registered_outcomes(): # Call termination callbacks self.call_termination_cbs([s.name for s in self._ordered_states],outcome) self._returned_outcomes = dict() return outcome else: raise smach.InvalidTransitionError("Outcome '%s' of state '%s' with transition target '%s' is neither a registered state nor a registered container outcome." % (outcome, self.name, outcome))