当前位置:网站首页>[advanced ROS] Lecture 1 Introduction to common APIs
[advanced ROS] Lecture 1 Introduction to common APIs
2022-06-26 00:10:00 【Life is like Zhaoxu】
【ROS Advanced 】 Lesson one Commonly used API Introduce

List of articles
Preface
In previous blogs , We have achieved the goal of ROS Basic introductory teaching , from ROS Of Be born 、 How to use the foundation , We go through C++ Programming and command line Two ways to ROS Of Communication mechanism In-depth analysis , It also introduces such as TF Coordinate transformation 、 Parameters use 、launch file And other function packages and extension libraries , The main purpose of the advanced chapter is to break away from the previous perspective , Consider the problem from a macro perspective , A clearer grasp of ROS Ecosystem of , And focus on the use of several tools tutorial , This section is mainly about ROS Commonly used API Introduction and summary of . Including information about initialization 、 Communications 、 loop 、 Time and some node status and log output How to use .

Commonly used API
1. initialization
- ROS Node initialization is related to API
/** @brief ROS Initialization function . * * This function can parse and use the parameters passed in when the node is started ( Set the node name through parameters 、 Namespace ...) * * This function has multiple overloaded versions , If you use NodeHandle It is recommended to call this version . * * \param argc Number of parameters * \param argv parameter list * \param name The name of the node , It needs to be unique , Namespace is not allowed * \param options Node startup options , Encapsulated in ros::init_options * */
void init(int &argc, char **argv, const std::string& name, uint32_t options = 0);
2. Communications
Topic communication
- Publisher :
/** * \brief Generate publishing objects according to topics * * stay ROS master Register and return a publisher object , This object can publish messages * * An example is as follows : * * ros::Publisher pub = handle.advertise<std_msgs::Empty>("my_topic", 1); * * \param topic The topic used to post messages * * \param queue_size Maximum number of messages waiting to be sent to subscribers * * \param latch (optional) If true, The last message posted on this topic will be saved , And later, when a subscriber connects, the message will be sent to the subscriber * * \return When the call succeeds , Will return a publishing object * * */
template <class M>
Publisher advertise(const std::string& topic, uint32_t queue_size, bool latch = false)
- Release the news
/** * Release the news */
template <typename M>
void publish(const M& message) const
- subscriber
/** * \brief Generate a subscription object for a topic * * This function will be based on the given topic in ROS master register , And automatically connect publishers of the same topic , Every time I receive a message , Will call the callback * function , And pass in the shared pointer of the message , This message cannot be modified , Because other subscription objects may also use this message . * * An example is as follows : void callback(const std_msgs::Empty::ConstPtr& message) { } ros::Subscriber sub = handle.subscribe("my_topic", 1, callback); * * \param M [template] M Refers to the message type * \param topic Subscription topics * \param queue_size Message queue length , Beyond the length , The message in the header will be discarded * \param fp When you subscribe to a message , The callback function that needs to be executed * \return When the call succeeds , Returns a subscriber object , When the failure , Return empty object * void callback(const std_msgs::Empty::ConstPtr& message){...} ros::NodeHandle nodeHandle; ros::Subscriber sub = nodeHandle.subscribe("my_topic", 1, callback); if (sub) // Enter if subscriber is valid { ... } */
template<class M>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, void(*fp)(const boost::shared_ptr<M const>&), const TransportHints& transport_hints = TransportHints())
Service Newsletter
- The server
/** * \brief Generate the server object * * This function can be connected to ROS master, And provide a service object with a given name . * * An example is as follows : \verbatim bool callback(std_srvs::Empty& request, std_srvs::Empty& response) { return true; } ros::ServiceServer service = handle.advertiseService("my_service", callback); \endverbatim * * \param service Subject name of the service * \param srv_func When a request is received , The callback function that needs to process the request * \return The service object is returned when the request is successful , Otherwise return empty object : \verbatim bool Foo::callback(std_srvs::Empty& request, std_srvs::Empty& response) { return true; } ros::NodeHandle nodeHandle; Foo foo_object; ros::ServiceServer service = nodeHandle.advertiseService("my_service", callback); if (service) // Enter if advertised service is valid { ... } \endverbatim */
template<class MReq, class MRes>
ServiceServer advertiseService(const std::string& service, bool(*srv_func)(MReq&, MRes&))
- client
/** * @brief Create a service client object * * When clearing the reference handle of the last connection , Connection will be closed . * * @param service_name Service subject name */
template<class Service>
ServiceClient serviceClient(const std::string& service_name, bool persistent = false,
const M_string& header_values = M_string())
- Send a request
/** * @brief Send a request * The return value is bool type ,true, Request processed successfully ,false, Processing failed . */
template<class Service>
bool call(Service& service)
- Waiting for service
/** * ros::service::waitForService("addInts"); * \brief Waiting for service to be available , Otherwise, the consistency is blocked * \param service_name By " wait for " Topic name of the service * \param timeout Waiting for the most often , The default is -1, You can wait forever until the node shuts down * \return Successfully returns true, Otherwise return to false. */
ROSCPP_DECL bool waitForService(const std::string& service_name, ros::Duration timeout = ros::Duration(-1));
/** * client.waitForExistence(); * \brief Waiting for service to be available , Otherwise, the consistency is blocked * \param timeout Waiting for the most often , The default is -1, You can wait forever until the node shuts down * \return Successfully returns true, Otherwise return to false. */
bool waitForExistence(ros::Duration timeout = ros::Duration(-1));
3. loop
- Purpose : Handling callback functions
- spinOnce()
/** * \brief Deal with a round of callback * * General application scenarios : * In the circulatory system , Handle all available callback functions * */
ROSCPP_DECL void spinOnce();
- spin()
/** * \brief Enter the loop processing callback */
ROSCPP_DECL void spin();
- difference :
- ros::spin() Is to enter the loop and execute the callback function , stay ros::spin() The following sentence Not execute To
- ros::spinOnce() It's only going to be executed once Callback function ( No cycle ), and ros::spinOnce() The following statement can execute .
4. Time
- Get time / Set the specified time :
ros::init(argc,argv,"hello_time");
ros::NodeHandle nh;// You must create a handle , Otherwise, the time is not initialized , Lead to the following API Call failed
ros::Time right_now = ros::Time::now();// Encapsulate the current time into an object
ROS_INFO(" The current moment :%.2f",right_now.toSec());// Get the distance 1970 year 01 month 01 Japan 00:00:00 The number of seconds
ROS_INFO(" The current moment :%d",right_now.sec);// Get the distance 1970 year 01 month 01 Japan 00:00:00 The number of seconds
ros::Time someTime(100,100000000);// Parameters 1: Number of seconds Parameters 2: nanosecond
ROS_INFO(" moment :%.2f",someTime.toSec()); //100.10
ros::Time someTime2(100.3);// Direct in double Type of seconds
ROS_INFO(" moment :%.2f",someTime2.toSec()); //100.30
- Set the time interval :
ROS_INFO(" The current moment :%.2f",ros::Time::now().toSec());
ros::Duration du(10);// continued 10 Second , Parameter is double Type of , In seconds
du.sleep();// Sleep for the specified duration
ROS_INFO(" The duration of the :%.2f",du.toSec());// Convert the duration into seconds
ROS_INFO(" The current moment :%.2f",ros::Time::now().toSec());
- Time operations :
ROS_INFO(" Time operations ");
ros::Time now = ros::Time::now();
ros::Duration du1(10);
ros::Duration du2(20);
ROS_INFO(" The current moment :%.2f",now.toSec());
//1.time And duration operation
ros::Time after_now = now + du1;
ros::Time before_now = now - du1;
ROS_INFO(" After the current moment :%.2f",after_now.toSec());
ROS_INFO(" Before the present moment :%.2f",before_now.toSec());
//2.duration Between them
ros::Duration du3 = du1 + du2;
ros::Duration du4 = du1 - du2;
ROS_INFO("du3 = %.2f",du3.toSec());
ROS_INFO("du4 = %.2f",du4.toSec());
//PS: time And time No arithmetic
// ros::Time nn = now + before_now;// abnormal
- Set the operating frequency :
ros::Rate rate(1);// Specified frequency
while (true)
{
ROS_INFO("-----------code----------");
rate.sleep();// Sleep , Sleep time = 1 / frequency .
}
- Timer :
ros::NodeHandle nh;// You must create a handle , Otherwise, the time is not initialized , Lead to the following API Call failed
// ROS Timer
/** * \brief Create a timer , Call the callback function at the specified frequency . * * \param period The time interval * \param callback Callback function * \param oneshot If set to true, Execute the callback function only once , Set to false, Just loop . * \param autostart If true, Returns the timer that has been started , Set to false, It needs to be started manually . */
//Timer createTimer(Duration period, const TimerCallback& callback, bool oneshot = false,
// bool autostart = true) const;
// ros::Timer timer = nh.createTimer(ros::Duration(0.5),doSomeThing);
ros::Timer timer = nh.createTimer(ros::Duration(0.5),doSomeThing,true);// Only once
// ros::Timer timer = nh.createTimer(ros::Duration(0.5),doSomeThing,false,false);// It needs to be started manually
// timer.start();
ros::spin(); // must spin
// Callback function
void doSomeThing(const ros::TimerEvent &event){
ROS_INFO("-------------");
ROS_INFO("event:%s",std::to_string(event.current_real.toSec()).c_str());
}
5. node
- The state of the node can control the condition of the loop , It is often used in common use
ros::ok()To judge , That is, whether the node is closed (ctrl+c) Or exit due to startup with the same name
/** \brief Check whether the node has exited * * ros::shutdown() After being called and executed , The function will return false * * \return true If the node is still alive , false If the node has been cremated . */
bool ok();
- Called node shutdown API:shutdown()
/* * Close the node */
void shutdown();
6. journal
- DEBUG( debugging ): Use only when debugging , Such messages are not output to the console ;
ROS_DEBUG("hello,DEBUG"); // No output- INFO( Information ): Standard message , It is generally used to describe the operation being performed in the system ;
ROS_INFO("hello,INFO"); // Default white font- WARN( Warning ): Remind some exceptions , But the program can still be executed ;
ROS_WARN("Hello,WARN"); // Default yellow font- ERROR( error ): Error message , Such errors will affect the operation of the program ;
ROS_ERROR("hello,ERROR");// Default red font- FATAL( Serious mistakes ): Such errors will prevent the node from continuing to run ;
ROS_FATAL("hello,FATAL");// Default red font
summary
- Statement : The blog section of this section refers to CSDN User zhaoxuzuo ROS course , About API You can also refer to the following reference websites :
- http://wiki.ros.org/APIs
- https://docs.ros.org/en/api/roscpp/html/

