ROS 2 & Robot Software Architecture (Fundamentals) · Lesson 07
Actions — Long-Running Robot Tasks
Est. 50–70 min
Why
Why this lesson matters
Think of ordering a pizza. You place the order (the goal), and the restaurant can accept or refuse it. While you wait, the app shows “baking… out for delivery… 2 km away” (the feedback). At the end you get the pizza, or a message saying what went wrong (the result). And until it leaves the shop you can cancel. A ROS 2 action works the same way.
By the end of this lesson you will be able to: explain goal, feedback and result; know when the docs say to use an action instead of a service; read a .action file; write an action server that rejects bad goals, sends feedback and holds safely on cancel; write a client that shows feedback and can cancel; and use ros2 action list -t, type, info and send_goal --feedback.

Concept
How an action works
The official definition
The Jazzy docs describe actions as being for long-running remote procedure calls with feedback and the ability to cancel or pre-empt the goal. The Understanding actions tutorial adds that actions are built on topics and services: goal and result work like services, and feedback works like a topic.
| Rule from the docs | What it means for our arm |
|---|---|
| Actions are for long-running tasks with feedback | Moving a joint for 2–5 s, homing, calibrating |
| A goal can be cancelled or pre-empted | Stop the move when someone enters the cell |
| There should be one server per action name | One move_joint server per arm namespace |
| There can be many clients | Planner, dashboard and terminal can all send goals |
| Actions carry extra overhead | For a short yes/no job, a service (Lesson 6) is simpler |
The .action file: goal --- result --- feedback
A .action file has three parts separated by ---: the goal, then the result, then the feedback. Ours lives in the arm_interfaces package from Lesson 5:
# MoveJoint.action - add to arm_interfaces/action/ and list it in rosidl_generate_interfaces
# Goal
float64 target_deg
float64 duration_s
---
# Result
float64 final_deg
bool success
string message
---
# Feedback
float64 current_deg
float64 progress # 0.0 .. 1.0Server and client in rclpy
- Server:
ActionServer(node, MoveJoint, 'move_joint', execute_callback, goal_callback=…, cancel_callback=…). The goal callback can reject a goal; the execute callback callsgoal_handle.publish_feedback(...), thengoal_handle.succeed()orcanceled()and returns a Result. - Cancelling safely: inside the loop, check
goal_handle.is_cancel_requested. Our server then holds the current angle rather than snapping somewhere. - Executor: like the rclpy
minimal_action_serverexample, we use aReentrantCallbackGroupandMultiThreadedExecutorso cancel requests can be handled while the goal runs. - Client:
ActionClient(node, MoveJoint, 'move_joint'),wait_for_server, thensend_goal_async(goal, feedback_callback=…); when accepted,get_result_async(); to stop,cancel_goal_async().
Visual
Visualise it: goal, feedback, result and cancel
Send an action goal, watch feedback arrive, and cancel it — then compare with a service.
Interactive · Service / action explorer
ROS 2 communication simulator — educational only (not a live ROS 2 runtime)
Service /set_mode · type example_interfaces/srv/SetBool (conceptual)
- No calls yet — send a request.
Code lab
Code lab: a toy action, then a real server and client
action_sim.py (plain Python, no ROS needed) shows a normal goal with feedback, a goal the server refuses, a cancel half-way that holds position, and the same move as a service versus an action. Run python3 action_sim.py.
"""action_sim.py - goal / feedback / result / cancel in plain Python (no ROS 2 needed).
Models the ROS 2 Jazzy "Actions" concept page: a long-running remote procedure call
with FEEDBACK and the ability to CANCEL. The server can REJECT a goal it cannot do.
The motion uses the cubic time-scaling from Stage 9: s(t) = 3(t/T)^2 - 2(t/T)^3.
Teaching model only - not the real ROS 2 action protocol.
"""
LIMITS = (10.0, 170.0)
def cubic(t, T):
r = min(max(t / T, 0.0), 1.0)
return 3 * r * r - 2 * r ** 3
def run_goal(start, target, T, cancel_at=None, rate_hz=10):
print(f" goal: move {start:.0f} -> {target:.0f} deg in {T:.1f} s")
if not (LIMITS[0] <= target <= LIMITS[1]):
print(f" REJECTED: target outside {LIMITS} deg")
return start, "REJECTED"
if T <= 0:
print(" REJECTED: duration must be > 0")
return start, "REJECTED"
print(" ACCEPTED")
pos = start
steps = int(T * rate_hz)
for k in range(1, steps + 1):
t = k / rate_hz
if cancel_at is not None and t > cancel_at:
print(f" cancel requested at t={cancel_at:.1f} s -> stop and HOLD at {pos:.1f} deg")
return pos, "CANCELED"
pos = start + (target - start) * cubic(t, T)
if k % (rate_hz // 2) == 0: # feedback twice a second
print(f" feedback t={t:.1f}s current={pos:6.1f} deg progress={100 * t / T:5.1f} %")
return pos, "SUCCEEDED"
print("Part 1: normal goal with feedback")
pos, status = run_goal(30, 120, 2.0)
print(f" result: final={pos:.1f} deg status={status}\n")
print("Part 2: goal the server must refuse")
pos2, status = run_goal(pos, 185, 2.0)
print(f" result: status={status}, arm stays at {pos2:.1f}\n")
print("Part 3: cancel half-way (someone walks into the cell)")
pos3, status = run_goal(pos, 40, 3.0, cancel_at=1.2)
print(f" result: final={pos3:.1f} deg status={status}\n")
print("Part 4: same 3 s move as a SERVICE vs an ACTION")
print(" service: client waits 3.0 s, sees nothing, cannot cancel, gets one reply")
print(" action : client sees 6 feedback messages, can cancel any time, gets a result + status")Output (run with python3 action_sim.py)
Part 1: normal goal with feedback
goal: move 30 -> 120 deg in 2.0 s
ACCEPTED
feedback t=0.5s current= 44.1 deg progress= 25.0 %
feedback t=1.0s current= 75.0 deg progress= 50.0 %
feedback t=1.5s current= 105.9 deg progress= 75.0 %
feedback t=2.0s current= 120.0 deg progress=100.0 %
result: final=120.0 deg status=SUCCEEDED
Part 2: goal the server must refuse
goal: move 120 -> 185 deg in 2.0 s
REJECTED: target outside (10.0, 170.0) deg
result: status=REJECTED, arm stays at 120.0
Part 3: cancel half-way (someone walks into the cell)
goal: move 120 -> 40 deg in 3.0 s
ACCEPTED
feedback t=0.5s current= 114.1 deg progress= 16.7 %
feedback t=1.0s current= 99.3 deg progress= 33.3 %
cancel requested at t=1.2 s -> stop and HOLD at 91.8 deg
result: final=91.8 deg status=CANCELED
Part 4: same 3 s move as a SERVICE vs an ACTION
service: client waits 3.0 s, sees nothing, cannot cancel, gets one reply
action : client sees 6 feedback messages, can cancel any time, gets a result + statusTry it: send an action goal, watch the feedback, and cancel it half-way.
Interactive · Service / action explorer
ROS 2 communication simulator — educational only (not a live ROS 2 runtime)
Service /set_mode · type example_interfaces/srv/SetBool (conceptual)
- No calls yet — send a request.
The server: move_joint_server.py
A real rclpy action server for ROS 2 Jazzy, following the official minimal_action_server pattern. It rejects targets outside 10–170°, moves with a cubic profile at 50 Hz, publishes feedback, and holds on cancel. With port set it sends P<deg> to the Arduino; otherwise it simulates.
"""move_joint_server.py - rclpy (ROS 2 Jazzy) ACTION SERVER for one joint.
Action: move_joint (arm_interfaces/action/MoveJoint - see MoveJoint.action)
goal_callback rejects targets outside the safe window or bad durations
execute_callback moves with the Stage 9 cubic s(t) at 50 Hz, publishes feedback,
checks for cancel every step (on cancel: HOLD where it is)
Structure follows the official rclpy minimal_action_server example (ReentrantCallbackGroup
+ MultiThreadedExecutor, so cancel requests are handled while a goal is running).
python3 move_joint_server.py --ros-args -r __ns:=/arm1 # simulated
python3 move_joint_server.py --ros-args -r __ns:=/arm1 -p port:=/dev/ttyACM0 # servo_position.ino
"""
import time
import rclpy
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from arm_interfaces.action import MoveJoint
MIN_DEG, MAX_DEG = 10.0, 170.0
RATE_HZ = 50.0
class MoveJointServer(Node):
def __init__(self):
super().__init__('move_joint_server')
self.declare_parameter('port', '')
self.declare_parameter('start_deg', 90.0)
port = self.get_parameter('port').value
self.serial = None
if port:
import serial # pyserial
self.serial = serial.Serial(port, 115200, timeout=0.05)
self.pos = float(self.get_parameter('start_deg').value)
self.busy = False
self._server = ActionServer(
self, MoveJoint, 'move_joint',
execute_callback=self.execute,
callback_group=ReentrantCallbackGroup(),
goal_callback=self.on_goal,
cancel_callback=self.on_cancel)
def on_goal(self, goal):
if self.busy:
self.get_logger().warn('rejecting goal: already moving')
return GoalResponse.REJECT
if not (MIN_DEG <= goal.target_deg <= MAX_DEG) or goal.duration_s <= 0.0:
self.get_logger().warn(f'rejecting goal {goal.target_deg:.1f} deg / {goal.duration_s:.2f} s')
return GoalResponse.REJECT
return GoalResponse.ACCEPT
def on_cancel(self, goal_handle):
self.get_logger().info('cancel requested - will hold position')
return CancelResponse.ACCEPT
def send(self, deg):
self.pos = deg
if self.serial is not None:
self.serial.write(f'P{deg:.1f}\n'.encode())
def execute(self, goal_handle):
self.busy = True
start, target = self.pos, goal_handle.request.target_deg
T = goal_handle.request.duration_s
fb = MoveJoint.Feedback()
result = MoveJoint.Result()
t0 = time.monotonic()
try:
while True:
if goal_handle.is_cancel_requested:
goal_handle.canceled()
result.final_deg, result.success, result.message = self.pos, False, 'canceled, holding'
return result
r = min((time.monotonic() - t0) / T, 1.0)
self.send(start + (target - start) * (3 * r * r - 2 * r ** 3))
fb.current_deg, fb.progress = self.pos, r
goal_handle.publish_feedback(fb)
if r >= 1.0:
break
time.sleep(1.0 / RATE_HZ)
goal_handle.succeed()
result.final_deg, result.success, result.message = self.pos, True, 'reached'
return result
finally:
self.busy = False
def main():
rclpy.init()
node = MoveJointServer()
try:
rclpy.spin(node, executor=MultiThreadedExecutor())
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()The client: move_joint_client.py
"""move_joint_client.py - rclpy (ROS 2 Jazzy) ACTION CLIENT for move_joint.
python3 move_joint_client.py 120 2.0 --ros-args -r __ns:=/arm1 # target 120 deg in 2 s
python3 move_joint_client.py 40 3.0 1.2 --ros-args -r __ns:=/arm1 # ...and cancel after 1.2 s
Prints every feedback message, then the result and final status.
"""
import sys
import rclpy
from action_msgs.msg import GoalStatus
from rclpy.action import ActionClient
from rclpy.node import Node
from rclpy.utilities import remove_ros_args
from arm_interfaces.action import MoveJoint
def main():
rclpy.init(args=sys.argv)
args = remove_ros_args(sys.argv)[1:]
target = float(args[0]) if args else 120.0
duration = float(args[1]) if len(args) > 1 else 2.0
cancel_after = float(args[2]) if len(args) > 2 else None
node = Node('move_joint_client')
client = ActionClient(node, MoveJoint, 'move_joint')
try:
if not client.wait_for_server(timeout_sec=5.0):
node.get_logger().error('move_joint server not available')
return
goal = MoveJoint.Goal(target_deg=target, duration_s=duration)
fb = lambda msg: node.get_logger().info(
f'feedback: {msg.feedback.current_deg:6.1f} deg, {100 * msg.feedback.progress:5.1f} %')
send_future = client.send_goal_async(goal, feedback_callback=fb)
rclpy.spin_until_future_complete(node, send_future)
handle = send_future.result()
if not handle.accepted:
node.get_logger().warn('goal REJECTED by server')
return
if cancel_after is not None:
node.create_timer(cancel_after, lambda: handle.cancel_goal_async())
result_future = handle.get_result_async()
rclpy.spin_until_future_complete(node, result_future)
res = result_future.result()
names = {GoalStatus.STATUS_SUCCEEDED: 'SUCCEEDED', GoalStatus.STATUS_CANCELED: 'CANCELED',
GoalStatus.STATUS_ABORTED: 'ABORTED'}
node.get_logger().info(f'result: {res.result.final_deg:.1f} deg, "{res.result.message}", '
f'status {names.get(res.status, res.status)}')
finally:
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()python3 move_joint_server.py --ros-args -r __ns:=/arm1
ros2 action list -t # names with [types]
ros2 action type /arm1/move_joint
ros2 action info /arm1/move_joint # clients and servers
ros2 interface show arm_interfaces/action/MoveJoint
ros2 action send_goal /arm1/move_joint arm_interfaces/action/MoveJoint "{target_deg: 120.0, duration_s: 2.0}" --feedback
# target 120 deg, 3 s move, cancel after 1.2 s
python3 move_joint_client.py 120 3 1.2 --ros-args -r __ns:=/arm1Before writing your own, try the tutorial’s turtlesim action /turtle1/rotate_absolute (turtlesim/action/RotateAbsolute): goal theta, result delta, feedback remaining.
Real world
Actions in the real world
- turtlesim (official tutorial):
rotate_absoluteturns the turtle to an angle and reports the remaining angle as feedback. - Robot arms: “move to pose” and “follow this trajectory” are long jobs with progress and cancel — natural actions.
- Mobile robots: “drive to that point” takes minutes, reports distance left and must be cancellable.
- Planetary rovers: with long delays, rovers are given goals and work through them on their own, reporting progress back.

Bench build
Bench build: one joint moved by an action
One hobby servo stands in for a joint. The action server does the smooth motion and sends many small P<deg> steps; the Arduino just clamps each angle to 10–170° and moves the servo.
| From | To | Note |
|---|---|---|
| Servo signal | Arduino D9 | Signal only |
| Servo + (red) | Separate 5–6 V supply + | Not the Arduino 5V pin or any GPIO |
| Servo − (brown/black) | Supply − | — |
| Supply − | Arduino GND | Common ground |
| Arduino USB | ROS 2 computer | 115200 baud |
// servo_position.ino - one servo follows position commands "P<deg>" (e.g. P93.5) at up to ~50 Hz.
// Used by move_joint_server.py, which does the smooth cubic profile on the computer.
// Clamps to 10..170 deg and uses writeMicroseconds for finer steps than whole degrees.
// With no new commands the servo simply holds its last position.
// POWER: servo red (+) to a SEPARATE 5-6 V supply, never the Arduino 5V pin or a GPIO. Join grounds.
#include <Servo.h>
const int SERVO_PIN = 9;
const float MIN_DEG = 10.0, MAX_DEG = 170.0;
Servo joint;
char buf[16];
byte n = 0;
int degToUs(float d) { return (int)(544.0 + (2400.0 - 544.0) * d / 180.0); } // Servo library default range
void setup() {
Serial.begin(115200);
joint.attach(SERVO_PIN);
joint.writeMicroseconds(degToUs(90.0));
}
void loop() {
while (Serial.available()) {
char c = Serial.read();
if (c == '\n') {
buf[n] = 0;
if (n > 1 && buf[0] == 'P') {
float d = atof(buf + 1);
if (d < MIN_DEG) d = MIN_DEG;
if (d > MAX_DEG) d = MAX_DEG;
joint.writeMicroseconds(degToUs(d));
}
n = 0;
} else if (n < sizeof(buf) - 1) {
buf[n++] = c;
}
}
}Test without the arm
With the horn free, send
P90,P30,P150from Serial Monitor. Then close Serial Monitor.Start the server
python3 move_joint_server.py --ros-args -r __ns:=/arm1 -p port:=/dev/ttyACM0Send a goal
Use
ros2 action send_goal … --feedbackand watch the feedback match the servo.Cancel it
Run the client with a cancel time. The servo should stop and stay where it is.

Debugging
Debugging actions
| Symptom | Likely cause | Fix |
|---|---|---|
| “server not available” | Server not running or in another namespace | ros2 action list -t and compare full names |
| Cancel only works after the move ends | Single-threaded executor blocked by the loop | MultiThreadedExecutor + ReentrantCallbackGroup; check is_cancel_requested |
| No feedback appears | Forgot --feedback, or no feedback_callback | Add them; call publish_feedback in the loop |
| Goal rejected | Target outside the limits | Read the log message; send a safe target |
send_goal fails to parse | Wrong type name or YAML | Copy the type from ros2 action type |
| Servo jerks or resets the board | Servo powered from the board | Separate supply, common ground |
Think
Think about it
Think
A goal is running and a new goal arrives for the same joint. Should the server reject the new goal, queue it, or cancel the old one and start the new one? Which is safest for a robot arm, and why?
Experiment
Try it in the lab
About 40 minutes with Python; the ROS 2 and bench steps need ROS 2 Jazzy, the arm_interfaces package and the servo build.
Experiment
Goal, feedback, result — and cancel
You will need
- `action_sim.py` and Python 3
- Service/action explorer (in your browser)
- Optional: ROS 2 Jazzy, `move_joint_server.py`, `move_joint_client.py`, Arduino UNO, hobby servo, separate 5–6 V supply
Steps
- Run `action_sim.py`. Change Part 3’s cancel time to 0.3 s and 2.8 s. Where does the arm hold each time?
- Change the safe range in the simulator to 20–160° and send 15°. What happens?
- With ROS 2: run turtlesim and send a `rotate_absolute` goal with `--feedback`.
- With ROS 2: start `move_joint_server.py` and send a goal from the terminal, then from the client with a cancel time.
- With ROS 2: run `ros2 action info /arm1/move_joint` while the client is running.
- Bench: repeat with the servo. Check the servo stops when cancelled.
Interactive · Service / action explorer
ROS 2 communication simulator — educational only (not a live ROS 2 runtime)
Service /set_mode · type example_interfaces/srv/SetBool (conceptual)
- No calls yet — send a request.
An action lets the caller see progress and stop the job. The server decides what “stop” means — for an arm, holding still is the safe answer.
Knowledge check
Check your understanding
Knowledge check
1. A ROS 2 action is best for…
2. What are the three parts of a `.action` file, in order?
3. Actions are built on…
4. A goal asks for 185° on a joint limited to 10–170°. The server should…
5. Why does our server use a MultiThreadedExecutor?
6. Which terminal command shows feedback while sending a goal?
7. Is cancelling an action an emergency stop?
Mini assignment
Hands-on assignment
Mini assignment
Action plan for your 6DOF arm
Find the long jobs in your arm, design their actions, and prove one works with feedback and cancel.
Deliverables
- A table of 3–5 actions: full name in `/arm1`, goal, result and feedback fields, expected duration, and what cancel should do.
- Output of `action_sim.py` after your experiment changes.
- Optional (ROS 2): `ros2 action list -t`, `ros2 action info` and a `send_goal --feedback` run.
- Optional (bench): a short video of the servo moving, then stopping on cancel.
Do this, step by step
- Run
python3 action_sim.pyand try cancel times of 0.3 s and 2.8 s; write where the arm holds each time. - Make a table of 3–5 actions for your arm: name, goal, result, feedback, duration and what cancel does.
- Change the safe range to 20–160° and send 15°; note whether the goal is rejected or aborted.
- Optional with ROS 2: start
move_joint_server.py, send a goal with--feedback, then cancel from the client. - Optional bench: confirm the servo really stops on cancel (keep the motor-supply switch in reach).
Stuck? Hints, one at a time
- A goal outside the safe range should be rejected before it starts, not aborted halfway.
- On cancel, the server should stop and hold where it is — not jump back to the start.
- Feedback is for progress (e.g. current angle); the result is the final answer sent once.
Challenges (pick by level)
- 🟢 Easy: Send turtlesim
rotate_absolutegoals and cancel one from the terminal with Ctrl+C. - 🟡 Medium: Add a
max_speed_dpscheck to the goal callback that rejects moves that are too fast. - 🟠 Hard-ish: Make the server pre-empt: a new goal stops the old one smoothly and starts from the current angle.
- 🔴 Hard: Extend
MoveJointto two joints and send both angles to the Arduino. - ⚫ Research: Read the rclpy
minimal_action_serverexamples and compare the single-goal and queue-goals versions.
Next step
You now know all three ways nodes talk. In Lesson 8 — Packages & Workspace you will put the nodes and interfaces into proper ROS 2 packages and build them with colcon.
Look back: Lesson 6: Services — Request/Response. Next: Lesson 8: ROS 2 Packages & Workspace. Related: Stage 9 — Trajectory Planning.
Sources
- ROS 2 Jazzy docs — Actions — long-running RPC with feedback, cancel/pre-empt, one server per name, overhead.
- ROS 2 Jazzy docs — Understanding actions (tutorial) — goal/feedback/result, built on topics and services,
ros2 action list -t/type/info/send_goal --feedback, turtlesim RotateAbsolute. - ROS 2 Jazzy docs — Writing an action server and client (Python) —
ActionServer,publish_feedback,succeed,send_goal_async,get_result_async. - ros2/examples (jazzy) — rclpy minimal_action_server — goal/cancel callbacks, ReentrantCallbackGroup, MultiThreadedExecutor.
- example_interfaces Fibonacci.action (jazzy) — the goal/result/feedback layout.
- Arduino Servo library —
attach,writeMicroseconds. - Docs text read from the official docs source ros2/ros2_documentation (jazzy branch).
- Photos: Wikimedia Commons (credits under each image).
Self-attested for now — keep artifacts in your lab notebook.
Complete
Today's goal
0 of 1 done today
Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).