当前位置:网站首页>2、 Topic communication principle, code implementation
2、 Topic communication principle, code implementation
2022-07-26 17:53:00 【Rock magnon】
List of articles
1、 Communication principle

The whole communication process is divided into six steps ,0-4 Step adoption RPC agreement ,5-6 Step adoption TCP agreement . Besides , The first step and the second step are in no order , But because of talker Registration takes time , The subscriber may not receive the first few messages , It can be solved by setting the delay .
0、talker register
talker adopt RPC Agreement to master Register node information :
- Topic name :bar
- RPC Address :1234
1、listener register
listener adopt RPC Agreement to master Register your own information :
- Topic name to subscribe to :bar
2、ROS Master Realize information matching
ROS Master Match the information according to the registry , And pass RPC Agreement to listener send out talker Of RPC Address
3、Listener towards Talker Send a connection request
listener according to master Provided RPC Address , towards talker Send a connection request :
- Subscribed topic name
- Message type
- Communication protocol (TCP/UDP)
4、Talker Confirm the request
talker After receiving the connection request, connect , adopt RPC Agreement to listener Confirm connection :
- TCP Address
5、 Establishing a connection
listener According to the fourth No TCP Address establishment connection , here , If ROS Master close , The two can still establish a connection
6、Talker towards Listener Send a message
2、 Code implementation
1、C++ edition
- Create a workspace and compile
mkdir -p workspace/src // Create a workspace cd workspace // Enter the workspace catkin_make // compile , Generate devel and build Folder - establish ROS Package and add dependencies
cd src catkin_creat_pkg Function package name roscpp rospy std_msgs - C++ The source code to achieve
//1. Include header file #include "ros/ros.h" #include "std_msgs/String.h"// Used to define the type of transmission information #include <sstream> int main(int argc, char *argv[]){ setlocale(LC_ALL,"");// Prevent confusion code //2. Node initialization // The first two parameters are used to pass information , Which of the following is the node name , stay rqt_graph Unique identification ros::init(argc,argv,"talker"); //3. Create node handle ros::NodeHandle nh; //4. Create a publishing object // The first parameter is the published topic , The second parameter is the maximum number of messages saved , When it exceeds , The earliest messages will be deleted ros::Publisher pub = nh.advertise<std_msgs::String>("chatter",10); //5. Organize published data std_msgs::String msg;// Create data to publish std::string msg_front = "hello Hello! !"; int count = 0; ros::Rate r(1);// Set the data publishing rate while(ros::ok()){ std::stringstream ss; ss << msg_front << count; msg.data = ss.str(); pub.publish(msg);// Release the news ROS_INFO(" Message sent :%s",msg.data.c_str()); r.sleep(); count++; ros::spinOnce(); } return 0; }//1. Include header file #include "ros/ros.h" #include "std_msgs/String.h" void doMsg(const std_msgs::String::ConstPtr&msg_p){ ROS_INFO(" I hear :%s",msg_p->data.c_str()); } int main(int argc, char *argv[]){ setlocale(LC_ALL,""); //2. Initialize node ros::init(argc,argv,"listener"); //3. establish ROS Handle ros::NodeHandle nh; //4. Instantiate the subscription object , Including topic name , The length of the message , Callback function ros::Subscriber sub = nh.subscribe<std_msgs::String>("chatter",10,doMsg); //5. Process subscribed messages //6. Set loop call callback function ros::spin(); return 0; } - Configure the file and compile
add_executable(Hello_pub src/Hello_pub.cpp ) add_executable(Hello_sub src/Hello_sub.cpp ) target_link_libraries(Hello_pub ${ catkin_LIBRARIES} ) target_link_libraries(Hello_sub ${ catkin_LIBRARIES} ) - Compile and run
cd working space catkin_make roscore cd working space source ./devel/setup.bash rosrun Package name The node name
2、Python edition
- establish sripts Folder
- Code implementation
#! /usr/bin/env python #1. Guide pack import rospy from std_msgs.msg import String # Packages that define data types if __name__ == "__main__": #2. initialization ROS node rospy.init_node("talker_p")# Unique node name , Otherwise, an error will be reported #3. Instantiate the publisher object pub = rospy.Publisher("chatter_p",String,queue_size=10) #4. Organize the release of data msg = String() msg_font = "hello python" count = 0 # Set the cycle frequency rate = rospy.Rate(10) while not rospy.is_shutdown(): msg.data = msg_font + str(count) pub.publish(msg) rate.sleep() rospy.loginfo("data:%s",msg.data) count += 1#! /usr/bin/env python #1. Guide pack import rospy from std_msgs.msg import String def doMsg(msg): rospy.loginfo(" I hear :%s",msg.data) if __name__ == "__main__": #2. initialization ROS node rospy.init_node("listener_p") #3. Instantiate subscribers sub = rospy.Subscriber("chatter",String,doMsg,queue_size=10) #4. Process subscribed messages #5. Set loop call callback function rospy.spin() - To configure Cmakelists.txt file
catkin_install_python(PROGRAMS scripts/talker_p.py scripts/listener_p.py DESTINATION ${ CATKIN_PACKAGE_BIN_DESTINATION} ) - Run code
cd working space catkin_make roscore source devel/setup.bash rosrun Package name .py
边栏推荐
- [day3] reconstruction of roads
- 图的遍历的定义以及深度优先搜索和广度优先搜索(一)
- 来吧开发者!不只为了 20 万奖金,试试用最好的“积木”来一场头脑风暴吧!
- [training day3] delete
- Deep learning experiment: softmax realizes handwritten digit recognition
- 兆骑科创海外高层次人才引进平台,创业赛事活动路演
- JS 闭包 模拟私有变量 面试题 立即执行函数IIFE
- Brief introduction to CUDA image construction
- [template] segment tree 1
- 浅析接口测试
猜你喜欢