边栏推荐
猜你喜欢

7. common instructions (Part 2): common operations of v-on, v-bind and V-model

迅为RK3568开发板使用RKNN-Toolkit-lite2运行测试程序

Connecting MySQL database with VBScript_ Old bear passing by_ Sina blog

EBS R12.2.0升级到R12.2.6
![Find the minimum value of flipped array [Abstract bisection]](/img/b9/1e0c6196e6dc51ae2c48f6c5e83289.png)
Find the minimum value of flipped array [Abstract bisection]

anchor free dection简介

Literature research (I): hourly energy consumption prediction of office buildings based on integrated learning and energy consumption pattern classification

Recherche documentaire (3): examen des modèles de prévision de la consommation d'énergie des bâtiments fondés sur les données

Establishment of multiple background blocks in botu software_ Old bear passing by_ Sina blog

86.(cesium篇)cesium叠加面接收阴影效果(gltf模型)
随机推荐
How postman tests interfaces that require login
Explain in detail the three types of local variables, global variables and static variables
6. common instructions (upper) v-cloak, v-once, v-pre
Realize the conversion between analog quantity value and engineering quantity value in STEP7_ Old bear passing by_ Sina blog
dbca静默安装及建库
Some common operation methods of array
How to configure SQL Server 2008 Manager_ Old bear passing by_ Sina blog
[reprint]rslogix 5000 instance tutorial
Shredding Company poj 1416
Establishment of multiple background blocks in botu software_ Old bear passing by_ Sina blog
Servlet response下载文件
linux安装redis
Bit compressor [Blue Bridge Cup training]
Bit Compressor [蓝桥杯题目训练]
Network protocol: detailed explanation of redis protocol
huibian
Redis之跳跃表
Rocket之消息存储
解决线程并发安全问题
Stop eating vitamin C tablets. These six fruits have the highest vitamin C content