Service话题
首先使用同样的方法可以完成srv文件的导入
服务端的实现。Hierarchy窗口的“+→Create”Empty”创建空GameObject,命名为“AddTwoIntsServer”,添加新的脚本“AddTwoIntsServer”
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using Unity.Robotics.ROSTCPConnector.ROSGeometry;
using AddTwoIntsRequest = RosMessageTypes.Hello.AddTwoIntsRequest;
using AddTwoIntsResponse = RosMessageTypes.Hello.AddTwoIntsResponse;
public class AddTwoIntsServer : MonoBehaviour
{
void Start()
{
// 向ROS连接注册Service服务
ROSConnection.GetOrCreateInstance().ImplementService<
AddTwoIntsRequest, AddTwoIntsResponse >("add_two_ints", AddTwoIntsCallback);
}
private AddTwoIntsResponse AddTwoIntsCallback(AddTwoIntsRequest request)
{
AddTwoIntsResponse response = new AddTwoIntsResponse();
response.sum = request.a + request.b;
return response;
}
}
客户端的实现。Hierarchy窗口的“+→Create”Empty”创建空GameObject,命名为“AddTwoIntsClient”,添加新的脚本“AddTwoIntsClient”,编辑如下。
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using AddTwoIntsRequest = RosMessageTypes.Hello.AddTwoIntsRequest;
using AddTwoIntsResponse = RosMessageTypes.Hello.AddTwoIntsResponse;
public class AddTwoIntsClient : MonoBehaviour
{
ROSConnection ros;
void Start()
{
// 向ROS连接注册Service服务
ros = ROSConnection.GetOrCreateInstance();
ros.RegisterRosService< AddTwoIntsRequest, AddTwoIntsResponse >("add_two_ints");
// 请求生成
AddTwoIntsRequest request = new AddTwoIntsRequest(1, 2);
// 请求发送
ros.SendServiceMessage< AddTwoIntsResponse >("add_two_ints", request, AddTwoIntsCallback);
}
void AddTwoIntsCallback(AddTwoIntsResponse response)
{
print("1 + 2 = " + response.sum);
}
}
全部0条评论
快来发表一下你的评论吧 !