机器人编程趣味实践04-逻辑判断(if)

举报
zhangrelay 发表于 2021/07/14 22:42:41 2021/07/14
【摘要】 在上一节中,介绍了简单的运算规则。核心代码如下: 服务端: RCLCPP_INFO( g_node->get_logger(), "分别获取两个整数 %" PRId64 " + %" PRId64, request->a, request->b); response->sum = request->a + request->b; ...

在上一节中,介绍了简单的运算规则。核心代码如下:

服务端:


  
  1. RCLCPP_INFO( g_node->get_logger(),
  2. "分别获取两个整数 %" PRId64 " + %" PRId64, request->a, request->b);
  3. response->sum = request->a + request->b;

当然,+可以更换为其他运算。

客户端:


  
  1. RCLCPP_INFO(
  2. node->get_logger(), "结果 %" PRId64 " + %" PRId64 " = %" PRId64,
  3. request->a, request->b, result->sum);

这里的结果是由服务端发送给客户端的,这是一个简单的运算调用案例。

在实际运行中,由于使用中文字符,出现了乱码的情况,后续将以英文字符为主,毕竟国外开源代码几乎都是全英文的嘛。


最初,介绍了基本的消息传递,然后是运算,本节将重点关注逻辑判断,如if。

黄金分割与斐波那契数列

先上程序

服务器端:


  
  1. #include <inttypes.h>
  2. #include <memory>
  3. #include "example_interfaces/action/fibonacci.hpp"
  4. #include "rclcpp/rclcpp.hpp"
  5. // TODO(jacobperron): Remove this once it is included as part of 'rclcpp.hpp'
  6. #include "rclcpp_action/rclcpp_action.hpp"
  7. class MinimalActionServer : public rclcpp::Node
  8. {
  9. public:
  10. using Fibonacci = example_interfaces::action::Fibonacci;
  11. using GoalHandleFibonacci = rclcpp_action::ServerGoalHandle<Fibonacci>;
  12. explicit MinimalActionServer(const rclcpp::NodeOptions & options = rclcpp::NodeOptions())
  13. : Node("minimal_action_server", options)
  14. {
  15. using namespace std::placeholders;
  16. this->action_server_ = rclcpp_action::create_server<Fibonacci>(
  17. this->get_node_base_interface(),
  18. this->get_node_clock_interface(),
  19. this->get_node_logging_interface(),
  20. this->get_node_waitables_interface(),
  21. "fibonacci",
  22. std::bind(&MinimalActionServer::handle_goal, this, _1, _2),
  23. std::bind(&MinimalActionServer::handle_cancel, this, _1),
  24. std::bind(&MinimalActionServer::handle_accepted, this, _1));
  25. }
  26. private:
  27. rclcpp_action::Server<Fibonacci>::SharedPtr action_server_;
  28. rclcpp_action::GoalResponse handle_goal(
  29. const rclcpp_action::GoalUUID & uuid,
  30. std::shared_ptr<const Fibonacci::Goal> goal)
  31. {
  32. RCLCPP_INFO(this->get_logger(), "Received goal request with order %d", goal->order);
  33. (void)uuid;
  34. // Let's reject sequences that are over 9000
  35. if (goal->order > 9000) {
  36. return rclcpp_action::GoalResponse::REJECT;
  37. }
  38. return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
  39. }
  40. rclcpp_action::CancelResponse handle_cancel(
  41. const std::shared_ptr<GoalHandleFibonacci> goal_handle)
  42. {
  43. RCLCPP_INFO(this->get_logger(), "Received request to cancel goal");
  44. (void)goal_handle;
  45. return rclcpp_action::CancelResponse::ACCEPT;
  46. }
  47. void execute(const std::shared_ptr<GoalHandleFibonacci> goal_handle)
  48. {
  49. RCLCPP_INFO(this->get_logger(), "Executing goal");
  50. rclcpp::Rate loop_rate(1);
  51. const auto goal = goal_handle->get_goal();
  52. auto feedback = std::make_shared<Fibonacci::Feedback>();
  53. auto & sequence = feedback->sequence;
  54. sequence.push_back(0);
  55. sequence.push_back(1);
  56. auto result = std::make_shared<Fibonacci::Result>();
  57. for (int i = 1; (i < goal->order) && rclcpp::ok(); ++i) {
  58. // Check if there is a cancel request
  59. if (goal_handle->is_canceling()) {
  60. result->sequence = sequence;
  61. goal_handle->canceled(result);
  62. RCLCPP_INFO(this->get_logger(), "Goal Canceled");
  63. return;
  64. }
  65. // Update sequence
  66. sequence.push_back(sequence[i] + sequence[i - 1]);
  67. // Publish feedback
  68. goal_handle->publish_feedback(feedback);
  69. RCLCPP_INFO(this->get_logger(), "Publish Feedback");
  70. loop_rate.sleep();
  71. }
  72. // Check if goal is done
  73. if (rclcpp::ok()) {
  74. result->sequence = sequence;
  75. goal_handle->succeed(result);
  76. RCLCPP_INFO(this->get_logger(), "Goal Succeeded");
  77. }
  78. }
  79. void handle_accepted(const std::shared_ptr<GoalHandleFibonacci> goal_handle)
  80. {
  81. using namespace std::placeholders;
  82. // this needs to return quickly to avoid blocking the executor, so spin up a new thread
  83. std::thread{std::bind(&MinimalActionServer::execute, this, _1), goal_handle}.detach();
  84. }
  85. }; // class MinimalActionServer
  86. int main(int argc, char ** argv)
  87. {
  88. rclcpp::init(argc, argv);
  89. auto action_server = std::make_shared<MinimalActionServer>();
  90. rclcpp::spin(action_server);
  91. rclcpp::shutdown();
  92. return 0;
  93. }

