Reputation: 105
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()
Upvotes: 1
Views: 3459
Reputation: 5036
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()
Upvotes: 1