ros简版Action通讯SimpleAction

一.python

1.非ui界面版

1.1client.py

#!/usr/bin/env python
# coding:utf-8
import rospy
from actionlib import SimpleActionClient
from demo_actions.msg import CountNumberAction, CountNumberGoal,CountNumberResult
from actionlib import GoalStatus# 结果回调
def done_cb(state,result):if state==GoalStatus.SUCCEEDED:rospy.loginfo('succeed {}'.format(result.count))elif state==GoalStatus.ABORTED:rospy.loginfo('aborted {}'.format(result.count))elif state==GoalStatus.PREEMPTED:rospy.loginfo('cancel {}'.format(result.count))# 激活
def active_cb():rospy.loginfo('active')# 进度
def feedback_cb(feedback):rospy.loginfo('feedback {}'.format(feedback.percent))if __name__ == '__main__':# 创建节点rospy.init_node("action_client")# action的名字actionName = 'action_py'# 创建client端client = SimpleActionClient(actionName, CountNumberAction)# 等待client.wait_for_server()# 目标goal = CountNumberGoal()goal.max = 10goal.duration = 1# 发送目标client.send_goal(goal,done_cb,active_cb,feedback_cb)# 睡眠两秒钟取消rate = rospy.Rate(0.5)rate.sleep()client.cancel_goal()# 阻塞rospy.spin()

1.2 server.py

#!/usr/bin/env python
# coding:utf-8
import rospy
from actionlib import SimpleActionServer
from demo_actions.msg import CountNumberAction,CountNumberFeedback,CountNumberResultdef execute_cb(goal):rospy.loginfo('receive goal')max = goal.maxduration = goal.duration# 结果result = CountNumberResult()rate = rospy.Rate(duration)for i in range(1,max):# 发布进度feedback = CountNumberFeedback()feedback.percent = float(i)/maxserver.publish_feedback(feedback)# 取消判断if server.is_preempt_requested():result.count = iserver.set_aborted(result)return# 睡眠rate.sleep()# 成功result.count = maxserver.set_succeeded(result)if __name__ == '__main__':# 创建节点rospy.init_node("action_server")# action的名字actionName = 'action_py'# 创建serverserver = SimpleActionServer(actionName,CountNumberAction,execute_cb,auto_start=False)# 启动serverserver.start()# 阻塞rospy.spin()

2.ui版

2.1 MainWIndowClient.py

#!/usr/bin/env python
# coding:utf-8
import rospy
from PyQt5.QtWidgets import *
from actionlib import SimpleActionClient
from demo_actions.msg import CountNumberAction, CountNumberGoal,CountNumberResult
from actionlib import GoalStatusclass MainWindow(QWidget):def __init__(self):super(MainWindow, self).__init__()print 'helo'self.setWindowTitle("hello")layout = QFormLayout()self.setLayout(layout)maxEdit = QLineEdit()durationEdit = QLineEdit()activeL = QLabel()feedbackL = QLabel()doneL = QLabel()sendBtn = QPushButton('发送目标')cancelBtn = QPushButton('取消目标')layout.addRow('max目标:',maxEdit)layout.addRow('duration目标:',durationEdit)layout.addRow('激活状态:',activeL)layout.addRow('进度:',feedbackL)layout.addRow('完成状态:',doneL)layout.addRow('',sendBtn)layout.addRow('',cancelBtn)# action的名字actionName = 'action_py'# 创建client端self.client = SimpleActionClient(actionName, CountNumberAction)sendBtn.clicked.connect(self.send)cancelBtn.clicked.connect(self.cancel)def cancel(self):self.client.cancel_goal()def send(self):# 目标goal = CountNumberGoal()goal.max = 10goal.duration = 1# 发送目标self.client.send_goal(goal,self.done_cb,self.active_cb,self.feedback_cb)# 结果回调def done_cb(self,state,result):if state==GoalStatus.SUCCEEDED:rospy.loginfo('succeed {}'.format(result.count))elif state==GoalStatus.ABORTED:rospy.loginfo('aborted {}'.format(result.count))elif state==GoalStatus.PREEMPTED:rospy.loginfo('cancel {}'.format(result.count))# 激活def active_cb(self):rospy.loginfo('active')# 进度def feedback_cb(self,feedback):rospy.loginfo('feedback {}'.format(feedback.percent))

2.2

MainWindowServer.py

