📡Listening Ears

gayatri kumargayatri kumar
5 min read

🏙️ What's Happening in Robot Town?

So far, our robots have been shouting into the town square — WeatherBot has been broadcasting temperatures like a weather announcer on a rooftop.

But what's a town without listeners? It’s time to give our bots ears — so they can hear and react to messages from other bots.

This begins with a Subscriber.


🧠 ROS2 Analogy Recap

Real-World AnalogyRobot TownROS2 Concept
Public radio station/weatherTopic name
DJ broadcasting updatesWeatherBotPublisher node
Listener with a radioUmbrellaBotSubscriber node

🏗️ Project Overview

🎯 Goal:

Create a bot called UmbrellaBot in a new house (package) that listens to the /weather topic.
If it hears "Rainy" in the message, it opens an umbrella ☂️.

🔁 Flow:

  1. WeatherBot keeps publishing weather updates.

  2. UmbrellaBot listens in.

  3. If it hears "Rainy" → prints "🌧️ It's rainy! Opening umbrella!"


🏠 Step 1: Create the UmbrellaBot Package

Navigate to your workspace:

cd ~/robot_town_ws/src

Create the package:

ros2 pkg create umbrella_bot --build-type ament_python --dependencies rclpy std_msgs

Folder created:

umbrella_bot/
├── umbrella_bot/
│   └── __init__.py
├── package.xml
└── setup.py

🧱 Step 2: Write the Subscriber Node

Create the script file:

cd umbrella_bot/umbrella_bot
touch umbrella_listener.py
chmod +x umbrella_listener.py

Paste the code below into umbrella_listener.py:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class UmbrellaBot(Node):
    def __init__(self):
        # Initialize the node with the name 'umbrella_bot'
        super().__init__('umbrella_bot')

        # Create a subscription to listen to the '/weather' topic
        # Parameters explained:
        #   - String: the message type we expect to receive (std_msgs/String)
        #   - '/weather': the topic name to subscribe to
        #   - self.weather_callback: the function to call when a new message arrives
        #   - 10: the size of the incoming message queue (buffer size)
        self.subscription = self.create_subscription(
            String,
            '/weather',
            self.weather_callback,
            10
        )

        # Log that UmbrellaBot is ready and listening on the /weather topic
        # get_logger() returns the node's logger interface
        # info() logs an informational message to the console/output
        self.get_logger().info("☂️ UmbrellaBot is listening on /weather...")

    def weather_callback(self, msg):
        # This function is called whenever a new message arrives on the '/weather' topic
        # 'msg' is an instance of the String message type

        # Log the received message data to show what UmbrellaBot hears
        self.get_logger().info(f"📡 Heard: {msg.data}")

        # Check if the word 'Rainy' appears in the message data
        if 'Rainy' in msg.data:
            # If it does, log that UmbrellaBot is opening its umbrella
            self.get_logger().info("🌧️ It's rainy! Opening umbrella!")

def main(args=None):
    rclpy.init(args=args)
    node = UmbrellaBot()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

🧩 Step 3: Setup Entry Point

Open setup.py and add the executable in the entry_points section:

entry_points={
    'console_scripts': [
        'umbrella_listener = umbrella_bot.umbrella_listener:main',
    ],
},

Update package.xml and setup.cfg if needed like in previous bots.
Then go to the root of your workspace:

cd ~/robot_town_ws
colcon build

Source:

source install/setup.bash

🗂️ Current Folder Structure

robot_town_ws/
└── src/
    ├── mayor_bot/
    ├── door_bot/
    ├── chatter_bot/
    ├── weather_bot/       <-- Publishes weather reports
    └── umbrella_bot/      <-- Listens to weather and reacts!

🧪 Step 4: Time to Test! Running Both Bots Together

Open two terminals, and don’t forget to source your workspace in each:

source ~/robot_town_ws/install/setup.bash

🪄 Terminal 1: Launch WeatherBot (our Publisher)

ros2 run weather_bot weather_publisher

You should see:

🌤️ WeatherBot reporting: Sunny
🌤️ WeatherBot reporting: Rainy
🌤️ WeatherBot reporting: Cloudy

🎧 Terminal 2: Launch UmbrellaBot (our Subscriber)

ros2 run umbrella_bot umbrella_listener

Expected output:

☂️ UmbrellaBot is listening on /weather...
📡 Heard: Sunny
📡 Heard: Rainy
🌧️ It's rainy! Opening umbrella!
📡 Heard: Cloudy

💡 Congrats! The bots are now talking and reacting in real-time via the /weather topic!


🔍 What Just Happened?

Let’s break down what ROS2 is doing behind the scenes.

🧱 Nodes in Action

  • WeatherBot: Uses create_publisher() to broadcast weather reports.

  • UmbrellaBot: Uses create_subscription() to listen on the same topic.

  • ROS2 matches both bots on the /weather topic based on message type (std_msgs/String) and name.

If the types don’t match? 🚨 The bots won’t communicate.


🧰 Bonus Tools for Debugging

📻 See What’s Being Published

ros2 topic echo /weather

You’ll see a stream of weather messages printed to your terminal.

🔎 Topic Info

ros2 topic info /weather

Sample output:

Type: std_msgs/msg/String
Publisher count: 1
Subscription count: 1

Helpful to make sure your bots are properly connected!


🧠 ROS Concepts Reinforced

ConceptExampleMeaning
Topic/weatherA named channel for messages
PublisherWeatherBotSends messages on a topic
SubscriberUmbrellaBotListens for messages on a topic
Message Typestd_msgs/msg/StringStructure of data being exchanged
Entry Pointumbrella_listenerExposes the bot via ros2 run

🌦️ Mini Project Challenge: Weather-Reactive Town

Here’s a challenge for your town!

🔨 Build Your Own Weather-Reacting Bot:

  • SunBot that says "☀️ Great day for solar charging!" on sunny days

  • WindBot that spins a fan when it hears "Windy"

  • SnowBot that logs "❄️ Deploying snow tires"

Use the same /weather topic. Just react differently based on the message!

Each bot becomes smarter, more responsive, and more fun!


🏁 Recap: What We Achieved

✅ Built a ROS2 Subscriber
✅ Connected to an existing Publisher
✅ Reacted in real-time to messages
✅ Learned how nodes communicate using topics


🧭 What’s Next? Speak Clearly! ROS2 Messages Explained

Next up, we’ll dive into how bots in Robot Town craft and understand their messages.
Learn how messages are structured, where they come from, and how to create your own using .msg files!

✍️ Time to become the town’s linguist!


Let’s keep walking the cobblestone streets of Robot Town — one bot at a time 🤖🌧️📡

0
Subscribe to my newsletter

Read articles from gayatri kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

gayatri kumar
gayatri kumar