ROS2雖然從RTPS網路結構改成了DDS。但實際的訊息傳輸還是由發佈以及訂閱構成。唯一的差別大概在於,ROS2大量使用物件導向式的寫法。 我們來看一個簡單的推送範例: ```python import rclpy from rclpy.node import Node from std_msgs.msg import String class Ex3_pub(Node): def __init__(self): super().__init__('Ex3_pub') # 定義節點包含一個發送端 self.publisher_ = self.create_publisher(String, 'chatter', 10) self.timer = self.create_timer(1, self.timer_callback) def timer_callback(self): msg = String() # 由於是物件導向,訊息也是字串物件裡面的一個屬性 msg.data = 'Hello World' # 呼叫發送端發送訊息 self.publisher_.publish(msg) if __name__ == '__main__': rclpy.init() ex3_publisher = Ex3_pub() rclpy.spin(ex3_publisher) ex3_publisher.destroy_node() rclpy.shutdown() ``` 這個範例中,我們持續對chatter這個頻道發送hello world 訊息。 我們可以使用ros2 topic list去查看是否新增了一個chatter頻道,並用ros2 topic echo /chatter指令去監聽頻道,確認發送狀況。 這些步驟其實和ROS1相去不遠,實際上從1改到2並不會花上太多工夫--唯一需要克服的物件導向,若是程式設計人員也不是什麼障礙。 有了發送節點,接著我們要來設計接收節點了。 承接上半部,我們來看一個簡單的接收範例: ```python import rclpy from rclpy.node import Node from std_msgs.msg import String class Ex3_sub(Node): def __init__(self): super().__init__('Ex3_sub') self.subscription = self.create_subscription (String,"chatter",self.listener_callback,10) self.subscription #prevent unused variable warning def listener_callback(self, msg): self.get_logger().info('I heard: "%s"' % msg.data) if __name__ == '__main__': rclpy.init() ex3_subscriber = Ex3_sub() rclpy.spin(ex3_subscriber) ex3_subscriber.destroy_node() rclpy.shutdown() ``` 若你沒有關閉[[4.發佈與訂閱(上)_ROS2]]中的節點,此時執行這段程式碼,應該會開始看到印出"hello world"字串了。 ROS1.0中,還是以函式的方式呼叫,因此使用rospy.spin()指令維持函式的執行。而ROS2.0也差不多,只差在必須把要維持的物件傳遞給他而已。 而接收的資料會在msg.data中,因應接收資料做出相應的反應,相信各位比我更擅長,這邊就不多做處理了。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up