Skip to content

BabyROS Publisher/Subscriber Tutorial

Goal: Create and run a Publisher and Subscriber node using Python.

Level: Beginner

Time: ~2 minutes

Background

In this tutorial, you will create two nodes that exchange information over a topic. One node publishes data (called a Publisher), and the other subscribes to that topic to receive messages (called a Subscriber).

We will use BabyROS to send simple dictionary messages representing sensor data, such as IMU readings.

1. Create a Publisher

Create a file named publisher_example.py:

python
"""
Zenoh Publisher Example
"""
import time
import babyros


if __name__ == "__main__":
    # The session is created automatically inside the Publisher
    imu_pub = babyros.node.Publisher(topic="imu")

    # Get list of topics in the session
    topics = babyros.get_topics_in_session()
    print("Active topics in current session:", topics)

    # Start publishing
    print("Starting sensor stream... (Press Ctrl+C to stop)")
    count = 0
    try:
        while True:
            data = {
                "acceleration": [0.1, 0.0, 9.8],
                "gyro": [0.0, 0.01, 0.0],
                "seq": [count]
            }
            
            imu_pub.publish(data=data)
            print(f"Sent seq: {count}")
            
            count += 1
            time.sleep(0.1)  # 10 Hz
            
    except KeyboardInterrupt:
        print("\n[Publisher] Interrupted by user.")
    finally:
        # CRITICAL: Close the Zenoh session gracefully
        imu_pub.delete()
        print("[Publisher] Cleanup complete.")

2. Create a Subscriber

Create a file named subscriber_example.py:

python
import time
import babyros

def log_imu(msg: dict):
    """
    Callback to print received IMU messages.
    """
    print(f"Received IMU data: Seq {msg['seq']} | Accel: {msg['acceleration']}")

if __name__ == "__main__":
    # Create a subscriber node for the "imu" topic
    sub = babyros.node.Subscriber(topic="imu", callback=log_imu)
    print("Subscriber created successfully!")

    try:
        while True:
            time.sleep(1)  # Keep script alive
    except KeyboardInterrupt:
        print("\n[Subscriber] Interrupted by user.")
    finally:
        sub.delete()  # Clean up resources
        print("Subscriber cleanup complete.")

3. Run the Nodes

  1. Open one terminal and run the publisher:
bash
python publisher_example.py

You should see messages being published every 0.1 seconds.

  1. Open a second terminal and run the subscriber:
bash
python subscriber_example.py

The subscriber will print each IMU message as it receives it.

INFO

Press Ctrl+C in both terminals to stop the nodes.

Summary

You have:

  • Created a Publisher node that sends dictionary messages over a topic.
  • Created a Subscriber node that receives and processes those messages.
  • Observed real-time messaging using BabyROS with minimal setup.

Next Steps

  • Experiment with different data types in your messages.
  • Add multiple Subscriber nodes to the same topic.
  • Integrate with real sensors or simulation data for robotics applications.