Module API


A mock robot and tutorials for py_trees on ROS2.


Behaviours for the tutorials.

class py_trees_ros_tutorials.behaviours.FlashLedStrip(name, topic_name='/led_strip/command', colour='red')[source]

Bases: py_trees.behaviour.Behaviour

This behaviour simply shoots a command off to the LEDStrip to flash a certain colour and returns RUNNING. Note that this behaviour will never return with SUCCESS but will send a clearing command to the LEDStrip if it is cancelled or interrupted by a higher priority behaviour.

  • /led_strip/command (std_msgs.msg.String)
    • colourised string command for the led strip [‘red’, ‘green’, ‘blue’]
  • name (str) – name of the behaviour
  • topic_name (str) – name of the battery state topic
  • colour (str) – colour to flash [‘red’, ‘green’, blue’]

Setup the publisher which will stream commands to the mock robot.

Parameters:**kwargs (dict) – look for the ‘node’ object being passed down from the tree
Raises:KeyError – if a ros2 node isn’t passed under the key ‘node’ in kwargs

Shoot off a clearing command to the led strip.

Parameters:new_status (Status) – the behaviour is transitioning to this new status

Annoy the led strip to keep firing every time it ticks over (the led strip will clear itself if no command is forthcoming within a certain period of time). This behaviour will only finish if it is terminated or priority interrupted from above.

Return type:Status
Returns:Always returns RUNNING
class py_trees_ros_tutorials.behaviours.ScanContext(name)[source]

Bases: py_trees.behaviour.Behaviour

Alludes to switching the context of the runtime system for a scanning action. Technically, it reaches out to the mock robots safety sensor dynamic parameter, switches it off in initialise() and maintains that for the the duration of the context before returning it to it’s original value in terminate().

Parameters:name (str) – name of the behaviour

Reset the cached context and trigger the chain of get/set parameter calls involved in changing the context.


Completing the chain of service calls here (with rclpy.spin_until_future_complete(node, future)) is not possible if this behaviour is encapsulated inside, e.g. a tree tick activated by a ros2 timer callback, since it is already part of a scheduled job in a spinning node. It will just deadlock.

Prefer instead to chain a sequence of events that will be completed over a span of ticks instead of at best, blocking here and at worst, falling into deadlock.


Setup the ros2 communications infrastructure.

Parameters:**kwargs (dict) – look for the ‘node’ object being passed down from the tree
Raises:KeyError – if a ros2 node isn’t passed under the key ‘node’ in kwargs

Reset the parameters back to their original (cached) values.

Parameters:new_status (Status) – the behaviour is transitioning to this new status

Complete the chain of calls begun in initialise() and then maintain the context (i.e. py_trees.behaviour.Behaviour and return RUNNING).

Return type:Status


A mocked robot for use in the tutorials.


Action servers and clients

class py_trees_ros_tutorials.mock.actions.DockClient[source]

Bases: py_trees_ros_tutorials.mock.actions.GenericClient

A mock docking controller client.

class py_trees_ros_tutorials.mock.actions.GenericClient(node_name, action_name, action_type, generate_feedback_message=None)[source]

Bases: object

Generic action client that can be used to test the mock action servers.

  • node_name (str) – name to use when creating the node for this process
  • action_name (str) – the action namespace under which topics and services exist (e.g. move_base)
  • action_type (Any) – the action type (e.g. move_base_msgs.msg.MoveBaseAction)
  • generate_feedback_message (Optional[Callable[[Any], str]]) – format the feedback message

Cancel response callback

Parameters:future (<sphinx.ext.autodoc.importer._MockObject object at 0x7f2f04e52780>) – details returning from the server about the cancel request

Prints the feedback on the node’s logger.

Parameters:msg (Any) – the feedback message, particular to the action type definition

Finally, at the end of the pipeline, what was the result!?

Parameters:future (<sphinx.ext.autodoc.importer._MockObject object at 0x7f2f04e52668>) – details returning from the server about the goal result

Handle goal response, proceed to listen for the result if accepted.

Parameters:future (<sphinx.ext.autodoc.importer._MockObject object at 0x7f2f04e52080>) – details returning from the server about the goal request

Start the cancel request, chain it to cancel_response_callback().


Send the goal and get a future back, but don’t do any spinning here to await the future result. Chain it to goal_response_callback().

Returns:the future awaits…
Return type:rclpy.task.Future

Middleware communications setup. This uses a hard coded default of 2.0 seconds to wait for discovery of the action server. If it should fail, it raises a timed out error.


Shutdown, cleanup.


Common spin method for clients.

Parameters:cancel (bool) – send a cancel request shortly after sending the goal request
class py_trees_ros_tutorials.mock.actions.MoveBaseClient[source]

Bases: py_trees_ros_tutorials.mock.actions.GenericClient

A mock move base client.

class py_trees_ros_tutorials.mock.actions.RotateClient[source]

Bases: py_trees_ros_tutorials.mock.actions.GenericClient

