Wait for timer to stop in action callback

asked 2022-03-04 04:54:23 -0600

dannee gravatar image

Hey,

I want to send control inputs to a robot from an action callback at 15 ms interval. I thought that creating a timer within the action callback would be a good solution to send the feedback at a constant time interval. This works, however, when the timer is started the action callback returns immediately without waiting for the timer stop.

I would like a good way of waiting until the timer is complete before returning from the action callback. A naive approach would be to have a while loop that waits for the completion of the timer, but I'm wondering if there is a better way. Below is an example of what want to do but without the naive while loop.

import timer
from functools import partial
import rclpy
from rclpy.node import Node

class MyNode(Node):

def __init__(self, *args, **kwargs):
    super().__init__('my_node', *args, **kwargs)
    self.action_done = False
    self._action_server = ActionServer(
        self,
        MyAction, 
        'my_node/action',
        self.action_cb,
    )

def action_cb(self, goal_handle):
    self.timer = self.create_timer(
        0.015, 
        partial(self.bf_timer_cb, goal_handle=goal_handle)
    )

    #wait until timer has stopped, the naive way
    while self.action_done is False:
        time.sleep(0.1)

    return MyAction.Result()

def timer_cb(self, goal_handle):
    #Do some calculation here

    #Send control commands as feedback to the reobot
    feedback_msg = MyAction.Feedback()
    goal_handle.publish_feedback(feedback_msg)

    if condition:#When the robot has reached its goal
        self.action_done = True 
        self.timer.stop()
        goal_handle.succeed()
edit retag flag offensive close merge delete