编写代码实现ROS中的Service通讯:首先需要自定义srv 文件,创建服务端与客户端;创建一个服务节点,该节点提供了一个查询服务,允许客户端通过发送身份证号来获取对应的人名和工号
时间: 2024-10-04 15:00:51 浏览: 42
在Robot Operating System (ROS) 中实现Service通信涉及以下几个步骤:
1. **自定义srv文件**:
首先,你需要在`msg`目录下为服务定义一个`.srv`文件(如`QueryPerson.srv`),它通常包含两个字段:一个是请求消息(例如`Request`),包含身份证号;另一个是响应消息(例如`Response`),包含人名和工号。
```yaml
syntax: "rosmsg"
package: your_package_name
message QueryPersonRequest {
string id_number
}
message QueryPersonResponse {
string name;
int32 id_number;
}
```
2. **创建服务端**:
在服务节点(service_server.py)中,导入定义好的`QueryPerson.srv`,定义一个处理函数并注册服务:
```python
import rospy
from std_msgs.msg import String
from your_package_name.srv import QueryPerson, QueryPersonRequest, QueryPersonResponse
def handle_query_person(req):
# 实现查询逻辑,这里是示例,实际应连接数据库或其他数据源
name = '张三'
employee_id = 123456
response = QueryPersonResponse(name=name, id_number=employee_id)
return response
def service_server():
rospy.init_node('query_person_service')
s = rospy.Service('query_person', QueryPerson, handle_query_person)
print("Service is ready.")
rospy.spin()
```
3. **创建客户端**:
客户端(service_client.py)订阅该服务,并调用它来获取信息:
```python
import rospy
from your_package_name.srv import QueryPerson
def query_person_client(id_number):
rospy.wait_for_service('query_person') # 等待服务可用
try:
client = rospy.ServiceProxy('query_person', QueryPerson)
request = QueryPersonRequest(id_number=id_number)
response = client(request)
print(f"Name: {response.name}, ID: {response.id_number}")
except rospy.ServiceException as e:
print(f"Service call failed: {e}")
if __name__ == '__main__':
rospy.init_node('query_person_client')
id_number = input("Enter ID number to search: ")
query_person_client(id_number)
rospy.signal_shutdown("Client finished.")
```
阅读全文