Asemi rectifier bridge kbpc3510, kbpc3510 package, kbpc3510 application
![[virtual machine data recovery] data recovery cases in which XenServer virtual machine is unavailable due to accidental power failure and virtual disk files are lost](/img/99/e5404a09ec7f52a7c5d7be23e43e85.jpg)
[virtual machine data recovery] data recovery cases in which XenServer virtual machine is unavailable due to accidental power failure and virtual disk files are lost
![[300 opencv routines] 240. Shi Tomas corner detection in opencv](/img/3a/0b81fb06e91e681ccc928e67297188.png)
[300 opencv routines] 240. Shi Tomas corner detection in opencv

hosts该文件已设置为只读的解决方法
![[Oumi reading club] talk about the creator economy in the meta universe: infinite dimension](/img/60/17cb0295f81dc580cc3ff8543ec253.png)
[Oumi reading club] talk about the creator economy in the meta universe: infinite dimension

AI zhetianchuan ml integrated learning

硬件开发与市场产业

SQL中去去重的三种方式

Tianyi cloud web application firewall (edge cloud version) supports the detection and interception of Apache spark shell command injection vulnerabilities

(25)Blender源码分析之顶层菜单Blender菜单
随机推荐
Use replace regexp to add a sequence number at the beginning of a line
[machine learning] principle and code of mean shift
跨站点请求伪造(CSRF)
kudu设计-tablet
Hardware development and market industry
JS recursive Fibonacci sequence deep cloning
2.1.2 同步始终失败
Leetcode:1206. design jump table [jump table board]
Kudu design tablet
Gan (generative adversarial network, GaN) generative countermeasure network
kaggle猫狗数据集开源——用于经典CNN分类实战
跨站脚本攻击(XSS)
Spark数据格式UnsafeRow
中国聚异丁烯市场研究与投资价值报告(2022版)
我们被一个 kong 的性能 bug 折腾了一个通宵
【元宇宙欧米说】剖析 Web3 风险挑战,构筑 Web3 生态安全
VS Code 格式化后 自动让函数名后有空格
国际象棋机器人夹断7岁男孩手指,原因是「棋手违反安全规则」?
Spark统一内存划分
[training Day1] Dwaves line up