[ROS2] using dynamic parameters in Python
I want to use dynamic parameters in my ROS2 code. I defined a callback function, if a parameter is changed with following line:
self.add_on_set_parameters_callback(self.cb_params)
I wrote a little example to test it:
import rclpy
from rclpy.node import Node
from rclpy.exceptions import ParameterNotDeclaredException
class MinimalParam(Node):
def __init__(self):
super().__init__('minimal_param_node')
timer_period = 2 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.declare_parameter("name", "world")
self.add_on_set_parameters_callback(self.cb_params)
self.name = self.get_parameter("name").get_parameter_value().string_value
def cb_params(self, data):
self.get_logger().warn("parameter changed...")
self.successful = True
self.name = self.get_parameter("name").get_parameter_value().string_value
return self
def timer_callback(self):
self.get_logger().info('Hello %s!' % self.name)
def main():
rclpy.init()
node = MinimalParam()
rclpy.spin(node)
if __name__ == '__main__':
main()
I changed the parameter over the ros2 command in a terminal with:
ros2 param set /minimal_param_node name "earth"
With the log message I can see that the callback is working, but the parameter is not changed the first time. When I call the ros2 command again, the parameter changed to the value set before.
FYI: The line:
self.successful = True
return self
is needed, because without them the code is crashing with an Error:
AttributeError: 'NoneType' object has no attribute 'successful'
I'm working with Foxy on Ubuntu 20.04 . Unfortunately I could not find any documentation/tutorial on this. What did i wrong?