ros_sugar.core.routine#

Routine: an ordered sequence of monitored steps with a published cursor

Module Contents#

Classes#

RoutineStatus

Routine lifecycle status.

Routine

An ordered sequence of Action steps, run to completion or to a failure.

API#

class ros_sugar.core.routine.RoutineStatus#

Bases: ros_sugar.config.StrEnum

Routine lifecycle status.

Published on the cursor topic and readable through the host’s get_routine_state.

is_terminal() → bool#

Whether the routine reach an “end” lifecycle status and cannot transition further

Return type:

bool

classmethod get_enum(__value: str) → Optional[ros_sugar.config.robot.T]#

Get Enum member equal to the given value

Parameters:

__value (str) – Reference value

Returns:

Enum member

Return type:

StrEnum | None

classmethod values() → List[str]#

Get all enum values

capitalize()#

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()#

Return a version of the string suitable for caseless comparisons.

center()#

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()#

S.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode()#

Encode the string using the codec registered for encoding.

encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()#

S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs()#

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()#

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format()#

S.format(*args, **kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map()#

S.format_map(mapping) -> str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()#

S.index(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()#

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()#

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()#

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()#

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()#

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()#

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()#

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()#

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()#

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()#

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()#

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()#

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join()#

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust()#

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()#

Return a copy of the string converted to lowercase.

lstrip()#

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition()#

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix()#

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix()#

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace()#

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()#

S.rfind(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex()#

S.rindex(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust()#

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition()#

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit()#

Return a list of the substrings in the string, using sep as the separator string.

sep The separator used to split the string.

When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.

maxsplit Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip()#

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split()#

Return a list of the substrings in the string, using sep as the separator string.

sep The separator used to split the string.

When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.

maxsplit Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines()#

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()#

S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip()#

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()#

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()#

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate()#

Replace each character in the string using the given translation table.

table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via getitem, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()#

Return a copy of the string converted to uppercase.

zfill()#

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

name()#

The name of the Enum member.

value()#

The value of the Enum member.

class ros_sugar.core.routine.Routine(name: str, steps: List[Union[ros_sugar.core.action.Action, ros_sugar.core.action.ActionServerGoal, Callable]], on_complete: Optional[Union[ros_sugar.core.action.Action, ros_sugar.core.action.ActionServerGoal, Callable]] = None, on_abort: Optional[Union[ros_sugar.core.action.Action, ros_sugar.core.action.ActionServerGoal, Callable]] = None, on_pause: Optional[Union[ros_sugar.core.action.Action, ros_sugar.core.action.ActionServerGoal, Callable, Sequence[Union[ros_sugar.core.action.Action, ros_sugar.core.action.ActionServerGoal, Callable]]]] = None, description: Optional[str] = None)#

An ordered sequence of Action steps, run to completion or to a failure.

A Routine is a procedure that can be declared in a Recipe implicitly or added at runtime through the ‘Monitor’: ‘detect, then pre-grasp, then close, then lift’. A routine gives each step its own success test and retry policy, and publishes where it has got to.

A step is an ordinary Action. The success, timeout and max_retries attributes decide whether a step worked; on_fail and fallback, which only a routine reads, decide what the sequence does when it did not.

pick = Routine(
    "pick_object",
    steps=[
        Action(perception.detect_object,
               success=perception_out.msg.object_found.is_true(),
               timeout=5.0),
        Action(arm.move_to_pregrasp,
               success=arm_state.msg.at_pregrasp.is_true(),
               timeout=10.0, cancel_method=arm.stop),
        Action(gripper.close, name="grasp",
               success=gripper_state.msg.closed.is_true(),
               timeout=3.0, max_retries=2,
               on_fail="fallback", fallback=gripper.reopen),
        Action(arm.lift, success=arm_state.msg.at_lift.is_true()),
    ],
    on_abort=safety.open_gripper_and_home,
)
launcher.on(pick_requested, pick)

Triggering: launcher.on(pick_requested, pick), as with any action.

A routine reports that it started, not that it succeeded. Steps are driven by callbacks rather than by a parked thread, so triggering one returns as soon as the first step is dispatched. The outcome arrives later, through on_complete / on_abort and the published cursor.

Pausing preempts the step in flight, and on_pause makes that safe. Preempting a step only stops what the step itself runs, not what it set in motion: on_pause is where a routine undoes that, such as stopping a robot a navigation step had driving. Resuming re-enters the step, once the on_pause actions are done.

Parameters:
  • name – Routine name, used in the cursor and its topic

  • steps – Ordered steps. Each is an Action or a plain callable, and they must end up with unique names

  • on_complete – Action run when the last step succeeds

  • on_abort – Action run when the routine fails or is aborted

  • on_pause – Action, or actions run in order, when the routine is paused. One that fails is logged and the next one still runs

  • description – What the routine is for, in plain words, for whoever lists the routines available and has to choose one: an operator, or an LLM planning with them

classmethod from_spec(spec: Dict, resolve: Callable[[Dict], ros_sugar.core.action.Action]) → ros_sugar.core.routine.Routine#

Build a routine from a plain dictionary, as sent over a service.

Only the shape is checked here. Turning a step into something callable needs a registry and clients, so that is the host’s job (Monitor) and arrives as resolve.

Routine.from_spec(
    {"name": "mission", "steps": [{"ref": "planner/main_action"}]},
    monitor._action_from_spec,
)
Parameters:
  • spec – {name, steps, on_complete, on_abort, on_pause, description}, where each step is whatever resolve understands, and on_pause is one of them or a list

  • resolve – Turns one step dictionary into an Action

Raises:

ValueError – If the spec names no routine or carries no steps

Return type:

Routine

set_host(host) → None#

Register the host node to the routine, and every action it runs.

Parameters:

host – A node exposing add_runtime_event_listener

set_state_publisher(publish: Optional[Callable[[str], None]]) → None#

Install the callable used to publish the cursor.

Injected by the host rather than created here, so the driver itself has no ROS dependency and can be tested without a node.

Parameters:

publish – Called with the cursor as a JSON string

actions() → List[ros_sugar.core.action.Action]#

Every action this routine can run: its steps, their fallbacks and its terminal actions.

What a host has to reach to register, verify or tear down a routine: anything in here can be dispatched, so all of it has to be accounted for, not only the steps.

Return type:

List[Action]

stop_watching() → None#

Stop monitoring the success conditions of every action of the routine.

Called when the routine is removed, so the conditions of a routine that is gone are not evaluated on every message of their topics.

get_required_topics() → List[ros_sugar.io.Topic]#

Topics needed by the routine, which is every topic its steps need.

Reported up so that the host subscribes to all of them, and the steps can resolve their topic arguments whenever they are reached.

Return type:

List[Topic]

property state: Dict#

Current lifecycle state of the routine

Return type:

Dict

property latest_step_messages: Dict[str, str]#

What each step that finished in this run returned, by step name.

A step its fallback stood in for holds the fallback’s message, where step_messages has both. A step that was preempted, by a pause or an abort, has not finished and is not here. Cleared when the routine starts.

Return type:

Dict[str, str]

step_messages(index: Optional[int] = None) → Union[List[Dict], Dict]#

Every step that finished in this run, in the order it finished.

Each entry is {"step", "succeeded", "message", "fallback"}, where fallback marks the result of the step’s fallback rather than of the step itself. Cleared when the routine starts.

Parameters:

index – Only this entry, counting from the end when negative

Raises:

IndexError – If there is no entry at index

Return type:

Union[List[Dict], Dict]

pause(**_) → ros_sugar.utils.ActionReturnType#

Stop at the current step without ending the routine.

The step in flight is preempted, then the on_pause actions run, and resume() runs the step again from the start: a step is the smallest thing a routine can be positioned at.

Return type:

ActionReturnType

resume(**_) → ros_sugar.utils.ActionReturnType#

Re-enter the step the routine was paused at.

While the on_pause actions are still running the resume waits for them, rather than starting the step again alongside what is undoing it

Return type:

ActionReturnType

abort(reason: str = 'aborted by request', run_on_abort: bool = True, **_) → ros_sugar.utils.ActionReturnType#

End the routine now, preempting whatever it is running and running on_abort

Parameters:
  • reason – Recorded in the cursor as abort_reason, and logged

  • run_on_abort – Dispatch the on_abort action. A host tearing the routine down passes False: an action dispatched into a node that is going away cannot report back, and would outlive the node it calls

Return type:

ActionReturnType

halt_in_flight() → None#

Preempt whatever the routine has running right now.

That is the step, the fallback recovering it, an on_pause action or a terminal action: every one of them is dispatched the same way and can outlive the routine, so every one of them has to be stoppable. Used by pause and abort, and by a host taking the routine down.