ROS2自定义服务接口
在src/village_interface 下构建srv文件夹
src/village_interface/srv 下新建一个BorrowMoney.srv 遵循大小写编程规范
# 客户端请求
string name
uint32 money
# 中间这三个横杠很重要 不能删掉
---
# 服务端响应
bool success
uint32 money
接口编译
修改cmakelists.txt
# find_package(sensor_msgs REQUIRED) 如果使用了 sensor_msgs下的数据类型
find_package(rosidl_default_generators REQUIRED) # 生成接口依赖
rosidl_generate_interfaces(${PROJECT_NAME}
"srv/BorrowMoney.srv"
# 如果有该服务接口中的数据类型有依赖其他接口如sensor_msgs
应再加一句 DEPENDENCIES sensor_msgs
)
如果使用了其他的依赖还要修改package.xml(以sensor_msgs为例)
<depend>sensor_msgs</depend>
<build_depend>rosidl_default_generators</build_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
ros2 service call /borrow_money village_interface/srv/BorrowMoney "{name: "acan", money: 5}"
ros2 service call 服务名称 服务消息类型 消息内容
import rclpy
from rclpy.node import Node
from std_msgs.msg import String,UInt32
from village_interface.srv import BorrowMoney
class WriterNode(Node):
def __init__(self,name):
super().__init__(name)
self.get_logger().info('大家好,我是%s.' % name)
# String 话题消息类型
# "sexy_gril" 话题名
# 10 话题发布类型
# self.create_publisher(消息类型, 话题名, 发布频率)
# 创建发布者
self.pub_novel = self.create_publisher(String, "sexy_gril", 10)
# self.create_subscription(消息类型,话题名,回调函数,队列长度)
# 创建订阅者
self.sub_money = self.create_subscription(UInt32,"sexy_gril_money",self.rev_money_callback,10)
# 创建客户端
self.borrow_server = self.create_service(BorrowMoney,"borrow_money",self.borrowmoney_callback)
self.timer_period = 5
self.timer = self.create_timer(self.timer_period,self.timer_callback)
self.counter = 0
self.count = 80
# 创建服务端回调函数
def borrowmoney_callback(self, request, response):
"""
request: 来自客户端的请求数据
response:来自服务端的响应数据
"""
self.get_logger().info("收到来自:%s的请求,目前账户里有%d元"%(request.name,self.count))
if request.money <= self.count * 0.1:
response.success = True
response.money = request.money
self.count -= request.money
self.get_logger().info("借钱成功,借出%d元,目前账户结余%d"%(request.money,self.count))
else:
response.success = False
response.money = 0
self.get_logger().info("借钱失败!!")
return response
def timer_callback(self):
msg = String()
msg.data = '第%d回:潋滟湖 %d 次偶遇胡艳娘' %(self.counter,self.counter)
self.pub_novel.publish(msg=msg)
self.get_logger().info("发布消息: %s" % msg.data)
self.counter = self.counter + 1
def rev_money_callback(self,money):
self.count = self.count + money.data
self.get_logger().info("收到了%d的钱"%money.data)
def hello(args=None):
rclpy.init(args=args)
li3_node = WriterNode("li4")
rclpy.spin(li3_node)
rclpy.shutdown()