#!/usr/bin/env python
# coding:utf-8
import rospy
from actionlib import SimpleActionServer
from demo_actions.msg import CountNumberAction,CountNumberFeedback,CountNumberResult
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QTimerclass MainWindow(QWidget):def __init__(self):super(MainWindow, self).__init__()self.timer = QTimer(self)self.timer.setInterval(100)self.timer.timeout.connect(self.timeout)self.timer.start()self.setFixedSize(200,100)layout = QFormLayout()self.setLayout(layout)maxL = QLabel()durationL = QLabel()btn = QPushButton("中止")layout.addRow("max:",maxL)layout.addRow("duration:",durationL)layout.addRow("",btn)self.isAbort = False# action的名字actionName = 'action_py'# 创建serverself.server = SimpleActionServer(actionName,CountNumberAction,self.execute_cb,auto_start=False)# 启动serverself.server.start()btn.clicked.connect(self.abort)def timeout(self):if rospy.is_shutdown():QApplication.quit()def abort(self):self.isAbort = Truedef execute_cb(self,goal):rospy.loginfo('receive goal')self.isAbort = Falsemax = goal.maxduration = goal.duration# 结果result = CountNumberResult()rate = rospy.Rate(duration)for i in range(1,max):# 发布进度feedback = CountNumberFeedback()feedback.percent = float(i)/maxself.server.publish_feedback(feedback)# 取消判断if self.isAbort:result.count = iself.server.set_aborted(result)return# 取消判断if self.server.is_preempt_requested():result.count = iself.server.set_preempted(result)return# 睡眠rate.sleep()# 成功result.count = maxself.server.set_succeeded(result)

2.3

client_gui.py

#!/usr/bin/env python
# coding:utf-8from MainWIndowClient import *
import sysif __name__ == '__main__':# 创建节点rospy.init_node("action_client")app = QApplication(sys.argv)w = MainWindow()w.show()sys.exit(app.exec_())

2.4

server_gui.py

#!/usr/bin/env python
# coding:utf-8
import rospy
from MainWindowServer import *import sysif __name__ == '__main__':# 创建节点rospy.init_node("action_server")app = QApplication(sys.argv)w = MainWindow()w.show()exec_ = app.exec_()sys.exit(exec_)

二.c++

1.非ui版

1.1 simple_client.cpp

