创建 std_srvs::Empty 型 Service (参数为空的服务)

1 篇文章 0 订阅

参考:ros::NodeHandle::advertiseService() API docs

1 包含头文件


#include <std_srvs/Empty.h>

2 创建服务,并绑定服务的回调函数


restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB, this);

3 定义服务回调函数功能,注意回调函数的参数为(1)std_srvs::Empty::Request &req; (2)std_srvs::Empty::Response &res


bool bp_hdw_common::restart_whole_robot_serviceCB(std_srvs::Empty::Request &req,  std_srvs::Empty::Response &res)
{
    return true;
}

在应用中遇到的两个问题:

(1)创建服务错误


restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB)

报警:


error: no matching function for call to ‘ros::NodeHandle::advertiseService(const char [20], bool (bp_hdw::bp_hdw_common::*)(std_srvs::Empty::Request&, std_srvs::Empty::Response&))’

原因是丢掉了this,函数原型为 advertiseService (const std::string &service, bool(T::*srv_func)(MReq &, MRes &), T *obj),正确结果如下:


restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB, this);

(2)通过参考链接将回调函数的参数写为std_srvs::Empty &req 和 std_srvs::Empty &res


restart_whole_robot_serviceCB(std_srvs::Empty &req,  std_srvs::Empty &res)

报警:


error: ‘const struct std_srvs::Empty’ has no member named ‘serialize’

正确结果为


restart_whole_robot_serviceCB(std_srvs::Empty::Request &req,  std_srvs::Empty::Response &res)

