Write a ROS 2 node
You need a little Python (what a function and a class are), and to have done ROS 2, hands on.
A node that listens
Section titled “A node that listens”This node prints the robot’s depth. In ~/avbotz/playground, create depth_watcher.py:
"""Print the vehicle's depth twice a second."""
import rclpyfrom nav_msgs.msg import Odometryfrom rclpy.executors import ExternalShutdownExceptionfrom rclpy.node import Node
class DepthWatcher(Node): def __init__(self): super().__init__("depth_watcher") self.latest_z = None self.create_subscription(Odometry, "/marlin_v3/odometry/filtered", self.on_odometry, 10) self.create_timer(0.5, self.print_depth)
def on_odometry(self, msg): self.latest_z = msg.pose.pose.position.z
def print_depth(self): if self.latest_z is None: self.get_logger().info("no odometry yet") else: self.get_logger().info(f"depth: {-self.latest_z:.2f} m")
def main(): rclpy.init() try: rclpy.spin(DepthWatcher()) except (KeyboardInterrupt, ExternalShutdownException): pass
if __name__ == "__main__": main()| Code | What it does |
|---|---|
import rclpy |
The ROS 2 library for Python |
from nav_msgs.msg import Odometry |
The message type of the topic. ros2 topic info tells you which one you need |
class DepthWatcher(Node) |
Our node, built on ROS 2’s Node class |
super().__init__("depth_watcher") |
Names the node, as ros2 node list shows it |
self.create_subscription(Odometry, ".../odometry/filtered", self.on_odometry, 10) |
“When a message arrives on this topic, call on_odometry.” The 10 is how many messages to queue if we fall behind |
self.create_timer(0.5, self.print_depth) |
“Call print_depth every 0.5 seconds” |
msg.pose.pose.position.z |
The same field you read with --field pose.pose.position.z |
-self.latest_z |
z is negative underwater, so we flip the sign to get depth |
rclpy.spin(...) |
Runs the node until you stop it: it waits for messages and timers, and calls your functions |
You never call on_odometry yourself: ROS 2 calls it whenever a message arrives. This is a callback.
Run it
Section titled “Run it”Start the simulator in one terminal, and wait for armed:
cd ~/avbotz/thalassicpixi run upRun your node in another, inside pixi shell so Python can find ROS 2:
cd ~/avbotz/thalassicpixi shellpython ~/avbotz/playground/depth_watcher.py[INFO] [1793586882.379677586] [depth_watcher]: depth: 0.13 m[INFO] [1793586882.879320704] [depth_watcher]: depth: 0.13 m[INFO] [1793586883.379378441] [depth_watcher]: depth: 0.13 mIn a third terminal (also cd ~/avbotz/thalassic, then pixi shell), make the robot dive and watch the number change:
ros2 topic pub --once /marlin_v3/motion_setpoint sub_control_interfaces/msg/MotionSetpoint '{mode: [0, 0, 1, 0, 0, 0], position: [0.0, 0.0, -1.0, 0.0, 0.0, 0.0]}'Press Ctrl-C in Terminal 2 to stop it.
A node that commands
Section titled “A node that commands”This node sends the robot to the other of two depths every 15 seconds. Create depth_bobber.py:
"""Every 15 seconds, send the vehicle to the other of two depths."""
import rclpyfrom rclpy.executors import ExternalShutdownExceptionfrom rclpy.node import Nodefrom sub_control_interfaces.msg import MotionSetpoint
SHALLOW_Z = -0.5DEEP_Z = -1.5
class DepthBobber(Node): def __init__(self): super().__init__("depth_bobber") self.publisher = self.create_publisher(MotionSetpoint, "/marlin_v3/motion_setpoint", 10) self.target_z = SHALLOW_Z self.create_timer(15.0, self.switch_target)
def switch_target(self): self.target_z = DEEP_Z if self.target_z == SHALLOW_Z else SHALLOW_Z
msg = MotionSetpoint() z = 2 # axes are [x, y, z, roll, pitch, yaw] msg.mode[z] = MotionSetpoint.POSITION msg.position[z] = self.target_z self.publisher.publish(msg) self.get_logger().info(f"new target: z = {self.target_z} m")
def main(): rclpy.init() try: rclpy.spin(DepthBobber()) except (KeyboardInterrupt, ExternalShutdownException): pass
if __name__ == "__main__": main()The new pieces:
| Code | What it does |
|---|---|
self.create_publisher(MotionSetpoint, ".../motion_setpoint", 10) |
Lets this node send messages on the topic |
msg = MotionSetpoint() |
A new, empty message. Every mode starts at 0, which means KEEP: leave this axis alone |
msg.mode[z] = MotionSetpoint.POSITION |
The named form of the 1 you typed by hand, defined in MotionSetpoint.msg |
self.publisher.publish(msg) |
Sends it |
Run it the same way, with depth_watcher beside it to watch the depth. After 15 seconds:
[INFO] [1793586899.569396041] [depth_bobber]: new target: z = -1.5 m[INFO] [1793586914.549367140] [depth_bobber]: new target: z = -0.5 mWhen you stop the node, the robot stays at its last target: sub_control holds the last target it was sent.
Exercises
Section titled “Exercises”- Print how far there is to go. Subscribe to
/marlin_v3/control/error. Its type isError, imported withfrom sub_control_interfaces.msg import Error, andmsg.pos_erroris a list of three numbers. Print the z error. - Combine them. Rather than waiting 15 seconds, have
depth_bobberswitch targets once the depth is within 5 cm of the target. You will need a subscription and a publisher in one node. - Swim a square. Rewrite your square mission as a Python node, and compare it with the XML.
How real nodes differ
Section titled “How real nodes differ”- They are in a package, so
ros2 runand launch files can find them. See howsrc/sub_vision/sub_vision/setup.pylists its node underconsole_scripts. - Topic names are relative. Real nodes use
odometry/filteredwith no/marlin_v3in front, and the launch file puts them in the right namespace. So the same code runs on a robot with any name. - They use the message’s timestamp to tell how old the data is, rather than assuming it just arrived. Safety explains why.
The official Python publisher and subscriber tutorial shows how to make a package from scratch.