//
// Created by wt on 2020/7/3.
//
#include <iostream>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <demo_actions/CountNumberAction.h>using namespace std;
//结果回调 (包含了很多状态  成功  取消  错误)
void done_cb(const actionlib::SimpleClientGoalState &state,const demo_actions::CountNumberResult::ConstPtr &result) {if (state==actionlib::SimpleClientGoalState::SUCCEEDED){//服务端setSuccedROS_INFO_STREAM("succeed"<<result->count);}else if(state==actionlib::SimpleClientGoalState::ABORTED){//setAbortedROS_INFO_STREAM("aborted"<<result->count);}else if(state==actionlib::SimpleClientGoalState::PREEMPTED){//setAbortedROS_INFO_STREAM("preempted"<<result->count);}
}
//激活回调
void active_cb(){ROS_INFO_STREAM("active");
}//进度回调
void feedback_cb(const demo_actions::CountNumberFeedback::ConstPtr & feedback){ROS_INFO_STREAM("feedback"<<feedback->percent);
}int main(int argc, char *argv[]) {//节点名string nodeName = "action_client";//初始化节点ros::init(argc, argv, nodeName,ros::init_options::AnonymousName);//创建节点ros::NodeHandle node;//通信名string actionName = "action_cpp";//创建客户端actionlib::SimpleActionClient<demo_actions::CountNumberAction> client(node, actionName);//等待client.waitForServer();//目标demo_actions::CountNumberGoal goal;goal.max = 10;goal.duration = 1;//发送目标(发布topic)client.sendGoal(goal,done_cb,active_cb,feedback_cb);//等2秒钟 取消任务ros::Rate rate(0.5);rate.sleep();//取消任务
//    client.cancelGoal();//事件轮询ros::spin();return 0;
}

1.2

simple_server.cpp

//
// Created by wt on 2020/7/3.
//
#include <iostream>
#include <ros/ros.h>
//action通信server端
#include <actionlib/server/simple_action_server.h>
#include <demo_actions/CountNumberAction.h>using namespace std;//参数:发送的目标指针
void execute_callback(const demo_actions::CountNumberGoal::ConstPtr &goal,actionlib::SimpleActionServer<demo_actions::CountNumberAction> *server) {ROS_INFO_STREAM("receive goal");//获取目标中的数据long max = goal->max;double duration = goal->duration;//回调结果demo_actions::CountNumberResult result;//rateros::Rate rate(duration);for (int i = 1; i < max; ++i) {
//        if(i==2){
//            //认为服务器出错
//            result.count = -1;
//            server->setAborted(result);
//            return;
//        }/*-------------------------- 取消 --------------------------*///是否请求被取消if(server->isPreemptRequested()){//必须要知道客户端已经取消了任务,才能通过这个方法返回结果result.count = i;server->setPreempted(result);return;}//进度demo_actions::CountNumberFeedback feedback;feedback.percent = (double)i/(double)max;//发布进度server->publishFeedback(feedback);//睡眠rate.sleep();}//成功result.count = max;server->setSucceeded(result);}int main(int argc, char *argv[]) {//节点名string nodeName = "action_server";//初始化节点ros::init(argc, argv, nodeName);//创建节点ros::NodeHandle node;//通信名string actionName = "action_cpp";//创建服务端actionlib::SimpleActionServer<demo_actions::CountNumberAction> server(actionName, boost::bind(execute_callback,_1,&server), false);//启动服务server.start();//事件轮询ros::spin();return 0;
}

2.ui界面版

2.1

MainWindowClient.h

//
// Created by wt on 2020/7/5.
//#ifndef DEMO_USE_ACTION_MAINWINDOWCLIENT_H
#define DEMO_USE_ACTION_MAINWINDOWCLIENT_H
#include <QWidget>
#include <QFormLayout>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <actionlib/client/simple_action_client.h>
#include <demo_actions/CountNumberAction.h>
#include <actionlib/server/simple_action_server.h>
#include <QTimer>
class MainWindowClient: public QWidget {
private:QFormLayout layout;QLineEdit maxEdit;QLineEdit durationEdit;QLabel activeL;QLabel feedbackL;QLabel doneL;QPushButton sendBtn;QPushButton cancelBtn;actionlib::SimpleActionClient<demo_actions::CountNumberAction> *client;QTimer timer;public:MainWindowClient(ros::NodeHandle node,QWidget* parent = Q_NULLPTR);~MainWindowClient();//发送目标void send();//取消void cancel();//完成回调void done_cb(const actionlib::SimpleClientGoalState &state,const demo_actions::CountNumberResult::ConstPtr &result);//激活void active_cb();//进度void feedback_cb(const demo_actions::CountNumberFeedback::ConstPtr & feedback);void timeout();
};#endif //DEMO_USE_ACTION_MAINWINDOWCLIENT_H

2.2

MainWindowClient.cpp

//
// Created by wt on 2020/7/5.
//#include "MainWindowClient.h"MainWindowClient::MainWindowClient(ros::NodeHandle node,QWidget* parent):QWidget(parent),sendBtn("发送目标"),
cancelBtn("取消目标"){setLayout(&layout);layout.addRow("max目标:",&maxEdit);layout.addRow("duration目标:",&durationEdit);layout.addRow("激活状态:",&activeL);layout.addRow("进度:",&feedbackL);layout.addRow("完成状态:",&doneL);layout.addRow("",&sendBtn);layout.addRow("",&cancelBtn);client = new actionlib::SimpleActionClient<demo_actions::CountNumberAction>(node,"action_cpp");client->waitForServer();//这里不需要用这个,会阻塞窗口, 用client->is*** 来判断是否连上了//定时器timer.setInterval(10);timer.start();//定时信号connect(&timer,&QTimer::timeout,this,&WindoClient::timeout);//信号和槽connect(&sendBtn,&QPushButton::clicked,this,&MainWindowClient::send);connect(&cancelBtn,&QPushButton::clicked,this,&MainWindowClient::cancel);
}MainWindowClient::~MainWindowClient() {
ros::shutdown();}void MainWindowClient::send() {demo_actions::CountNumberGoal goal;goal.max = maxEdit.text().toLong();goal.duration = durationEdit.text().toDouble();client->sendGoal(goal,boost::bind(&MainWindowClient::done_cb,this,_1,_2),boost::bind(&MainWindowClient::active_cb,this),boost::bind(&MainWindowClient::feedback_cb,this,_1));
}void MainWindowClient::done_cb(const actionlib::SimpleClientGoalState &state,const demo_actions::CountNumberResult::ConstPtr &result){if (state==actionlib::SimpleClientGoalState::SUCCEEDED){//服务端setSuccedROS_INFO_STREAM("succeed"<<result->count);doneL.setText("成功");}else if(state==actionlib::SimpleClientGoalState::ABORTED){//setAbortedROS_INFO_STREAM("aborted"<<result->count);doneL.setText("服务出错");}else if(state==actionlib::SimpleClientGoalState::PREEMPTED){//setAbortedROS_INFO_STREAM("preempted"<<result->count);doneL.setText("取消");}
}
void MainWindowClient::active_cb() {ROS_INFO_STREAM("active");activeL.setText("激活");
}void MainWindowClient::feedback_cb(const demo_actions::CountNumberFeedback::ConstPtr & feedback){ROS_INFO_STREAM("feedback  "<<feedback->percent);feedbackL.setText(QString::number(feedback->percent));
}void MainWindowClient::cancel() {//取消目标client->cancelGoal();
}//定时的槽函数
void WindoClient::timeout(){//处理消息if(ros::isShuttingDown()){QApplication::quit();}}

2.3

MainWindowServer.h

//
// Created by wt on 2020/7/5.
//
#ifndef DEMO_USE_ACTION_MAINWINDOWSERVER_H
#define DEMO_USE_ACTION_MAINWINDOWSERVER_H
#include <QWidget>
#include <QFormLayout>
#include <QPushButton>
#include <QLabel>
#include <actionlib/server/simple_action_server.h>
#include <demo_actions/CountNumberAction.h>class MainWindowServer: public QWidget {
private:QFormLayout layout;QLabel maxL;QLabel dL;QPushButton btn;actionlib::SimpleActionServer<demo_actions::CountNumberAction> *server;//记录是否服务出错bool isAborted = false;
public:MainWindowServer(QWidget* parent = Q_NULLPTR);~MainWindowServer();//回调void execute_callback(const demo_actions::CountNumberGoal::ConstPtr &goal);//服务出错void aborted();
};#endif //DEMO_USE_ACTION_MAINWINDOWSERVER_H

2.4

MainWindowServer.cpp

//
// Created by wt on 2020/7/5.
//#include "MainWindowServer.h"MainWindowServer::MainWindowServer(QWidget* parent):QWidget(parent),btn("aborted") {setFixedSize(200,100);setLayout(&layout);layout.addRow("max:",&maxL);layout.addRow("duration:",&dL);layout.addRow("",&btn);//创建server端server = new actionlib::SimpleActionServer<demo_actions::CountNumberAction>("action_cpp",boost::bind(&MainWindowServer::execute_callback,this,_1), false);server->start();//服务端出错connect(&btn,&QPushButton::clicked,this,&MainWindowServer::aborted);
}MainWindowServer::~MainWindowServer() {delete server;
}void MainWindowServer::execute_callback(const demo_actions::CountNumberGoal::ConstPtr &goal) {ROS_INFO_STREAM("receive goal");//获取目标中的数据long max = goal->max;double duration = goal->duration;//设置控件maxL.setText(QString::number(max));dL.setText(QString::number(duration));//回调结果demo_actions::CountNumberResult result;//rateros::Rate rate(duration);for (int i = 1; i < max; ++i) {if(this->isAborted){//认为服务器出错result.count = -1;server->setAborted(result);return;}/*-------------------------- 取消 --------------------------*///是否请求被取消if(server->isPreemptRequested()){//必须要知道客户端已经取消了任务,才能通过这个方法返回结果result.count = i;server->setPreempted(result);return;}//进度demo_actions::CountNumberFeedback feedback;feedback.percent = (double)i/(double)max;//发布进度server->publishFeedback(feedback);//睡眠rate.sleep();}//成功result.count = max;server->setSucceeded(result);
}void MainWindowServer::aborted() {this->isAborted = true;
}

2.5

client_ui.cpp

//
// Created by wt on 2020/7/5.
//
#include <iostream>
#include <ros/ros.h>
#include <QApplication>
#include "MainWindowClient.h"
using namespace std;int main(int argc,char *argv[]){//节点名string nodeName = "action_client";//初始化节点ros::init(argc,argv,nodeName);//创建节点ros::NodeHandle node;/*-------------------------- qt --------------------------*/QApplication app(argc,argv);MainWindowClient w(node);w.show();return QApplication::exec();
}

2.6

//
// Created by wt on 2020/7/5.
//
#include <iostream>
#include <ros/ros.h>
#include <QApplication>
#include "MainWindowServer.h"
using namespace std;int main(int argc,char *argv[]){//节点名string nodeName = "action_server";//初始化节点ros::init(argc,argv,nodeName);//创建节点ros::NodeHandle node;/*-------------------------- asy --------------------------*/ros::AsyncSpinner spinner(1);spinner.start();/*-------------------------- qt --------------------------*/QApplication app(argc,argv);MainWindowServer w;w.show();return QApplication::exec();
}

ros简版Action通讯SimpleAction相关推荐

  1. ros标准版Action通讯

    ros标准版Action通讯 Action通讯模型 Action通讯模型组成¶ ROS中,节点与节点间通讯,提供了新的方式,就是Action通讯. Action通讯分为Client端和Server端, ...

  2. 来,一起手撸一个简版 Redis(附源码)

    点击上方 视学算法,选择 设为星标 优质文章,及时送达 作者 | 凯京技术团队 来自 | my.oschina.net/keking/blog/3037372 今天主要介绍两个开源项目,然后创建应用最 ...

  3. react-redux简版实现

    Provider组件 Provider用于建立能够被子组件访问的全局属性,核心API有两个: childContextTypes静态属性,用于指定被子组件访问的全局属性类型 getChildConte ...

  4. 写一个简版 asp.net core

    动手写一个简版 asp.net core Intro 之前看到过蒋金楠老师的一篇 200 行代码带你了解 asp.net core 框架,最近参考蒋老师和 Edison 的文章和代码,结合自己对 as ...

  5. 初识react(二) 实现一个简版的html+redux.js的demo

    回顾 初识react(一) 揭开jsx语法和虚拟DOM面纱 初识react(二) 实现一个简版的html+redux.js的demo 初识react(三)在 react中使用redux来实现简版计数器 ...

  6. [置顶]完美简版学生信息管理系统(附有源码)管理系统

    简版学生信息管理系统 目前为止找到的简版系统中最新.最全的java类管理系统 点击进入简版系统 如果无法直接连接,请进入: https://blog.csdn.net/weixin_43419816/ ...

  7. 7句话让Codex给我做了个小游戏,还是极简版塞尔达,一玩简直停不下来

    点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 梦晨 萧箫 发自 凹非寺 量子位 | 公众号 QbitAI 什么,7 ...

  8. 2012年中国移动地图和导航市场研究报告简版

    2019独角兽企业重金招聘Python工程师标准>>> 2012年中国移动地图和导航市场研究报告简版 2012年中国移动地图和导航市场用户规模为2.53亿人,增长率为62.2%.伴随 ...

  9. 10分钟手撸极简版ORM框架!

    最近很多小伙伴对ORM框架的实现很感兴趣,不少读者在冰河的微信上问:冰河,你知道ORM框架是如何实现的吗?比如像MyBatis和Hibernte这种ORM框架,它们是如何实现的呢? 为了能够让小伙伴们 ...

最新文章

  1. 根据redis自增生成全局唯一订单id
  2. php获得注册信息,PHP网络编程:获取用户的注册信息[2]
  3. 微信小游戏“跳一跳”,Python“外挂”已上线
  4. 如何利用MySQL加密函数保护Web网站敏感数据
  5. java堆和客栈_JAVA中堆、栈,静态方法和非静态方法的速度问题
  6. 物流系统开发中,Dev倥件的使用
  7. 任何时候都不要轻易满仓
  8. php中 被遗忘的函数
  9. java反编译能拿到源码吗_大牛带你解读Spring源码,编写自定义标签,您能学会吗?
  10. Hadoop快速入门——第一章、认识Hadoop与创建伪分布式模式
  11. dcdc芯片效率不高的原因_浅析影响DC-DC转换器效率的主要因素
  12. 如何配置android的adb环境变量,windows系统下配置adb环境变量的方法步骤
  13. 现在流行的画原型图工具_原型资源图:8种流行原型工具的综合指南
  14. 韩昊20190912-3 词频统计
  15. 终极选择---老男孩教育
  16. Buffer Pool详解
  17. 开放原子训练营(第一季)铜锁探密:基于铜锁,在前端对登录密码进行加密,实现隐私数据保密性
  18. 基于51单片机的温湿度检测及调节系统
  19. Possibly consider using a shorter maxLifetime value.解决方法
  20. python中“end=”用法

热门文章

  1. 解析搜索引擎的Robots协议
  2. 聊聊 Python 的单元测试框架(二):nose 和它的继任者 nose2
  3. 网络协议 22 - RPC 协议(下)- 二进制类 RPC 协议
  4. 面向对象的原型与继承
  5. 如何使用 Cloud Insight SDK 实现 Druid 监控?
  6. 关于运放电路放大倍数的计算
  7. jboss7.1.0配置数据库(mysql)
  8. Longest Valid Parentheses leetcode java
  9. Zabbix监控Redis状态(内含Zabbix、Redis福利资料)
  10. Eclipse中,lombok安装