A mock rotation controller client.


Spin up a docking client and manage it from init to shutdown. Some customisation possible via the command line arguments.


Spin up a move base client and manage it from init to shutdown.


Spin up a rotation client and manage it from init to shutdown.


Mock the state of a battery component.

class py_trees_ros_tutorials.mock.battery.Battery[source]

Bases: object

Mocks the processed battery state for a robot (/battery/sensor_state).

Node Name:
  • battery
  • ~state (sensor_msgs.msg.BatteryState)
    • full battery state information
Dynamic Parameters:
  • ~charging_percentage (float)
    • one-shot setter of the current battery percentage
  • ~charging (bool)
    • charging or discharging
  • ~charging_increment (float)
    • the current charging/discharging increment

On startup it is in a DISCHARGING state and updates every 200ms. Use the dashboard to dynamically reconfigure parameters.


Cleanup ROS components.


Timer callback that processes the battery state update and publishes.


Entry point for the mock batttery node.


Mocks a docking controller

class py_trees_ros_tutorials.mock.dock.Dock(duration=2.0)[source]

Bases: sphinx.ext.autodoc.importer._MockObject

Simple action server that docks/undocks depending on the instructions in the goal requests.

Node Name:
  • docking_controller
Action Servers:
  • /dock (py_trees_ros_interfaces.action.Dock)
    • docking/undocking control
Parameters:duration (float) – mocked duration of a successful docking/undocking action

Create a feedback message that populates the percent completed.

Returns:the populated feedback message
Return type:py_trees_actions.Dock_Feedback

Set the title of the action depending on whether a docking or undocking action was requestions (‘Dock’/’UnDock’)


Entry point for the mocked docking controller.


Launch the mock robot.


Launch the mock robot (i.e. launch all mocked components).

Return type:<sphinx.ext.autodoc.importer._MockObject object at 0x7f2f04e5e5c0>
Returns:the launch description

Generate an action node for launch.

Return type:List[<sphinx.ext.autodoc.importer._MockObject object at 0x7f2f04e5e080>]
Returns:a list of the mock robot ros nodes as actions for launch


Mock a hardware LED strip.

class py_trees_ros_tutorials.mock.led_strip.LEDStrip[source]

Bases: object

Emulates command/display of an led strip so that it flashes various colours.

Node Name:
  • led_strip
  • ~display (std_msgs.msg.String)
    • colourised string display of the current led strip state
  • ~command (std_msgs.msg.String)
    • send it a colour to express, it will flash this for the next 3 seconds

If the notification identified by the given uuid is still relevant (i.e. new command requests haven’t come in) then publish an update with an empty display message.

Parameters:this_uuid (UUID) – the uuid of the notification to cancel

If the requested state is different from the existing state, update and restart a periodic timer to affect the flashing effect.

Parameters:msg (std_msgs.msg.String) – incoming command message

Generate a formatted string representation of the the current state of the led strip.

Parameters:colour (bool) – use shell escape sequences for colour, matching the specified text colour label
Return type:str

Cleanup ROS components.


Entry point for the mock led strip.


Mocks a simple action server that rotates the robot 360 degrees.

class py_trees_ros_tutorials.mock.move_base.MoveBase(duration=None)[source]

Bases: sphinx.ext.autodoc.importer._MockObject

Simulates a move base style interface.

Node Name:
  • move_base_controller
Action Servers:
  • /move_base (py_trees_ros_interfaces.action.MoveBase)
    • point to point move base action
Parameters:duration – mocked duration of a successful action

Do a fake pose incremenet and populate the feedback message.

Returns:the populated feedback message
Return type:py_trees_actions.MoveBase.Feedback

Entry point for the mock move base node.


Mocks a simple action server that rotates the robot 360 degrees.

class py_trees_ros_tutorials.mock.rotate.Rotate(rotation_rate=1.57)[source]

Bases: sphinx.ext.autodoc.importer._MockObject

Simple server that controls a full rotation of the robot.

Node Name:
  • rotation_controller
Action Servers:
  • /rotate (py_trees_ros_interfaces.action.Dock)
    • motion primitives - rotation server
Parameters:rotation_rate (float) – rate of rotation (rad/s)

Create a feedback message that populates the percent completed.

Returns:the populated feedback message
Return type:py_trees_actions.Rotate.Feedback

Entry point for the mock rotation controller node.


Mocks a battery provider.

class py_trees_ros_tutorials.mock.safety_sensors.SafetySensors[source]

Bases: object

Mocks the ability to enable/disable a safety sensor processing pipeline. This emulates a component which needs to be enabled contextually so that cpu resources can be efficiently optimised or to resolve contextual conflicts in the usage of the sensors.

Node Name:
  • safety_sensors
Dynamic Parameters:
  • ~enable (bool)
    • enable/disable the safety sensor pipeline (default: False)

Use the dashboard to dynamically reconfigure the parameters.


Cleanup ROS components.


Entry point for the mock safety sensors node.


Version number accessible to users of the package.