Overview
Subscribers receive data from ROS2 topics. Use subscribers to process sensor data, react to commands, and monitor system state.Basic Subscriber Template
simple_subscriber.py
Practical Examples
1. Velocity Command Subscriber
cmd_vel_subscriber.py
2. LaserScan Subscriber (Obstacle Detection)
obstacle_detector.py
3. Multi-Subscriber Node
robot_monitor.py
Advanced: Subscriber with QoS
reliable_subscriber.py
Callback Best Practices
Keep Callbacks Fast
- Process data quickly in callback
- Don’t block for I/O operations
- Move heavy computation to separate thread
- Callbacks should return within milliseconds
Thread Safety
- Callbacks run in separate threads
- Use locks for shared data
- Or use class variables (atomic in Python)
- Avoid race conditions
Error Handling
- Wrap callbacks in try-except
- Validate message data
- Log errors, don’t crash
- Handle missing fields gracefully
Data Validation
- Check for NaN/inf values
- Verify array sizes match expected
- Validate timestamps
- Ignore stale data
Common Patterns
Message Synchronizer
Throttled Subscriber
Troubleshooting
Callback not called
Callback not called
Solutions:
- Verify topic exists:
- Check message type matches:
- Ensure publisher is running
- Check QoS compatibility
Old/stale data received
Old/stale data received
Solutions:
- Check timestamp in message header
- Increase queue_size if processing slowly
- Use BEST_EFFORT QoS for real-time data
- Filter based on age:
High CPU usage
High CPU usage
Cause: Callback processing too slowSolutions:
- Profile callback execution time
- Downsample data (every Nth message)
- Use throttled subscriber pattern
- Move computation to separate thread