客户端:


  
  1. #include <inttypes.h>
  2. #include <memory>
  3. #include <string>
  4. #include <iostream>
  5. #include "example_interfaces/action/fibonacci.hpp"
  6. #include "rclcpp/rclcpp.hpp"
  7. // TODO(jacobperron): Remove this once it is included as part of 'rclcpp.hpp'
  8. #include "rclcpp_action/rclcpp_action.hpp"
  9. class MinimalActionClient : public rclcpp::Node
  10. {
  11. public:
  12. using Fibonacci = example_interfaces::action::Fibonacci;
  13. using GoalHandleFibonacci = rclcpp_action::ClientGoalHandle<Fibonacci>;
  14. explicit MinimalActionClient(const rclcpp::NodeOptions & node_options = rclcpp::NodeOptions())
  15. : Node("minimal_action_client", node_options), goal_done_(false)
  16. {
  17. this->client_ptr_ = rclcpp_action::create_client<Fibonacci>(
  18. this->get_node_base_interface(),
  19. this->get_node_graph_interface(),
  20. this->get_node_logging_interface(),
  21. this->get_node_waitables_interface(),
  22. "fibonacci");
  23. this->timer_ = this->create_wall_timer(
  24. std::chrono::milliseconds(500),
  25. std::bind(&MinimalActionClient::send_goal, this));
  26. }
  27. bool is_goal_done() const
  28. {
  29. return this->goal_done_;
  30. }
  31. void send_goal()
  32. {
  33. using namespace std::placeholders;
  34. this->timer_->cancel();
  35. this->goal_done_ = false;
  36. if (!this->client_ptr_) {
  37. RCLCPP_ERROR(this->get_logger(), "Action client not initialized");
  38. }
  39. if (!this->client_ptr_->wait_for_action_server(std::chrono::seconds(10))) {
  40. RCLCPP_ERROR(this->get_logger(), "Action server not available after waiting");
  41. this->goal_done_ = true;
  42. return;
  43. }
  44. auto goal_msg = Fibonacci::Goal();
  45. goal_msg.order = 10;
  46. RCLCPP_INFO(this->get_logger(), "Sending goal");
  47. auto send_goal_options = rclcpp_action::Client<Fibonacci>::SendGoalOptions();
  48. send_goal_options.goal_response_callback =
  49. std::bind(&MinimalActionClient::goal_response_callback, this, _1);
  50. send_goal_options.feedback_callback =
  51. std::bind(&MinimalActionClient::feedback_callback, this, _1, _2);
  52. send_goal_options.result_callback =
  53. std::bind(&MinimalActionClient::result_callback, this, _1);
  54. auto goal_handle_future = this->client_ptr_->async_send_goal(goal_msg, send_goal_options);
  55. }
  56. private:
  57. rclcpp_action::Client<Fibonacci>::SharedPtr client_ptr_;
  58. rclcpp::TimerBase::SharedPtr timer_;
  59. bool goal_done_;
  60. void goal_response_callback(std::shared_future<GoalHandleFibonacci::SharedPtr> future)
  61. {
  62. auto goal_handle = future.get();
  63. if (!goal_handle) {
  64. RCLCPP_ERROR(this->get_logger(), "Goal was rejected by server");
  65. } else {
  66. RCLCPP_INFO(this->get_logger(), "Goal accepted by server, waiting for result");
  67. }
  68. }
  69. void feedback_callback(
  70. GoalHandleFibonacci::SharedPtr,
  71. const std::shared_ptr<const Fibonacci::Feedback> feedback)
  72. {
  73. RCLCPP_INFO(
  74. this->get_logger(),
  75. "Next number in sequence received: %" PRId32,
  76. feedback->sequence.back());
  77. }
  78. void result_callback(const GoalHandleFibonacci::WrappedResult & result)
  79. {
  80. this->goal_done_ = true;
  81. switch (result.code) {
  82. case rclcpp_action::ResultCode::SUCCEEDED:
  83. break;
  84. case rclcpp_action::ResultCode::ABORTED:
  85. RCLCPP_ERROR(this->get_logger(), "Goal was aborted");
  86. return;
  87. case rclcpp_action::ResultCode::CANCELED:
  88. RCLCPP_ERROR(this->get_logger(), "Goal was canceled");
  89. return;
  90. default:
  91. RCLCPP_ERROR(this->get_logger(), "Unknown result code");
  92. return;
  93. }
  94. RCLCPP_INFO(this->get_logger(), "Result received");
  95. for (auto number : result.result->sequence) {
  96. RCLCPP_INFO(this->get_logger(), "%" PRId32, number);
  97. }
  98. }
  99. }; // class MinimalActionClient
  100. int main(int argc, char ** argv)
  101. {
  102. rclcpp::init(argc, argv);
  103. auto action_client = std::make_shared<MinimalActionClient>();
  104. while (!action_client->is_goal_done()) {
  105. rclcpp::spin_some(action_client);
  106. }
  107. rclcpp::shutdown();
  108. return 0;
  109. }