解释以下代码bool ret = laser.initialize(); if (ret) { ret = laser.turnOn(); } else { RCLCPP_ERROR(node->get_logger(), "%s\n", laser.DescribeError()); } auto laser_pub = node->create_publisher<sensor_msgs::msg::LaserScan>("scan", rclcpp::SensorDataQoS()); auto stop_scan_service = [&laser](const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<std_srvs::srv::Empty::Request> req, std::shared_ptr<std_srvs::srv::Empty::Response> response) -> bool { return laser.turnOff(); }; auto stop_service = node->create_service<std_srvs::srv::Empty>("stop_scan",stop_scan_service); auto start_scan_service = [&laser](const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<std_srvs::srv::Empty::Request> req, std::shared_ptr<std_srvs::srv::Empty::Response> response) -> bool { return laser.turnOn(); }; auto start_service = node->create_service<std_srvs::srv::Empty>("start_scan",start_scan_service); rclcpp::WallRate loop_rate(20); while (ret && rclcpp::ok()) { LaserScan scan;// if (laser.doProcessSimple(scan)) { auto scan_msg = std::make_shared<sensor_msgs::msg::LaserScan>(); scan_msg->header.stamp.sec = RCL_NS_TO_S(scan.stamp); scan_msg->header.stamp.nanosec = scan.stamp - RCL_S_TO_NS(scan_msg->header.stamp.sec); scan_msg->header.frame_id = frame_id; scan_msg->angle_min = scan.config.min_angle; scan_msg->angle_max = scan.config.max_angle; scan_msg->angle_increment = scan.config.angle_increment; scan_msg->scan_time = scan.config.scan_time; scan_msg->time_increment = scan.config.time_increment; scan_msg->range_min = scan.config.min_range; scan_msg->range_max = scan.config.max_range; int size = (scan.config.max_angle - scan.config.min_angle)/ scan.config.angle_increment + 1; scan_msg->ranges.resize(size); scan_msg->intensities.resize(size); for(size_t i=0; i < scan.points.size(); i++) { int index = std::ceil((scan.points[i].angle - scan.config.min_angle)/scan.config.angle_increment); if(index >=0 && index < size) { scan_msg->ranges[index] = scan.points[i].range; scan_msg->intensities[index] = scan.points[i].intensity; } } laser_pub->publish(*scan_msg); } else { RCLCPP_ERROR(node->get_logger(), "Failed to get scan"); } if(!rclcpp::ok()) { break; } rclcpp::spin_some(node); loop_rate.sleep(); } RCLCPP_INFO(node->get_logger(), "[YDLIDAR INFO] Now YDLIDAR is stopping ......."); laser.turnOff(); laser.disconnecting(); rclcpp::shutdown(); return 0; }
05-30
#include <ros/ros.h> #include <turtlesim/Pose.h> #include <geometry_msgs/Twist.h> #include <std_srvs/Empty.h> #include <cmath> ros::Publisher twist_pub; void poseCallback(const turtlesim::Pose& pose) { static bool is_forward = true; static int count = 0; static float x_start = pose.x; static float y_start = pose.y; static float theta_start = pose.theta; // Calculate distance from starting points float dist = std::sqrt(std::pow(pose.x - x_start, 2) + std::pow(pose.y - y_start, 2)); geometry_msgs::Twist twist_msg; twist_msg.linear.x = 1.0; twist_msg.linear.y = 0.0; twist_msg.linear.z = 0.0; twist_msg.angular.x = 0.0; twist_msg.angular.y = 0.0; twist_msg.angular.z = 0.0; // Check if turtle has reached distance of 2. If so, stop and shutdown the node. if (pose.x - x_start1) { twist_msg.linear.x = 0.0; twist_msg.linear.y = 1.0; twist_pub.publish(twist_msg); // Publish command if(pose.y - y_start>=2.0){ twist_msg.linear.x = -1.0; twist_msg.linear.y = 0.0; twist_pub.publish(twist_msg); // Publish command if(dist<=2.0){ twist_msg.linear.x = 0.0; twist_msg.linear.y = -1.0; twist_pub.publish(twist_msg); // Publish command ROS_INFO("Stop and Completed!"); twist_pub.publish(twist_msg); // Publish command ros::shutdown(); } } } twist_pub.publish(twist_msg); // Publish command } int main(int argc, char** argv) { ros::init(argc, argv, "lab1_node"); ros::NodeHandle nh; twist_pub = nh.advertise<geometry_msgs::Twist>("turtle1/cmd_vel", 1); ros::Subscriber pose_sub = nh.subscribe("turtle1/pose", 1, poseCallback); // reset the turtlesim when this node starts ros::ServiceClient reset = nh.serviceClient<std_srvs::Empty>("reset"); std_srvs::Empty empty; reset.call(empty); ros::spin(); // Keep node running until ros::shutdown() return 0; } 这段代码为什么不能实现乌龟沿完整矩形轨迹运动?并给出修改后的代码
最新发布
07-09
#include<iostream> #include<ctime> #include<chrono> #include<string> #include<filesystem> #include<fstream> #include<sstream> #include<thread> #include<boost/filesystem.hpp> const uintmax_t MAX_LOGS_SIZE = 10ull * 1024ull * 1024ull * 1024ull; //const uintmax_t MAX_LOGS_SIZE = 10ull; void create_folder(std::string folder_name) { boost::filesystem::create_directory(folder_name); std::string sub_foldername=folder_name+"/logs_ros"; boost::filesystem::create_directory(sub_foldername); } std::string get_current_time() { auto now = std::chrono::system_clock::now(); std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::tm parts = *std::localtime(&now_c); char buffer[20]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d-%H-%M", &parts); return buffer; } void check_logs_size() { std::string logs_path = "/home/sage/logs/"; boost::filesystem::path logs_dir(logs_path); std::uintmax_t total_size = 0; for (const auto& file : boost::filesystem::recursive_directory_iterator(logs_dir)) { if (boost::filesystem::is_regular_file(file)) { total_size += boost::filesystem::file_size(file); } } if (total_size > MAX_LOGS_SIZE) { boost::filesystem::path earliest_dir; std::time_t earliest_time = std::time(nullptr); for (const auto& dir : boost::filesystem::directory_iterator(logs_dir)) { if (boost::filesystem::is_directory(dir)) { std::string dir_name = dir.path().filename().string(); std::tm time_parts = {}; std::istringstream ss(dir_name); std::string part; std::getline(ss, part, '-'); time_parts.tm_year = std::stoi(part) - 1900; std::getline(ss, part, '-'); time_parts.tm_mon = std::stoi(part) - 1; std::getline(ss, part, '-'); time_parts.tm_mday = std::stoi(part); std::getline(ss, part, '-'); time_parts.tm_hour = std::stoi(part); std::getline(ss, part, '-'); time_parts.tm_min = std::stoi(part); std::time_t dir_time = std::mktime(&time_parts); if (dir_time < earliest_time) { earliest_time = dir_time; earliest_dir = dir.path(); } } } if (!earliest_dir.empty()) { boost::filesystem::remove_all(earliest_dir); } } } int main() { std::string logs_path = "/home/sage/logs/"; while (true) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::tm parts = *std::localtime(&now_c); if (parts.tm_min % 10 == 0) { std::string folder_name = logs_path + get_current_time(); create_folder(folder_name); } check_logs_size(); std::this_thread::sleep_for(std::chrono::minutes(1)); } return 0; }修改为ros节点
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值