-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathServiceCaller.cs
More file actions
172 lines (138 loc) · 4.74 KB
/
ServiceCaller.cs
File metadata and controls
172 lines (138 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Iviz.Msgs;
using Iviz.Roslib.Utils;
using Iviz.Tools;
namespace Iviz.Roslib;
internal sealed class ServiceCaller : IDisposable
{
const int DefaultTimeoutInMs = 5000;
const byte ErrorByte = 0;
readonly bool requestNoDelay;
readonly ServiceInfo serviceInfo;
readonly TcpClient tcpClient;
bool disposed;
public bool IsAlive => tcpClient.Client.CheckIfAlive();
public string ServiceType => serviceInfo.Type;
public Uri? RemoteUri { get; private set; }
public ServiceCaller(ServiceInfo serviceInfo, bool requestNoDelay = true)
{
this.serviceInfo = serviceInfo;
this.requestNoDelay = requestNoDelay;
tcpClient = new TcpClient(AddressFamily.InterNetworkV6)
{
Client = { DualMode = true },
ReceiveTimeout = DefaultTimeoutInMs,
SendTimeout = DefaultTimeoutInMs
};
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
tcpClient.Dispose();
}
ValueTask SendHeaderAsync(bool persistent, CancellationToken token)
{
string[] contents =
{
$"callerid={serviceInfo.CallerId}",
$"service={serviceInfo.Service}",
$"type={serviceInfo.Type}",
$"md5sum={serviceInfo.Md5Sum}",
requestNoDelay ? "tcp_nodelay=1" : "tcp_nodelay=0",
persistent ? "persistent=1" : "persistent=0",
};
return tcpClient.WriteHeaderAsync(contents, token);
}
async ValueTask ProcessHandshakeAsync(bool persistent, CancellationToken token)
{
await SendHeaderAsync(persistent, token);
List<string> responses;
using (var readBuffer = await ReceivePacketAsync(token))
{
responses = RosUtils.ParseHeader(readBuffer);
}
var values = RosUtils.CreateHeaderDictionary(responses);
if (values.TryGetValue("error", out string? message))
{
throw new RosHandshakeException($"Partner sent error message: [{message}]");
}
}
public async ValueTask StartAsync(Uri remoteUri, bool persistent, CancellationToken token)
{
RemoteUri = remoteUri;
string remoteHostname = remoteUri.Host;
int remotePort = remoteUri.Port;
await tcpClient.TryConnectAsync(remoteHostname, remotePort, token, DefaultTimeoutInMs);
await ProcessHandshakeAsync(persistent, token);
}
async ValueTask<Rent<byte>> ReceivePacketAsync(CancellationToken token)
{
byte[] lengthBuffer = new byte[4];
if (!await tcpClient.ReadChunkAsync(lengthBuffer, 4, token))
{
throw new IOException("Partner closed connection");
}
int length = lengthBuffer.ReadInt();
if (length == 0)
{
return Rent.Empty<byte>();
}
var readBuffer = new Rent<byte>(length);
try
{
if (!await tcpClient.ReadChunkAsync(readBuffer, token))
{
throw new IOException("Partner closed connection");
}
}
catch
{
readBuffer.Dispose();
throw;
}
return readBuffer;
}
public async ValueTask ExecuteAsync(IService service, CancellationToken token)
{
if (tcpClient == null)
{
throw new InvalidOperationException("Service caller has not been started!");
}
if (service?.Request == null)
{
throw new NullReferenceException("Request cannot be null");
}
service.Request.RosValidate();
var requestMsg = service.Request;
int msgLength = requestMsg.RosMessageLength;
using var writeBuffer = new Rent<byte>(msgLength);
requestMsg.SerializeTo(writeBuffer);
await tcpClient.WriteChunkAsync(BitConverter.GetBytes(msgLength), 4, token);
await tcpClient.WriteChunkAsync(writeBuffer, token);
byte statusByte = await ReadOneByteAsync(token);
using var readBuffer = await ReceivePacketAsync(token);
if (statusByte == ErrorByte)
{
throw new RosServiceCallFailed(serviceInfo.Service, BuiltIns.UTF8.GetString(readBuffer));
}
service.Response = (IResponse)service.Response.DeserializeFrom(readBuffer);
}
async ValueTask<byte> ReadOneByteAsync(CancellationToken token)
{
byte[] statusBuffer = new byte[1];
if (!await tcpClient.ReadChunkAsync(statusBuffer, 1, token))
{
throw new IOException("Partner closed the connection");
}
return statusBuffer[0];
}
}