What is the correct way to structure a service server class

For my solution, I use two methods:

laser_callback()

This method just updates some distance-related stuff every time it is called.

and a second method

service_callback(self, request, response)
    while self.wall_found == false:
        do stuff
    return response

It works just fine, but I am wondering if it is the best design as the loop just cycles as fast as possible wasting CPU cycles for several seconds until the robot reaches its final position.

Is there a preferred method using timers so the loop only runs at a certain frequency?

I guess I could sleep for .1 seconds every loop to slow things down. but that doesn’t feel very elegant :frowning:

What do you mean by saying

as the loop just cycles as fast as possible

In ROS 1 you can do it all without a timer callback, I don’t think there is a preferred method as long as it accomplishes the task.

Why do you need to slow things down? I don’t think the CPU usage would even be noticeable for a simple service server, so maybe if there’s a strange behavior in the robot, it’s due to something else?

If you want to control the node spin frequency, you can use rospy.Rate(), even in your server callback I believe.

Hello @davef ,

As @roalgoal indicates, you should use rospy.Rate() for this. You can check this post for reference: How the rospy.sleep and how the rospy.Rate() works

1 Like

Thanks,
I had forgotten about rate. At first, I was just looping, then I just tried sleep(0.1) at the bottom of each loop. Rate makes much more sense.

Another interesting thing I came across was ‘spinonce’. At the top of each loop I ran spinonce which appears to interrupt the current loop and allows every other callback in the node to run long enough to clear its queue of messages.

I could have used executors and callback groups, but spinonce seems cleaner for such a simple program.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.