Sample Solution for Day 2 Coding

Exercises Writeup

Use this link to find the day 2 exercises.

test_message (non object-oriented)

Source: test_message_orig.py

#!/usr/bin/env python3

from geometry_msgs.msg import PointStamped, Point
from std_msgs.msg import Header
import rospy

rospy.init_node("test_node")
pub = rospy.Publisher('/my_point', PointStamped, queue_size=10)

r = rospy.Rate(2)
while not rospy.is_shutdown():
    my_header = Header(stamp=rospy.Time.now(), frame_id="base_link")
    my_point = Point(x=1.0, y=2.0)
    m = PointStamped(header=my_header, point=my_point)
    pub.publish(m)
    r.sleep()

receive_message (non object-oriented)

Source: receive_message_orig.py

#!/usr/bin/env python3

import rospy
from geometry_msgs.msg import PointStamped

def process_point(m):
    print(m)

rospy.init_node('receive_message_node')
rospy.Subscriber('/my_point', PointStamped, process_point)

rospy.spin()

test_message (object-oriented)

Source: test_message.py

#!/usr/bin/env python3

from geometry_msgs.msg import PointStamped, Point
from std_msgs.msg import Header
import rospy

class TestMessageNode(object):
    """ This node publishes a message at 2 Hz """
    def __init__(self):
        rospy.init_node("test_node")
        self.pub = rospy.Publisher('/my_point', PointStamped, queue_size=10)

    def run(self):
        r = rospy.Rate(2)
        while not rospy.is_shutdown():
            my_header = Header(stamp=rospy.Time.now(), frame_id="base_link")
            my_point = Point(x=1.0, y=2.0)
            m = PointStamped(header=my_header, point=my_point)
            self.pub.publish(m)
            r.sleep()

if __name__ == '__main__':
    node = TestMessageNode()
    node.run()

receive_message (object-oriented)

Source: receive_message.py

#!/usr/bin/env python3

import rospy
from geometry_msgs.msg import PointStamped

class ReceiveMessageNode(object):
    def __init__(self):
        rospy.init_node('receive_message_node')
        rospy.Subscriber('/my_point', PointStamped, self.process_point)

    def process_point(self, m):
        print(m)

    def run(self):
        rospy.spin()

if __name__ == '__main__':
    node = ReceiveMessageNode()
    node.run()