forked from KIT-ISAS/iviz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RosPublisher.cs
354 lines (295 loc) · 9.04 KB
/
RosPublisher.cs
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Iviz.Msgs;
using Iviz.Roslib.XmlRpc;
using Iviz.Tools;
namespace Iviz.Roslib;
/// <summary>
/// Manager for a ROS publisher.
/// </summary>
/// <typeparam name="TMessage">Topic type</typeparam>
public sealed class RosPublisher<TMessage> : IRosPublisher<TMessage> where TMessage : IMessage
{
readonly RosClient client;
readonly List<string> ids = new();
readonly SenderManager<TMessage> manager;
readonly CancellationTokenSource runningTs = new();
int totalPublishers;
bool disposed;
internal RosPublisher(RosClient client, TopicInfo topicInfo)
{
this.client = client;
manager = new SenderManager<TMessage>(this, topicInfo) { ForceTcpNoDelay = true };
}
/// <summary>
/// Whether this publisher is valid.
/// </summary>
public bool IsAlive => !CancellationToken.IsCancellationRequested;
/// <summary>
/// The number of ids generated by this publisher.
/// </summary>
public int NumIds => ids.Count;
/// <summary>
/// The queue size in bytes.
/// If a message arrives that makes the queue larger than this, the oldest message will be discarded.
/// </summary>
public int MaxQueueSizeInBytes
{
get => manager.MaxQueueSizeInBytes;
set => manager.MaxQueueSizeInBytes = value;
}
/// <summary>
/// A cancellation token that gets canceled when the publisher is disposed.
/// </summary>
public CancellationToken CancellationToken => runningTs.Token;
public string Topic => manager.Topic;
public string TopicType => manager.TopicType;
public int NumSubscribers => manager.NumConnections;
public int TimeoutInMs
{
get => manager.TimeoutInMs;
set => manager.TimeoutInMs = value;
}
public bool ForceTcpNoDelay
{
get => manager.ForceTcpNoDelay;
set => manager.ForceTcpNoDelay = value;
}
public bool LatchingEnabled
{
get => manager.Latching;
set => manager.Latching = value;
}
/// <summary>
/// Manually sets the latched message.
/// </summary>
public TMessage LatchedMessage
{
set => manager.LatchedMessage = value;
}
public PublisherTopicState GetState()
{
AssertIsAlive();
return new PublisherTopicState(Topic, TopicType, ids, manager.GetStates());
}
void IRosPublisher.Publish(IMessage message)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
if (message is not TMessage tMessage)
{
throw new RosInvalidMessageTypeException("Type does not match publisher.");
}
message.RosValidate();
AssertIsAlive();
manager.Publish(tMessage);
}
ValueTask IRosPublisher.PublishAsync(IMessage message, RosPublishPolicy policy, CancellationToken token)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
if (message is not TMessage tMessage)
{
throw new RosInvalidMessageTypeException("Type does not match publisher.");
}
return PublishAsync(tMessage, policy, token);
}
/// <summary>
/// Publishes the given message into the topic.
/// </summary>
/// <param name="message">The message to be published.</param>
/// <exception cref="ArgumentNullException">The message is null</exception>
/// <exception cref="RosInvalidMessageTypeException">The message type does not match.</exception>
public void Publish(in TMessage message)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
AssertIsAlive();
message.RosValidate();
manager.Publish(message);
}
public ValueTask PublishAsync(in TMessage message, RosPublishPolicy policy = RosPublishPolicy.DoNotWait,
CancellationToken token = default)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
AssertIsAlive();
message.RosValidate();
switch (policy)
{
case RosPublishPolicy.DoNotWait:
manager.Publish(message);
return default;
case RosPublishPolicy.WaitUntilSent:
return manager.PublishAndWaitAsync(message, token);
default:
return default;
}
}
TopicRequestRpcResult IRosPublisher.RequestTopicRpc(bool requestsTcp, RpcUdpTopicRequest? requestsUdp,
out Endpoint? tcpResponse, out RpcUdpTopicResponse? udpResponse)
{
if (disposed)
{
tcpResponse = null;
udpResponse = null;
return TopicRequestRpcResult.Disposing;
}
if (requestsTcp)
{
tcpResponse = new Endpoint(client.CallerUri.Host, manager.Endpoint.Port);
udpResponse = null;
return TopicRequestRpcResult.Success;
}
if (requestsUdp == null)
{
throw new InvalidOperationException("Either UDP or TCP needs to be requested");
}
tcpResponse = null;
udpResponse = manager.CreateUdpConnection(requestsUdp, client.CallerUri.Host);
return TopicRequestRpcResult.Success;
}
void IDisposable.Dispose()
{
Dispose();
}
public async ValueTask DisposeAsync(CancellationToken token)
{
if (disposed)
{
return;
}
disposed = true;
runningTs.Cancel();
ids.Clear();
await manager.DisposeAsync(token).AwaitNoThrow(this);
NumSubscribersChanged = null;
}
void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
runningTs.Cancel();
ids.Clear();
manager.Dispose();
NumSubscribersChanged = null;
}
public string Advertise()
{
AssertIsAlive();
string id = GenerateId();
ids.Add(id);
return id;
}
public bool Unadvertise(string id, CancellationToken token = default)
{
if (!IsAlive)
{
return true;
}
bool removed = RemoveId(id ?? throw new ArgumentNullException(nameof(id)));
if (ids.Count == 0)
{
TaskUtils.Run(() => RemovePublisherAsync(token), token).WaitAndRethrow();
}
return removed;
}
public async ValueTask<bool> UnadvertiseAsync(string id, CancellationToken token = default)
{
if (!IsAlive)
{
return true;
}
bool removed = RemoveId(id ?? throw new ArgumentNullException(nameof(id)));
if (ids.Count == 0)
{
await RemovePublisherAsync(token);
}
return removed;
}
Task RemovePublisherAsync(CancellationToken token)
{
var disposeTask = DisposeAsync(token).AwaitNoThrow(this);
var unadvertiseTask = client.RemovePublisherAsync(this, token).AwaitNoThrow(this);
return (disposeTask, unadvertiseTask).WhenAll();
}
public bool ContainsId(string id)
{
if (id is null)
{
throw new ArgumentNullException(nameof(id));
}
return ids.Contains(id);
}
/// <summary>
/// Checks whether the given type matches the publisher message type <see cref="TMessage"/>
/// </summary>
public bool MessageTypeMatches(Type type)
{
return type == typeof(TMessage);
}
/// <summary>
/// Called when the number of subscribers has changed.
/// </summary>
public event Action<RosPublisher<TMessage>>? NumSubscribersChanged;
internal void RaiseNumSubscribersChanged()
{
if (NumSubscribersChanged == null)
{
return;
}
Task.Run(() =>
{
try
{
NumSubscribersChanged?.Invoke(this);
}
catch (Exception e)
{
Logger.LogErrorFormat("{0}: Exception from NumSubscribersChanged : {1}", this, e);
}
}, default);
}
void AssertIsAlive()
{
if (!IsAlive)
{
throw new ObjectDisposedException("this", "This is not a valid publisher");
}
}
string GenerateId()
{
int currentCount = Interlocked.Increment(ref totalPublishers);
int lastId = currentCount - 1;
return lastId == 0 ? Topic : $"{Topic}-{lastId.ToString()}";
}
bool RemoveId(string topicId)
{
return ids.Remove(topicId);
}
internal bool TryGetLoopbackReceiver(in Endpoint endpoint, out ILoopbackReceiver<TMessage>? receiver)
{
return client.TryGetLoopbackReceiver(Topic, endpoint, out receiver);
}
public void UnsetLatch()
{
manager.UnsetLatch();
}
public override string ToString()
{
return $"[{nameof(RosPublisher<TMessage>)} {Topic} [{TopicType}] ]";
}
}