那么这时候,就需要引入逻辑判断了,if


  
  1. RCLCPP_INFO(this->get_logger(), "Received goal request with order %d", goal->order);
  2. (void)uuid;
  3. // Let's reject sequences that are over 9000
  4. if (goal->order > 9000) {
  5. return rclcpp_action::GoalResponse::REJECT;
  6. }
  7. return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;

当需要计算量大于9000时,需要拒绝,这个数值可以修改。同样也可以发现这个程序运行时间比上一个案例中简单加减要长,并且过程也复杂。

那么中途如果不需要,就可以取消等。


  
  1. rclcpp_action::CancelResponse handle_cancel( const std::shared_ptr<GoalHandleFibonacci> goal_handle )
  2. {
  3. RCLCPP_INFO(this->get_logger(), "Received request to cancel goal");
  4. (void)goal_handle;
  5. return rclcpp_action::CancelResponse::ACCEPT;
  6. }

先看看效果^_^  分别计算6,66……

计算6阶,还是一切正常的,但是66阶,明显就不对劲啦,这时候溢出,需要终止程序,无需继续下去:

上图中的有明显问题,-1323752223

虽然运行到最后,也会出现如下:

当然,可以查看更多详细信息,使用如下命令:

  1. ros2 action list
  2. ros2 action info /fibonacci
  3. ros2 action send_goal /fibonacci example_interfaces/action/Fibonacci order:\ 20\

示例程序中有大量的判断,下一节将融合图形化界面进行扩展。


 

文章来源: zhangrelay.blog.csdn.net,作者:zhangrelay,版权归原作者所有,如需转载,请联系作者。

原文链接:zhangrelay.blog.csdn.net/article/details/116668434

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。