I have made a node to run some calculations using data from another topic (odom in this case) and publish them to another topic. How do I set the rate of this node to be slower than the subscribed topic?
Here is what I have but I can't get it to work:
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
import traceback
from std_msgs.msg import Float64MultiArray
from nav_msgs.msg import Odometry
class CalculatedNode(Node):
def __init__(self):
super().__init__('calculated_node')
# Create publisher
self.calculated_node = self.create_publisher(Float64MultiArray, '/calculated_stuff', 10)
# Subscribe to node
self.subscription = self.create_subscription(
Odometry,
'/odom',
self.update_calculations,
1)
def update_calculations(self, msg):
try:
# DO SOME CALCULATIONS WITH MSG DATA
# [...]
# Publish Odom
self.calculated_node.publish(Float64MultiArray())
except Exception as e:
traceback.print_exc()
print(self.get_clock().now())
# print(e)
def main(args=None):
rclpy.init(args=args)
calculated_node = CalculatedNode()
try:
rate = calculated_node.create_rate(2)
rclpy.spin(calculated_node)
while rclpy.ok:
rate.sleep()
except KeyboardInterrupt:
pass
calculated_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
This was simpler than I though. Here is an example using the chatter tutorial:
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.msg_store = None
self.subscription = self.create_subscription(
String,
'topic',
self.listener_callback,
1)
self.subscription # prevent unused variable warning
self.create_timer(2, self.timed_call)
def listener_callback(self, msg):
self.msg_store = msg
def timed_call(self):
self.get_logger().info('I heard: "%s"' % self.msg_store.data)
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = MinimalSubscriber()
rclpy.spin(minimal_subscriber)
minimal_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
This however has an issue. The timed callback "timed_call" gets called every other trigger event. This is the output:
[INFO] [1683201706.818698434] [minimal_subscriber]: I heard: "Hello World: 6"
[INFO] [1683201708.805167207] [minimal_subscriber]: I heard: "Hello World: 10"
[INFO] [1683201710.804572917] [minimal_subscriber]: I heard: "Hello World: 14"
[INFO] [1683201712.804249021] [minimal_subscriber]: I heard: "Hello World: 18"