ROS2_pubsub/src/pubsub/pubsub/topic_listener.py

83 lines
2.6 KiB
Python
Raw Normal View History

2021-01-13 15:28:01 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#********************************************#
# Listener Template
# Creted for:
# ROS2 Workshop 2020
# Roverentwicklung für Explorationsaufgaben
# Institute for Space Systems
# University of Stuttgart
# Created by Patrick Winterhalder
# IRS, University of Stuttgart
#********************************************#
import rclpy
from rclpy.node import Node
# Import Subscriber Library
2023-03-25 16:33:56 +01:00
from pubsub.pubsub_library_v4 import MinimalSubscriber
2021-01-13 15:28:01 +01:00
# Import Message Types
2021-04-29 16:04:31 +02:00
from custom_interfaces.msg import CustomMsg1
from custom_interfaces.msg import CustomMsg2
2021-01-13 15:28:01 +01:00
def main(args=None):
rclpy.init(args=args)
# Start nodes here, should create object <node_name> for every node
2021-04-29 16:04:31 +02:00
listener_1 = MinimalSubscriber(NODE_NAME="pubsub_listener_1", TOPIC_NAME="/chatter1",MSG_TYPE=CustomMsg1, NUM_MSGS=0)
listener_2 = MinimalSubscriber(NODE_NAME="pubsub_listener_2", TOPIC_NAME="/chatter2",MSG_TYPE=CustomMsg2, NUM_MSGS=0)
2021-01-13 15:28:01 +01:00
2021-04-29 16:04:31 +02:00
# create empty variables of msg type (optional)
msg_1 = CustomMsg1()
msg_2 = CustomMsg2()
2021-01-13 15:28:01 +01:00
while rclpy.ok():
try:
# Insert main looping script here...
2021-04-29 16:04:31 +02:00
# Receive msgs by running nodes
2021-01-13 15:28:01 +01:00
rclpy.spin_once(listener_1, timeout_sec=0.01)
rclpy.spin_once(listener_2, timeout_sec=0.01)
2021-04-29 16:04:31 +02:00
# Check if msg received
2021-01-13 15:28:01 +01:00
if listener_1.topic_received is True:
2021-04-29 16:04:31 +02:00
listener_1.topic_received = False # gleich zurücksetzen
2021-01-13 15:28:01 +01:00
msg_1 = listener_1.return_msg()
#*********************************
# Do sth based on received message
2021-04-29 16:04:31 +02:00
print("/chatter1 received")
print(msg_1)
2021-01-13 15:28:01 +01:00
#*********************************
if listener_2.topic_received is True:
2021-04-29 16:04:31 +02:00
listener_2.topic_received = False # gleich zurücksetzen
2021-01-13 15:28:01 +01:00
msg_2 = listener_2.return_msg()
#*********************************
# Do sth based on received message
2021-04-29 16:04:31 +02:00
print("/chatter2 received")
print(msg_2)
2021-01-13 15:28:01 +01:00
#*********************************
# Here, you can now also publish/pass on the results of this script by
2021-04-29 16:04:31 +02:00
# using the "MinimalPublisher" class. For this please refer to "talker.py"
2021-01-13 15:28:01 +01:00
except (KeyboardInterrupt, SystemExit):
print("\n\nShutting down...")
# Insert "<node_name>.destroy_node()" here for all running nodes in this script
# eg:
listener_1.destroy_node()
listener_2.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()