1

I have a service that echoes an integer (out of a convoluted array package) in a permanent loop. This loop would constantly print different statuses like this:

1 (new assignment)
1
1
1
3 (success)
3
3
1 (new assignment)
1
1
1
1
4 (failure)
4
4
1 (new assignment)
1
1
3 (success)

With python, I want to print a message once when the integer changes (such as those in the parentheses), I've been unlucky in finding a suitable solution so far. The main issue is that the callback function (that prints those integers for me) gets called every second or so, which would result in the update messages being printed every time one of the conditions are met.

The code is as following, the rospy class creates the loop that will keep on triggering the callback:

def callback(data):
    status = data.status_list[0].status
    if status == 1:
        print("new assignment")
    if status == 3:
        print("success")
    if status == 4:
        print("failure")

rospy.init_node('listener', anonymous=True)
rospy.Subscriber("move_base/status", GoalStatusArray, callback)
rospy.spin()
2
  • 3
    Add your code where you're iterating. Commented Mar 7, 2019 at 12:08
  • Can you not wrap that in a descriptor and have the descriptor call the function when it's assigned a new value? Commented Mar 7, 2019 at 12:18

1 Answer 1

1

You need to keep track of the previous value so you can compare it with the current one and print it if they're different. Something like this:

 class StatusChecker(object):
    def __init__(self):
        self.previous = None

    def callback(self, data):
        status = data.status_list[0].status
        if status != self.previous:
            if status == 1:
                print("new assignment")
            elif status == 3:
                print("success")
            elif status == 4:
                print("failure")
            # Remember this value so we can see if it changes
            self.previous = status

   checker = StatusChecker()
   rospy.init_node('listener', anonymous=True)
   rospy.Subscriber("move_base/status", GoalStatusArray, checker.callback)
   rospy.spin()
Sign up to request clarification or add additional context in comments.

1 Comment

I've performed a few tests with this snippet and it did exactly as told and expected. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.