当前位置:网站首页>Advanced ROS communication mechanism
Advanced ROS communication mechanism
2022-07-19 01:08:00 【2021 Nqq】
List of articles
API: Application programming interface
Commonly used API(C++ edition )
1. initialization
ros::init(argc,argv,“erGouZi”,ros::init_options::AnonymousName)
effect : ROS Initialization function
Parameters :
1. argc ----- Number of encapsulated arguments (n+1) The first 1 One is the file itself
2. argv ----- Encapsulate parameter array ( Array of strings )
3. name ----- Name the node ( Uniqueness )
4. options -- Node startup options
Return value :void
Use details :
1. argc And argv Use
If according to ROS Pass in arguments in a specific format in , that ROS It can be used , For example, it is used to set global parameters , Rename the node
2. options Use
The node name needs to be unique , It can lead to a problem : The same node cannot be started repeatedly
problem :ROS When the node with the same name in starts , The previous node will be shut down
demand : Under specific scenarios , A node needs to be started many times and can operate normally , What do I do ?
( scene : Such as installation 2 Nodes for cameras )
solve : Set boot entry ros::init_options::AnonymousName
When creating a ROS Node time , The user-defined node name will be suffixed with a random number , So as to avoid the problem of duplicate names
2. Topics and service related objects
ros::Publisher pub = nh.advertise<std_msgs::String>(“fang”,10,true)
effect : Create publisher object
Templates : The type of message being published
Parameters :
1. Topic name
2. The queue length
3. latch( Optional ) If set to true, The last message of the publisher will be saved , also
When a new subscription object connects to the publisher , The publisher will send the message to the subscriber
Use :
latch Set to true The role of ?
Take the static map as an example ,
programme 1: Map data can be sent using a fixed frequency , But low efficiency
programme 2: You can publish maps to objects latch Set to true, And the publisher only releases the data once , Whenever subscribers connect ,
Map data can be sent to subscribers ( Send only once ), Improve the efficiency of data transmission .
3. Cyclotron function
ros::spin() && ros::spinOnce
- The same thing : Both are used to handle callback functions
- Difference :ros::spin() Is to enter the loop and execute the callback function , and ros::spinOnce() The callback function will only be executed once ( No cycle ), stay ros::spin() The following statement will not execute to , and ros::spinOnce() The following statement can execute
4. Time
4.1 moment
Get time , Or set a specified time
C++ Code
#include"ros/ros.h"
/* demand : Demonstrate time related operations ( Get the current time + Set the setting time ) Realization : 1. Get ready ( The header file 、 Node initialization 、NodeHandle establish ) 2. Get the current time 3. Set the specified time */
int main(int argc, char *argv[])
{
// 1. Get ready ( The header file 、 Node initialization 、NodeHandle establish )
setlocale(LC_ALL,"");
ros::init(argc,argv,"hello_time");
ros::NodeHandle nh;// Be careful : must . Otherwise, it will lead to time API Call failed ( Again NodeHandle Will initialize the time operation )
// 2. Get the current time
// now The function encapsulates the current time and returns
// The current moment :now The moment it is called to execute
// Reference system :1970 year 1 month 1 Japan 00:00:00
ros::Time right_now = ros::Time::now();// Time away from the reference system
ROS_INFO(" The current moment :%.2f",right_now.toSec());// Calculate the total elapsed time in seconds ,dounle type
ROS_INFO(" The current moment :%d",right_now.sec);// Calculate the total elapsed time in seconds , Integer types
// 3. Set the specified time
ros::Time t1(20,312345678);// Constructors , It means distance from the reference system 20 second , as well as 312345678 nanosecond
ros::Time t2(100.35);// floating-point B
ROS_INFO("t1 = %.2f",t1.toSec());
ROS_INFO("t2 = %.2f",t2.toSec());
return 0;
}
Python Code
if __name__ == "__main__":
# demand 1: Demonstrate time related operations ( Get the current time + Set the specified time )
rospy.init_node("hello_time")
# Get time
right_now = rospy.Time.now() # Get the current time (1.now The moment the function is executed 2. Reference resources 1970 year 01 month 01 Japan 00:00) And encapsulate it as an object
rospy.loginfo(" The current moment :%.2f",right_now.to_sec()) # floating-point
rospy.loginfo(" The current moment :%.2f",right_now.secs) # integer secs There is no ()
# Set the specified
time1 = rospy.Time(100.5) # Encapsulate time into time object , take 1970 year 01 month 01 Japan 00:00 Pass away 100.5 second
time2 = rospy.Time(100,312345678) # Followed by nanoseconds , take 1970 year 01 month 01 Japan 00:00 Pass away 100.312345678 second
rospy.loginfo(" Designated time 1:%.2f",time1.to_sec()) # floating-point
rospy.loginfo(" Designated time 1:%.2f",time2.to_sec()) # floating-point
# Get a time object from a time value
time3 = rospy.Time.from_sec(210.12)
rospy.loginfo(" Designated time 1:%.2f",time3.to_sec()) # floating-point
4.2 The duration of the
C++ Realization
ROS_INFO("------------------ The duration of the --------------");
ros::Time start = ros::Time::now();
ROS_INFO(" Start sleeping : %.2f",start.toSec());
ros::Duration du(4.5); // Duration encapsulates 4.5 second
du.sleep();// sleep 4.5s
ros::Time end = ros::Time::now();
ROS_INFO(" End of sleep :%.2f",end.toSec());
pyhton Realization
# demand 2: Pause in program execution 5 second
rospy.loginfo(" Before dormancy -------------------")
# 1. Encapsulate a duration object (5 second )
du = rospy.Duration(5,0) # The second position is nanosecond
# 2. Then sleep the duration
rospy.sleep(du)
rospy.loginfo(" After hibernation -------------------")
4.3 Duration and operation
1. Time and duration can be added or subtracted
2. You can add or subtract between durations
3. Values can be subtracted between times , You can't add up
C++ Realization
// Time and duration operation
// 1. Get the moment when execution starts
ros::Time begin = ros::Time::now();
// 2. Simulation run time (N second )
ros::Duration du1(5);
// 3. Calculate the end time = Start + The duration of the
ros::Time stop = begin + du1; // It can also be used. -
ROS_INFO(" Starting time :%.2f",begin.toSec());
ROS_INFO(" End time :%.2f",stop.toSec());
// Time and time operation
// ros::Time sum = begin + stop; You can't add up
ros::Duration du2 = begin - stop;//-5
ROS_INFO(" Time subtracts :%.2f",du2.toSec());
// Operation of duration and duration
ros::Duration du3 = du1 + du2;// 0
ros::Duration du4 = du1 - du2;// 10
ROS_INFO("du1 + du2 = %.2f",du3.toSec());
ROS_INFO("du1 - du2 = %.2f",du4.toSec());
Python Realization
# demand 3: Get the restrictions on the start of program execution , And has been running for , Calculate the time when the program ends
# 1. Get a moment t1
t1 = rospy.Time.now()
# 2. Set a duration du1
du1 = rospy.Duration(5)
# 3. End time t2 = t1 + du1
t2 = t1 + du1
rospy.loginfo(" Starting time :%.2f",t1.to_sec())
rospy.loginfo(" End time :%.2f",t2.to_sec())
du2 = du + du1
rospy.loginfo(" Add the duration :%.2f",du2.to_sec())
4.4 Operating frequency and timer
Be careful :
establish : nh.createTimer()
Parameters 1: The time interval
Parameters 2: Callback function ( Time event TimerEvent)
Parameters 3: Whether to execute only 1 Time
Parameters 4: Auto start or not ( When setting false when , Manual call required timer.start())
When the timer starts : ros::spin()
/* ros::Timer createTimer(ros::Duration period, // The time interval --- 1 const ros::TimerCallback &callback, // Callback function --- Packaging business bool oneshot = false, // Is it 1 Secondary ,dalse Every 1 Execute in seconds 1 Sub callback function , Loop execution bool autostart = true) // Auto start */
// ros::Timer timer = nh.createTimer(ros::Duration(1),cb);// every other 1 Execute the callback function once per second
// ros::Timer timer = nh.createTimer(ros::Duration(1),cb,true);//true Execute the callback function only once
ros::Timer timer = nh.createTimer(ros::Duration(1),cb,false,false);//false It doesn't start automatically
timer.start();// Manual start
ros::spin();// Need to rotate
Timer Python Realization
def doMsg(event):
rospy.loginfo("+++++++++++++")
rospy.loginfo(" When the callback function is called :%.2f",event.current_real.to_sec()) # current_real yes rospy.Time type
# demand 4: Create timer , The implementation is similar to ros::Rate The function of ( Perform an operation at a certain time interval )
""" @param period: desired period between callbacks Call interval between callback functions @type period: rospy.Duration @param callback: callback to be called @type callback: function taking rospy.TimerEvent @param oneshot: if True, fire only once, otherwise fire continuously until shutdown is called [default: False] @type oneshot: bool """
# timer = rospy.Timer(rospy.Duration(2),doMsg,True) # Create a timer object , Every 2 Execute a callback every second
timer = rospy.Timer(rospy.Duration(2),doMsg) # Create a timer object , Every 2 Execute a callback every second
rospy.spin()
4.5 General procedure
C++ Realization
#include"ros/ros.h"
/* demand 1: Demonstrate time related operations ( Get the current time + Set the setting time ) Realization : 1. Get ready ( The header file 、 Node initialization 、NodeHandle establish ) 2. Get the current time 3. Set the specified time demand 2: Pause in program execution 5 second Realization : 1. Create duration object 2. Sleep demand 3: Know the time when the program starts running and the time when the program runs , Find the time when the operation ends Realization : 1. Get the moment when execution starts 2. Simulation run time (N second ) 3. Calculate the end time = Start + The duration of the Be careful : 1. Time and duration can be added or subtracted 2. You can add or subtract between durations 3. Values can be subtracted between times , You can't add up demand 4: every other 1 In the second , Output a piece of text on the console . Realization : Strategy 1:ros::Rate() Strategy 2: Timer Be careful : establish : nh.createTimer() Parameters 1: The time interval Parameters 2: Callback function ( Time event TimerEvent) Parameters 3: Whether to execute only 1 Time Parameters 4: Auto start or not ( When setting false when , Manual call required timer.start()) When the timer starts : ros::spin() */
// Callback function
void cb(const ros::TimerEvent& event){
ROS_INFO("----------");
ROS_INFO(" When the function is called :%.2f",event.current_real.toSec());
}
int main(int argc, char *argv[])
{
// demand 1
// 1. Get ready ( The header file 、 Node initialization 、NodeHandle establish )
setlocale(LC_ALL,"");
ros::init(argc,argv,"hello_time");
ros::NodeHandle nh;// Be careful : must . Otherwise, it will lead to time API Call failed ( Again NodeHandle Will initialize the time operation )
// 2. Get the current time
// now The function encapsulates the current time and returns
// The current moment :now The moment it is called to execute
// Reference system :1970 year 1 month 1 Japan 00:00:00
ros::Time right_now = ros::Time::now();// Time away from the reference system
ROS_INFO(" The current moment :%.2f",right_now.toSec());// Calculate the total elapsed time in seconds ,dounle type
ROS_INFO(" The current moment :%d",right_now.sec);// Calculate the total elapsed time in seconds , Integer types
// 3. Set the specified time
ros::Time t1(20,312345678);// Constructors , It means distance from the reference system 20 second , as well as 312345678 nanosecond
ros::Time t2(100.35);// floating-point B
ROS_INFO("t1 = %.2f",t1.toSec());
ROS_INFO("t2 = %.2f",t2.toSec());
// demand 2
ROS_INFO("------------------ The duration of the --------------");
ros::Time start = ros::Time::now();
ROS_INFO(" Start sleeping : %.2f",start.toSec());
ros::Duration du(4.5); // Duration encapsulates 4.5 second
du.sleep();// sleep 4.5s
ros::Time end = ros::Time::now();
ROS_INFO(" End of sleep :%.2f",end.toSec());
// demand 3
ROS_INFO("------------------ Time operations --------------");
// Time and duration operation
// 1. Get the moment when execution starts
ros::Time begin = ros::Time::now();
// 2. Simulation run time (N second )
ros::Duration du1(5);
// 3. Calculate the end time = Start + The duration of the
ros::Time stop = begin + du1; // It can also be used. -
ROS_INFO(" Starting time :%.2f",begin.toSec());
ROS_INFO(" End time :%.2f",stop.toSec());
// Time and time operation
// ros::Time sum = begin + stop; You can't add up
ros::Duration du2 = begin - stop;//-5
ROS_INFO(" Time subtracts :%.2f",du2.toSec());
// Operation of duration and duration
ros::Duration du3 = du1 + du2;// 0
ros::Duration du4 = du1 - du2;// 10
ROS_INFO("du1 + du2 = %.2f",du3.toSec());
ROS_INFO("du1 - du2 = %.2f",du4.toSec());
// demand 4
ROS_INFO("------------------ Timer --------------");
/* ros::Timer createTimer(ros::Duration period, // The time interval --- 1 const ros::TimerCallback &callback, // Callback function --- Packaging business bool oneshot = false, // Is it 1 Secondary ,dalse Every 1 Execute in seconds 1 Sub callback function , Loop execution bool autostart = true) // Auto start */
// ros::Timer timer = nh.createTimer(ros::Duration(1),cb);// every other 1 Execute the callback function once per second
// ros::Timer timer = nh.createTimer(ros::Duration(1),cb,true);//true Execute the callback function only once
ros::Timer timer = nh.createTimer(ros::Duration(1),cb,false,false);//false It doesn't start automatically
timer.start();// Manual start
ros::spin();// Need to rotate
return 0;
}
Python Realization
5 journal
C++ Realization
#include"ros/ros.h"
/* ROS Log in : Demonstrate the use of different levels of logs */
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"hello_log");
ros::NodeHandle nh;
// Log output
ROS_DEBUG(" Debugging information ");// Will not print on the console
ROS_INFO(" General information ");
ROS_WARN(" Warning message ");
ROS_ERROR(" error message ");
ROS_FATAL(" Serious mistakes ");
return 0;
}
Python Realization
#! /usr/bin/env python
import rospy
if __name__ == "__main__":
# Demo log function
rospy.init_node("hello_log")
rospy.logdebug("DEBUG news ...")
rospy.loginfo("INFO news ...")
rospy.logwarn("WARN news ...")
rospy.logerr("ERROR news ...")
rospy.logfatal("FATAL news ...")
6. Custom header file call
The header file hello.h
#ifndef _HELLO_H
#define _HELLO_H
/* Statement namespace |-- class |-- run */
namespace hello_ns{
class MyHello{
public:
void run();
};
}
#endif
Main documents
#include"ros/ros.h"
#include"plumbing_head/hello.h" // c_cpp_properties Configuration path
namespace hello_ns{
void MyHello::run(){
ROS_INFO("run Function execution .....");
}
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"hello_head");
// Function call
hello_ns::MyHello myHello;
myHello.run();
return 0;
}
边栏推荐
- 高等数学---第八章多元函数微分学---多元函数的极值与最值
- Vite3.0 release
- 【MD5】快速实现MD5加密解密(盐值)
- NVIDIA的jetson利用deepstream加速常见问题分析,deepstream消息发出外部接收,xvaier自启动程序,优秀的博客总结(精二)
- 一小时搭建属于属于自己的博客系统网站
- 面试官:怎么不用定时任务实现关闭订单?
- Julia初学者教程2022
- JSP基本语法实验
- Comment conditionalonmissingbean implémente l'écrasement des haricots dans les composants tiers
- (零七)Flask有手就行——初识数据库(Flask-SQLAlchemy)
猜你喜欢
随机推荐
MySQL data table query
Redis命令
war或jar使用Resource或ClassPathResource加载classpath下文件失败
[untitled]
@How can conditionalonmissingbean cover beans in third-party components
Comment conditionalonmissingbean implémente l'écrasement des haricots dans les composants tiers
【日常训练】剑指 Offer II 041. 滑动窗口的平均值
从22顶会看对比学习在推荐的应用
Application of optimistic lock and pessimistic lock in kubernetes
【集合】常见操作ArrayList集合的方法
Perspective rendering
【Gradle】快速配置
mysql插入数据会失败?为什么?
乐观锁和悲观锁在kubernetes中的应用
Performance management in digital intelligence era: reality and future
玩转CSDN编辑器
@ConditionalOnMissingBean 如何实现覆盖第三方组件中的 Bean
Which is the best bag grabbing tool (violent theft foreplay)
必备基础:加签验签
API design principles from the requirements of compiler for instruction set









